text:
#define TYTI_NO_L_UNDEF
#include "../vdf_parser.hpp"
#define T_L(x) TYTI_L(charT, x)
using namespace tyti;

#include "catch.hpp"

const std::string testdata_dir = SOURCE_DIR "/testdata/";

#ifdef _WIN32
#include <direct.h>
#define cwd _getcwd
#define cd _chdir
#else
#include "unistd.h"
#define cwd getcwd
#define cd chdir
#endif

template <typename charT>
void check_DST_AST(const vdf::basic_object<charT> &obj)
{
    CHECK(obj.name == T_L("AppState"));
    REQUIRE(obj.attribs.size() == 24);
    REQUIRE(obj.childs.size() == 4);

    CHECK(obj.attribs.at(T_L("appid")) == T_L("343050"));

    CHECK(obj.attribs.at(T_L("buildid")) == T_L("1101428"));
    CHECK(obj.attribs.at(T_L("#1_attrib")) == T_L("1"));
    CHECK(obj.attribs.at(T_L("emptyAttrib")) == T_L(""));
    CHECK(obj.attribs.at(T_L("escape_quote")) == T_L(R"("quote")"));
    CHECK(obj.attribs.at(T_L("no_quoted_attrib_support")) == T_L("yes"));
// "C2017 can occur when the stringize operator is used with strings that include escape sequences."
// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/29t70y03(v=vs.120)
#if !defined(_MSC_VER) || (_MSC_VER > 1800)
    CHECK(obj.attribs.at(T_L("escape_quote_backslash")) == T_L("quote_with_other_escapes\\\"\\"));
    CHECK(obj.attribs.at(T_L("tab_escape")) == T_L("new\\ttab"));
    CHECK(obj.attribs.at(T_L("new_line_escape")) == T_L("new\\nline"));
#endif

    CHECK(obj.childs.at(T_L("UserConfig"))->name == T_L("UserConfig"));
    CHECK(obj.childs.at(T_L("UserConfig"))->childs.empty());

    const auto &inc = obj.childs.at(T_L("IncludedStuff"));
    CHECK(inc->name == T_L("IncludedStuff"));
    const auto &base = obj.childs.at(T_L("BaseInclude"));
    REQUIRE(base->attribs.size() == 1);
    CHECK(base->attribs.at(T_L("BaseAttrib")) == T_L("Yes"));
    CHECK(obj.attribs.at(T_L("another attribute with fancy space")) == T_L("yay"));
}

template <typename charT>
void check_DST_AST_multikey(const vdf::basic_multikey_object<charT> &obj)
{
    CHECK(obj.name == T_L("AppState"));
    REQUIRE(obj.attribs.size() == 25);
    REQUIRE(obj.childs.size() == 4);

    CHECK(obj.attribs.find(T_L("appid"))->second == T_L("343050"));

    CHECK(obj.attribs.find(T_L("buildid"))->second == T_L("1101428"));
    CHECK(obj.attribs.find(T_L("#1_attrib"))->second == T_L("1"));
    CHECK(obj.attribs.find(T_L("emptyAttrib"))->second == T_L(""));
    CHECK(obj.attribs.find(T_L("no_quoted_attrib_support"))->second == T_L("yes"));

    CHECK(obj.attribs.count(T_L("UpdateResult")) == 2);

    CHECK(obj.childs.find(T_L("UserConfig"))->second->name == T_L("UserConfig"));
    CHECK(obj.childs.find(T_L("UserConfig"))->second->childs.empty());

    const auto &inc = obj.childs.find(T_L("IncludedStuff"))->second;
    CHECK(inc->name == T_L("IncludedStuff"));
    const auto &base = obj.childs.find(T_L("BaseInclude"))->second;
    REQUIRE(base->attribs.size() == 1);
    CHECK(base->attribs.find(T_L("BaseAttrib"))->second == T_L("Yes"));
    CHECK(obj.attribs.find(T_L("another attribute with fancy space"))->second == T_L("yay"));
}

template <typename charT>
void read_check_DST_file_ok()
{
    std::basic_ifstream<charT> file("DST_Manifest.acf");
    bool ok;
    auto objects = vdf::read(file, &ok);

    REQUIRE(ok);
    auto it = objects.childs.find(T_L("AppState"));
    CHECK(it != objects.childs.end());
    check_DST_AST(*(it->second));
}

template <typename charT>
void read_check_DST_file_ec()
{
    std::basic_ifstream<charT> file("DST_Manifest.acf");
    std::error_code ec;
    auto objects = vdf::read(file, ec);

    REQUIRE(!ec);
    auto it = objects.childs.find(T_L("AppState"));
    CHECK(it != objects.childs.end());
    check_DST_AST(*(it->second));
}

template <typename charT>
void read_check_DST_file_throw()
{
    std::basic_ifstream<charT> file("DST_Manifest.acf");
    auto objects = vdf::read(file);
    auto it = objects.childs.find(T_L("AppState"));
    CHECK(it != objects.childs.end());
    check_DST_AST(*(it->second));
}

template <typename charT>
void read_check_DST_file_multikey_throw()
{
    std::basic_ifstream<charT> file("DST_Manifest.acf");
    auto objects = vdf::read<vdf::basic_multikey_object<charT>>(file);
    auto it = objects.childs.find(T_L("AppState"));
    CHECK(it != objects.childs.end());
    check_DST_AST_multikey(*(it->second));
}

TEST_CASE("Read File", "[read]")
{
    REQUIRE(cd(testdata_dir.c_str()) == 0);
    read_check_DST_file_ok<char>();
    read_check_DST_file_ok<wchar_t>();
    read_check_DST_file_ec<char>();
    read_check_DST_file_ec<wchar_t>();
    read_check_DST_file_throw<char>();
    read_check_DST_file_throw<wchar_t>();
}

template <typename charT>
void read_string()
{
    std::basic_string<charT> attribs(T_L("\"firstNode\"{\"SecondNode\"{\"Key\" \"Value\" //myComment\n}}"));
    bool ok;
    vdf::read(attribs.begin(), attribs.end(), &ok);

    REQUIRE(ok);
}

template <typename charT>
void check_string(const vdf::basic_object<charT> &obj)
{
    CHECK(obj.name == T_L("firstNode"));

    CHECK(obj.attribs.empty() == true);
    REQUIRE(obj.childs.size() == 1);
    const auto &secondNode = obj.childs.at(T_L("SecondNode"));

    CHECK(secondNode->name == T_L("SecondNode"));
    REQUIRE(secondNode->attribs.size() == 1);
    CHECK(secondNode->childs.empty() == true);
    CHECK(secondNode->attribs.at(T_L("Key")) == T_L("Value"));
}

TEST_CASE("Read String", "[read]")
{
    read_string<char>();
    read_string<wchar_t>();
}

template <typename charT>
void check_fail()
{
    bool ok;
    std::basic_string<charT> attribs(T_L("\"firstNode\"{\"SecondNode\"{\"Key\" //myComment\n}}"));
    vdf::read(attribs.begin(), attribs.end(), &ok);

    REQUIRE(!ok);
}
//todo: error checking
TEST_CASE("Find Error", "[read_error]")
{
    check_fail<char>();
    check_fail<wchar_t>();
}

template <typename charT>
void write_and_read()
{
    std::basic_string<charT> attribs(T_L("\"firstNode\"{\"SecondNode\"{\"Key\" \"Value\" //myComment\n}}"));
    bool ok;
    auto objs = vdf::read(attribs.begin(), attribs.end(), &ok);

    REQUIRE(ok);

    std::basic_stringstream<charT> output;
    vdf::write(output, objs);
    objs = vdf::read(output);

    check_string(objs);
}

TEST_CASE("Write and Read", "[read_write]")
{
    write_and_read<char>();
    write_and_read<wchar_t>();
}

TEST_CASE("read multikey", "[read]")
{
    read_check_DST_file_multikey_throw<char>();
    read_check_DST_file_multikey_throw<wchar_t>();
}

/////////////////////////////////////////////////////////////
// readme test
/////////////////////////////////////////////////////////////

struct counter
{
    size_t num_attributes;
    counter() : num_attributes(0) {}
    void add_attribute(std::string key, std::string value)
    {
        ++num_attributes;
    }
    void add_child(std::unique_ptr<counter> child)
    {
        num_attributes += child->num_attributes;
    }
    void set_name(std::string n)
    {
    }
};

