text:
package dbseer.comp.clustering;

import com.esotericsoftware.minlog.Log;
import dbseer.comp.data.Transaction;
import dbseer.gui.DBSeerGUI;
import dbseer.gui.user.DBSeerDataSet;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by dyoon on 9/29/15.
 */
public class IncrementalDBSCAN
{
	private int clusterId;
	private int outlierId;
	private int initPts;
	private int minPts;
	private double epsilon;
	private volatile boolean initialized;
	private volatile boolean initializing;

	private Collection<Cluster> allClusters = new ArrayList<Cluster>();
	private Collection<Cluster> clusters = new ArrayList<Cluster>();
	private Collection<Cluster> outliers = new ArrayList<Cluster>();

	private long maxEndTime;

	public IncrementalDBSCAN(int minPts, double epsilon, int initPts)
	{
		this.clusterId = 0;
		this.outlierId = -1;
		this.initPts = initPts;
		this.minPts = minPts;
		this.epsilon = epsilon;
		this.initialized = false;
		this.initializing = false;
		this.maxEndTime = -1;
	}

	public synchronized void initialDBSCAN(Collection<Transaction> transactions)
	{
//		Log.set(Log.LEVEL_INFO);

		if (initialized)
		{
			System.err.println("Incremental DBSCAN has already been initialized.");
			return;
		}

		this.initializing = true;

//		Log.info("Initial DBSCAN Started with # of transactions = " + transactions.size());

		Collection<Transaction> actualTransactions = new ArrayList<Transaction>();
		for (Transaction t : transactions)
		{
			if (!t.isNoRowsReadWritten() && t.getEntireStatement() != null)
			{
				actualTransactions.add(t);
			}
		}

		for (Transaction t : actualTransactions)
		{
			if (t.getClassification() != Transaction.CLASSIFIED)
			{
				t.setClassification(Transaction.CLASSIFIED);
				ArrayList<Transaction> neighbors = getNeighbors(actualTransactions, t);

				if (neighbors.size() >= this.minPts || neighbors.size() > actualTransactions.size() - 1)
				{
					Cluster c = new Cluster(clusterId++);
					expandCluster(c, actualTransactions, neighbors);
					c.insert(t);
					clusters.add(c);
					allClusters.add(c);
				}
				else
				{
					t.setClassification(Transaction.UNCLASSIFIED);
				}
			}
			if (t.getEndTime() > this.maxEndTime)
			{
				this.maxEndTime = t.getEndTime();
			}
		}
		// reset live dataset.
		DBSeerDataSet dataset = DBSeerGUI.liveDataset;
		dataset.clearTransactionTypes();
		int count = 0;

		for (Cluster c : allClusters)
		{
			dataset.addTransactionType("Type " + (++count));
		}

		if (clusters.size() > 0)
		{
			initialized = true;
//			Log.info("DBSCAN iniitialized with total cluster size = " + clusters.size());
		}
		this.initializing = false;
	}

	public synchronized Collection<Cluster> getCurrentClusters()
	{
		ArrayList<Cluster> currentClusters = new ArrayList<Cluster>();
		for (Cluster c : clusters)
		{
			currentClusters.add(c.copy());
		}
		return currentClusters;
	}

	public synchronized Collection<Cluster> getAllClusters()
	{
		ArrayList<Cluster> clusters = new ArrayList<Cluster>();
		for (Cluster c : allClusters)
		{
			clusters.add(c.copy());
		}
		return clusters;
	}

	public synchronized String[] getTransactionSamples(int index)
	{
		ArrayList<Cluster> clusters = (ArrayList<Cluster>)allClusters;
		if (clusters.size() <= index)
		{
			return null;
		}
		return clusters.get(index).getTransactionSamples();
	}

	public synchronized void train(Transaction t)
	{
		if (t.getEntireStatement() == null)
		{
			return;
		}

		// find the closest cluster
		Cluster closest = findClosestCluster(t, clusters);

		// minimum-distance cluster has been found.
		if (closest != null)
		{
			double dist = closest.getDistance(t);

			// if it fits into an existing cluster, add it.
			if (dist <= this.epsilon && closest.getSize() >= this.minPts)
			{
				closest.insert(t);
			}
			// if not, look at outliers.
			else
			{
				Cluster closestOutlier = findClosestCluster(t, outliers);
				if (closestOutlier != null)
				{
					dist = closestOutlier.getDistance(t);
					// if it fits into an existing outlier cluster, add it.
					if (dist <= this.epsilon)
					{
						closest.insert(t);
					}
					// if not, create a new outlier cluster
					else
					{
						addNewOutlierCluster(t);
					}
				}
				// there is no outlier clusters.. so add new one.
				else
				{
					addNewOutlierCluster(t);
				}

				// check outlier clusters and see if any of them can become a valid cluster.
				ArrayList<Cluster> promotionList = new ArrayList<Cluster>();
				for (Cluster c : outliers)
				{
					if (c.getSize() >= this.minPts)
					{
						promotionList.add(c);
					}
				}
				DBSeerDataSet dataset = DBSeerGUI.liveDataset;
				int count = dataset.getNumTransactionTypes();
				// promote the outlier clusters with more than minPts transactions.
				for (Cluster c : promotionList)
				{
					System.out.println("Promotion");
					c.setId(clusterId++);
					clusters.add(c);
					allClusters.add(c);
					outliers.remove(c);

					// add it to live dataset.
					dataset.addTransactionType("Type " + (++count));
				}
			}
		}
		// there is no cluster at all for some reason... just add an outlier cluster for now.
		else
		{
			addNewOutlierCluster(t);
		}

		if (t.getEndTime() > this.maxEndTime)
		{
			this.maxEndTime = t.getEndTime();
		}
	}

	private Cluster findClosestCluster(Transaction t, Collection<Cluster> clc)
	{
		Cluster minCluster = null;
		double minDist = 0.0;

		// find the closest cluster
		for (Cluster c : clc)
		{
			double dist = c.getDistance(t);
			if (minCluster == null)
			{
				minCluster = c;
				minDist = dist;
			}
			else if (dist < minDist)
			{
				minCluster = c;
				minDist = dist;
			}
		}
		return minCluster;
	}

	private void addNewOutlierCluster(Transaction t)
	{
		Cluster c = new Cluster(outlierId--);
		c.insert(t);
		this.outliers.add(c);
	}

	private ArrayList<Transaction> getNeighbors(Collection<Transaction> transactions, Transaction t)
	{
		ArrayList<Transaction> neighbors = new ArrayList<Transaction>();
		for (Transaction neighborT : transactions)
		{
			if (neighborT.getClassification() != Transaction.CLASSIFIED)
			{
				if (t.getEuclideanDistance(neighborT) <= this.epsilon)
				{
					neighbors.add(neighborT);
				}
			}
		}
		return neighbors;
	}

	private void expandCluster(Cluster c, Collection<Transaction> transactions, ArrayList<Transaction> neighbors)
	{
		for (Transaction neighbor : neighbors)
		{
			if (neighbor.getClassification() != Transaction.CLASSIFIED)
			{
				neighbor.setClassification(Transaction.CLASSIFIED);
				c.insert(neighbor);
				ArrayList<Transaction> neighbors2 = getNeighbors(transactions, neighbor);
				if (neighbors2.size() >= minPts)
				{
					expandCluster(c, transactions, neighbors2);
				}
			}
		}
	}

	public int getInitPts()
	{
		return initPts;
	}

	public boolean isInitialized()
	{
		return initialized;
	}

	public boolean isInitializing()
	{
		return initializing;
	}

	public long getMaxEndTime()
	{
		return maxEndTime;
	}
}


text:
namespace llvm {
  class MCAsmInfo;
  class MCExpr;
  class MCSection;
  class MCSymbol;
  class MCLabel;
  class MCDwarfFile;
  class MCDwarfLoc;
  class MCObjectFileInfo;
  class MCRegisterInfo;
  class MCLineSection;
  class StringRef;
  class Twine;
  class MCSectionMachO;
  class MCSectionELF;

  /// MCContext - Context object for machine code objects.  This class owns all
  /// of the sections that it creates.
  ///
  class MCContext {
    MCContext(const MCContext&); // DO NOT IMPLEMENT
    MCContext &operator=(const MCContext&); // DO NOT IMPLEMENT
  public:
    typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
  private:

    /// The MCAsmInfo for this target.
    const MCAsmInfo &MAI;

    /// The MCRegisterInfo for this target.
    const MCRegisterInfo &MRI;

    /// The MCObjectFileInfo for this target.
    const MCObjectFileInfo *MOFI;

    /// Allocator - Allocator object used for creating machine code objects.
    ///
    /// We use a bump pointer allocator to avoid the need to track all allocated
    /// objects.
    BumpPtrAllocator Allocator;

    /// Symbols - Bindings of names to symbols.
    SymbolTable Symbols;

    /// UsedNames - Keeps tracks of names that were used both for used declared
    /// and artificial symbols.
    StringMap<bool, BumpPtrAllocator&> UsedNames;

    /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
    /// symbol.
    unsigned NextUniqueID;

    /// Instances of directional local labels.
    DenseMap<unsigned, MCLabel *> Instances;
    /// NextInstance() creates the next instance of the directional local label
    /// for the LocalLabelVal and adds it to the map if needed.
    unsigned NextInstance(int64_t LocalLabelVal);
    /// GetInstance() gets the current instance of the directional local label
    /// for the LocalLabelVal and adds it to the map if needed.
    unsigned GetInstance(int64_t LocalLabelVal);

    /// The file name of the log file from the environment variable
    /// AS_SECURE_LOG_FILE.  Which must be set before the .secure_log_unique
    /// directive is used or it is an error.
    char *SecureLogFile;
    /// The stream that gets written to for the .secure_log_unique directive.
    raw_ostream *SecureLog;
    /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
    /// catch errors if .secure_log_unique appears twice without
    /// .secure_log_reset appearing between them.
    bool SecureLogUsed;

    /// The dwarf file and directory tables from the dwarf .file directive.
    std::vector<MCDwarfFile *> MCDwarfFiles;
    std::vector<StringRef> MCDwarfDirs;

    /// The current dwarf line information from the last dwarf .loc directive.
    MCDwarfLoc CurrentDwarfLoc;
    bool DwarfLocSeen;

    /// Honor temporary labels, this is useful for debugging semantic
    /// differences between temporary and non-temporary labels (primarily on
    /// Darwin).
    bool AllowTemporaryLabels;