TEST_CASE("counter test", "[counter]")
{
    std::ifstream file("DST_Manifest.acf");
    counter num = tyti::vdf::read<counter>(file);
    CHECK(num.num_attributes == 29);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.hadoop.mapreduce.TaskID (Hadoop 0.20.205.0 API)
</TITLE>

<META NAME="date" CONTENT="2011-10-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.hadoop.mapreduce.TaskID

Packages that use TaskID

org.apache.hadoop.mapred
A software framework for easily writing applications which process vast
amounts of data (multi-terabyte data-sets) parallelly on large clusters
(thousands of nodes) built of commodity hardware in a reliable, fault-tolerant
manner.

org.apache.hadoop.mapreduce

Uses of TaskID in org.apache.hadoop.mapred

Subclasses of TaskID in org.apache.hadoop.mapred

 class
TaskID

          TaskID represents the immutable and unique identifier for
 a Map or Reduce Task.

Methods in org.apache.hadoop.mapred with parameters of type TaskID

static TaskID
TaskID.downgrade(TaskID old)

          Downgrade a new TaskID to an old one

Uses of TaskID in org.apache.hadoop.mapreduce

Methods in org.apache.hadoop.mapreduce that return TaskID

static TaskID
TaskID.forName(String str)

          Construct a TaskID object from given string

 TaskID
TaskAttemptID.getTaskID()

          Returns the TaskID object that this task attempt belongs to

Constructors in org.apache.hadoop.mapreduce with parameters of type TaskID

TaskAttemptID(TaskID taskId,
              int id)

          Constructs a TaskAttemptID object from given TaskID.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2009 The Apache Software Foundation

redpajama_set_name: RedPajamaGithub


text:
package edu.mayo.mprc.qa;

import com.google.common.base.Joiner;
import edu.mayo.mprc.MprcException;
import edu.mayo.mprc.io.KeyedTsvReader;
import edu.mayo.mprc.utilities.FileUtilities;
import edu.mayo.mprc.utilities.StringUtilities;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;

/**
 * Loads data from the UV controller. Organizes them by retention time, so for each spectrum we can quickly look
 * up the closest RT from the controller. This is important because the UV controller uses different timing intervals
 * and the R code (and the user) benefit from having a single, collated, output document
 *
 * @author Roman Zenka
 */
public final class UvDataReader implements KeyedTsvReader {
	private static final Logger LOGGER = Logger.getLogger(UvDataReader.class);

	private TreeMap<Double/* Retention time */, String/*The full line without id and RT*/> lines;
	private String[] header;
	private static final String ID_HEADER = "id";
	private static final String RT_HEADER = "rt";
	private static final String[] DEFAULT_HEADER = new String[]{
			"UV.RT", // Retention time as reported by the UV module
			"PumpModule.LoadingPump.Flow",
			"PumpModule.NC_Pump.%B",
			"PumpModule.LoadingPump.Pressure",
			"PumpModule.NC_Pump.Flow",
			"PumpModule.NC_Pump.Pressure",
			"ColumnOven.ValveRight",
			"ColumnOven.Temperature",
			"ColumnOven.ColumnOven_Temp.Signal",
			"Sampler.Status",
			"Sampler.Position",
			"Sampler.Volume"
	};
	private static final String EMPTY_LINE;
	private static final Pattern TAB_SPLIT = Pattern.compile("\t");

	static {
		// Empty line has a tab for each header item (minus one)
		EMPTY_LINE = StringUtilities.repeat('\t', DEFAULT_HEADER.length - 1);
	}

	/**
	 * Prepare the reader. In this implementation, the entire file is loaded at once and cached in memory (we
	 * expect the file to have around 10000 lines).
	 *
	 * @param uvDataFile rawDump file to process
	 */
	public UvDataReader(final File uvDataFile) {
		if (uvDataFile == null || !uvDataFile.exists() || uvDataFile.length() == 0) {
			// Null files are honored - they will act as if there was no input information
			// Use default header (otherwise we use header obtained from the file).
			header = DEFAULT_HEADER;
		} else {
			lines = new TreeMap<Double, String>();
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(uvDataFile));
				parse(reader, lines);
			} catch (Exception t) {
				throw new MprcException("Cannot parse uv data file [" + uvDataFile.getAbsolutePath() + "]", t);
			} finally {
				FileUtilities.closeQuietly(reader);
			}
		}
	}

	/**
	 * @return A tab-separated header line (sans the Scan number column) for all columns in the data in proper format
	 */
	@Override
	public String getHeaderLine() {
		return Joiner.on("\t").join(header);
	}

	@Override
	public String getEmptyLine() {
		return EMPTY_LINE;
	}

	/**
	 * @param key Retention time to get data for, in string format.
	 * @return Entire line for the closest earlier entry for given retention time.
	 */
	@Override
	public String getLineForKey(final String key) {
		if (lines == null) {
			return EMPTY_LINE;
		}
		Map.Entry<Double, String> entry = lines.floorEntry(Double.parseDouble(key));
		if (entry == null) {
			// Try ceiling if nothing below
			entry = lines.ceilingEntry(Double.parseDouble(key));
		}
		final String line = entry.getValue();
		if (line == null) {
			return EMPTY_LINE;
		}
		return line;
	}

	private void parse(final BufferedReader br, final Map<Double, String> lines) {
		try {
			header = readHeader(br);
			String line;
			int ignoredLines = 0;
			while (true) {
				line = br.readLine();
				if (line == null) {
					break;
				}
				final int firstTab = line.indexOf('\t');
				if (firstTab > 0) {
					final int secondTab = line.indexOf('\t', firstTab + 1);
					// We have data
					final String scanNumStr = line.substring(firstTab + 1, secondTab);
					final double retentionTime = Double.parseDouble(scanNumStr);

					lines.put(retentionTime, line.substring(firstTab + 1));
				} else {
					// Ignore the line
					ignoredLines++;
				}
			}
			if (ignoredLines > 0) {
				LOGGER.info("Ignored lines when parsing rawDump output file: " + ignoredLines);
			}
		} catch (Exception t) {
			throw new MprcException("Failed to parse rawDump output file", t);
		}
	}

	private static String[] readHeader(final BufferedReader br) throws IOException {
		final String line = br.readLine();
		if (line == null) {
			throw new MprcException("The rawDump output has no header");
		}
		final String[] tmpHeader = TAB_SPLIT.split(line);
		if (tmpHeader.length < 2) {
			throw new MprcException(String.format("Unknown rawDump output format - we expect at least %d columns, got %d", DEFAULT_HEADER.length + 2, tmpHeader.length));
		}
		if (!ID_HEADER.equals(tmpHeader[0])) {
			throw new MprcException(String.format("Unknown rawDump output format (first column should be '%s', was '%s'.", ID_HEADER, tmpHeader[0]));
		}
		if (!RT_HEADER.equals(tmpHeader[1])) {
			throw new MprcException(String.format("Unknown rawDump output format (first column should be '%s', was '%s'.", RT_HEADER, tmpHeader[1]));
		}
		final String[] parsedHeader = new String[tmpHeader.length - 1];
		System.arraycopy(tmpHeader, 2, parsedHeader, 1, tmpHeader.length - 2);
		parsedHeader[0] = "UV.RT";
		return parsedHeader;
	}
}


text:
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 * Copyright 1993 by OpenVision Technologies, Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appears in all copies and
 * that both that copyright notice and this permission notice appear in
 * supporting documentation, and that the name of OpenVision not be used
 * in advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission. OpenVision makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 * OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#include "gssapiP_krb5.h"

OM_uint32 KRB5_CALLCONV
krb5_gss_release_cred(minor_status, cred_handle)
    OM_uint32 *minor_status;
    gss_cred_id_t *cred_handle;
{
    krb5_context context;
    krb5_gss_cred_id_t cred;
    krb5_error_code code1, code2, code3;

    code1 = krb5_gss_init_context(&context);
    if (code1) {
        *minor_status = code1;
        return GSS_S_FAILURE;
    }

    if (*cred_handle == GSS_C_NO_CREDENTIAL) {
        *minor_status = 0;
        krb5_free_context(context);
        return(GSS_S_COMPLETE);
    }

    cred = (krb5_gss_cred_id_t)*cred_handle;

    k5_mutex_destroy(&cred->lock);
    /* ignore error destroying mutex */

    if (cred->ccache) {
        if (cred->destroy_ccache)
            code1 = krb5_cc_destroy(context, cred->ccache);
        else
            code1 = krb5_cc_close(context, cred->ccache);
    } else
        code1 = 0;

    if (cred->client_keytab)
        krb5_kt_close(context, cred->client_keytab);

#ifndef LEAN_CLIENT
    if (cred->keytab)
        code2 = krb5_kt_close(context, cred->keytab);
    else
#endif /* LEAN_CLIENT */
        code2 = 0;

    if (cred->rcache)
        code3 = krb5_rc_close(context, cred->rcache);
    else
        code3 = 0;
    if (cred->name)
        kg_release_name(context, &cred->name);

    krb5_free_principal(context, cred->impersonator);

    if (cred->req_enctypes)
        free(cred->req_enctypes);

    if (cred->password != NULL)
        zapfree(cred->password, strlen(cred->password));

    xfree(cred);

    *cred_handle = NULL;

    *minor_status = 0;
    if (code1)
        *minor_status = code1;
    if (code2)
        *minor_status = code2;
    if (code3)
        *minor_status = code3;

    if (*minor_status)
        save_error_info(*minor_status, context);
    krb5_free_context(context);
    return(*minor_status?GSS_S_FAILURE:GSS_S_COMPLETE);
}


text:
#ifndef CGridMapAligner_H
#define CGridMapAligner_H

#include <mrpt/slam/CMetricMapsAlignmentAlgorithm.h>
#include <mrpt/slam/CLandmarksMap.h>
#include <mrpt/utils/CLoadableOptions.h>
#include <mrpt/poses/CPosePDFSOG.h>
#include <mrpt/vision/CFeatureExtraction.h>
#include <mrpt/slam/COccupancyGridMapFeatureExtractor.h>

namespace mrpt
{
	namespace slam
	{
		using namespace poses;
		using namespace utils;

		/** A class for aligning two multi-metric maps (with an occupancy grid maps and a points map, at least) based on features extraction and matching.
		 * The matching pose is returned as a Sum of Gaussians (poses::CPosePDFSOG).
		 *
		 *  This class can use three methods (see options.methodSelection):
		 *   - amCorrelation: "Brute-force" correlation of the two maps over a 2D+orientation grid of possible 2D poses.
		 *   - amRobustMatch: Detection of features + RANSAC matching
		 *   - amModifiedRANSAC: Detection of features + modified multi-hypothesis RANSAC matching as described in was reported in the paper http://www.mrpt.org/Paper%3AOccupancy_Grid_Matching
		 *
		 * See CGridMapAligner::Align for more instructions.
		 *
		 * \sa CMetricMapsAlignmentAlgorithm
		 * \ingroup mrpt_slam_grp
		 */
		class SLAM_IMPEXP  CGridMapAligner : public CMetricMapsAlignmentAlgorithm
		{
		private:
			/** Private member, implements one the algorithms.
			  */
			CPosePDFPtr AlignPDF_correlation(
					const CMetricMap		*m1,
					const CMetricMap		*m2,
					const CPosePDFGaussian	&initialEstimationPDF,
					float					*runningTime = NULL,
					void					*info = NULL );

			/** Private member, implements both, the "robustMatch" and the newer "modifiedRANSAC" algorithms.
			  */
			CPosePDFPtr AlignPDF_robustMatch(
					const CMetricMap		*m1,
					const CMetricMap		*m2,
					const CPosePDFGaussian	&initialEstimationPDF,
					float					*runningTime = NULL,
					void					*info = NULL );

			COccupancyGridMapFeatureExtractor	m_grid_feat_extr; //!< Grid map features extractor
		public:

			CGridMapAligner() :
				options()
			{}

			/** The type for selecting the grid-map alignment algorithm.
			  */
			enum TAlignerMethod
			{
				amRobustMatch = 0,
				amCorrelation,
				amModifiedRANSAC
			};

			/** The ICP algorithm configuration data
			 */
			class SLAM_IMPEXP TConfigParams : public utils::CLoadableOptions
			{
			public:
				/** Initializer for default values:
				  */
				TConfigParams();

				/** See utils::CLoadableOptions
				  */
				void  loadFromConfigFile(
					const mrpt::utils::CConfigFileBase  &source,
					const std::string &section);