    /// The dwarf line information from the .loc directives for the sections
    /// with assembled machine instructions have after seeing .loc directives.
    DenseMap<const MCSection *, MCLineSection *> MCLineSections;
    /// We need a deterministic iteration order, so we remember the order
    /// the elements were added.
    std::vector<const MCSection *> MCLineSectionOrder;

    void *MachOUniquingMap, *ELFUniquingMap, *COFFUniquingMap;

    MCSymbol *CreateSymbol(StringRef Name);

  public:
    explicit MCContext(const MCAsmInfo &MAI, const MCRegisterInfo &MRI,
                       const MCObjectFileInfo *MOFI);
    ~MCContext();

    const MCAsmInfo &getAsmInfo() const { return MAI; }

    const MCRegisterInfo &getRegisterInfo() const { return MRI; }

    const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }

    void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }

    /// @name Symbol Management
    /// @{

    /// CreateTempSymbol - Create and return a new assembler temporary symbol
    /// with a unique but unspecified name.
    MCSymbol *CreateTempSymbol();

    /// CreateDirectionalLocalSymbol - Create the definition of a directional
    /// local symbol for numbered label (used for "1:" definitions).
    MCSymbol *CreateDirectionalLocalSymbol(int64_t LocalLabelVal);

    /// GetDirectionalLocalSymbol - Create and return a directional local
    /// symbol for numbered label (used for "1b" or 1f" references).
    MCSymbol *GetDirectionalLocalSymbol(int64_t LocalLabelVal, int bORf);

    /// GetOrCreateSymbol - Lookup the symbol inside with the specified
    /// @p Name.  If it exists, return it.  If not, create a forward
    /// reference and return it.
    ///
    /// @param Name - The symbol name, which must be unique across all symbols.
    MCSymbol *GetOrCreateSymbol(StringRef Name);
    MCSymbol *GetOrCreateSymbol(const Twine &Name);

    /// LookupSymbol - Get the symbol for \p Name, or null.
    MCSymbol *LookupSymbol(StringRef Name) const;

    /// getSymbols - Get a reference for the symbol table for clients that
    /// want to, for example, iterate over all symbols. 'const' because we
    /// still want any modifications to the table itself to use the MCContext
    /// APIs.
    const SymbolTable &getSymbols() const {
      return Symbols;
    }

    /// @}

    /// @name Section Management
    /// @{

    /// getMachOSection - Return the MCSection for the specified mach-o section.
    /// This requires the operands to be valid.
    const MCSectionMachO *getMachOSection(StringRef Segment,
                                          StringRef Section,
                                          unsigned TypeAndAttributes,
                                          unsigned Reserved2,
                                          SectionKind K);
    const MCSectionMachO *getMachOSection(StringRef Segment,
                                          StringRef Section,
                                          unsigned TypeAndAttributes,
                                          SectionKind K) {
      return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
    }

    const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
                                      unsigned Flags, SectionKind Kind);

    const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
                                      unsigned Flags, SectionKind Kind,
                                      unsigned EntrySize, StringRef Group);

    const MCSectionELF *CreateELFGroupSection();

    const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
                                    int Selection, SectionKind Kind);

    const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
                                    SectionKind Kind) {
      return getCOFFSection (Section, Characteristics, 0, Kind);
    }

    /// @}

    /// @name Dwarf Management
    /// @{

    /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
    unsigned GetDwarfFile(StringRef FileName, unsigned FileNumber);

    bool isValidDwarfFileNumber(unsigned FileNumber);

    bool hasDwarfFiles() const {
      return !MCDwarfFiles.empty();
    }

    const std::vector<MCDwarfFile *> &getMCDwarfFiles() {
      return MCDwarfFiles;
    }
    const std::vector<StringRef> &getMCDwarfDirs() {
      return MCDwarfDirs;
    }

    const DenseMap<const MCSection *, MCLineSection *>
    &getMCLineSections() const {
      return MCLineSections;
    }
    const std::vector<const MCSection *> &getMCLineSectionOrder() const {
      return MCLineSectionOrder;
    }
    void addMCLineSection(const MCSection *Sec, MCLineSection *Line) {
      MCLineSections[Sec] = Line;
      MCLineSectionOrder.push_back(Sec);
    }

    /// setCurrentDwarfLoc - saves the information from the currently parsed
    /// dwarf .loc directive and sets DwarfLocSeen.  When the next instruction
    /// is assembled an entry in the line number table with this information and
    /// the address of the instruction will be created.
    void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
                            unsigned Flags, unsigned Isa,
                            unsigned Discriminator) {
      CurrentDwarfLoc.setFileNum(FileNum);
      CurrentDwarfLoc.setLine(Line);
      CurrentDwarfLoc.setColumn(Column);
      CurrentDwarfLoc.setFlags(Flags);
      CurrentDwarfLoc.setIsa(Isa);
      CurrentDwarfLoc.setDiscriminator(Discriminator);
      DwarfLocSeen = true;
    }
    void ClearDwarfLocSeen() { DwarfLocSeen = false; }

    bool getDwarfLocSeen() { return DwarfLocSeen; }
    const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }

    /// @}

    char *getSecureLogFile() { return SecureLogFile; }
    raw_ostream *getSecureLog() { return SecureLog; }
    bool getSecureLogUsed() { return SecureLogUsed; }
    void setSecureLog(raw_ostream *Value) {
      SecureLog = Value;
    }
    void setSecureLogUsed(bool Value) {
      SecureLogUsed = Value;
    }

    void *Allocate(unsigned Size, unsigned Align = 8) {
      return Allocator.Allocate(Size, Align);
    }
    void Deallocate(void *Ptr) {
    }
  };

} // end namespace llvm

// operator new and delete aren't allowed inside namespaces.
// The throw specifications are mandated by the standard.
/// @brief Placement new for using the MCContext's allocator.
///
/// This placement form of operator new uses the MCContext's allocator for
/// obtaining memory. It is a non-throwing new, which means that it returns
/// null on error. (If that is what the allocator does. The current does, so if
/// this ever changes, this operator will have to be changed, too.)
/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
/// @code
/// // Default alignment (16)
/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
/// // Specific alignment
/// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
/// @endcode
/// Please note that you cannot use delete on the pointer; it must be
/// deallocated using an explicit destructor call followed by
/// @c Context.Deallocate(Ptr).
///
/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
/// @param C The MCContext that provides the allocator.
/// @param Alignment The alignment of the allocated memory (if the underlying
///                  allocator supports it).
/// @return The allocated memory. Could be NULL.
inline void *operator new(size_t Bytes, llvm::MCContext &C,
                          size_t Alignment = 16) throw () {
  return C.Allocate(Bytes, Alignment);
}
/// @brief Placement delete companion to the new above.
///
/// This operator is just a companion to the new above. There is no way of
/// invoking it directly; see the new operator for more details. This operator
/// is called implicitly by the compiler if a placement new expression using
/// the MCContext throws in the object constructor.
inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
              throw () {
  C.Deallocate(Ptr);
}

/// This placement form of operator new[] uses the MCContext's allocator for
/// obtaining memory. It is a non-throwing new[], which means that it returns
/// null on error.
/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
/// @code
/// // Default alignment (16)
/// char *data = new (Context) char[10];
/// // Specific alignment
/// char *data = new (Context, 8) char[10];
/// @endcode
/// Please note that you cannot use delete on the pointer; it must be
/// deallocated using an explicit destructor call followed by
/// @c Context.Deallocate(Ptr).
///
/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
/// @param C The MCContext that provides the allocator.
/// @param Alignment The alignment of the allocated memory (if the underlying
///                  allocator supports it).
/// @return The allocated memory. Could be NULL.
inline void *operator new[](size_t Bytes, llvm::MCContext& C,
                            size_t Alignment = 16) throw () {
  return C.Allocate(Bytes, Alignment);
}

/// @brief Placement delete[] companion to the new[] above.
///
/// This operator is just a companion to the new[] above. There is no way of
/// invoking it directly; see the new[] operator for more details. This operator
/// is called implicitly by the compiler if a placement new[] expression using
/// the MCContext throws in the object constructor.
inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {
  C.Deallocate(Ptr);
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package io.github.andreybgm.gigreminder.screen.artists;

import android.support.test.espresso.matcher.ViewMatchers;

import io.github.andreybgm.gigreminder.R;
import io.github.andreybgm.gigreminder.test.PageObject;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;

public class ArtistsPage extends PageObject {

    public static ArtistsPage obtain() {
        return new ArtistsPage();
    }

    @Override
    public ArtistsPage assertOn() {
        assertIsDisplayed(R.id.screen_artists);

        return this;
    }

    public ArtistsPage clickNewArtist() {
        onView(ViewMatchers.withId(R.id.fab_add_artist)).perform(click());

        return this;
    }
}


text:
using System;
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.DataFactory.Models
{
    /// <summary> DatabricksSparkJar activity. </summary>
    public partial class DatabricksSparkJarActivity : ExecutionActivity
    {
        /// <summary> Initializes a new instance of DatabricksSparkJarActivity. </summary>
        /// <param name="name"> Activity name. </param>
        /// <param name="mainClassName"> The full name of the class containing the main method to be executed. This class must be contained in a JAR provided as a library. Type: string (or Expression with resultType string). </param>
        /// <exception cref="ArgumentNullException"> <paramref name="name"/> or <paramref name="mainClassName"/> is null. </exception>
        public DatabricksSparkJarActivity(string name, BinaryData mainClassName) : base(name)
        {
            Argument.AssertNotNull(name, nameof(name));
            Argument.AssertNotNull(mainClassName, nameof(mainClassName));

            MainClassName = mainClassName;
            Parameters = new ChangeTrackingList<BinaryData>();
            Libraries = new ChangeTrackingList<IDictionary<string, BinaryData>>();
            ActivityType = "DatabricksSparkJar";
        }

        /// <summary> Initializes a new instance of DatabricksSparkJarActivity. </summary>
        /// <param name="name"> Activity name. </param>
        /// <param name="activityType"> Type of activity. </param>
        /// <param name="description"> Activity description. </param>
        /// <param name="dependsOn"> Activity depends on condition. </param>
        /// <param name="userProperties"> Activity user properties. </param>
        /// <param name="additionalProperties"> Additional Properties. </param>
        /// <param name="linkedServiceName"> Linked service reference. </param>
        /// <param name="policy"> Activity policy. </param>
        /// <param name="mainClassName"> The full name of the class containing the main method to be executed. This class must be contained in a JAR provided as a library. Type: string (or Expression with resultType string). </param>
        /// <param name="parameters"> Parameters that will be passed to the main method. </param>
        /// <param name="libraries"> A list of libraries to be installed on the cluster that will execute the job. </param>
        internal DatabricksSparkJarActivity(string name, string activityType, string description, IList<ActivityDependency> dependsOn, IList<ActivityUserProperty> userProperties, IDictionary<string, BinaryData> additionalProperties, FactoryLinkedServiceReference linkedServiceName, ActivityPolicy policy, BinaryData mainClassName, IList<BinaryData> parameters, IList<IDictionary<string, BinaryData>> libraries) : base(name, activityType, description, dependsOn, userProperties, additionalProperties, linkedServiceName, policy)
        {
            MainClassName = mainClassName;
            Parameters = parameters;
            Libraries = libraries;
            ActivityType = activityType ?? "DatabricksSparkJar";
        }

        /// <summary>
        /// The full name of the class containing the main method to be executed. This class must be contained in a JAR provided as a library. Type: string (or Expression with resultType string).
        /// <para>
        /// To assign an object to this property use <see cref="BinaryData.FromObjectAsJson{T}(T, System.Text.Json.JsonSerializerOptions?)"/>.
        /// </para>
        /// <para>
        /// To assign an already formated json string to this property use <see cref="BinaryData.FromString(string)"/>.
        /// </para>
        /// <para>
        /// Examples:
        /// <list type="bullet">
        /// <item>
        /// <term>BinaryData.FromObjectAsJson("foo")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("\"foo\"")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromObjectAsJson(new { key = "value" })</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("{\"key\": \"value\"}")</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// </list>
        /// </para>
        /// </summary>
        public BinaryData MainClassName { get; set; }
        /// <summary>
        /// Parameters that will be passed to the main method.
        /// <para>
        /// To assign an object to the element of this property use <see cref="BinaryData.FromObjectAsJson{T}(T, System.Text.Json.JsonSerializerOptions?)"/>.
        /// </para>
        /// <para>
        /// To assign an already formated json string to this property use <see cref="BinaryData.FromString(string)"/>.
        /// </para>
        /// <para>
        /// Examples:
        /// <list type="bullet">
        /// <item>
        /// <term>BinaryData.FromObjectAsJson("foo")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("\"foo\"")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromObjectAsJson(new { key = "value" })</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("{\"key\": \"value\"}")</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// </list>
        /// </para>
        /// </summary>
        public IList<BinaryData> Parameters { get; }
        /// <summary> A list of libraries to be installed on the cluster that will execute the job. </summary>
        public IList<IDictionary<string, BinaryData>> Libraries { get; }
    }
}


text:
var gulp = require('gulp'),
    template = require('gulp-template-compile'),
    concat  = require('gulp-concat'),
    rimraf = require('gulp-rimraf'),
    requirejsOptimize = require('gulp-requirejs-optimize'),
    p = require('./package.json');

// cleanup
gulp.task('clean', function () {
    return gulp.src('./templates/templates.js', {read: false})
        .pipe(rimraf({force: true}));
});

// cleanup
gulp.task('clean-build', function () {
    return gulp.src('./dist/' + p.name + '_' + p.version + '.min.js', {read: false})
        .pipe(rimraf({force: true}));
});

// build the templates
gulp.task('jst', ['clean'], function () {
    return gulp.src('templates/**/*.html')
        .pipe(template())
        .pipe(concat('templates.js'))
        .pipe(gulp.dest('./templates'));
});

// build
gulp.task('build', ['clean-build', 'jst'], function () {
    var config  = {
        baseUrl: __dirname,
        mainConfigFile: 'init.js',
        generateSourceMaps: false,
        out: '' + p.name + '_' + p.version + '.min.js',
        optimize: 'uglify2',
        findNestedDependencies: true,
        // Include a minimal AMD implementation shim.
        name: 'node_modules/almond/almond.js',
        wrap: true,
        preserveLicenseComments: true
    };
    return gulp.src('init.js')
        .pipe(requirejsOptimize(config))
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['jst'], function() {
    gulp.watch('templates/**/*.html', ['jst']);
});


text:
module Skirt
  module AmazonAPI

    def client
      return @client if @client
      @client = ::PayWithAmazon::Client.new(
        Config.seller_id,
        Config.mws_access_key_id,
        Config.mws_secret_key,
        sandbox: !Rails.env.production?,
        currency_code: :jpy,
        region: :jp
      )
    end

    # オーソライズAPI呼び出し
    def call_authorize(transaction_timeout = nil)
      self.authorization_reference_id = self.generate_authorization_reference_id

      client.authorize(
        self.amazon_order_reference_id,
        self.authorization_reference_id,
        self.amount,

        currency_code: 'JPY', # Default: USD
        seller_authorization_note: Config.seller_authorization_note,

        # Set to 0 for synchronous mode
        transaction_timeout: transaction_timeout,
        capture_now: false
      )
    end

    # オーソリ取り消し
    def call_close_authorization
      client.close_authorization(self.amazon_authorization_id)
    end

    # キャプチャ(支払い)
    def call_capture(capture_amount = nil)
      client.capture(
        self.amazon_authorization_id,
        self.generate_capture_reference_id,
        capture_amount || self.amount,
        currency_code: 'JPY',
        seller_capture_note: ''
      )
    end

    def call_confirm_order_reference(amazon_order_reference_id)
      client.confirm_order_reference(amazon_order_reference_id)
    end

    def call_get_order_reference_details(amazon_order_reference_id,
                                         address_consent_token = nil)

      client.get_order_reference_details(
        amazon_order_reference_id,
        address_consent_token: address_consent_token
      )
    end

    def call_get_authorization_details(amazon_authorization_id)
      client.get_authorization_details(amazon_authorization_id)
    end

    def call_set_order_reference_details(seller_order_id = '')
      client.set_order_reference_details(
        amazon_order_reference_id,
        self.amount,
        # currency_code: 'JPY', # Default: USD
        seller_order_id:  seller_order_id,
        seller_note:      Config.seller_note,
        store_name:       Config.store_name
      )
    end

    def call_cancel_order_reference(amazon_order_reference_id)
      client.cancel_order_reference(amazon_order_reference_id)
    end

    def call_close_order_reference(amazon_order_reference_id)
      client.close_order_reference(amazon_order_reference_id)
    end

    def treat_error(ret_xml, column)
      error_code = parse_error_code(ret_xml)
      self.update_column(column, error_code) unless self.new_record?

      error_code
    end

    def parse_error_code(ret_xml)
      code = nil
      response = Hash.from_xml ret_xml.body
      if response["ErrorResponse"]
        code = response["ErrorResponse"]["Error"]["Code"]
      end

      code
    end

    # Set a unique id for your current authorization
    # of this payment.
    def generate_authorization_reference_id
      return self.authorization_reference_id if self.authorization_reference_id

      "auth-#{Time.now.to_i}-#{self.id}"
    end

    # Set a unique id for your current authorization
    # of this payment.
    def generate_capture_reference_id
      return self.capture_reference_id if self.capture_reference_id

      self.capture_reference_id = "capture-#{Time.now.to_i}-#{self.id}"
    end

  end

end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello Knockout.JS</title>

             +

             -


text:
(function(ns){

    var oNS = $yobi.createNamespace(ns);
    oNS.container[oNS.name] = function(htOptions){

        var htVar = {};
        var htElement = {};

        function _init(htOptions){
            _initVar(htOptions);
            _initElement(htOptions);
            _attachEvent();

            _initFormValidator();
        }

        /**
         * initialize variables
         */
        function _initVar(htOptions){
            htVar.sFormName = htOptions.sFormName || "newproject";
            htVar.rxPrjName = /^[0-9A-Za-z-_\.]+$/;
            htVar.aReservedWords = [".", "..", ".git"];
        }

        /**
         * initialize element
         */
        function _initElement(htOptions){
            htElement.welInputVCS = $("#vcs"); // input type="hidden"
            htElement.welBtnVCSSelected = $("#vcs_msg"); // <button data-toggle="dropdown">
            htElement.aVCSItems = $("#vcs_dropdown li a");
            htElement.svnWarning = $("#svn");
            htElement.welInputProjectName = $("#project-name");
            htElement.welInputProjectOwner = $("#project-owner");
            htElement.welProtected = $("#protected, .label-protected");

            htElement.welInputProjectName.focus();
        }

        /**
         * attach event handler
         */
        function _attachEvent(){
            htElement.aVCSItems.click(_onSelectVCSItem);
            htElement.welInputProjectOwner.on("change", _onChangeProjectOwner);
        }

        function _onSelectVCSItem(){
            var sText = $(this).text();
            var sValue = $(this).attr("data-value");

            htElement.welInputVCS.val(sValue);
            htElement.welBtnVCSSelected.text(sText);

            if(sText == "Subversion") {
                htElement.svnWarning.show();
            } else {
                htElement.svnWarning.hide();
            }
        }

        function _onChangeProjectOwner() {
            var sType = $("#project-owner option:selected").data("type");
            if (sType == "user") {
                if ($("#protected").is(":checked")) {
                    $("#public").prop("checked", true);
                }
                htElement.welProtected.hide();
            } else {
                htElement.welProtected.show();
            }
        }

        /**
         * initialize formValidator
         * @require validate.js
         */
        function _initFormValidator(){
            // name : name of input element
            // rules: rules to apply to the input element.
            var aRules = [];

            htVar.oValidator = new FormValidator(htVar.sFormName, aRules, function(aErrors){
                var oForm = $(document.forms[htVar.sFormName]);
                var oElement = oForm.find("input[name=name]");
                var sPrjName = oElement.val();
                if(!htVar.rxPrjName.test(sPrjName)){
                    aErrors.push({
                        id: oElement.attr("id"),
                        name: oElement.attr("name"),
                        message: Messages("project.name.alert")
                    });
                }
                if(htVar.aReservedWords.indexOf(sPrjName) >= 0){
                    aErrors.push({
                        id: oElement.attr("id"),
                        name: oElement.attr("name"),
                        message: Messages("project.name.reserved.alert")
                    });
                }
                _onFormValidate(aErrors);
            });
        }

        /**
         * handler for validation errors.
         */
        function _onFormValidate(aErrors){
            if(aErrors.length > 0){
                $('span.warning').hide();
                $('span.msg').html(aErrors[0].message).show();
            } else {
                new Spinner({
                    lines: 13, // The number of lines to draw
                    length: 10, // The length of each line
                    width: 5, // The line thickness
                    radius: 10, // The radius of the inner circle
                    corners: 1, // Corner roundness (0..1)
                    rotate: 0, // The rotation offset
                    direction: 1, // 1: clockwise, -1: counterclockwise
                    color: '#000', // #rgb or #rrggbb
                    speed: 1, // Rounds per second
                    trail: 60, // Afterglow percentage
                    shadow: false, // Whether to render a shadow
                    hwaccel: false, // Whether to use hardware acceleration
                    className: 'spinner', // The CSS class to assign to the spinner
                    zIndex: 2e9, // The z-index (defaults to 2000000000)
                    top: 'auto', // Top position relative to parent in px
                    left: 'auto' // Left position relative to parent in px
                }).spin(document.forms[htVar.sFormName]);
            }
        }

        _init(htOptions || {});
    };

})("yobi.project.New");


text:
/**
 * Transaction Builder
 * ===================
 *
 * Transaction Builder. This is a, yet unfinished, convenience class for
 * building pubkeyhash and p2sh transactions, and also for verifying arbitrary
 * transactions (and their inputs). You can (or will be able to) pay to
 * pubkeyhash to p2sh and can spend pubkeyhash or p2sh-pubkeyhash or
 * p2sh-multisig.
 */
var Tx = require('./tx');
var Txout = require('./txout');
var Address = require('./address');
var Script = require('./script');
var BN = require('./bn');
var Block = require('./block');
var BufR = require('./bufr');
var Interp = require('./interp');

var Txbuilder = function Txbuilder(obj) {
  if (!(this instanceof Txbuilder))
    return new Txbuilder(obj);
  if (obj) {
    this.initialize();
    this.set(obj);
  } else {
    this.initialize();
  }
};

module.exports = Txbuilder;

Txbuilder.prototype.initialize = function() {
  this.tx = Tx();
  this.prevtxoutsmap = {};
  return this;
};

Txbuilder.prototype.set = function(obj) {
  this.tx = obj.tx || this.tx;
  this.prevtxoutsmap = obj.prevtxoutsmap || this.prevtxoutsmap;
  return this;
};

Txbuilder.prototype.addToAddress = function(valuebn, addr) {
  if (!(addr instanceof Address) || !(valuebn instanceof BN))
    throw new Error('addr must be an Address, and valuebn must be a BN');
  if (addr.type() === 'scripthash') {
    var script = Script().fromScripthash(addr.hashbuf);
  } else if (addr.type() === 'pubkeyhash') {
    var script = Script().fromPubkeyhash(addr.hashbuf);
  } else {
    throw new Error('invalid address type');
  }
  var txout = Txout(valuebn, script);
  this.tx.addTxout(txout);
  return this;
};

/**
 * Verifies that the transaction is valid both by performing basic checks, such
 * as ensuring that no two inputs are the same, as well as by verifying every
 * script. The two checks are checktxstr, which is analagous to bitcoind's
 * CheckTransaction, and verifytxstr, which runs the script interpreter.
 *
 * This does NOT check that any possible claimed fees are accurate; checking
 * that the fees are accurate requires checking that the input transactions are
 * valid, which is not performed by this test. That check is done with the
 * normal verify function.
 */
Txbuilder.prototype.verifytx = function(flags) {
  return !this.checktxstr() && !this.verifytxstr(flags);
};

/**
 * Check that a transaction passes basic sanity tests. If not, return a string
 * describing the error. This function contains the same logic as
 * CheckTransaction in bitcoin core.
 */
Txbuilder.prototype.checktxstr = function() {
  // Basic checks that don't depend on any context
  if (this.tx.txins.length === 0 || this.tx.txinsvi.toNumber() === 0)
    return "transaction txins empty";
  if (this.tx.txouts.length === 0 || this.tx.txoutsvi.toNumber() === 0)
    return "transaction txouts empty";

  // Size limits
  if (this.tx.toBuffer().length > Block.MAX_BLOCK_SIZE)
    return "transaction over the maximum block size";

  // Check for negative or overflow output values
  var valueoutbn = BN(0);
  for (var i = 0; i < this.tx.txouts.length; i++) {
    var txout = this.tx.txouts[i];
    if (txout.valuebn.lt(0))
      return "transaction txout " + i + " negative";
    if (txout.valuebn.gt(Tx.MAX_MONEY))
      return "transaction txout " + i + " greater than MAX_MONEY";
    valueoutbn = valueoutbn.add(txout.valuebn);
    if (valueoutbn.gt(Tx.MAX_MONEY))
      return "transaction txout " + i + " total output greater than MAX_MONEY";
  }

  // Check for duplicate inputs
  var txinmap = {};
  for (var i = 0; i < this.tx.txins.length; i++) {
    var txin = this.tx.txins[i];
    var inputid = txin.txhashbuf.toString('hex') + ':' + txin.txoutnum;
    if (typeof txinmap[inputid] !== 'undefined')
      return "transaction input " + i + " duplicate input";
    txinmap[inputid] = true;
  }

  if (this.tx.isCoinbase()) {
    var buf = this.tx.txins[0].script.toBuffer();
    if (buf.length < 2 || buf.length > 100)
      return "coinbase trasaction script size invalid";
  } else {
    for (var i = 0; i < this.tx.txins.length; i++) {
      if (this.tx.txins[i].hasNullInput())
        return "tranasction input " + i + " has null input";
    }
  }
  return false;
};

/**
 * verify the transaction inputs by running the script interpreter. Returns a
 * string of the script interpreter is invalid, otherwise returns false.
 */
Txbuilder.prototype.verifytxstr = function(flags) {
  for (var i = 0; i < this.tx.txins.length; i++) {
    if (!this.verifytxnin(i, flags))
      return "input " + i + " failed script verify";
  }
  return false;
};

/**
 * Verify a particular input by running the script interpreter. Returns true if
 * the input is valid, false otherwise.
 */
Txbuilder.prototype.verifytxnin = function(nin, flags) {
  var txin = this.tx.txins[nin];
  var scriptSig = txin.script;
  var txoutnum = txin.txoutnum;
  var txidbuf = BufR(txin.txhashbuf).readReverse();
  var txidhex = txidbuf.toString('hex');
  var mapid = txidhex + ":" + txoutnum;
  var scriptPubkey = this.prevtxoutsmap[mapid].script;
  var interp = Interp()
  var verified = interp.verify(scriptSig, scriptPubkey, this.tx, nin, flags);
  return verified;
};


text:
package org.spongepowered.mod.mixin.core.text;

import net.minecraft.util.ChatComponentStyle;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.TextBuilder;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextStyle;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.mod.text.ChatComponentIterable;
import org.spongepowered.mod.text.SpongeChatComponent;
import org.spongepowered.mod.text.SpongeChatStyle;
import org.spongepowered.mod.text.SpongeClickEvent;
import org.spongepowered.mod.text.SpongeHoverEvent;
import org.spongepowered.mod.text.format.SpongeTextColor;

import java.util.List;

@Mixin(ChatComponentStyle.class)
public abstract class MixinChatComponentStyle implements SpongeChatComponent {

    @Shadow private ChatStyle style;
    @Shadow protected List<IChatComponent> siblings;

    private Iterable<IChatComponent> childrenIterable;

    private char[] formatting;

    protected TextBuilder createBuilder() {
        throw new UnsupportedOperationException();
    }

    public boolean isFlowerPot() {
        return false;
    }
    @Override
    public Iterable<IChatComponent> withChildren() {
        if (this.childrenIterable == null) {
            this.childrenIterable = new ChatComponentIterable((IChatComponent) this);
        }

        return this.childrenIterable;
    }

    private char[] getFormatting() {
        if (this.formatting == null) {
            this.formatting = ((SpongeChatStyle) this.style).asFormattingCode();
        }

        return this.formatting;
    }

    @Override
    public String toPlain() {
        StringBuilder builder = new StringBuilder();

        for (IChatComponent component : withChildren()) {
            builder.append(component.getUnformattedTextForChat());
        }

        return builder.toString();
    }

    @Override
    public String toLegacy(char code) {
        StringBuilder builder = new StringBuilder();

        for (IChatComponent component : withChildren()) {
            char[] formatting = ((MixinChatComponentStyle) component).getFormatting();
            builder.ensureCapacity(formatting.length * 2 + 16);
            for (char formattingCode : formatting) {
                builder.append(code).append(formattingCode);
            }

            builder.append(component.getUnformattedTextForChat());
            builder.append(code).append(EnumChatFormatting.RESET.formattingCode);
        }

        return builder.toString();
    }

    @Override
    public Text toText() {
        TextBuilder builder = createBuilder();

        if (this.style != null) {
            if (this.style.color != null) {
                builder.color(SpongeTextColor.of(this.style.color));
            }

            builder.style(new TextStyle(this.style.bold, this.style.italic, this.style.underlined, this.style.strikethrough, this.style.obfuscated));

            if (this.style.chatClickEvent != null) {
                builder.onClick(((SpongeClickEvent) this.style.chatClickEvent).getHandle());
            }
            if (this.style.chatHoverEvent != null) {
                builder.onHover(((SpongeHoverEvent) this.style.chatHoverEvent).getHandle());
            }
            if (this.style.insertion != null) {
                builder.onShiftClick(TextActions.insertText(this.style.insertion));
            }
        }

        for (IChatComponent child : this.siblings) {
            builder.append(((SpongeChatComponent) child).toText());
        }

        return builder.build();
    }

}


text:
using namespace std;

int main(int argc, char * argv[])
{
    srand(time(NULL));

	QApplication app(argc, argv);
	GameWindow window;

	window.showMaximized();
	app.exec();
}


text:
package com.mkyong.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER");
		auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
		auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {

		http.authorizeRequests()
			.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
			.antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
			.and().formLogin();

	}
}


text:
(function(){
	if(!window.localStorage.justjavascriptmvc) window.localStorage.justjavascriptmvc = JSON.stringify({settings: {persist: false}, todos: []});
	var storage = {
		settings: function(value){
			if(value){
				var justjavascriptmvc = JSON.parse(window.localStorage.justjavascriptmvc);
				justjavascriptmvc.settings = value;
				window.localStorage.justjavascriptmvc = JSON.stringify(justjavascriptmvc);
				return value;
			}
			var s = JSON.parse(window.localStorage.justjavascriptmvc).settings;
			var obj = new settings();
			obj.persist = s.persist;
			return obj;
		}
		, todos: function(){
			var list = JSON.parse(window.localStorage.justjavascriptmvc).todos;
			return list;
		}
		, add_todo: function(t){
			var todos = this.todos();
			todos.push(t);
			var justjavascriptmvc = JSON.parse(window.localStorage.justjavascriptmvc);
			justjavascriptmvc.todos = todos;
			window.localStorage.justjavascriptmvc = JSON.stringify(justjavascriptmvc);
		}
		, remove_todo: function(t){
			var todos = this.todos();
			for(i in todos){
				if(t.timestamp === parseInt(todos[i].timestamp)){
					todos.splice(i, 1);
					break;
				}
			}
			var justjavascriptmvc = JSON.parse(window.localStorage.justjavascriptmvc);
			justjavascriptmvc.todos = todos;
			window.localStorage.justjavascriptmvc = JSON.stringify(justjavascriptmvc);
		}
		, save: function(todos){
			var justjavascriptmvc = JSON.parse(window.localStorage.justjavascriptmvc);
			justjavascriptmvc.todos = todos;
			window.localStorage.justjavascriptmvc = JSON.stringify(justjavascriptmvc);
		}
		, save_todo: function(t){
			var todos = this.todos();
			for(var i = 0; i < todos.length; i++){
				if(t.timestamp === parseInt(todos[i].timestamp)){
					todos[i] = t;
					break;
				}
			}
			var justjavascriptmvc = JSON.parse(window.localStorage.justjavascriptmvc);
			justjavascriptmvc.todos = todos;
			window.localStorage.justjavascriptmvc = JSON.stringify(justjavascriptmvc);
		}
	};

	function model(){
		var dependents = [];
		this.subscribe = function(key, subscriber){
			if(dependents[key] === undefined) dependents[key] = [];
			dependents[key].push(subscriber);
		};
		this.unsubscribe = function(subscriber){
			var i = 0;
			var ubounds = dependents.length;
			for(i; i<ubounds; i++){
				var k = 0;
				var upper = dependents[i].length;
				for(k = 0; k < upper; k++){
					if(dependents[i][k] === subscriber){
						dependents[i].splice(k, 1);
						if(dependents[i].length === 0) delete dependents[i];
						break;
					}
				}
			}
		};
		this.changed = function(key, old, v){
			if(dependents[key] === undefined) return;
			var i = 0;
			var ubounds = dependents[key].length;
			for(i; i<ubounds; i++){
				dependents[key][i].update(key, old, v, this);
			}
		}
	}
	function todo(obj){
		model.apply(this, []);
		if(!obj) obj = {};
		var timestamp = obj.timestamp ? obj.timestamp : (new Date()).getTime();
		this.__defineGetter__("timestamp", function(){
			return timestamp;
		});
		this.__defineSetter__("timestamp", function(v){
			var old = timestamp;
			timestamp = v;
			this.changed("timestamp", old, v);
		});
		var order = obj.order ? obj.order : 0;
		this.__defineGetter__("order", function(){
			return order;
		});
		this.__defineSetter__("order", function(v){
			var old = order;
			order = v;
			this.changed("order", old, v);
		});
		var done = obj.done ? obj.done : false;
		this.__defineGetter__("done", function(){
			return done;
		});
		this.__defineSetter__("done", function(v){
			var old = done;
			done = v;
			this.changed("done", old, v);
		});
		var editing = obj.editing ? obj.editing : false;
		this.__defineGetter__("editing", function(){
			return editing;
		});
		this.__defineSetter__("editing", function(v){
			var old = editing;
			editing = v;
			this.changed("editing", old, v);
		});
		var content = obj.content ? obj.content : null;
		this.__defineGetter__("content", function(){
			return content;
		});
		this.__defineSetter__("content", function(v){
			var old = content;
			content = v;
			this.changed("content", old, v);
		});
		return this;
	}
	function settings(){
		model.apply(this, []);
		this.persist = false;
		return this;
	}

	/*Controllers namespace*/
	var DEVICE = (function(){
		var self = {};
		self.CANTOUCH = ("createTouch" in document);
		self.MOUSEDOWN = self.CANTOUCH ? "touchstart" : "mousedown";
		self.MOUSEMOVE = self.CANTOUCH ? "touchmove" : "mousemove";
		self.MOUSEUP = self.CANTOUCH ? "touchend" : "mouseup";
		self.CLICK = "click";
		self.DOUBLECLICK = "dblclick";
		self.KEYUP = "keyup";
		self.SEARCH = "search";
		self.INPUT = "input";
		self.BLUR = "blur";
		self.UNLOAD = "unload";
		self.CHANGE = "change";
		self.SCROLL = "scroll";
		self.FOCUS = "focus";
		self.SUBMIT = "submit";
		return self;
	})();
	/*List controller*/
	var controllers = {};
	controllers.list = function(){
		var view = null;
		var model = null;
		var self = this;
		var mouseDownDelegate = function(e){self[DEVICE.MOUSEDOWN](e);};
		var mouseUpDelegate = function(e){self[DEVICE.MOUSEUP](e);};
		var mouseMoveDelegate = function(e){self[DEVICE.MOUSEMOVE](e);};
		this.settings = null;
		this.isSwiping = false;
		var startY = 0;
		var startX = 0;
		var timer = null;
		var xVelocity = 0;
		var calculating = false;
		var previousTime = null;
		var shouldDelete = false;
		this[DEVICE.MOUSEDOWN] = function(e){
			this.isSwiping = true;
			startY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
			startX = e.targetTouches ? e.targetTouches[0].pageY : e.pageX;
			timer = (new Date()).getTime();
			previousTime = timer;
			view.container.addEventListener(DEVICE.MOUSEMOVE, mouseMoveDelegate, true);
		};
		this[DEVICE.MOUSEUP] = function(e){
			this.isSwiping = false;
			view.container.removeEventListener(DEVICE.MOUSEMOVE, mouseMoveDelegate, true);
			timer = null;
			previousTime = null;
			if(!shouldDelete) return;
			shouldDelete = false;
			var todo = this.model.find(parseInt(e.target.id));
			this.model.pop(todo);
			if(this.settings.persist) storage.save(this.model.items());
		};
		this[DEVICE.MOUSEMOVE] = function(e){
			if(calculating) return;
			calculating = true;
			var yDeviation = e.pageY - startY;
			var xDeviation = Math.abs(e.pageX - startX);
			var now = (new Date()).getTime();
			var previousXVelocity = xVelocity;
			xVelocity = xDeviation / (now-timer);
			var rate = Math.abs(xVelocity - previousXVelocity) / (now-previousTime);
			console.log([xDeviation, rate]);
			if(xDeviation > 160 && e.target && e.target.id && e.target.nodeName === "INPUT" && rate > .01){
				shouldDelete = true;
			}
			calculating = false;
			previousTime = now;
		};

		this.__defineGetter__("view", function(){
			return view;
		});
		this.__defineSetter__("view", function(v){
			if(view) view.release();
			view = v;
			view.container.addEventListener("blur", this, true);
			view.container.addEventListener("keypress", this, true);
			view.container.addEventListener("click", this, true);
			view.container.addEventListener(DEVICE.MOUSEDOWN, mouseDownDelegate, true);
			view.container.addEventListener(DEVICE.MOUSEUP, mouseUpDelegate, true);
			model = v.model;
			this.settings = v.settings;
			if(model.length() > 0){
				for(i in model.items()){
					view.add(model.item(i));
				}
				view.update_stats(model.length());
			}
		});
		this.__defineGetter__("model", function(){
			return model;
		});
		this.__defineSetter__("model", function(v){
			model = v;
		});
		return this;
	};
	controllers.list.prototype = {
		save: function(id, value){
			for(var i = 0; i < this.model.length(); i++){
				if(id === this.model.item(i).timestamp){
					this.model.item(i).content = value;
					if(this.settings.persist){
						storage.save_todo(this.model.item(i));
					}
					break;
				}
			}
		}
		, handleEvent: function(e){
			if(this[e.type]) this[e.type](e);
		}
		, blur: function(e){
			this.save(parseInt(e.target.id), e.target.value);
		}
		, keypress: function(e){
			if(e.which !== 13) return;
			this.view.select_next(e.target);
		}
		, click: function(e){
			if(e.target.type && e.target.type === "submit"){
				var todo = this.model.find(parseInt(e.target.id.replace("done_", "")));
				todo.done = !todo.done;
				if(this.settings.persist) storage.save_todo(todo);
			}
		}
	};
	/*Editing controller*/
	controllers.editing = function(){
		var view = null;
		var model = null;
		this.settings = null;
		this.__defineGetter__("view", function(){
			return view;
		});
		this.__defineSetter__("view", function(v){
			if(view) view.release();
			v.add_button.addEventListener("click", this, true);
			v.field.addEventListener("keypress", this, true);
			view = v;
			model = v.model;
			this.settings = v.settings;
		});
		this.__defineGetter__("model", function(){
			return model;
		});
		this.__defineSetter__("model", function(v){
			model = v;
		});
		this.release = function(v){
			view = null;
		};
		return this;
	};
	controllers.editing.prototype.handleEvent = function(e){
		if(this.view.value.length === 0) return;
		if(this[e.type]) this[e.type](e);
	};
	controllers.editing.prototype.add = function(value){
		var t = new todo();
		t.order = this.model.length();
		t.content = value;
		this.model.push(t);
		if(this.settings.persist){
			storage.add_todo(t);
		}
	};
	controllers.editing.prototype.keypress = function(e){
		if(e.which !== 13) return;
		this.add(e.target.value);
		e.target.value = "";
	};
	controllers.editing.prototype.click = function(e){
		if(e.target !== this.view.add_button) return;
		this.add(this.view.value);
		this.view.value = "";
		this.view.focus();
	};

	controllers.settings = function(){
		var view = null;
		var model = null;
		this.__defineGetter__("view", function(){
			return view;
		});
		this.__defineSetter__("view", function(v){
			if(view) view.release();
			v.checkbox.addEventListener("click", this, true);
			view = v;
			model = v.model;
		});
		this.release = function(v){
			view = null;
		};
		return this;
	};
	controllers.settings.prototype.handleEvent = function(e){
		if(this[e.type]) this[e.type](e);
	};
	controllers.settings.prototype.click = function(e){
		this.model.persist = this.view.value;
		storage.settings(this.model);
	};

	/*parent view*/
	function view(id, model, controller){
		this.container = document.getElementById(id);
		this.model = model;
		this.controller = controller;
		this.release = function(){
			this.controller.release(this);
			this.model.unsubscribe(this);
		};
		return this;
	}

	/*views namespace*/
	var views = {};
	views.editing = function(id, model, controller){
		view.apply(this, [id, model, controller]);
		this.__defineGetter__("field", function(){
			return field;
		});
		this.__defineGetter__("value", function(){
			return field.value;
		});
		this.__defineSetter__("value", function(v){
			field.value = v;
		});

		var field = this.container.querySelector("input");
		this.add_button = this.container.querySelector("#add_button");
		this.model = model.list;
		this.settings = model.settings;
		this.model.subscribe("todos.push", this);
		this.model.subscribe("todos.pop", this);
		this.controller.view = this;
		this.controller.model = this.model;

		// Define as priveleged so we can keep the field property private.
		this.focus = function(){
			field.focus();
		};
		return this;
	}
	views.editing.prototype.update = function(key, old, v, m){
		if(this[key] === undefined) return;
		this[key](old, v, m);
	};
	/*list view*/
	views.list = function(id, model, controller){
		this.__defineGetter__("value", function(){
			return this.container.querySelector("input:focus").value;
		});
		this.__defineSetter__("value", function(v){
			this.container.querySelector("input:focus").value = v;
		});
		view.apply(this, [id, model, controller]);
		this.stats = document.getElementById("todo-stats");
		this.model = model.list;
		this.settings = model.settings;
		this.model.subscribe("todos.push", this);
		this.model.subscribe("todos.pop", this);
		var ubounds = this.model.length();
		var i = 0;
		for(i=0; i < ubounds; i++){
			this.model.item(i).subscribe("done", this);
		}
		this.controller.view = this;
		this.controller.model = this.model;
		return this;
	}
	views.list.prototype.select_next = function(elem){
		var li = elem.parentNode;
		var items = this.container.querySelectorAll("li");
		var i = 0;
		var item = null;
		for(i = 0; i < items.length - 1; i++){
			if(li === items[i]){
				item = items[i+1];
			}
		}
		if(item === null) return;
		item.querySelector("input[type='text']").focus();
	}
	views.list.prototype.update = function(key, old, v, m){
		if(this[key] === undefined) return;
		this[key](old, v, m);
	};
	views.list.prototype.remove = function(todo){
		var elements = this.container.querySelectorAll('li input[type="text"]');
		for(i in elements){
			if(parseInt(elements[i].id) === todo.timestamp){
				this.container.removeChild(elements[i].parentNode);
				break;
			}
		}
	};
	views.list.prototype.add = function(todo){
		var item = document.createElement("li");
		var field = document.createElement("input");
		var doneButton = document.createElement("button");
		doneButton.type = "button";
		doneButton.innerHTML = todo.done ? "o" : "x";
		doneButton.id = "done_" + todo.timestamp;
		field.value = todo.content;
		field.type = "text";
		field.id = todo.timestamp;
		item.appendChild(field);
		item.appendChild(doneButton);
		item.className = todo.done ? "done" : "";
		this.container.appendChild(item);
		return item;
	};
	views.list.prototype.update_stats = function(count){
		this.stats.innerHTML = count + " items left.";
	};
	views.list.prototype["done"] = function(old, v, m){
		var button = document.getElementById("done_" + m.timestamp);
		button.parentNode.className = v ? "done" : "";
		button.parentNode.querySelector("input").disabled = v ? true : false;
		button.innerHTML = v ? "o" : "x";
	};
	views.list.prototype["todos.push"] = function(old, v, m){
		v.subscribe("done", this);
		this.update_stats(m.length());
		this.add(v);
	};
	views.list.prototype["todos.pop"] = function(old, v, m){
		m.unsubscribe("done", this);
		this.update_stats(m.length());
		this.remove(v);
	};

	views.settings = function(id, model, controller){
		this.__defineGetter__("value", function(){
			return this.container.checked;
		});
		this.__defineSetter__("value", function(v){
			this.container.checked = v;
		});
		view.apply(this, [id, model, controller]);
		this.checkbox = this.container;
		this.model.subscribe("settings.persist", this);
		this.controller.view = this;
		this.controller.model = this.model;
		this.checkbox.checked = this.model.persist;
		return this;
	};

	function todos(list){
		if(!list) list = [];
		for(var i = 0; i < list.length; i++){
			list[i] = new todo(list[i]);
		}
		var self = {
			push: function(todo){
				var found = false;
				for(i in list){
					if(list[i].timestamp === todo.timestamp){
						list[i] = todo;
						found = true;
					}
				}
				if(!found) list.push(todo);
				this.changed("todos.push", null, todo, this);
			}
			, pop: function(todo){
				var i = 0;
				var ubounds = list.length;
				for(i; i<ubounds; i++){
					if(list[i].timestamp === todo.timestamp){
						var removed = list.splice(i, 1);
						this.changed("todos.pop", removed, todo, this);
						return removed;
					}
				}
			}
			, item: function(i){
				return list[i];
			}
			, items: function(){
				return list;
			}
			, length: function(){
				return list.length;
			}
			, find: function(id){
				id = parseInt(id);
				for(i in list){
					if(id === list[i].timestamp) return this.item(i);
				}
				return null;
			}
		};
		model.apply(self, []);
		return self;
	}

	var list = new todos();
	var s = storage.settings();
	if(s.persist){
		list = new todos(storage.todos());
	}
	var editing_controller = new controllers.editing();
	var editing = new views.editing("todoapp", {list: list, settings: s}, editing_controller);
	editing.focus();
	var todos_list = new views.list("todos", {list: list, settings: s}, new controllers.list());
	var settings_view = new views.settings("settings.persist", s, new controllers.settings());
})();


text:
from oslo_policy import policy

from sahara.common.policies import base

job_types_policies = [
    policy.DocumentedRuleDefault(
        name=base.DATA_PROCESSING_JOB_TYPES % 'get_all',
        check_str=base.UNPROTECTED,
        description='List job types.',
        operations=[{'path': '/v1.1/{project_id}/job-types',
                     'method': 'GET'}]),
]

def list_rules():
    return job_types_policies


text:
// <copyright file="Svd.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2015 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>

using System;

namespace MathNet.Numerics.LinearAlgebra.Factorization
{
    ///
    /// <para>A class which encapsulates the functionality of the singular value decomposition (SVD).</para>
    /// <para>Suppose M is an m-by-n matrix whose entries are real numbers.
    /// Then there exists a factorization of the form M = UΣVT where:
    /// - U is an m-by-m unitary matrix;
    /// - Σ is m-by-n diagonal matrix with nonnegative real numbers on the diagonal;
    /// - VT denotes transpose of V, an n-by-n unitary matrix;
    /// Such a factorization is called a singular-value decomposition of M. A common convention is to order the diagonal
    /// entries Σ(i,i) in descending order. In this case, the diagonal matrix Σ is uniquely determined
    /// by M (though the matrices U and V are not). The diagonal entries of Σ are known as the singular values of M.</para>
    ///
    /// <remarks>
    /// The computation of the singular value decomposition is done at construction time.
    /// </remarks>
    /// <typeparam name="T">Supported data types are double, single, <see cref="Complex"/>, and <see cref="Complex32"/>.</typeparam>
    public abstract class Svd<T> : ISolver<T>
        where T : struct, IEquatable<T>, IFormattable
    {
        readonly Lazy<Matrix<T>> _lazyW;

        /// Indicating whether U and VT matrices have been computed during SVD factorization.
        protected readonly bool VectorsComputed;

        protected Svd(Vector<T> s, Matrix<T> u, Matrix<T> vt, bool vectorsComputed)
        {
            S = s;
            U = u;
            VT = vt;

            VectorsComputed = vectorsComputed;

            _lazyW = new Lazy<Matrix<T>>(ComputeW);
        }

        Matrix<T> ComputeW()
        {
            var rows = U.RowCount;
            var columns = VT.ColumnCount;
            var result = Matrix<T>.Build.SameAs(U, rows, columns);
            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < columns; j++)
                {
                    if (i == j)
                    {
                        result.At(i, i, S[i]);
                    }
                }
            }

            return result;
        }

        ///
        /// Gets the singular values (Σ) of matrix in ascending value.
        ///
        public Vector<T> S { get; }

        ///
        /// Gets the left singular vectors (U - m-by-m unitary matrix)
        ///
        public Matrix<T> U { get; }

        ///
        /// Gets the transpose right singular vectors (transpose of V, an n-by-n unitary matrix)
        ///
        public Matrix<T> VT { get; }

        ///
        /// Returns the singular values as a diagonal <see cref="Matrix{T}"/>.
        ///
        /// <returns>The singular values as a diagonal <see cref="Matrix{T}"/>.</returns>
        public Matrix<T> W => _lazyW.Value;

        ///
        /// Gets the effective numerical matrix rank.
        ///
        /// <value>The number of non-negligible singular values.</value>
        public abstract int Rank { get; }

        ///
        /// Gets the two norm of the <see cref="Matrix{T}"/>.
        ///
        /// <returns>The 2-norm of the <see cref="Matrix{T}"/>.</returns>
        public abstract double L2Norm { get; }

        ///
        /// Gets the condition number max(S) / min(S)
        ///
        /// <returns>The condition number.</returns>
        public abstract T ConditionNumber { get; }

        ///
        /// Gets the determinant of the square matrix for which the SVD was computed.
        ///
        public abstract T Determinant { get; }

        ///
        /// Solves a system of linear equations, AX = B, with A SVD factorized.
        ///
        /// <param name="input">The right hand side <see cref="Matrix{T}"/>, B.</param>
        /// <returns>The left hand side <see cref="Matrix{T}"/>, X.</returns>
        public virtual Matrix<T> Solve(Matrix<T> input)
        {
            if (!VectorsComputed)
            {
                throw new InvalidOperationException("The singular vectors were not computed.");
            }

            var x = Matrix<T>.Build.SameAs(U, VT.ColumnCount, input.ColumnCount, fullyMutable: true);
            Solve(input, x);
            return x;
        }

        ///
        /// Solves a system of linear equations, AX = B, with A SVD factorized.
        ///
        /// <param name="input">The right hand side <see cref="Matrix{T}"/>, B.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, X.</param>
        public abstract void Solve(Matrix<T> input, Matrix<T> result);

        ///
        /// Solves a system of linear equations, Ax = b, with A SVD factorized.
        ///
        /// <param name="input">The right hand side vector, b.</param>
        /// <returns>The left hand side <see cref="Vector{T}"/>, x.</returns>
        public virtual Vector<T> Solve(Vector<T> input)
        {
            if (!VectorsComputed)
            {
                throw new InvalidOperationException("The singular vectors were not computed.");
            }

            var x = Vector<T>.Build.SameAs(U, VT.ColumnCount);
            Solve(input, x);
            return x;
        }

        ///
        /// Solves a system of linear equations, Ax = b, with A SVD factorized.
        ///
        /// <param name="input">The right hand side vector, b.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, x.</param>
        public abstract void Solve(Vector<T> input, Vector<T> result);
    }
}