				/** See utils::CLoadableOptions
				  */
				void  dumpToTextStream(CStream	&out) const;

				TAlignerMethod		methodSelection;		//!< The aligner method:

				/** The feature descriptor to use: 0=detector already has descriptor, 1= SIFT, 2=SURF, 4=Spin images, 8=Polar images, 16=log-polar images */
				mrpt::vision::TDescriptorType	feature_descriptor;

				/** All the parameters for the feature detector. */
				mrpt::vision::CFeatureExtraction::TOptions	feature_detector_options;

				/** RANSAC-step options:
				  * \sa CICP::robustRigidTransformation
				  */
				float	ransac_minSetSizeRatio;  //!< The ratio of landmarks that must be inliers to accepto an hypotheses (typ: 0.20)
				float	ransac_SOG_sigma_m;	//!< The square root of the uncertainty normalization variance var_m (see papers...)

				/** [amRobustMatch method only] RANSAC-step options:
				  * \sa CICP::robustRigidTransformation
				  */
				float	ransac_mahalanobisDistanceThreshold;

				double  ransac_chi2_quantile;	//!< [amModifiedRANSAC method only] The quantile used for chi-square thresholding (default=0.99)

				double	ransac_prob_good_inliers; //!< Probability of having a good inliers (def:0,9999), used for automatic number of iterations
				float	featsPerSquareMeter;	//!< Features extraction from grid map: How many features to extract
				float	threshold_max;		//!< Correspondences are considered if their distances are below this threshold (in the range [0,1]) (default=0.15).
				float	threshold_delta;	//!< Correspondences are considered if their distances to the best match are below this threshold (in the range [0,1]) (default=0.15).

				float   min_ICP_goodness;	//!< The minimum goodness (0-1) of the post-matching ICP to accept a hypothesis as good (default=0.25)
				double  max_ICP_mahadist;	//!< The maximum Mahalanobis distance between the initial and final poses in the ICP not to discard the hypothesis (default=10)
				double  maxKLd_for_merge;	//!< Maximum KL-divergence for merging modes of the SOG (default=0.9)

				bool	save_feat_coors;	//!< DEBUG - Dump all feature correspondences in a directory "grid_feats"
				bool	debug_show_corrs;	//!< DEBUG - Show graphs with the details of each feature correspondences
				bool	debug_save_map_pairs;	//!< DEBUG - Save the pair of maps with all the pairings.

			} options;

			/** The ICP algorithm return information.
			 */
			struct SLAM_IMPEXP TReturnInfo
			{
				/** Initialization
				  */
				TReturnInfo() :
					cbSize(sizeof(TReturnInfo)),
					goodness(0),
					noRobustEstimation()
				{
				}

				size_t		cbSize;	//!< Size of the structure, do not change, it's set automatically

				/** A goodness measure for the alignment, it is a [0,1] range indicator of percentage of correspondences.
				 */
				float			goodness;

				/** The "brute" estimation from using all the available correspondences, provided just for comparison purposes (it is not the robust estimation, available as the result of the Align method).
				  */
				CPose2D			noRobustEstimation;

				/** The different SOG densities at different steps of the algorithm:
				  *   - sog1 : Directly from the matching of features
				  *   - sog2 : Merged of sog1
				  *   - sog3 : sog2 refined with ICP
				  *
				  *   - The final sog is the merge of sog3.
				  *
				  */
				CPosePDFSOGPtr	sog1,sog2,sog3;

				/** The landmarks of each map (the indices of these landmarks correspond to those in "correspondences")  */
				CLandmarksMapPtr	landmarks_map1, landmarks_map2;

				/** All the found correspondences (not consistent) */
				mrpt::utils::TMatchingPairList	correspondences;

				struct TPairPlusDistance
				{
					TPairPlusDistance(size_t i1, size_t i2, float d) :
						idx_this(i1), idx_other(i2), dist(d)
					{ }
					size_t		idx_this,idx_other;
					float		dist;
				};

				std::vector<TPairPlusDistance>  correspondences_dists_maha;	//!< Mahalanobis distance for each potential correspondence

				std::vector<double>	icp_goodness_all_sog_modes;	//!< The ICP goodness of all potential SOG modes at the stage "sog2", thus before the removing of "bad" ICP matches.
			};

			/** The method for aligning a pair of 2D points map.
			 *   The meaning of some parameters are implementation dependant,
			 *    so look for derived classes for instructions.
			 *  The target is to find a PDF for the pose displacement between
			 *   maps, thus the pose of m2 relative to m1. This pose
			 *   is returned as a PDF rather than a single value.
			 *
			 *  NOTE: This method can be configurated with "options"
			 *
			 * \param m1			[IN] The first map (Must be a mrpt::slam::CMultiMetricMap class)
			 * \param m2			[IN] The second map (Must be a mrpt::slam::CMultiMetricMap class)
			 * \param initialEstimationPDF	[IN] (IGNORED IN THIS ALGORITHM!)
			 * \param runningTime	[OUT] A pointer to a container for obtaining the algorithm running time in seconds, or NULL if you don't need it.
			 * \param info			[OUT] A pointer to a CAlignerFromMotionDraws::TReturnInfo struct, or NULL if result information are not required.
			 *
			 * \note The returned PDF depends on the selected alignment method:
			 *		- "amRobustMatch" --> A "poses::CPosePDFSOG" object.
			 *		- "amCorrelation" --> A "poses::CPosePDFGrid" object.
			 *
			 * \return A smart pointer to the output estimated pose PDF.
			 * \sa CPointsMapAlignmentAlgorithm, options
			 */
			CPosePDFPtr AlignPDF(
					const CMetricMap		*m1,
					const CMetricMap		*m2,
					const CPosePDFGaussian	&initialEstimationPDF,
					float					*runningTime = NULL,

					void					*info = NULL );

			/** The virtual method for aligning a pair of metric maps, aligning the full 6D pose.
			 *   The meaning of some parameters are implementation dependant,
			 *    so look at the derived classes for more details.
			 *  The goal is to find a PDF for the pose displacement between
			 *   maps, that is, the pose of m2 relative to m1. This pose
			 *   is returned as a PDF rather than a single value.
			 *
			 *  \note This method can be configurated with a "options" structure in the implementation classes.
			 *
			 * \param m1			[IN] The first map (MUST BE A COccupancyGridMap2D  derived class)
			 * \param m2			[IN] The second map. (MUST BE A CPointsMap derived class) The pose of this map respect to m1 is to be estimated.
			 * \param initialEstimationPDF	[IN] An initial gross estimation for the displacement.
			 * \param runningTime	[OUT] A pointer to a container for obtaining the algorithm running time in seconds, or NULL if you don't need it.
			 * \param info			[OUT] See derived classes for details, or NULL if it isn't needed.
			 *
			 * \return A smart pointer to the output estimated pose PDF.
			 * \sa CICP
			 */
			CPose3DPDFPtr Align3DPDF(
					const CMetricMap		*m1,
					const CMetricMap		*m2,
					const CPose3DPDFGaussian	&initialEstimationPDF,
					float					*runningTime = NULL,
					void					*info = NULL )
			{
				THROW_EXCEPTION("Align3D method not applicable to gridmap-aligner");
			}

		};

	} // End of namespace

	// Specializations MUST occur at the same namespace:
	namespace utils
	{
		template <>
		struct TEnumTypeFiller<slam::CGridMapAligner::TAlignerMethod>
		{
			typedef slam::CGridMapAligner::TAlignerMethod enum_t;
			static void fill(bimap<enum_t,std::string>  &m_map)
			{
				m_map.insert(slam::CGridMapAligner::amRobustMatch,    "amRobustMatch");
				m_map.insert(slam::CGridMapAligner::amCorrelation,    "amCorrelation");
				m_map.insert(slam::CGridMapAligner::amModifiedRANSAC, "amModifiedRANSAC");
			}
		};
	} // End of namespace

} // End of namespace

#endif


text:
'''
Created on 20. jan. 2012

@author: jpaasen_adm
'''

import framework.mynumpy as np
import matrixDecomp as md

def solveBiCG(A, b, x0, tol, itr):

   ''' Solves the complex linear system Ax = b using the complex-biconjugate-gradient method

      Arguments:
      A   -- Coefficient matrix
      b   -- Right-side vector
      x0  -- Initial solution (default: 0-vector)
      tol -- Stop solver when error is less than tol (default: 0)
      itr -- Stop solver after itr iterations -- default
   '''

   # Check arguments
   m,n = len(A),len(A[0])
   if m != n:
      raise Exception('Coefficient matrix is not square')
   if len(b) != n:
      raise Exception('Dimension mismatch between A and b')

   x = x0 # make origin as starting point if no x is passed

   # Calculate initial residual r = b - Ax0 and search direction p
   r0 = b - np.dot(A, x)
   r = r0
   normr0 = np.euclidnorm(r0)

   if (np.euclidnorm(r) / normr0) <= tol: # break if error is less-than tolerance.
      # TODO: Should also test bir
      return x
   p = np.array(r)

   # init biresidual and bidirection
   bir = r.conjugate()
   bip = p.conjugate()

   numerator,denominator = 0,0
   alpha,betha = 0,0
   AH = np.conjugatetranspose(A) # Simplification: since A is Hermitian and semi-positive definite in our case, we can avoid this step...

   if itr <= 0 or itr > m:
      itr = m

   for i in range(itr):

      # Calculate common matrix-vector products
      Ap = np.dot(A, p)
      AHbip = np.dot(AH, bip)

      # Calculate step-length parameter
      numerator = np.vdot(bir, r)
      denominator = np.vdot(bip, Ap)
      alpha = numerator / denominator

      # Obtain new solution
      x = x + (alpha * p)

      # Calculate new residual and biresidual
#      r = r - (alpha * Ap)

      for i in range(m):
         r[i] = r[i] - alpha * Ap[i]   # Calculate new residual and biresidual

      if np.euclidnorm(r) / normr0 <= tol:
         # TODO: Should also test bir
         return x
      bir = bir - (alpha.conjugate() * AHbip)

      # Calculate the biconjugacy coefficient
      numerator = np.vdot(AHbip, r)
      denominator = np.vdot(bip, Ap)
      betha = -1.0 * (numerator / denominator)

      # Obtain new search and bi-search-direction
      p = r + (betha * p)
      bip = bir + (betha.conjugate() * bip)

   return x

def solveCholesky(A, b, n):
   ''' Solves the Hermitian positive definite system Ax = b using cholesky decomposition'''

   U = md.cholesky(A, n)

   UT = np.conjugatetranspose(U)

   y = forwardSolve(UT, b, n)
   x = backtrackSolve(U, y, n)

   return x

def solveCholeskyCpp(A, b, n):
   ''' Solves the Hermitian positive definite system Ax = b using cholesky decomposition'''

   U = md.cholesky(A, n)

   UT = np.conjugatetranspose(U)

   y = forwardSolve(UT, b, n)
   x = backtrackSolve(U, y, n)

def solveUHDU(A, b, n):
   ''' Solves the Hermitian positive definite system Ax = b using U'DU decomposition'''

   UD = md.uhdu(A, n);

   UH = np.conjugatetranspose(UD[0])

   y = forwardSolve(UH, b, n)
   z = diagonalSolve(UD[1], y, n)
   x = backtrackSolve(UD[0], z, n)

   return x

' Under follows methods for solving triangular and diagonal systems '

def forwardSolve(A, b, n):
   ''' Forward solve the lower triangular system Ax = b '''
   x = np.zeros(n, A.dtype)

   for i in range(n):

      x[i] = b[i]

      for k in range(i):
         x[i] -= A[i, k] * x[k]

      x[i] /= A[i, i]

   return x

def backtrackSolve(A, b, n):
   ''' Backtrack solve the upper triangular system Ax = b '''
   x = np.zeros(n, A.dtype)

   for i in reversed(range(n)):

      x[i] = b[i]

      for k in reversed(range(i+1, n)):
         x[i] -= A[i, k] * x[k]

      x[i] /= A[i, i]

   return x

def diagonalSolve(A, b, n):
   ''' Solve the diagonal system Ax = b, A is sparse, hence a vector '''
   x = np.zeros(n, A.dtype)

   for i in range(n):
      x[i] = b[i] / A[i]

   return x


text:
package com.twu.biblioteca;

public class Movie {

    private User user;
    private String name;
    private String year;
    private String director;
    private int movieRating;
    private Boolean isBorrowed;

    public Movie(String name, String year, String director, int movieRating) {
        this.name = name;
        this.year = year;
        this.director = director;
        this.movieRating = movieRating;
        this.isBorrowed = false;
    }

    public String getName() {
        return this.name;
    }

    public String getYear() {
        return this.year;
    }

    public String getDirector() {
        return this.director;
    }

    public int getMovieRating() {
        return this.movieRating;
    }

    public Boolean getIsBorrowed() {
        return this.isBorrowed;
    }

    public void setIsBorrowed(Boolean isBorrowed) {
        this.isBorrowed = isBorrowed;
    }

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getMovieInfo() {
        return " BookName: " + this.name + " Year: " + this.year +
               " Director: " + this.director + " MovieRating: "+ this.movieRating +'\n';
    }

    public String getMovieInfoWithBorrower() {
        return " BookName: " + this.name + " Year: " + this.year + " Director: " + this.director +
               " MovieRating: "+ this.movieRating + " Loaned To: " + this.user.getName() + '\n';
    }
}


text:
package org.jetbrains.plugins.scala.codeInsight.intention.types

import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.ScalaBundle
import org.jetbrains.plugins.scala.codeInsight.intention.IntentionUtil
import org.jetbrains.plugins.scala.lang.psi.TypeAdjuster
import org.jetbrains.plugins.scala.lang.psi.api.base.patterns.{ScBindingPattern, ScTypedPattern, ScWildcardPattern}
import org.jetbrains.plugins.scala.lang.psi.api.base.types.ScTypeElement
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.ScParameter
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScFunctionDefinition, ScPatternDefinition, ScVariableDefinition}
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory
import org.jetbrains.plugins.scala.lang.psi.types.{BaseTypes, ScType, ScTypeText}
import org.jetbrains.plugins.scala.util.IntentionAvailabilityChecker

/**
  * Author: Svyatoslav Ilinskiy
  * Date: 22.12.15.
  */
class MakeTypeMoreSpecificIntention extends PsiElementBaseIntentionAction {
  override def invoke(project: Project, editor: Editor, element: PsiElement): Unit = {
    ToggleTypeAnnotation.complete(new MakeTypeMoreSpecificStrategy(Option(editor)), element)
  }

  override def isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean = {
    if (element == null || !IntentionAvailabilityChecker.checkIntention(this, element)) false
    else {
      var isAvailable = false
      def text(s: String): Unit = {
        setText(s)
        isAvailable = true
      }
      val desc = new StrategyAdapter {
        override def removeFromVariable(variable: ScVariableDefinition): Unit = {
          for {
            declared <- variable.declaredType
            expr <- variable.expr
            tp <- expr.getType()
            if MakeTypeMoreSpecificStrategy.computeBaseTypes(declared, tp).nonEmpty
          } text(ScalaBundle.message("make.type.more.specific"))
        }

        override def removeFromValue(value: ScPatternDefinition): Unit = {
          for {
            declared <- value.declaredType
            expr <- value.expr
            tp <- expr.getType()
            if MakeTypeMoreSpecificStrategy.computeBaseTypes(declared, tp).nonEmpty
          } text(ScalaBundle.message("make.type.more.specific"))
        }

        override def removeFromFunction(function: ScFunctionDefinition): Unit = {
          for {
            declared <- function.returnType
            expr <- function.body
            tp <- expr.getType()
            if MakeTypeMoreSpecificStrategy.computeBaseTypes(declared, tp).nonEmpty
          } text(ScalaBundle.message("make.type.more.specific.fun"))
        }
      }

      ToggleTypeAnnotation.complete(desc, element)
      isAvailable
    }
  }

  override def getFamilyName: String = ScalaBundle.message("make.type.more.specific")
}

class MakeTypeMoreSpecificStrategy(editor: Option[Editor]) extends Strategy {
  import MakeTypeMoreSpecificStrategy._

  def doTemplate(te: ScTypeElement, declaredType: ScType, dynamicType: ScType, context: PsiElement, editor: Editor): Unit = {
    val types = computeBaseTypes(declaredType, dynamicType).sortWith((t1, t2) => t1.conforms(t2))
    if (types.size == 1) {
      val replaced = te.replace(ScalaPsiElementFactory.createTypeElementFromText(types.head.canonicalText, te.getContext, te))
      TypeAdjuster.markToAdjust(replaced)
    } else {
      val texts = types.map(ScTypeText)
      val expr = new ChooseTypeTextExpression(texts, ScTypeText(declaredType))
      IntentionUtil.startTemplate(te, context, expr, editor)
    }
  }

  override def removeFromFunction(function: ScFunctionDefinition): Unit = {
    for {
      edit <- editor
      te <- function.returnTypeElement
      body <- function.body
      tp <- body.getType()
      declared <- te.getType()
    } doTemplate(te, declared, tp, function.getParent, edit)
  }

  override def removeFromValue(value: ScPatternDefinition): Unit = {
    for {
      edit <- editor
      te <- value.typeElement
      body <- value.expr
      tp <- body.getType()
      declared <- te.getType()
    } doTemplate(te, declared, tp, value.getParent, edit)
  }

  override def removeFromVariable(variable: ScVariableDefinition): Unit = {
    for {
      edit <- editor
      te <- variable.typeElement
      body <- variable.expr
      tp <- body.getType()
      declared <- te.getType()
    } doTemplate(te, declared, tp, variable.getParent, edit)
  }

  override def addToPattern(pattern: ScBindingPattern): Unit = ()

  override def addToWildcardPattern(pattern: ScWildcardPattern): Unit = ()

  override def addToValue(value: ScPatternDefinition): Unit = ()

  override def addToFunction(function: ScFunctionDefinition): Unit = ()

  override def removeFromPattern(pattern: ScTypedPattern): Unit = ()

  override def addToVariable(variable: ScVariableDefinition): Unit = ()

  override def removeFromParameter(param: ScParameter): Unit = ()

  override def addToParameter(param: ScParameter): Unit = ()
}

object MakeTypeMoreSpecificStrategy {
  def computeBaseTypes(declaredType: ScType, dynamicType: ScType): Seq[ScType] = {
    val baseTypes = dynamicType +: BaseTypes.get(dynamicType)
    baseTypes.filter(t => t.conforms(declaredType) && !t.equiv(declaredType))
  }
}