text:
layout: post
title:  "Big Data Solutions"
date:   2017-06-29 15:00:00 +0530
categories: science
author: "Jin Woo Park"
---

Writing informations for personal uses

1. Apache Oozie : server-based workflow scheduling system to manage Hadoop jobs.
2. Sqoop : command-line interface application for transferring data between relational databases and Hadoop.


text:
"""
    Artificial Intelligence for Humans
    Volume 2: Nature-Inspired Algorithms
    Python Version
    http://www.aifh.org
    http://www.jeffheaton.com

    Code repository:
    https://github.com/jeffheaton/aifh

    Copyright 2014 by Jeff Heaton

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    For more information on Heaton Research copyrights, licenses
    and trademarks visit:
    http://www.heatonresearch.com/copyright
    ============================================================================================================
    This example uses crossover to combine two parent genomes to produce two children.
    Both repeating and non-repeating splice are used.

Crossover Splice
Parent 1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Parent 2: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Offspring 1: [1, 2, 3, 4, 5, 6, 4, 3, 2, 1]
Offspring 2: [10, 9, 8, 7, 6, 5, 7, 8, 9, 10]

Crossover Splice No Repeat
Parent 1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Parent 2: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Offspring 1: [10, 3, 2, 4, 5, 6, 7, 8, 9, 1]
Offspring 2: [1, 8, 9, 7, 6, 5, 4, 3, 2, 10]

"""