text:
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyProduct("GitLab Extension for Visual Studio")]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("MaikeBing")]
[assembly: AssemblyCopyright("Copyright ? MaikeBing. 2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
namespace System
{
    internal static class AssemblyVersionInformation
    {
        internal const string Version = "1.0.0.0";
    }
}


text:
using System;

namespace SharpLib
{
    public static class Runtime
    {
        /// <summary>
        /// Проверка выполнения условия
        /// </summary>
        public static void Check(bool expr)
        {
            if (expr == false)
            {
                throw new Exception();
            }
        }

        public static void Check<T>(bool expr) where T : Exception, new()
        {
            if (expr == false)
            {
                throw new T();
            }
        }
    }
}


text:
#include <unistd.h>
#include <debug/DebugUtils.h>
#include <thread/Thread.h>
#include <thread/LockDebugger.h>
#include <thread/SpinLock.h>
#include <thread/Mutex.h>

using namespace oasys;

Mutex* lock1;
Mutex* lock2;
Mutex* lock3;
SpinLock* lock4;
SpinLock* lock5;

class MyThread : public Thread {
public:
    MyThread() : Thread("MyThread", CREATE_JOINABLE) {}

protected:
    void run() {
        for (int i=0; i<100000; ++i)
        {
            ASSERT(! Thread::lock_debugger()->check_class("m"));
            ASSERT(! Thread::lock_debugger()->check_class("s"));

            Thread::lock_debugger()->check();
            lock1->lock("test");
            lock2->lock("test");
            ASSERT(Thread::lock_debugger()->check_class("m"));
            ASSERT(! Thread::lock_debugger()->check_class("s"));

            LOCKED_BY_ME(lock1, lock2);
            lock5->lock("test");
            LOCKED_BY_ME(lock1, lock2, lock5);

            lock1->unlock();
            lock5->unlock();
            LOCKED_BY_ME(lock2);
            ASSERT(Thread::lock_debugger()->check_class("m"));
            ASSERT(! Thread::lock_debugger()->check_class("s"));
            lock2->unlock();
            ASSERT(! Thread::lock_debugger()->check_class("m"));
            ASSERT(! Thread::lock_debugger()->check_class("s"));
            LOCKED_BY_ME();
        }
    }
};

int
main()
{
    Log::init(LOG_DEBUG);

    MyThread t1, t2;

    lock1 = new Mutex("/test/lock1", Mutex::TYPE_RECURSIVE, true, "m");
    lock2 = new Mutex("/test/lock2", Mutex::TYPE_RECURSIVE, true, "m");
    lock3 = new Mutex("/test/lock3", Mutex::TYPE_RECURSIVE, true, "m");
    lock4 = new SpinLock("s");
    lock5 = new SpinLock("s");

    t1.start();
    t2.start();

    Thread::lock_debugger()->check();
    for (int i=0; i<100000; ++i)
    {
        Thread::lock_debugger()->check();
        lock2->lock("test");
        lock3->lock("test");
        LOCKED_BY_ME(lock2, lock3);
        lock4->lock("test");
        LOCKED_BY_ME(lock2, lock3, lock4);
        lock5->lock("test");
        LOCKED_BY_ME(lock2, lock3, lock4, lock5);

        ASSERT(Thread::lock_debugger()->check_class("m"));
        ASSERT(Thread::lock_debugger()->check_class("s"));

        lock2->unlock();
        lock5->unlock();
        Thread::lock_debugger()->check(lock3, lock4);
        lock4->unlock();
        Thread::lock_debugger()->check(lock3);
        ASSERT(Thread::lock_debugger()->check_class("m"));
        ASSERT(! Thread::lock_debugger()->check_class("s"));

        lock3->unlock();
        Thread::lock_debugger()->check();
        ASSERT(! Thread::lock_debugger()->check_class("m"));
        ASSERT(! Thread::lock_debugger()->check_class("s"));
    }

    t1.join();
    t2.join();
}


text:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script type="text/javascript" src="../lib/browser/test-matterjs.js"></script>
</body>
</html>


text:
package redis

import (
	"errors"
	"time"

	"fmt"

	config "aahframework.org/config.v0"
	log "aahframework.org/log.v0"
	"aahframework.org/security.v0/session"
	"github.com/garyburd/redigo/redis"
)

func init() {
	_ = session.AddStore("redis", &RedisStore{})
}

type RedisStore struct {
	Config    *Config
	pool      *redis.Pool
	Connected bool
}

func (r *RedisStore) Init(cfg *config.Config) error {
	r.Config = &Config{
		Network:       DefaultRedisNetwork,
		Addr:          DefaultRedisAddr,
		Password:      "",
		Database:      "",
		MaxIdle:       0,
		MaxActive:     0,
		IdleTimeout:   DefaultRedisIdleTimeout,
		Prefix:        "",
		MaxAgeSeconds: DefaultRedisMaxAgeSeconds,
	}

	r.Config.Network = cfg.StringDefault("security.session.store.redis.network", "tcp")
	r.Config.Addr = cfg.StringDefault("security.session.store.redis.addr", "127.0.0.1:6379")
	r.Config.Password = cfg.StringDefault("security.session.store.redis.password", "")
	r.Config.Database = cfg.StringDefault("security.session.store.redis.database", "")
	r.Config.Prefix = cfg.StringDefault("security.session.store.redis.prefix", "")

	r.Config.MaxIdle = cfg.IntDefault("security.session.store.redis.max_idle", 10)
	r.Config.MaxActive = cfg.IntDefault("security.session.store.redis.max_active", 30)

	r.connect()

	_, err := r.pingPong()

	if err != nil {
		return errors.New("Redis Connection error on Connect:" + err.Error())
	}
	return nil
}

func (r *RedisStore) Read(id string) string {

	c := r.pool.Get()
	defer c.Close()
	if err := c.Err(); err != nil {
		log.Errorf("session: redis store - read error: %v", err)
		return ""
	}

	redisVal, err := c.Do("GET", r.Config.Prefix+id)

	if err != nil {
		log.Errorf("session: redis store - read error: %v", err)
		return ""
	}
	if redisVal == nil {
		log.Errorf("session: redis store - Key '%s' doesn't", id)
		return ""
	}

	sVal, err := redis.String(redisVal, err)
	if err != nil {
		return ""
	}

	return sVal

}
func (r *RedisStore) Save(id, value string) (err error) {

	c := r.pool.Get()
	defer c.Close()
	if err = c.Err(); err != nil {
		return
	}
	_, err = c.Do("SETEX", r.Config.Prefix+id, r.Config.MaxAgeSeconds, value)

	return

}
func (r *RedisStore) Delete(id string) error {
	c := r.pool.Get()
	defer c.Close()

	if _, err := c.Do("DEL", r.Config.Prefix+id); err != nil {
		return err
	}
	return nil
}
func (r *RedisStore) IsExists(id string) bool {
	c := r.pool.Get()
	defer c.Close()

	if existed, err := redis.Int(c.Do("EXISTS", r.Config.Prefix+id)); err != nil || existed == 0 {
		return false
	}
	return true

}

func (r *RedisStore) Cleanup(m *session.Manager) {
	sessions, err := r.getAll("session")
	if err != nil {
		log.Error(err)
		return
	}
	cnt := 0
	for sid, sess := range sessions {

		if _, err := m.DecodeToSession(sess); err == session.ErrCookieTimestampIsExpired {
			if err := r.Delete(sid); err != nil {
				log.Error(err)
			} else {
				cnt++
			}
		}
	}

	log.Infof("%v expired session redis cleaned up", cnt)
}

func (r *RedisStore) getAll(key string) (map[string]string, error) {
	c := r.pool.Get()
	defer c.Close()
	if err := c.Err(); err != nil {
		return nil, err
	}

	reply, err := c.Do("HGETALL", r.Config.Prefix+key)

	if err != nil {
		return nil, err
	}
	if reply == nil {
		return nil, errors.New(fmt.Sprintf("Key '%s' doesn't found", key))
	}

	return redis.StringMap(reply, err)

}

func (r *RedisStore) pingPong() (bool, error) {
	c := r.pool.Get()
	defer c.Close()
	msg, err := c.Do("PING")
	if err != nil || msg == nil {
		return false, err
	}
	return (msg == "PONG"), nil
}

//************************redis connect****************
func (r *RedisStore) connect() {
	c := r.Config

	if c.IdleTimeout <= 0 {
		c.IdleTimeout = DefaultRedisIdleTimeout
	}

	if c.Network == "" {
		c.Network = DefaultRedisNetwork
	}

	if c.Addr == "" {
		c.Addr = DefaultRedisAddr
	}

	if c.MaxAgeSeconds <= 0 {
		c.MaxAgeSeconds = DefaultRedisMaxAgeSeconds
	}

	pool := &redis.Pool{IdleTimeout: DefaultRedisIdleTimeout, MaxIdle: c.MaxIdle, MaxActive: c.MaxActive}
	pool.TestOnBorrow = func(c redis.Conn, t time.Time) error {
		_, err := c.Do("PING")
		return err
	}

	if c.Database != "" {
		pool.Dial = func() (redis.Conn, error) {
			red, err := dial(c.Network, c.Addr, c.Password)
			if err != nil {
				return nil, err
			}
			if _, err = red.Do("SELECT", c.Database); err != nil {
				red.Close()
				return nil, err
			}
			return red, err
		}
	} else {
		pool.Dial = func() (redis.Conn, error) {
			return dial(c.Network, c.Addr, c.Password)
		}
	}
	r.Connected = true
	r.pool = pool

}
func dial(network string, addr string, pass string) (redis.Conn, error) {
	if network == "" {
		network = DefaultRedisNetwork
	}
	if addr == "" {
		addr = DefaultRedisAddr
	}
	log.Print(addr)
	c, err := redis.Dial(network, addr)
	log.Print("init")
	log.Print(err)
	if err != nil {
		return nil, err
	}
	if pass != "" {
		if _, err = c.Do("AUTH", pass); err != nil {
			c.Close()
			return nil, err
		}
	}
	return c, err
}


text:
__author__ = 'IRSEN'
# -*- coding: utf-8 -*-

from model.contact import Contact
import random
import string
import os.path
import jsonpickle
import getopt
import sys

try:
    opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
    getopt.usage()
    sys.exit(2)

n = 3
f = "data/contacts.json"

for o, a in opts:
    if o == "-n":
        n = int(a)
    elif o == "-f":
        f = a

def random_string(prefix, maxlen):
    symbols = string.ascii_letters + string.digits + " "*10
#   symbols = string.ascii_letters + string.digits + string.punctuation + " "*10
    return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])

def random_number(prefix, maxlen):
    numbers = string.digits + " "*5
#   numbers = string.digits + string.punctuation + " "*5
    return prefix + "".join([random.choice(numbers) for i in range(random.randrange(maxlen))])

testdata = [
    Contact(firstname=random_string("firstname", 7), lastname=random_string("lastname", 7),
            position=random_string("position", 5), company=random_string("company", 10),
            homephone=random_number("H", 9), mobilephone=random_number("M", 9), workphone=random_number("W", 9),
            secondaryphone=random_number("S", 9), address=random_string("address", 15),
            email=random_string("email", 7), email2=random_string("email2", 8),
            notes=random_string("notes", 15))
    for i in range(n)
]

file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)

with open(file, "w") as out:
    jsonpickle.set_encoder_options("json", indent=2)
    out.write(jsonpickle.encode(testdata))


text:
package org.apache.nifi.stateless.basics;