import sys
import os

# Find the AIFH core files
aifh_dir = os.path.dirname(os.path.abspath(__file__))
aifh_dir = os.path.abspath(aifh_dir + os.sep + ".." + os.sep + "lib" + os.sep + "aifh")
sys.path.append(aifh_dir)

from genetic import *
from genetic import Genome
from genetic import Species

p1 = [ 1,2,3,4,5,6,7,8,9,10 ]
p2 = [ 10,9,8,7,6,5,4,3,2,1 ]
off = [[],[]]

pop = Population()

print("Crossover Splice")
crossover_splice(pop, p1,p2,off)
print("Parent 1: " + str(p1))
print("Parent 2: " + str(p2))
print("Offspring 1: " + str(off[0]))
print("Offspring 2: " + str(off[1]))

print()
print("Crossover Splice No Repeat")
crossover_splice_no_repeat(pop, p1,p2,off)
print("Parent 1: " + str(p1))
print("Parent 2: " + str(p2))
print("Offspring 1: " + str(off[0]))
print("Offspring 2: " + str(off[1]))


text:
package org.languagetool.rules.en;

import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import static tech.units.indriya.unit.Units.*;

/**
 * @since 4.3
 */
public class UnitConversionRuleImperial extends UnitConversionRule {

  public UnitConversionRuleImperial(ResourceBundle messages) {
    super(messages);
    format = NumberFormat.getNumberInstance(Locale.UK);
    format.setMaximumFractionDigits(2);
    format.setRoundingMode(RoundingMode.HALF_UP);

    addUnit("(kilometre|kilometer)s? per hour", KILOMETRE_PER_HOUR, "kilometres per hour", 1, true);

    addUnit("kilomet(re|er)s?", METRE, "kilometres", 1e3, true);
    addUnit("met(re|er)s?", METRE, "metres", 1e0, true);
    addUnit("decimet(re|er)s?", METRE, "decimetres", 1e-1, false/*true*/); // Metric, but not commonly used
    addUnit("centimet(re|er)s?", METRE, "centimetres", 1e-2, true);
    addUnit("millimet(re|er)s?", METRE, "micrometres", 1e-3, true);
    addUnit("micromet(re|er)s?", METRE, "micrometres", 1e-6, true);
    addUnit("nanomet(re|er)s?", METRE, "nanometres", 1e-9, true);

    addUnit("square met(re|er)s?", SQUARE_METRE, "square metres", 1, true);
    addUnit("square kilomet(re|er)s?", SQUARE_METRE, "square kilometres", 1e6, true);
    addUnit("square decimet(re|er)s?", SQUARE_METRE, "square decimetres", 1e-2, false/*true*/); // Metric, but not commonly used
    addUnit("square centimet(re|er)s?", SQUARE_METRE, "square centimetres", 1e-4, true);
    addUnit("square millimet(re|er)s?", SQUARE_METRE, "square millimetres", 1e-6, true);
    addUnit("square micromet(re|er)s?", SQUARE_METRE, "square micrometres", 1e-12, true);
    addUnit("square nanomet(re|er)s?", SQUARE_METRE, "square nanometres", 1e-18, true);

    addUnit("cubic met(re|er)s?", CUBIC_METRE, "cubic metres", 1, true);
    addUnit("cubic kilomet(re|er)s?", CUBIC_METRE, "cubic kilometres", 1e9, true);
    addUnit("cubic decimet(re|er)s?", CUBIC_METRE, "cubic decimetres", 1e-3, false/*true*/); // Metric, but not commonly used
    addUnit("cubic centimet(re|er)s?", CUBIC_METRE, "cubic centimetres", 1e-6, true);
    addUnit("cubic millimet(re|er)s?", CUBIC_METRE, "cubic millimetres", 1e-9, true);
    addUnit("cubic micromet(re|er)s?", CUBIC_METRE, "cubic micrometres", 1e-18, true);
    addUnit("cubic nanomet(re|er)s?", CUBIC_METRE, "cubic nanometres", 1e-27, true);

    addUnit("lit(re|er)s?", LITRE, "litres", 1, true);
    addUnit("millilit(re|er)s?", LITRE, "millilitres", 1e-3, true);

    addUnit("qt\\.", IMP_QUART, "qt.", 1, false);
    addUnit("gal", IMP_GALLON, "gal", 1, false);
    addUnit("pt", IMP_PINT, "pt", 1, false);
    addUnit("(?:fl.? oz.?|oz. fl.)", IMP_FL_OUNCE, "fl oz", 1, false);

    addUnit("quarts?", IMP_QUART, "quarts", 1, false);
    addUnit("gallons?", IMP_GALLON, "gallons", 1, false);
    addUnit("pints?", IMP_PINT, "pints", 1, false);
    addUnit("(fluid )?ounces?", IMP_FL_OUNCE, "fluid ounces", 1, false);
  }