import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flow.VersionedPort;
import org.apache.nifi.flow.VersionedProcessor;
import org.apache.nifi.stateless.StatelessSystemIT;
import org.apache.nifi.stateless.VersionedFlowBuilder;
import org.apache.nifi.stateless.config.StatelessConfigurationException;
import org.apache.nifi.stateless.flow.DataflowTrigger;
import org.apache.nifi.stateless.flow.StatelessDataflow;
import org.apache.nifi.stateless.flow.TriggerResult;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class LoopingIT extends StatelessSystemIT {

    @Test
    public void testLooping() throws IOException, StatelessConfigurationException, InterruptedException {
        // Build the flow
        final VersionedFlowBuilder flowBuilder = new VersionedFlowBuilder();
        final VersionedPort outPort = flowBuilder.createOutputPort("Out");

        final VersionedProcessor generate = flowBuilder.createSimpleProcessor("GenerateFlowFile");
        final Map<String, String> generateProperties = new HashMap<>();
        generateProperties.put("Text", "abc\n123\nxyz\n321");
        generateProperties.put("Batch Size", "3");
        generate.setProperties(generateProperties);

        // Loop the FlowFile 10,000 times to be absolutely sure that we do not encounter any StackOverflowError's
        final String loopIterations = String.valueOf(10_000);
        final VersionedProcessor loop = flowBuilder.createSimpleProcessor("LoopFlowFile");
        loop.setProperties(Collections.singletonMap("Count", loopIterations));

        flowBuilder.createConnection(generate, loop, "success");
        flowBuilder.createConnection(loop, outPort, "finished");
        flowBuilder.createConnection(loop, loop, "loop");

        // Startup the dataflow
        final StatelessDataflow dataflow = loadDataflow(flowBuilder.getFlowSnapshot(), Collections.emptyList());

        // Enqueue data and trigger
        final DataflowTrigger trigger = dataflow.trigger();
        final TriggerResult result = trigger.getResult();
        assertTrue(result.isSuccessful());
        result.acknowledge();

        final List<FlowFile> flowFiles = result.getOutputFlowFiles("Out");
        assertEquals(3, flowFiles.size());

        for (final FlowFile flowFile : flowFiles) {
            assertEquals(loopIterations, flowFile.getAttribute("loop.count"));
        }
    }
}


text:
require 'spec_helper'

describe RSpec do
  let! :command do
    Class.new(SlackRubyBot::Commands::Base) do
      command 'raise'

      def self.call(_client, _data, match)
        raise ArgumentError, match[:command]
      end
    end
  end
  def app
    SlackRubyBot::App.new
  end
  it 'respond_with_error' do
    expect(message: "#{SlackRubyBot.config.user} raise").to respond_with_error(ArgumentError, 'raise')
  end
end


text:
bool GameTiledMap::init()
{
	if (!Node::init()){
		return false;
	}
	return true;
}

bool GameTiledMap::initMap(int level)
{
	switch (level)
	{
	case 1:
		m_map = TMXTiledMap::create("map/map1.tmx");
		break;
	case 2:
		m_map = TMXTiledMap::create("map/map1.tmx");
		break;
	case 3:
		m_map = TMXTiledMap::create("map/map1.tmx");
		break;
	default:
		break;
	}
	addChild(m_map);

	return true;
}

GameTiledMap* GameTiledMap::createGameMap(int level)
{
	auto gameMap = GameTiledMap::create();
	if (!gameMap->initMap(level)){
		return nullptr;
	}
	return gameMap;
}

TMXTiledMap* GameTiledMap::getTiledMap()
{
	return m_map;
}

float GameTiledMap::getMapWidth()
{
	return m_map->getMapSize().width * m_map->getTileSize().width;
}

float GameTiledMap::getMapHeight()
{
	return m_map->getMapSize().height * m_map->getTileSize().height;
}

//calculate the pos in tiledmap by pos in game
Vec2 GameTiledMap::calTilePosByPos(Vec2 pos)
{
	auto tiledSize = m_map->getTileSize();
	auto mapSize = m_map->getMapSize();
	int x = pos.x / tiledSize.width;
	int y = mapSize.height - pos.y / tiledSize.height - 1;
	return Vec2(x,y);
}

//detect the pos if is collidable
bool GameTiledMap::isCollidable(Vec2 pos)
{
	auto layer = m_map->getLayer("barrier");
	auto tilePos = calTilePosByPos(pos);
	auto tiledGid = layer->getTileGIDAt(tilePos);

	//not zero means the grid exist
	if (tiledGid != 0){
		auto properties = m_map->getPropertiesForGID(tiledGid);
		auto prop = properties.asValueMap().at("Collidable");//get collidable property value
		if (prop.asString().compare("true") == 0){
			return true;
		}
	}
	return false;
}


text:
module Frill
  class CyclicDependency < RuntimeError; end

  def self.included base
    self.dependency_graph.add base
    base.extend ClassMethods
  end

  def self.decorators
    @decorators ||= dependency_graph.to_a
    @decorators.dup
  end

  def self.reset!
    @decorators = nil
    @dependency_graph = nil
  end

  def self.decorate object, context, options={}
    frills = decorators

    if subset = options[:with]
      frills.select! {|d| subset.include? d}
    end

    frills.each do |f|
      object.extend f if f.frill? object, context
    end

    object
  end

  def self.dependency_graph
    @dependency_graph ||= DependencyGraph.new
  end

  module ClassMethods
    def before decorator
      Frill.dependency_graph.move_before self, decorator
    end

    def after decorator
      Frill.dependency_graph.move_before decorator, self
    end
  end

  class DependencyGraph
    def initialize
      @nodes = {}
    end

    def add label
      nodes[label] ||= Node.new label
    end

    def move_before label1, label2
      node1 = add label1
      node2 = add label2

      node1.move_before node2

      CycleDetecter.detect! nodes
    end

    def [](label)
      nodes[label]
    end

    def empty?
      nodes.empty?
    end

    def include? label
      nodes[label]
    end

    def index label
      to_a.index label
    end

    def to_a
      array = []

      nodes.values.each do |node|
        array += construct_array(node) unless array.include? node.label
      end

      array
    end

    private
    attr_reader :nodes

    def construct_array node
      array = []
      current_node = node.first

      while current_node
        array << current_node.label
        current_node = current_node.next
      end

      array
    end

    class CycleDetecter
      def self.detect! nodes
        new(nodes).detect!
      end

      def initialize nodes
        @nodes = nodes
        @visited = {}
      end

      def detect!
        nodes.values.each do |node|
          fan_out node unless visited[node.label]
        end
      end

      private
      attr_reader :nodes, :visited

      def fan_out node
        visited[node.label] = true

        fan :next, node
        fan :previous, node
      end

      def fan direction, start_node
        current_node = start_node.send direction

        while current_node
          raise Frill::CyclicDependency if visited[current_node.label]
          visited[current_node.label] = true
          current_node = current_node.send direction
        end
      end
    end

    class Node
      attr_accessor :next, :previous
      attr_reader :label

      def initialize(label)
        @label  = label
        @next = nil
        @previous  = nil
      end

      def move_before node
        next_node = node.first
        previous_node = self.last

        previous_node.next = next_node
        next_node.previous = previous_node
      end

      def first
        first_node = self
        first_node = first_node.previous while first_node.previous
        first_node
      end

      def last
        last_node = self
        last_node = last_node.next while last_node.next
        last_node
      end
    end
  end
end


text:
namespace GraphExec
{
    public interface IProviderInfo
    {
    }
}


text:
package com.incapture.rapgen.annotations;

public class SearchableAnnotation {

}


text:
<?php

/* CmarMeetingBundle:GroupAdmin:new.html.twig */
class __TwigTemplate_c7d881ed943e2a16d143a8896d090d4c extends Twig_Template
{
    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
Group creation

<form action=\"";
        // line 3
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("group_create"), "html", null, true);
        echo "\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderEnctype($this->getContext($context, "form"));
        echo ">
    ";
        // line 4
        echo $this->env->getExtension('form')->renderWidget($this->getContext($context, "form"));
        echo "

        <button type=\"submit\">Create</button>

</form>

        env, $this->env->getExtension('routing')->getPath("group"), "html", null, true);
        echo "\">
            Back to the list

";
    }

    public function getTemplateName()
    {
        return "CmarMeetingBundle:GroupAdmin:new.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
# Haxisms

A library of haxe code I find useful. Put online as an app because I don't know how to handle personal libraries with `haxelib`.

See `me.mbrezu.test.Main.hx` in `Source` for examples of use.

BSD 2-clause license.


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model ubud\dashboard\models\Warga_statusSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'ID') ?>

    <?= $form->field($model, 'RUMAH_STATUS') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
var map = L.map('mapid').setView([39.9526, -75.1652], 15);

//add openstreetmap tiles
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

var allStops = L.geoJSON().addTo(map);

allStops.addData();


text:
/**
 * Spring Security configuration.
 */
package net.tinyset.uaa.security;


text:
import org.junit.Test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public class JudgeTest {

    public JudgeTest() {
    }

    @Test
    public void testJudge() {
        Judge judge = JudgeFactory.create();

        assertThat(judge.judge(Hand.ROCK, Hand.ROCK), is(Result.DRAW));
        assertThat(judge.judge(Hand.ROCK, Hand.PAPER), is(Result.LOSE));
        assertThat(judge.judge(Hand.ROCK, Hand.SCISSORS), is(Result.WIN));

        assertThat(judge.judge(Hand.PAPER, Hand.ROCK), is(Result.WIN));
        assertThat(judge.judge(Hand.PAPER, Hand.PAPER), is(Result.DRAW));
        assertThat(judge.judge(Hand.PAPER, Hand.SCISSORS), is(Result.LOSE));

        assertThat(judge.judge(Hand.SCISSORS, Hand.ROCK), is(Result.LOSE));
        assertThat(judge.judge(Hand.SCISSORS, Hand.PAPER), is(Result.WIN));
        assertThat(judge.judge(Hand.SCISSORS, Hand.SCISSORS), is(Result.DRAW));
    }
}


text:
@interface ChecklistItem : NSObject<NSCoding>

@property(nonatomic, copy) NSString* text;
@property(nonatomic, assign) BOOL checked;

@property(nonatomic, copy) NSDate* dueDate;
@property(nonatomic, assign) BOOL shouldRemind;
@property(nonatomic, assign) NSInteger itemId;

- (void)toggleChecked;

- (void)scheduleNotification;
- (void)cancelNotification;

- (UILocalNotification*)notificationForThisItem;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
  targetNamespace="Examples">

  <process id="asyncService">

    <startEvent id="theStart" />
    <sequenceFlow id="flow1" sourceRef="theStart" targetRef="service" />

    <serviceTask id="service" camunda:class="org.camunda.bpm.engine.test.bpmn.async.AsyncService" camunda:async="true">
		<extensionElements>
			<camunda:executionListener event="start" class="org.camunda.bpm.engine.test.bpmn.async.AsyncListener" />
		</extensionElements>
	</serviceTask>

    <sequenceFlow id="flow2" sourceRef="service" targetRef="theEnd" />

    <endEvent id="theEnd" />

  </process>

</definitions>


text:
Snapshot
========

Before we can create a snapshot we must register a repository where snapshots will be stored, specifying the type (eg 'fs' for filesystem) and optionally some settings.
We should specify at least the location of the repository. Full settings can be found [here](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-snapshots.html).

This example creates a repostory called "_snapshot" located at "/mount/backup"

```scala
client.execute {
  repository create "_snapshot" `type` "fs" settings Map("location" -> "/mount/backup")
}
```

At some moment in time we can request a snapshot by specifying a name for the snapshot and the repository to save the snapshot to.
In this example waitForCompletion is set which will not complete the future until the the snapshot is completed.
If this is set to false (the default), the future will complete as soon as the request has been received.

```scala
client.execute {
  snapshot create "snap1" in "_snapshot" waitForCompletion true
}
```

Next we can get a specific snapshot's info with:

```scala
client.execute {
  get snapshot "snap1" from "_snapshot"
}
```

Next we can get ALL snapshots information in the repository with:

```scala
client.execute {
  get snapshot Seq() from "_snapshot"
}
```

Later on we can restore the snapshot with:

```scala
client.execute {
  snapshot restore "snap1" from "_snapshot"
}
```

Snapshots can be deleted thus:

```scala
client.execute {
  snapshot delete "snap1" in "_snapshot"
}
```


text:
<?php namespace Illuminate\Auth;

class GenericUser implements UserInterface {

	/**
	 * All of the user's attributes.
	 *
	 * @var array
	 */
	protected $attributes;

	/**
	 * Create a new generic User object.
	 *
	 * @param  array  $attributes
	 * @return void
	 */
	public function __construct(array $attributes)
	{
		$this->attributes = $attributes;
	}

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->attributes['id'];
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->attributes['password'];
	}

	/**
	 * Dynamically access the user's attributes.
	 *
	 * @param  string  $key
	 * @return mixed
	 */
	public function __get($key)
	{
		return $this->attributes[$key];
	}

	/**
	 * Dynamically set an attribute on the user.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return void
	 */
	public function __set($key, $value)
	{
		$this->attributes[$key] = $value;
	}

	/**
	 * Dynamically check if a value is set on the user.
	 *
	 * @return bool
	 */
	public function __isset($key)
	{
		return isset($this->attributes[$key]);
	}

	/**
	 * Dynamically unset a value on the user.
	 *
	 * @return bool
	 */
	public function __unset($key)
	{
		unset($this->attributes[$key]);
	}

}


text:
package net.sf.jasperreports.engine.util;

import net.sf.jasperreports.engine.JRPrintHyperlink;