  @Override public String getId() {
    return "METRIC_UNITS_EN_IMPERIAL";
  }

}


text:
struct Command;

class SceneNode : public sf::Transformable,
                  public sf::Drawable,
                  private sf::NonCopyable {
public:
  static unsigned int nSceneNode;
  typedef std::unique_ptr<SceneNode> Ptr;
  typedef std::pair<SceneNode *, SceneNode *> Pair;

public:
  SceneNode();
  void attachChild(Ptr child);
  Ptr detachChild();
  int getNumerOfChild() const;
  virtual unsigned int getId();

  virtual void update(sf::Time dt);
  sf::Vector2f getWorldPosition() const;
  sf::Transform getWorldTransform() const;
  std::vector<sf::Vector2f> getWorldPositionChildren();

  void onCommand(const Command &command);
  virtual unsigned int getCategory() const;

  virtual sf::FloatRect getBoundingRect() const;
  virtual bool isMarkedForRemoval() const;
  virtual bool isDestroyed() const;
  std::vector<unsigned int> getDyingNode(unsigned int category);

  // Check node in different layers
  void checkCollisionWith(SceneNode *node, std::set<Pair> &collisionPairs);
  void removeWrecks();

private:
  virtual void updateCurrent(sf::Time dt);
  void updateChildren(sf::Time dt);

  virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
  virtual void drawCurrent(sf::RenderTarget &target,
                           sf::RenderStates states) const;
  void drawChildren(sf::RenderTarget &target, sf::RenderStates states) const;

private:
  std::vector<Ptr> mChildren;
  SceneNode *mParent;
};