/**
 * @author Narcis Marcu (nmarcu@users.sourceforge.net)
 * @version $Id: HyperlinkData.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class HyperlinkData {

	private String id;
	private String href;
	private String selector;
	private JRPrintHyperlink hyperlink;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getHref() {
		return href;
	}

	public void setHref(String href) {
		this.href = href;
	}

	public String getSelector() {
		return selector;
	}

	public void setSelector(String selector) {
		this.selector = selector;
	}

	public JRPrintHyperlink getHyperlink() {
		return hyperlink;
	}

	public void setHyperlink(JRPrintHyperlink hyperlink) {
		this.hyperlink = hyperlink;
	}

}


text:
from __future__ import unicode_literals

from captcha.fields import CaptchaField
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError

# Login form
class LoginForm(forms.Form):
    username = forms.CharField(label=u"Username")
    password = forms.CharField(label=u"Password", widget=forms.PasswordInput)
    captcha = CaptchaField(label=u"Fill this captcha to login")

    def clean(self):
        cleaned_data = super(LoginForm, self).clean()
        user = authenticate(username=cleaned_data.get("username"), password=cleaned_data.get("password"))

        if not user or not user.is_active:
            raise ValidationError(u"Your authentication data is invalid. Please check your username and password")

        cleaned_data["user"] = user
        return cleaned_data


text:
import { fromJS } from 'immutable'

import * as C from '_/constants'
import { actionReducer } from './utils'
import { locale } from '_/intl'
import AppConfiguration from '_/config'
import type { UserOptionsType } from '_/ovirtapi/types'
import type { LoadUserOptionsActionType } from '_/actions/types'

const defaultOptions: UserOptionsType = {
  localOptions: {
    showNotifications: true,
    notificationSnoozeDuration: AppConfiguration.notificationSnoozeDurationInMinutes,
    tableView: false,
  },
  remoteOptions: {
    autoconnect: {
      id: undefined,
      content: '',
    },
    locale: {
      id: undefined,
      content: locale,
    },
    persistLocale: {
      id: undefined,
      content: AppConfiguration.persistLocale,
    },
    refreshInterval: {
      id: undefined,
      content: AppConfiguration.schedulerFixedDelayInSeconds,
    },
    fullScreenVnc: {
      id: undefined,
      content: false,
    },
    fullScreenNoVnc: {
      id: undefined,
      content: false,
    },
    ctrlAltEndVnc: {
      id: undefined,
      content: false,
    },
    fullScreenSpice: {
      id: undefined,
      content: false,
    },
    ctrlAltEndSpice: {
      id: undefined,
      content: false,
    },
    smartcardSpice: {
      id: undefined,
      content: AppConfiguration.smartcardSpice,
    },
    viewForVirtualMachines: {
      id: undefined,
      content: 'card',
    },
  },
  ssh: undefined,
  lastTransactions: {},
  consoleOptions: {},
}

const initialState: any = fromJS({ ...defaultOptions })

const options: any = actionReducer(initialState, {
  [C.SET_CONSOLE_OPTIONS] (clientState: any, { payload: { vmId, options } }: any): any {
    return clientState.setIn(['consoleOptions', vmId], options)
  },
  [C.LOAD_USER_OPTIONS]: (clientState: any, action: LoadUserOptionsActionType) => {
    const serverState = fromJS(action.payload.userOptions || {})

    const mergedRemote = clientState.get('remoteOptions').mergeWith((client, server, key) => {
      return server === undefined ? client : server
    }, serverState)

    return clientState.setIn(['remoteOptions'], mergedRemote)
  },
  [C.SET_OPTION] (state: any, { payload: { key, value } }: any): any {
    return state.setIn(key, fromJS(value))
  },
  [C.SET_SSH_KEY] (state: any, { payload: { key, id } }: any): any {
    return state.setIn(['ssh'], fromJS({ key: key || '', id }))
  },
  [C.DELETE_USER_OPTION] (state: any, { payload: { optionId } }: any): any {
    // applies only to remote options (local have no optionId)
    const [name] = state.get('remoteOptions')
      .findEntry((value, key) => value && value.get?.('id') === optionId) || []

    if (!name) {
      return state
    }

    // overwrite with default state
    return state.setIn(['remoteOptions', name], fromJS(defaultOptions.remoteOptions[name]))
  },
})

export default options
export {
  initialState,
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace Microsoft.Xna.Framework
{
    static public class MetroHelper
    {
        static public bool AppDataFileExists(string fileName)
        {
            var result = Task.Run( async () => {

                try
                {
                    var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileName);
                    return file == null ? false : true;
                }
                catch (FileNotFoundException)
                {
                    return false;
                }
            }).Result;

            return result;
        }
    }
}


text:
 #!/bin/bash
"""
Created on Mon Feb 14, 2011

@author:Isabel Restrepo

A script that encapsulates all steps needed to learn and classify based on corners features
"""

START=$(date +%s)

if [ $1 = "-r" ] ; then
  LEMS_PYTHONPATH=/Projects/lemsvxl/bin/Release/lib
  VXL_PYTHONPATH=/Projects/vxl/bin/Release/lib
else
  if [ $1 = "-d" ] ; then
       LEMS_PYTHONPATH=/Projects/lemsvxl/bin/Debug/lib
       VXL_PYTHONPATH=/Projects/vxl/bin/Debug/lib
  else
      echo "Need a flag, either -d or -r";
  fi
fi

#steps to run:
#-------------

#init all steps to false
compute_corner_measure=false;
compute_beaudet_measure=false;
threshold_corner_measure=false;
init_k_means=false;
run_k_means=false;
init_categories_info=false;   #inits xml and category_scene cells
learn_categories=false;
classify=false;

#----Set to true what you want to run---------
#compute_corner_measure=true;
#compute_beaudet_measure=true;
threshold_corner_measure=true;
init_k_means=true;  #Make sure the bof_info.xml is accurate
run_k_means=true;
learn_categories=true;  #Make sure the bof_categories_info.xml is accurate
classify=true;

################################################################################
# Set main directories - all other dirs are relative to this
main_dir="/Users/isa/Experiments/BOF/helicopter_providence";
################################################################################

################################################################################
# Compute harris measure and filter top % responses
################################################################################

taylor_dir=$main_dir"/taylor/global_taylor";
#param_dir=$main_dir"/corners/k_3";
param_dir=$main_dir"/beaudet_corners";
corners_dir=$param_dir"/global_corners";

if $compute_corner_measure; then

   export PYTHONPATH=$VXL_PYTHONPATH;
   echo "PYTHONPATH=" $PYTHONPATH

   num_cores=4;
   python /Projects/voxels-at-lems/scripts/bvpl/bvpl_octree/corners/global_corners/compute_harris_measure.py --taylor_dir $taylor_dir --corners_dir $corners_dir --num_cores $num_cores
   num_cores=8;
   python /Projects/voxels-at-lems/scripts/bvpl/bvpl_octree/corners/global_corners/explore_harris_measure_scenes.py --taylor_dir $taylor_dir --corners_dir $corners_dir --num_cores $num_cores
fi

if $compute_beaudet_measure; then

   export PYTHONPATH=$VXL_PYTHONPATH;
   echo "PYTHONPATH=" $PYTHONPATH

   num_cores=4;
   python /Projects/voxels-at-lems/scripts/bvpl/bvpl_octree/corners/global_corners/compute_beaudet_measure.py --taylor_dir $taylor_dir --corners_dir $corners_dir --num_cores $num_cores
   num_cores=8;
   python /Projects/voxels-at-lems/scripts/bvpl/bvpl_octree/corners/global_corners/explore_harris_measure_scenes.py --taylor_dir $taylor_dir --corners_dir $corners_dir --num_cores $num_cores
fi

if $threshold_corner_measure; then

   export PYTHONPATH=$VXL_PYTHONPATH;
   echo "PYTHONPATH=" $PYTHONPATH

   num_cores=8;
   python /Projects/voxels-at-lems/scripts/bvpl/bvpl_octree/corners/global_corners/threshold_corners.py --taylor_dir $taylor_dir --corners_dir $corners_dir --num_cores $num_cores
fi

export PYTHONPATH=$LEMS_PYTHONPATH;
echo "PYTHONPATH=" $PYTHONPATH

for num_thresh in 50
do

    bof_dir=$param_dir"/bof/thresh_"$num_thresh;

    for num_means in 20
    do
      init_k_means_dir=$bof_dir"/init_k_means_"$num_means
      k_means_dir=$bof_dir"/k_means_"$num_means
      fraction_subsamples=0.01;
      J=10;  #number of subsamples
      max_it=500; #max number of iteration for k-means

      ################################################################################
      # Learn corners codebook
      ################################################################################

      #Init K-means
      if  $init_k_means; then

          T=$(date +%s)
          python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_codebook/refined_init_k_means/rnd_sample_init_k_means.py --bof_dir $bof_dir --init_k_means_dir $init_k_means_dir --num_means $num_means
          DIFF=$(( $(date +%s) - $T ))
          echo "k_means_on_rnd_subsamples.py took $DIFF seconds"

          num_cores=8;
          T=$(date +%s)
          python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_codebook/refined_init_k_means/k_means_on_rnd_subsamples.py --bof_dir $bof_dir --init_k_means_dir $init_k_means_dir --fraction_subsamples $fraction_subsamples --max_it $max_it --num_subsamples $J --num_cores $num_cores
          DIFF=$(( $(date +%s) - $T ))
          echo "k_means_on_rnd_subsamples.py took $DIFF seconds"

          T=$(date +%s)
          python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_codebook/refined_init_k_means/k_means_on_CM_means.py --init_k_means_dir $init_k_means_dir --num_cores $num_cores --max_it $max_it
          DIFF=$(( $(date +%s) - $T ))
          echo "k_means_on_CM_means.py took $DIFF seconds"

          T=$(date +%s)
          python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_codebook/refined_init_k_means/choose_min_distortion_FM.py --init_k_means_dir $init_k_means_dir --k_means_dir $k_means_dir
          DIFF=$(( $(date +%s) - $T ))
          echo "choose_min_distortion_FM.py took $DIFF seconds"
      fi

      purge

      #K-means
      if $run_k_means; then
         num_cores=8;
         T=$(date +%s)
         python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_codebook/k_means/k_means_train.py --bof_dir $bof_dir --k_means_dir $k_means_dir --max_it $max_it --num_cores $num_cores
         DIFF=$(( $(date +%s) - $T ))
         echo "k_means_train.py took $DIFF seconds"

         num_cores=8;
         python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_codebook/k_means/k_means_on_CM_means.py --k_means_dir $k_means_dir --num_cores $num_cores --max_it $max_it
         python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_codebook/k_means/choose_min_distortion_FM.py --k_means_dir $k_means_dir

      fi

      purge

    ################################################################################
    # Learn distribution of corners categories
    ################################################################################
      class_histograms_dir=$bof_dir"/class_histograms_"$num_means

      if $learn_categories; then
        num_cores=8;
        T=$(date +%s)
        python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_categories/learn_categories.py --bof_dir $bof_dir --k_means_dir $k_means_dir --class_histograms_dir $class_histograms_dir --num_cores $num_cores
        DIFF=$(( $(date +%s) - $T ))
        echo "learn_categories.py took $DIFF seconds"
        python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_categories/combine_quatization.py --bof_dir $bof_dir --k_means_dir $k_means_dir --class_histograms_dir $class_histograms_dir
        python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/learn_categories/plot_category_histograms.py --bof_dir $bof_dir --class_histograms_dir $class_histograms_dir
        #python /Projects/voxels-at-lems/scripts/dbrec3d/bof/corners/learn_categories/save_category_scenes_raw.py --bof_dir $bof_dir --num_cores $num_cores
      fi

      purge

    ################################################################################
    #Classify corners
    ################################################################################

      if $classify; then
        num_cores=8;
        ncategories=5;
        classification_dir=$bof_dir"/classification_"$num_means
        python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/classify/classify.py --bof_dir $bof_dir --k_means_dir $k_means_dir --class_histograms_dir $class_histograms_dir --classification_dir $classification_dir --num_cores $num_cores --ncategories $ncategories
        python /Projects/voxels-at-lems/scripts/dbrec3d/bof/taylor/classify/display_classification_results.py --classification_dir $classification_dir --ncategories $ncategories
      fi

      purge

    done #num_means

done #num_thresh

END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Shell script took $DIFF seconds"


text:
$(document).ready(function(){
   // Activate the side menu
		$(".button-collapse").sideNav();
  });

$(document).ready(function(){
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('.modal-trigger').leanModal();
  });


text:
<!DOCTYPE html>

  	<meta charset="utf-8">
  	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  	<title>Class OptionDependentConfigBase
   | Rezolver IOC </title>
  	<meta name="viewport" content="width=device-width">
  	<meta name="title" content="Class OptionDependentConfigBase
   | Rezolver IOC ">
  	<meta name="generator" content="docfx 2.40.1.0">
  	<meta name="description" content="Rezolver is the portable open-source IOC container framework for .Net - built from the ground up for .Net Core, Asp.Net Core, and also optimised for the 'full .Net' :)">
  	<link rel="shortcut icon" href="../favicon.ico">
  	<link rel="stylesheet" href="../styles/docfx.vendor.css">
  	<link rel="stylesheet" href="../styles/docfx.css">
  	<link rel="stylesheet" href="../styles/main.css">
  	<meta property="docfx:navrel" content="../toc.html">
  	<meta property="docfx:tocrel" content="toc.html">

  	<meta property="docfx:rel" content="../">

  		<link rel="apple-touch-icon" sizes="57x57" href="../../apple-touch-icon-57x57.png">
  		<link rel="apple-touch-icon" sizes="60x60" href="../../apple-touch-icon-60x60.png">
  		<link rel="apple-touch-icon" sizes="72x72" href="../../apple-touch-icon-72x72.png">
  		<link rel="apple-touch-icon" sizes="76x76" href="../../apple-touch-icon-76x76.png">
  		<link rel="apple-touch-icon" sizes="114x114" href="../../apple-touch-icon-114x114.png">
  		<link rel="apple-touch-icon" sizes="120x120" href="../../apple-touch-icon-120x120.png">
  		<link rel="apple-touch-icon" sizes="144x144" href="../../apple-touch-icon-144x144.png">
  		<link rel="apple-touch-icon" sizes="152x152" href="../../apple-touch-icon-152x152.png">
  		<link rel="apple-touch-icon" sizes="180x180" href="../../apple-touch-icon-180x180.png">
  		<link rel="icon" type="image/png" href="../../favicon-32x32.png" sizes="32x32">
  		<link rel="icon" type="image/png" href="../../android-chrome-192x192.png" sizes="192x192">
  		<link rel="icon" type="image/png" href="../../favicon-96x96.png" sizes="96x96">
  		<link rel="icon" type="image/png" href="../../favicon-16x16.png" sizes="16x16">
  		<link rel="manifest" href="../../manifest.json">
  		<link rel="mask-icon" href="../../safari-pinned-tab.svg" color="#5bbad5">
  		<meta name="msapplication-TileColor" content="#da532c">
  		<meta name="msapplication-TileImage" content="../../mstile-144x144.png">
  		<meta name="theme-color" content="#ffffff">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

        		<form class="navbar-form navbar-right" role="search" id="search">

        			<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

        		</form>

          Show / Hide Table of Contents

Class OptionDependentConfigBase

Abstract base class for ITargetContainerConfig implementations which are dependent upon
one or more configuration objects having been applied before being applied themselves.

Inheritance

Object

OptionDependentConfigBase

InjectArrays

InjectAutoFuncs

InjectAutoLazies

OptionDependentConfig<TOption>

Implements

ITargetContainerConfig

IDependant

Inherited Members

      Object.Equals(Object)

      Object.Equals(Object, Object)

      Object.GetHashCode()

      Object.GetType()

      Object.MemberwiseClone()

      Object.ReferenceEquals(Object, Object)

      Object.ToString()

Namespace: Rezolver.Configuration

Assembly: Rezolver.dll

Syntax

public abstract class OptionDependentConfigBase : ITargetContainerConfig, IDependant

Remarks

Implement this type directly if your config object has dependencies on multiple config types/objects.

Your implementation of GetDependenciesBase() should return metadata which describes those
dependencies.  The easiest way to create these is through one of:

CreateOptionDependency<TOption>(Boolean)

CreateTypeDependency<TDependency>(IDependant, Boolean)

CreateObjectDependency<TDependency>(IDependant, TDependency, Boolean)

Properties

    |
    Improve this Doc

    View Source

Dependencies

Declaration

public IEnumerable<DependencyMetadata> Dependencies { get; }

Property Value

        Type
        Description

        IEnumerable<DependencyMetadata>

Methods

    |
    Improve this Doc

    View Source

Configure(IRootTargetContainer)

Declaration

public abstract void Configure(IRootTargetContainer targets)

Parameters

        Type
        Name
        Description

        IRootTargetContainer
        targets

    |
    Improve this Doc

    View Source

CreateOptionDependency<TOption>(Boolean)

Use this to create a Rezolver.Sdk.TypeDependency on an option of type TOption
being set with the Configure<TOption> ITargetContainerConfig configuration.

This enables your config to take a dependency on an option being set before being applied, thus enabling
it to take decisions based on that option value.

Declaration

protected DependencyMetadata CreateOptionDependency<TOption>(bool required = true)

    where TOption : class

Parameters

        Type
        Name
        Description

        Boolean
        required

Returns

        Type
        Description

        DependencyMetadata

Type Parameters

        Name
        Description

        TOption

    |
    Improve this Doc

    View Source

GetDependenciesBase()

Declaration

protected abstract IEnumerable<DependencyMetadata> GetDependenciesBase()

Returns

        Type
        Description

        IEnumerable<DependencyMetadata>

Implements

      ITargetContainerConfig

      IDependant

Extension Methods

      DependantExtensions.GetDependencies<T, TDependency>(T, IEnumerable<TDependency>)

      DependantExtensions.CreateTypeDependency<TDependency>(IDependant, Boolean)

      DependantExtensions.CreateObjectDependency<TDependency>(IDependant, TDependency, Boolean)

                    Improve this Doc

                    View Source

              Back to top

            Copyright ©2014 onwards Zolution Software Ltd
Generated by DocFX, with the Rezolver theme