bool collision(const SceneNode &lhs, const SceneNode &rhs);

#endif // SCENENODE_H


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>SolfHelp: Référence de la classe Accueil</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

SolfHelp

Widget d'apprentissage du solfege

Page principale

Classes

Fichiers

          <input type="text" id="MSearchField" value="Recherche" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Liste des classes

Index des classes

Hiérarchie des classes

Membres de classe

 Tout Classes Fonctions Variables

Connecteurs publics |
Fonctions membres publiques |
Liste de tous les membres

Référence de la classe Accueil

Graphe d'héritage de Accueil:

  <map id="Accueil_map" name="Accueil_map">
</map>

Connecteurs publics

void 	doCours ()

 	Fonction qui permet d'accéder à la fenetre de cours.  Plus de détails...

void 	doEntrainement ()

 	Fonction qui permet d'accéder à la fen^etre d'entrainement.  Plus de détails...

void 	doLibre ()

 	Fonction qui permet d'accéder à la fenetre de jeu libre.  Plus de détails...

Fonctions membres publiques

 	Accueil (QStackedWidget *p)

 	Constructeur.  Plus de détails...

void 	ecrireLog (QString s)

 	Fonction qui ouvre le fichier de log afin d'y ajouter la chaine de caractère passée en paramètre.  Plus de détails...

Documentation des constructeurs et destructeur

          void Accueil::Accueil
          (
          QStackedWidget *
          p	)

Constructeur.

Paramètres

p	Pointeur sur la structure de donnée contenant l'ensemble des fenetre, ne peut etre NULL

Documentation des fonctions membres

          void Accueil::doCours
          (
          	)

slot

Fonction qui permet d'accéder à la fenetre de cours.

Renvoie

void

          void Accueil::doEntrainement
          (
          	)

slot

Fonction qui permet d'accéder à la fen^etre d'entrainement.

Renvoie

void

          void Accueil::doLibre
          (
          	)

slot

Fonction qui permet d'accéder à la fenetre de jeu libre.

Renvoie

void

          void Accueil::ecrireLog
          (
          QString
          s	)

Fonction qui ouvre le fichier de log afin d'y ajouter la chaine de caractère passée en paramètre.

Paramètres

s	une chaine de type QString qui sera écrite dans le fichier log, ne peut etre NULL

Renvoie

void

La documentation de cette classe a été générée à partir des fichiers suivants :

accueil.h

accueil.cpp

<address class="footer">
Généré le Dimanche 20 Mars 2016 18:34:56 pour SolfHelp par

 1.8.6
</address>


text:
from flask_app.flask_app import db

class Speed(db.Model):
    __tablename__ = 'speed'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))
    warp = db.Column(db.Float)

    def __init__(self, name=None, warp=None):
        self.name = name
        self.type = type
        self.warp = warp

    def __repr__(self):
        pass


text: Improved intervals for Node.js


text:
require 'poise_python/python_providers/base'

module PoisePython
  module PythonProviders
    # Inversion provider for the `python_runtime` resource to use a fake Python,
    # for use in unit tests.
    #
    # @since 1.1.0
    # @provides dummy
    class Dummy < Base
      provides(:dummy)

      # Enable by default on ChefSpec.
      #
      # @api private
      def self.provides_auto?(node, _resource)
        node.platform?('chefspec')
      end

      # Manual overrides for dummy data.
      #
      # @api private
      def self.default_inversion_options(node, resource)
        super.merge({
          python_binary: ::File.join('', 'python'),
          python_environment: nil,
        })
      end

      # The `install` action for the `python_runtime` resource.
      #
      # @return [void]
      def action_install
        # This space left intentionally blank.
      end

      # The `uninstall` action for the `python_runtime` resource.
      #
      # @return [void]
      def action_uninstall
        # This space left intentionally blank.
      end

      # Path to the non-existent python.
      #
      # @return [String]
      def python_binary
        options['python_binary']
      end

      # Environment for the non-existent python.
      #
      # @return [String]
      def python_environment
        options['python_environment'] || super
      end

    end
  end
end


text:
namespace blink {
class FrameScheduler;

namespace scheduler {

// This enum is used for a histogram (RendererSchedulerFrameOriginType)
// and should not be renumbered.
enum class FrameOriginType {
  kMainFrame = 0,
  kSameOriginToMainFrame = 1,
  kCrossOriginToMainFrame = 2,
  kMaxValue = kCrossOriginToMainFrame,
};

FrameOriginType GetFrameOriginType(FrameScheduler* frame_scheduler);

const char* FrameOriginTypeToString(FrameOriginType origin);

}  // namespace scheduler
}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_FRAME_ORIGIN_TYPE_H_


text:
package main

import (
	"fmt"

	"github.com/google/gxui"
	"github.com/google/gxui/drivers/gl"
	"github.com/google/gxui/math"
	"github.com/google/gxui/samples/flags"
)

// Number picker uses the gxui.DefaultAdapter for driving a list
func numberPicker(theme gxui.Theme, overlay gxui.BubbleOverlay) gxui.Control {
	items := []string{
		"zero", "one", "two", "three", "four", "five",
		"six", "seven", "eight", "nine", "ten",
		"eleven", "twelve", "thirteen", "fourteen", "fifteen",
		"sixteen", "seventeen", "eighteen", "nineteen", "twenty",
	}

	adapter := gxui.CreateDefaultAdapter()
	adapter.SetItems(items)

	layout := theme.CreateLinearLayout()
	layout.SetDirection(gxui.TopToBottom)

	label0 := theme.CreateLabel()
	label0.SetText("Numbers:")
	layout.AddChild(label0)

	dropList := theme.CreateDropDownList()
	dropList.SetAdapter(adapter)
	dropList.SetBubbleOverlay(overlay)
	layout.AddChild(dropList)

	list := theme.CreateList()
	list.SetAdapter(adapter)
	list.SetOrientation(gxui.Vertical)
	layout.AddChild(list)

	label1 := theme.CreateLabel()
	label1.SetMargin(math.Spacing{T: 30})
	label1.SetText("Selected number:")
	layout.AddChild(label1)

	selected := theme.CreateLabel()
	layout.AddChild(selected)

	dropList.OnSelectionChanged(func(item gxui.AdapterItem) {
		if list.Selected() != item {
			list.Select(item)
		}
	})

	list.OnSelectionChanged(func(item gxui.AdapterItem) {
		if dropList.Selected() != item {
			dropList.Select(item)
		}
		selected.SetText(fmt.Sprintf("%s - %d", item, adapter.ItemIndex(item)))
	})

	return layout
}

type customAdapter struct {
	gxui.AdapterBase
}

func (a *customAdapter) Count() int {
	return 1000
}

func (a *customAdapter) ItemAt(index int) gxui.AdapterItem {
	return index // This adapter uses integer indices as AdapterItems
}

func (a *customAdapter) ItemIndex(item gxui.AdapterItem) int {
	return item.(int) // Inverse of ItemAt()
}

func (a *customAdapter) Size(theme gxui.Theme) math.Size {
	return math.Size{W: 100, H: 100}
}

func (a *customAdapter) Create(theme gxui.Theme, index int) gxui.Control {
	phase := float32(index) / 1000
	c := gxui.Color{
		R: 0.5 + 0.5*math.Sinf(math.TwoPi*(phase+0.000)),
		G: 0.5 + 0.5*math.Sinf(math.TwoPi*(phase+0.333)),
		B: 0.5 + 0.5*math.Sinf(math.TwoPi*(phase+0.666)),
		A: 1.0,
	}
	i := theme.CreateImage()
	i.SetBackgroundBrush(gxui.CreateBrush(c))
	i.SetMargin(math.Spacing{L: 3, T: 3, R: 3, B: 3})
	i.OnMouseEnter(func(ev gxui.MouseEvent) {
		i.SetBorderPen(gxui.CreatePen(2, gxui.Gray80))
	})
	i.OnMouseExit(func(ev gxui.MouseEvent) {
		i.SetBorderPen(gxui.TransparentPen)
	})
	i.OnMouseDown(func(ev gxui.MouseEvent) {
		i.SetBackgroundBrush(gxui.CreateBrush(c.MulRGB(0.7)))
	})
	i.OnMouseUp(func(ev gxui.MouseEvent) {
		i.SetBackgroundBrush(gxui.CreateBrush(c))
	})
	return i
}

// Color picker uses the customAdapter for driving a list
func colorPicker(theme gxui.Theme) gxui.Control {
	layout := theme.CreateLinearLayout()
	layout.SetDirection(gxui.TopToBottom)

	label0 := theme.CreateLabel()
	label0.SetText("Color palette:")
	layout.AddChild(label0)

	adapter := &customAdapter{}

	list := theme.CreateList()
	list.SetAdapter(adapter)
	list.SetOrientation(gxui.Horizontal)
	layout.AddChild(list)

	label1 := theme.CreateLabel()
	label1.SetMargin(math.Spacing{T: 30})
	label1.SetText("Selected color:")
	layout.AddChild(label1)

	selected := theme.CreateImage()
	selected.SetExplicitSize(math.Size{W: 32, H: 32})
	layout.AddChild(selected)

	list.OnSelectionChanged(func(item gxui.AdapterItem) {
		if item != nil {
			control := list.ItemControl(item)
			selected.SetBackgroundBrush(control.(gxui.Image).BackgroundBrush())
		}
	})

	return layout
}

func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)

	overlay := theme.CreateBubbleOverlay()

	holder := theme.CreatePanelHolder()
	holder.AddPanel(numberPicker(theme, overlay), "Default adapter")
	holder.AddPanel(colorPicker(theme), "Custom adapter")

	window := theme.CreateWindow(800, 600, "Lists")
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(holder)
	window.AddChild(overlay)
	window.OnClose(driver.Terminate)
	window.SetPadding(math.Spacing{L: 10, T: 10, R: 10, B: 10})
}

func main() {
	gl.StartDriver(appMain)
}


text:
#pragma once

#include "../simple/GenericNode.h"

namespace FilePersistence {

enum class ChangeType {Unclassified, Insertion, Deletion, Move, Stationary};

class FILEPERSISTENCE_API ChangeDescription
{
	public:
		ChangeDescription(GenericNode* nodeA, GenericNode* nodeB);
		~ChangeDescription();

		QString summary() const;

		static std::shared_ptr<ChangeDescription> newStructChange(
				Model::NodeIdType nodeId, std::shared_ptr<ChangeDescription> causingChange,
				std::shared_ptr<GenericTree> treeA, std::shared_ptr<GenericTree> treeB);

		/**
		 * If \a force is true then no check for ID uniqueness is performed.
		 */
		std::shared_ptr<ChangeDescription> copy(std::shared_ptr<GenericTree>& tree, bool force = false) const;

		enum UpdateType
		{
			NoFlags = 0,
			Label = 1,
			Value = 2,
			Type = 4,
			Structure = 8
		};
		Q_DECLARE_FLAGS(UpdateFlags, UpdateType)

		void computeFlags();
		bool hasFlags(const UpdateFlags flags) const;

		void print() const;

		void setStructureChangeFlag(bool value);

		Model::NodeIdType nodeId() const;

		const ChangeType& type() const;

		const UpdateFlags flags() const;

		GenericNode* nodeB() const;
		GenericNode* nodeA() const;

		/**
		 * This is only used for debugging. Do NOT use for other things.
		 */
		bool debugHasNodes();

		/**
		 * Returns \a true for changes that are stationary and have no flags set.
		 */
		bool isFake() const;
		bool onlyStructureChange() const;
		bool onlyLabelChange() const;

	private:
		ChangeDescription();

		Model::NodeIdType nodeId_{};

		ChangeType type_{};

		UpdateFlags updateFlags_{};

		bool pointsToChildA_;
		bool pointsToChildB_;

		// If pointsToChildA_ is true, this is a pointer to a node with parent whose ID is nodeId_.
		// Otherwise, this points to a node with ID = nodeId_. This is a lazy loading mechanic.
		GenericNode* nodeA_{};
		GenericNode* nodeB_{};
};

Q_DECLARE_OPERATORS_FOR_FLAGS(ChangeDescription::UpdateFlags)

inline ChangeDescription::ChangeDescription() {}
inline ChangeDescription::~ChangeDescription() {}

inline Model::NodeIdType ChangeDescription::nodeId() const { return nodeId_; }

inline bool ChangeDescription::hasFlags(const UpdateFlags flags) const { return (updateFlags_ & flags) == flags; }

inline const ChangeType& ChangeDescription::type() const { return type_; }

inline const ChangeDescription::UpdateFlags ChangeDescription::flags() const { return updateFlags_; }

inline bool ChangeDescription::isFake() const
{
	return type_ == ChangeType::Stationary && updateFlags_ == ChangeDescription::NoFlags;
}

inline bool ChangeDescription::onlyStructureChange() const {
	return (type_ == ChangeType::Stationary &&
			  (updateFlags_ == ChangeDescription::Structure ||
			  updateFlags_ == ChangeDescription::NoFlags));
}

inline bool ChangeDescription::onlyLabelChange() const {
	return (type_ == ChangeType::Stationary &&
			  (updateFlags_ == ChangeDescription::Label ||
			  updateFlags_ == ChangeDescription::NoFlags));
}

inline uint qHash(const std::shared_ptr<const ChangeDescription> change, uint seed = 0)
{
	return ::qHash(change.get(), seed);
}

inline bool ChangeDescription::debugHasNodes() { return nodeA_ || nodeB_; }

} /* namespace FilePersistence */