text:
package com.intellij.ide;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * This class is initialized in two class loaders: the bootstrap classloader and the main IDEA classloader. The bootstrap instance
 * has ourMirrorClass initialized by the Bootstrap class; it calls the main instance of itself via reflection.
 *
 * @author yole
 */
public class WindowsCommandLineProcessor {
  // The WindowsCommandLineProcessor class which is loaded in the main IDEA (non-bootstrap) classloader.
  public static Class<?> ourMirrorClass;

  public static WindowsCommandLineListener LISTENER;

  /**
   * NOTE: This method is called through JNI by the Windows launcher. Please do not delete or rename it.
   */
  @SuppressWarnings("unused")
  public static void processWindowsLauncherCommandLine(final String currentDirectory, final String[] args) {
    if (ourMirrorClass != null) {
      try {
        Method method = ourMirrorClass.getMethod("processWindowsLauncherCommandLine", String.class, String[].class);
        method.invoke(null, currentDirectory, args);
      }
      catch (NoSuchMethodException ignored) { }
      catch (InvocationTargetException ignored) { }
      catch (IllegalAccessException ignored) { }
    }
    else {
      if (LISTENER != null) {
        LISTENER.processWindowsLauncherCommandLine(currentDirectory, args);
      }
    }
  }
}


text:
package org.gradle.tooling.model.eclipse;

import org.gradle.tooling.model.DomainObjectSet;
import org.gradle.tooling.model.GradleProject;
import org.gradle.tooling.model.HasGradleProject;
import org.gradle.tooling.model.UnsupportedMethodException;

import javax.annotation.Nullable;

/**
 * The complete model of an Eclipse project.
 *
 *
Note that the names of Eclipse projects are unique, and can be used as an identifier for the project.
 *
 * @since 1.0-milestone-3
 */
public interface EclipseProject extends HierarchicalEclipseProject {
    /**
     * {@inheritDoc}
     */
    EclipseProject getParent();

    /**
     * {@inheritDoc}
     */
    DomainObjectSet<? extends EclipseProject> getChildren();

    /**
     * Returns the Java source settings for this project.
     *
     * @return the settings for Java sources or {@code null} if not a Java element.
     * @throws UnsupportedMethodException For Gradle versions older than 2.10, where this method is not supported.
     * @since 2.10
     */
    @Nullable
    EclipseJavaSourceSettings getJavaSourceSettings() throws UnsupportedMethodException;

    /**
     * The gradle project that is associated with this project.
     * Typically, a single Eclipse project corresponds to a single gradle project.
     *

     * See {@link HasGradleProject}
     *
     * @return associated gradle project
     * @since 1.0-milestone-5
     */
    GradleProject getGradleProject();

    /**
     * Returns the external dependencies which make up the classpath of this project.
     *
     * @return The dependencies. Returns an empty set if the project has no external dependencies.
     * @since 1.0-milestone-3
     */
    DomainObjectSet<? extends EclipseExternalDependency> getClasspath();

    /**
     * Returns the Eclipse natures configured on the project.
     *

     * Some natures are automatically added to the result based on the Gradle plugins applied on the project.
     * For example, if the project applies the 'java' plugin the result will contain the
     * {@code "org.eclipse.jdt.core.javanature"} entry. Note, that the exact list of automatically added
     * natures is not part of the API and can vary between Gradle releases.
     *

     * The result can be customized via the 'eclipse' plugin configuration.
     *
     * @return The list of Eclipse project natures.
     * @since 2.9
     * @throws UnsupportedMethodException For Gradle versions older than 2.9, where this method is not supported.
     */
    DomainObjectSet<? extends EclipseProjectNature> getProjectNatures() throws UnsupportedMethodException;

    /**
     * Returns the Eclipse build commands configured on the project.
     *

     * Some build commands are automatically added to the result based on the Gradle plugins applied on the project.
     * For example, if the project applies the 'java' plugin the result will contain the
     * {@code "org.eclipse.jdt.core.javabuilder"} build command. Note, that the exact list of automatically
     * added build commands is not part of the API and can vary between Gradle releases.
     *

     * The result can be customized via the 'eclipse' plugin configuration.
     *
     * @return The list of Eclipse build commands.
     * @since 2.9
     * @throws UnsupportedMethodException For Gradle versions older than 2.9, where this method is not supported.
     */
    DomainObjectSet<? extends EclipseBuildCommand> getBuildCommands() throws UnsupportedMethodException;

    /**
     * Returns the Eclipse classpath containers defined on the project.
     *
     * @return The list of classpath containers.
     * @since 3.0
     * @throws UnsupportedMethodException For Gradle versions older than 3.0, where this method is not supported.
     */
    DomainObjectSet<? extends EclipseClasspathContainer> getClasspathContainers() throws UnsupportedMethodException;

    /**
     * Returns the output location of this project.
     *
     * @return The project's output location.
     * @since 3.0
     * @throws UnsupportedMethodException For Gradle versions older than 3.0, where this method is not supported.
     */
    EclipseOutputLocation getOutputLocation() throws UnsupportedMethodException;
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://foobar wildH006.xsd http://bar wildH006a.xsd" xmlns="http://foobar" xmlns:foo="http://bar">
	<foo:bar>foo bar</foo:bar>
</foo>


text:
package nl.rivm.cib.episim.persist.hsql;

import java.sql.SQLException;

import org.aeonbits.owner.ConfigCache;
import org.apache.logging.log4j.Logger;
import org.junit.Test;

import io.coala.log.LogUtil;
import io.coala.persist.JDBCConfig;
import io.coala.persist.JDBCUtil;

/**
 * {@link DataSourceHSQLTest}
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
public class DataSourceHSQLTest
{
	/** */
	private static final Logger LOG = LogUtil
			.getLogger( DataSourceHSQLTest.class );

	@Test
	public void testJDBC() throws SQLException, ClassNotFoundException
	{
//		final DataSourceHSQL jdbc = DataSourceHSQL.getInstance();
		final JDBCConfig jdbc = ConfigCache.getOrCreate( JDBCConfig.class );
		jdbc.execute( "CREATE TABLE IF NOT EXISTS "//
				+ "REGISTRATION " //
				+ "(id INTEGER not NULL, " //
				+ " first VARCHAR(255), " //
				+ " last VARCHAR(255), " //
				+ " PRIMARY KEY ( id )" //
				+ ")", rs ->
				{
					LOG.trace( "Created table, result: {}",
							JDBCUtil.toString( rs ) );
				} );

		jdbc.execute( "TRUNCATE TABLE REGISTRATION", rs ->
		{
			LOG.trace( "Cleared table, result: {}", JDBCUtil.toString( rs ) );
		} );

		jdbc.execute( "INSERT INTO REGISTRATION " //
				+ "(id, first, last) " //
				+ "VALUES " //
				+ "(0,'Rick','van Krevelen')" //
				+ ", (1,'Joram','Hoogink')", rs ->
				{
					LOG.trace( "Filled table, result: {}",
							JDBCUtil.toString( rs ) );
				} );

		jdbc.execute( "SELECT * FROM REGISTRATION ", rs ->
		{
			LOG.trace( "Read table, result: {}", JDBCUtil.toString( rs ) );
		} );
	}

}


text:
//---------------------------------------------------------------------
// <copyright file="VocabularyAnnotationCache.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.OData.Service
{
    #region Namespaces

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using Microsoft.OData.Edm;
    using Microsoft.OData.Edm.Annotations;

    #endregion Namespaces

    ///
    /// Represents an annotated EDM model.
    ///
    internal sealed class VocabularyAnnotationCache
    {
        /// The primary model
        private readonly IEdmModel primaryModel;

        /// The unique collection of vocabulary annotatedModels that are either contained in the primary model or that target items in the primary model.
        private readonly HashSet<IEdmVocabularyAnnotation> uniqueAnnotationsStorage = new HashSet<IEdmVocabularyAnnotation>(new AnnotationComparer());

        ///
        /// Initializes a new instance of the VocabularyAnnotationCache class.
        ///
        /// <param name="primaryModel">The primary model the annotatedModels belong to.</param>
        internal VocabularyAnnotationCache(IEdmModel primaryModel)
        {
            Debug.Assert(primaryModel != null, "primaryModel != null");
            this.primaryModel = primaryModel;
        }

        ///
        /// Gets the collection of vocabulary annotatedModels that are either contained in the primary model or that
        /// target items in the primary model. In case of duplicates, the first annotation is taken and the rest are
        /// ignored (i.e. the ordering of the annotation models is significant). Uniqueness of annotatedModels is
        /// determined based on [target, term, qualifier].
        ///
        public IEnumerable<IEdmVocabularyAnnotation> VocabularyAnnotations
        {
            get
            {
                return this.uniqueAnnotationsStorage;
            }
        }

        ///
        /// Searches for vocabulary annotatedModels specified by the primary model or a referenced model (including the annotation models) for a given element.
        ///
        /// <param name="element">The annotated element.</param>
        /// <returns>The vocabulary annotatedModels for the element.</returns>
        public IEnumerable<IEdmVocabularyAnnotation> FindDeclaredVocabularyAnnotations(IEdmVocabularyAnnotatable element)
        {
            return this.VocabularyAnnotations.Where(a => a.Target == element);
        }

        ///
        /// Adds the specified annotation.
        ///
        /// <param name="annotation">The annotation to add.</param>
        internal void Add(IEdmVocabularyAnnotation annotation)
        {
            Debug.Assert(annotation != null, "annotation != null");

            IEdmVocabularyAnnotatable target = annotation.Target;
            if (target != null && IsModelMember(target, this.primaryModel))
            {
                this.uniqueAnnotationsStorage.Add(annotation);
            }
        }

        ///
        /// Populates the annotation cache based on the current configuration of the service.
        /// 1) Adds any annotatedModels specific to the current URL convention.
        /// 2) Invokes the user-provided 'AnnotationsBuilder' delegate.
        ///
        /// <param name="configuration">The service configuration.</param>
        internal void PopulateFromConfiguration(DataServiceConfiguration configuration)
        {
            Debug.Assert(configuration != null, "configuration != null");

            // Add any annotations for the current URL convention.
            this.AddAnnotations(UrlConvention.BuildMetadataAnnotations(configuration.DataServiceBehavior, this.primaryModel));

            IEnumerable<IEdmModel> annotatedModels = null;
            Func<IEdmModel, IEnumerable<IEdmModel>> annotationsBuilder = configuration.AnnotationsBuilder;
            if (annotationsBuilder != null)
            {
                annotatedModels = annotationsBuilder(this.primaryModel);
            }

            // if the delegate was not provided or returned null, stop now.
            if (annotatedModels == null)
            {
                return;
            }

            // add the annotations form each of the models to the vocab cache
            foreach (IEdmModel annotationModel in annotatedModels)
            {
                if (annotationModel == null)
                {
                    throw new InvalidOperationException(Strings.DataServiceProviderWrapper_AnnotationsBuilderCannotReturnNullModels);
                }

                // to avoid issues with the closure, create a local variable to store the model.
                IEdmModel localReferenceToModel = annotationModel;
                this.AddAnnotations(localReferenceToModel.VocabularyAnnotations);
            }
        }

        ///
        /// Checks whether an annotatable item is contained within a given model.
        ///
        /// <param name="item">The annotatable item.</param>
        /// <param name="model">The model to search within.</param>
        /// <returns>A boolean to indicate whether or not the item was found.</returns>
        private static bool IsModelMember(IEdmVocabularyAnnotatable item, IEdmModel model)
        {
            Debug.Assert(item != null, "item != null");
            Debug.Assert(model != null, "model != null");

            IEdmProperty propertyItem;

            if (item is IEdmSchemaElement)
            {
                // note that IEdmEntityContainer is a schema element, so a specific check for it is not needed.
                return model.SchemaElements.Contains(item);
            }

            if ((propertyItem = item as IEdmProperty) != null)
            {
                return model.SchemaElements.Contains((IEdmSchemaElement)propertyItem.DeclaringType);
            }

            if (item is IEdmEntityContainerElement)
            {
                return model.EntityContainer.Elements.Contains(item);
            }

            return false;
        }

        ///
        /// Adds a set of annotations that can be returned when either FindDeclaredVocabularyAnnotations or VocabulationAnnotations are accessed.
        ///
        /// <param name="annotations">The enumerable list of annotations.</param>
        private void AddAnnotations(IEnumerable<IEdmVocabularyAnnotation> annotations)
        {
            foreach (IEdmVocabularyAnnotation annotation in annotations)
            {
                this.Add(annotation);
            }
        }

        /// Equality comparer for IEdmVocabularyAnnotation.
        private class AnnotationComparer : IEqualityComparer<IEdmVocabularyAnnotation>
        {
            /// Determines whether two IEdmVocabularyAnnotations are the same.
            /// <param name="x">First AnnotationDescriptor to compare.</param>
            /// <param name="y">Second AnnotationDescriptor to compare.</param>
            /// <returns>true if both are the same; false otherwise.</returns>
            public bool Equals(IEdmVocabularyAnnotation x, IEdmVocabularyAnnotation y)
            {
                if (x == null || y == null)
                {
                    return (x == null && y == null);
                }

                return x.Target == y.Target &&
                        x.Term.Namespace == y.Term.Namespace &&
                        x.Term.Name == y.Term.Name &&
                        x.Qualifier == y.Qualifier;
            }

            /// Computes hashcode for IEdmVocabularyAnnotation.
            /// <param name="obj">Object to compute hashcode for.</param>
            /// <returns>Computed hashcode.</returns>
            public int GetHashCode(IEdmVocabularyAnnotation obj)
            {
                if (obj != null)
                {
                    int hashCode = obj.Target.GetHashCode() ^ obj.Term.Namespace.GetHashCode() ^ obj.Term.Name.GetHashCode();

                    return (obj.Qualifier != null)
                        ? hashCode ^ obj.Qualifier.GetHashCode()
                        : hashCode;
                }

                return 0;
            }
        }
    }
}


text:
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <core_io.h>

#include <config.h>
#include <consensus/amount.h>
#include <key_io.h>
#include <primitives/blockhash.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sigencoding.h>
#include <script/standard.h>
#include <serialize.h>
#include <streams.h>
#include <undo.h>
#include <util/check.h>
#include <util/strencodings.h>
#include <util/system.h>

#include <univalue.h>

std::string FormatScript(const CScript &script) {
    std::string ret;
    CScript::const_iterator it = script.begin();
    opcodetype op;
    while (it != script.end()) {
        CScript::const_iterator it2 = it;
        std::vector<uint8_t> vch;
        if (script.GetOp(it, op, vch)) {
            if (op == OP_0) {
                ret += "0 ";
                continue;
            }

            if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
                ret += strprintf("%i ", op - OP_1NEGATE - 1);
                continue;
            }

            if (op >= OP_NOP && op < FIRST_UNDEFINED_OP_VALUE) {
                std::string str(GetOpName(op));
                if (str.substr(0, 3) == std::string("OP_")) {
                    ret += str.substr(3, std::string::npos) + " ";
                    continue;
                }
            }

            if (vch.size() > 0) {
                ret += strprintf(
                    "0x%x 0x%x ",
                    HexStr(std::vector<uint8_t>(it2, it - vch.size())),
                    HexStr(std::vector<uint8_t>(it - vch.size(), it)));
            } else {
                ret +=
                    strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
            }

            continue;
        }

        ret +=
            strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
        break;
    }

    return ret.substr(0, ret.size() - 1);
}

const std::map<uint8_t, std::string> mapSigHashTypes = {
    {SIGHASH_ALL, "ALL"},
    {SIGHASH_ALL | SIGHASH_ANYONECANPAY, "ALL|ANYONECANPAY"},
    {SIGHASH_ALL | SIGHASH_FORKID, "ALL|FORKID"},
    {SIGHASH_ALL | SIGHASH_FORKID | SIGHASH_ANYONECANPAY,
     "ALL|FORKID|ANYONECANPAY"},
    {SIGHASH_NONE, "NONE"},
    {SIGHASH_NONE | SIGHASH_ANYONECANPAY, "NONE|ANYONECANPAY"},
    {SIGHASH_NONE | SIGHASH_FORKID, "NONE|FORKID"},
    {SIGHASH_NONE | SIGHASH_FORKID | SIGHASH_ANYONECANPAY,
     "NONE|FORKID|ANYONECANPAY"},
    {SIGHASH_SINGLE, "SINGLE"},
    {SIGHASH_SINGLE | SIGHASH_ANYONECANPAY, "SINGLE|ANYONECANPAY"},
    {SIGHASH_SINGLE | SIGHASH_FORKID, "SINGLE|FORKID"},
    {SIGHASH_SINGLE | SIGHASH_FORKID | SIGHASH_ANYONECANPAY,
     "SINGLE|FORKID|ANYONECANPAY"},
};

std::string SighashToStr(uint8_t sighash_type) {
    const auto &it = mapSigHashTypes.find(sighash_type);
    if (it == mapSigHashTypes.end()) {
        return "";
    }
    return it->second;
}

/**
 * Create the assembly string representation of a CScript object.
 * @param[in] script    CScript object to convert into the asm string
 * representation.
 * @param[in] fAttemptSighashDecode    Whether to attempt to decode sighash
 * types on data within the script that matches the format of a signature. Only
 * pass true for scripts you believe could contain signatures. For example, pass
 * false, or omit the this argument (defaults to false), for scriptPubKeys.
 */
std::string ScriptToAsmStr(const CScript &script,
                           const bool fAttemptSighashDecode) {
    std::string str;
    opcodetype opcode;
    std::vector<uint8_t> vch;
    CScript::const_iterator pc = script.begin();
    while (pc < script.end()) {
        if (!str.empty()) {
            str += " ";
        }

        if (!script.GetOp(pc, opcode, vch)) {
            str += "[error]";
            return str;
        }

        if (0 <= opcode && opcode <= OP_PUSHDATA4) {
            if (vch.size() <= static_cast<std::vector<uint8_t>::size_type>(4)) {
                str += strprintf("%d", CScriptNum(vch, false).getint());
            } else {
                // the IsUnspendable check makes sure not to try to decode
                // OP_RETURN data that may match the format of a signature
                if (fAttemptSighashDecode && !script.IsUnspendable()) {
                    std::string strSigHashDecode;
                    // goal: only attempt to decode a defined sighash type from
                    // data that looks like a signature within a scriptSig. This
                    // won't decode correctly formatted public keys in Pubkey or
                    // Multisig scripts due to the restrictions on the pubkey
                    // formats (see IsCompressedOrUncompressedPubKey) being
                    // incongruous with the checks in
                    // CheckTransactionSignatureEncoding.
                    uint32_t flags = SCRIPT_VERIFY_STRICTENC;
                    if (vch.back() & SIGHASH_FORKID) {
                        // If the transaction is using SIGHASH_FORKID, we need
                        // to set the appropriate flag.
                        // TODO: Remove after the Hard Fork.
                        flags |= SCRIPT_ENABLE_SIGHASH_FORKID;
                    }
                    if (CheckTransactionSignatureEncoding(vch, flags,
                                                          nullptr)) {
                        const uint8_t chSigHashType = vch.back();
                        const auto it = mapSigHashTypes.find(chSigHashType);
                        if (it != mapSigHashTypes.end()) {
                            strSigHashDecode = "[" + it->second + "]";
                            // remove the sighash type byte. it will be replaced
                            // by the decode.
                            vch.pop_back();
                        }
                    }

                    str += HexStr(vch) + strSigHashDecode;
                } else {
                    str += HexStr(vch);
                }
            }
        } else {
            str += GetOpName(opcode);
        }
    }

    return str;
}

std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags) {
    CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags);
    ssTx << tx;
    return HexStr(ssTx);
}

void ScriptToUniv(const CScript &script, UniValue &out, bool include_address) {
    out.pushKV("asm", ScriptToAsmStr(script));
    out.pushKV("hex", HexStr(script));

    std::vector<std::vector<uint8_t>> solns;
    TxoutType type = Solver(script, solns);
    out.pushKV("type", GetTxnOutputType(type));

    CTxDestination address;
    if (include_address && ExtractDestination(script, address) &&
        type != TxoutType::PUBKEY) {
        out.pushKV("address", EncodeDestination(address, GetConfig()));
    }
}

void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out,
                        bool fIncludeHex) {
    TxoutType type;
    std::vector<CTxDestination> addresses;
    int nRequired;

    out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
    if (fIncludeHex) {
        out.pushKV("hex", HexStr(scriptPubKey));
    }

    if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) ||
        type == TxoutType::PUBKEY) {
        out.pushKV("type", GetTxnOutputType(type));
        return;
    }

    out.pushKV("reqSigs", nRequired);
    out.pushKV("type", GetTxnOutputType(type));

    UniValue a(UniValue::VARR);
    for (const CTxDestination &addr : addresses) {
        a.push_back(EncodeDestination(addr, GetConfig()));
    }
    out.pushKV("addresses", a);
}

void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock,
              UniValue &entry, bool include_hex, int serialize_flags,
              const CTxUndo *txundo) {
    entry.pushKV("txid", tx.GetId().GetHex());
    entry.pushKV("hash", tx.GetHash().GetHex());
    // Transaction version is actually unsigned in consensus checks, just
    // signed in memory, so cast to unsigned before giving it to the user.
    entry.pushKV("version",
                 static_cast<int64_t>(static_cast<uint32_t>(tx.nVersion)));
    entry.pushKV("size", (int)::GetSerializeSize(tx, PROTOCOL_VERSION));
    entry.pushKV("locktime", (int64_t)tx.nLockTime);

    UniValue vin{UniValue::VARR};

    // If available, use Undo data to calculate the fee. Note that
    // txundo == nullptr for coinbase transactions and for transactions where
    // undo data is unavailable.
    const bool calculate_fee = txundo != nullptr;
    Amount amt_total_in = Amount::zero();
    Amount amt_total_out = Amount::zero();

    for (unsigned int i = 0; i < tx.vin.size(); i++) {
        const CTxIn &txin = tx.vin[i];
        UniValue in(UniValue::VOBJ);
        if (tx.IsCoinBase()) {
            in.pushKV("coinbase", HexStr(txin.scriptSig));
        } else {
            in.pushKV("txid", txin.prevout.GetTxId().GetHex());
            in.pushKV("vout", int64_t(txin.prevout.GetN()));
            UniValue o(UniValue::VOBJ);
            o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
            o.pushKV("hex", HexStr(txin.scriptSig));
            in.pushKV("scriptSig", o);
        }
        if (calculate_fee) {
            const CTxOut &prev_txout = txundo->vprevout[i].GetTxOut();
            amt_total_in += prev_txout.nValue;
        }
        in.pushKV("sequence", (int64_t)txin.nSequence);
        vin.push_back(in);
    }

    entry.pushKV("vin", vin);

    UniValue vout(UniValue::VARR);
    for (unsigned int i = 0; i < tx.vout.size(); i++) {
        const CTxOut &txout = tx.vout[i];

        UniValue out(UniValue::VOBJ);

        out.pushKV("value", txout.nValue);
        out.pushKV("n", int64_t(i));

        UniValue o(UniValue::VOBJ);
        ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
        out.pushKV("scriptPubKey", o);
        vout.push_back(out);

        if (calculate_fee) {
            amt_total_out += txout.nValue;
        }
    }

    entry.pushKV("vout", vout);

    if (calculate_fee) {
        const Amount fee = amt_total_in - amt_total_out;
        CHECK_NONFATAL(MoneyRange(fee));
        entry.pushKV("fee", fee);
    }

    if (!hashBlock.IsNull()) {
        entry.pushKV("blockhash", hashBlock.GetHex());
    }

    if (include_hex) {
        // The hex-encoded transaction. Used the name "hex" to be consistent
        // with the verbose output of "getrawtransaction".
        entry.pushKV("hex", EncodeHexTx(tx, serialize_flags));
    }
}


text:
using d60.Cirqus.Events;
using d60.Cirqus.PostgreSql;
using d60.Cirqus.PostgreSql.Events;
using d60.Cirqus.Tests.PostgreSql;

namespace d60.Cirqus.Tests.Contracts.EventStore.Factories
{
    public class PostgreSqlEventStoreFactory : IEventStoreFactory
    {
        readonly PostgreSqlEventStore _eventStore;

        public PostgreSqlEventStoreFactory()
        {
            PostgreSqlTestHelper.DropTable("Events");

            var connectionString = PostgreSqlTestHelper.PostgreSqlConnectionString;

            _eventStore = new PostgreSqlEventStore(connectionString, "Events");

            _eventStore.DropEvents();
        }

        public IEventStore GetEventStore()
        {
            return _eventStore;
        }
    }
}


text:
abstract class A[T, @specialized U] {
    def score(state: T): U
}

object B extends A[ Array[Byte], Int ] {
  def score(state: Array[Byte]): Int = {
    var index = 0
    while (index < state.length) { // (index < 2) leads to the #2755 NullPointerException
      if (state(index) == 0) {
        return -1
      }
    }

    return 0
  }
}


text:
using System;

class CompareCharArrays
{
    static void Main()
    {
        //Write a program that compares two char arrays lexicographically (letter by letter)

        Console.Write("Enter lenth N for first array  ");
        int n = int.Parse(Console.ReadLine());
        char[] firstArr = new char[n];
        for (int i = 0; i < firstArr.Length; i++)
        {
            Console.Write("Enter element with index {0}  ", i);
            firstArr[i] = char.Parse(Console.ReadLine());
        }
        Console.Write("Enter lenth M for second array  ");
        int m = int.Parse(Console.ReadLine());
        char[] secondArr = new char[m];
        for (int j = 0; j < secondArr.Length; j++)
        {
            Console.Write("Enter element with index {0}  ", j);
            secondArr[j] = char.Parse(Console.ReadLine());
        }

        if (firstArr.Length != secondArr.Length)
        {
            Console.WriteLine("Two arrays have different lenght.");
        }
        else
        {
            Console.Write("Two arrays have equal lenght ");
        }
        for (int i = 0; i < firstArr.Length; i++)
        {
            if (firstArr[i] != secondArr[i])
            {
                Console.WriteLine("but different elements.");
                break;
            }
        }
        Console.WriteLine("and equal elements.");
    }
}


text:
using System;
using Tt195361.Casl2Simulator.Common;
using Tt195361.Casl2Simulator.Properties;

namespace Tt195361.Casl2Simulator.Casl2
{
    /// <summary>
    /// プログラムの実行開始点についての情報を保持します。
    /// </summary>
    internal class EntryPoint
    {
        #region Instance Fields
        private readonly Label m_execStartLabel;
        private readonly Label m_entryLabel;
        private MemoryAddress m_execStartAddress;
        #endregion

        internal EntryPoint(Label execStartLabel, Label entryLabel)
        {
            m_execStartLabel = execStartLabel;
            m_entryLabel = entryLabel;
            m_execStartAddress = MemoryAddress.Zero;
        }

        /// <summary>
        /// 実行開始番地を参照するラベルを取得します。
        /// </summary>
        internal Label ExecStartLabel
        {
            get { return m_execStartLabel; }
        }

        /// <summary>
        /// 他のプログラムから入口名として参照できるラベルを取得します。
        /// </summary>
        internal Label EntryLabel
        {
            get { return m_entryLabel; }
        }

        /// <summary>
        /// 実行開始アドレスを取得します。
        /// </summary>
        internal MemoryAddress ExecStartAddress
        {
            get { return m_execStartAddress; }
        }

        /// <summary>
        /// 実行開始番地を参照するラベルのアドレスを解決し、実行開始アドレスを設定します。
        /// </summary>
        /// <param name="lblTable">
        /// 再配置可能モジュールで定義されたラベルを管理する <see cref="LabelTable"/> のオブジェクトです。
        /// </param>
        internal void ResolveExecStartAddress(LabelTable lblTable)
        {
            LabelDefinition labelDef = GetExecStartLabelDefinition(lblTable);
            m_execStartAddress = labelDef.AbsAddress;
        }

        private LabelDefinition GetExecStartLabelDefinition(LabelTable lblTable)
        {
            try
            {
                return lblTable.GetDefinitionFor(m_execStartLabel);
            }
            catch (Exception innerEx)
            {
                String message = String.Format(
                    Resources.MSG_CouldNotGetExecStartLabelDefinition, m_execStartLabel);
                throw new Casl2SimulatorException(message, innerEx);
            }
        }

        public override String ToString()
        {
            return String.Format(
                "ExecStart={0}: {1}, Entry={2}", m_execStartLabel, m_execStartAddress, m_entryLabel);
        }

        internal void SetExecStartAddressForUnitTest(MemoryAddress execStartAddress)
        {
            m_execStartAddress = execStartAddress;
        }
    }
}


text:
"""

File: step_sequence_policy.py

Purpose: Ordered list of notes that vary by a number of diatonic steps.

"""
from melody.constraints.abstract_constraint import AbstractConstraint
from structure.note import Note
from tonalmodel.pitch_scale import PitchScale
from misc.ordered_set import OrderedSet

class StepSequenceConstraint(AbstractConstraint):
    """
    Multi-note constraint that in sequence varies each to each by a number of diatonic steps.
    """

    def __init__(self, note_sequence, variance_list):
        """
        Constructor.
        :param note_sequence: list of v_notes that vary in sequence by a number of diatonic steps.
        :param variance_list:  list of numbers representing variances.
        Note: len(variance_list) = len(note_sequence) - 1
        """
        AbstractConstraint.__init__(self, note_sequence)
        if len(note_sequence) <= 1:
            raise Exception('StepSequencePolicy must have two or v-more notes.')
        if len(note_sequence) - 1 != len(variance_list):
            raise Exception("Illegan size for variance list")

        self._variance_list = variance_list

    @property
    def variance_list(self):
        return self._variance_list

    def clone(self, new_actors=None):
        return StepSequenceConstraint(new_actors if new_actors is not None else self.actors,
                                      self.variance_list)

    def verify(self, p_map):
        """

        :param p_map:
        :return:
        """
        notes = self.actors
        for v_note in notes:
            if v_note not in p_map:
                raise Exception('Improper parameter map in equal note constraints.')
            if p_map[v_note].note is None:
                return False

        # We compare diatonic distances, as the notes may be enharmonic due to differing tonalities.
        for i in range(0, len(notes) - 1):
            if p_map[notes[i + 1]].note.diatonic_pitch.diatonic_distance() - \
                    p_map[notes[i]].note.diatonic_pitch.diatonic_distance() != self.variance_list[i]:
                return False
        return True

    def values(self, p_map, v_note):
        """

        :param p_map:
        :param v_note:
        :return:
        """

        index = self.actors.index(v_note) if v_note in self.actors else None
        if index is None:
            raise Exception('Cannot find v_note in constraints actors')

        if p_map[v_note].note is not None:
            return OrderedSet([p_map[v_note].note])

        # find the first assigned note
        assigned_index = None
        for i in range(0, len(self.actors)):
            if p_map[self.actors[i]].note is not None:
                assigned_index = i
                break

        if assigned_index is None:
            pitches = p_map.all_tonal_pitches(v_note)
            return OrderedSet([Note(p, v_note.base_duration, v_note.num_dots) for p in pitches])

        known_note = p_map[self.actors[assigned_index]].note
        if assigned_index < index:
            for i in range(assigned_index + 1, index + 1):
                unknown_contextual_note = p_map[self.actors[i]]
                unknown_note = unknown_contextual_note.note
                if unknown_note is not None:
                    known_note = unknown_note
                    continue

                lower_index = self.variance_list[i - 1] if self.variance_list[i - 1] < 0 else 0
                upper_index = self.variance_list[i - 1] if self.variance_list[i - 1] > 0 else 0
                pitches = PitchScale.compute_tonal_pitch_range(
                    unknown_contextual_note.policy_context.harmonic_context.tonality,
                    known_note.diatonic_pitch, lower_index, upper_index)
                pitch_index = self.variance_list[i - 1] + (len(pitches) - 1 if self.variance_list[i - 1] < 0 else 0)
                if pitch_index < 0 or pitch_index >= len(pitches):
                    if pitches is None or len(pitches) == 0:
                       return OrderedSet()
                    pitch = pitches[0] if pitch_index < 0 else pitches[len(pitches) - 1]
                else:
                    pitch = pitches[pitch_index]
                known_note = Note(pitch, self.actors[i].base_duration, self.actors[i].num_dots)
            return OrderedSet([known_note])

        for i in range(assigned_index - 1, index - 1, -1):
            unknown_contextual_note = p_map[self.actors[i]]
            unknown_note = unknown_contextual_note.note
            if unknown_note is not None:
                known_note = unknown_note
                continue

            upper_index = -self.variance_list[i] if self.variance_list[i] < 0 else 0
            lower_index = -self.variance_list[i] if self.variance_list[i] > 0 else 0
            pitches = PitchScale.compute_tonal_pitch_range(
                unknown_contextual_note.policy_context.harmonic_context.tonality,
                known_note.diatonic_pitch, lower_index, upper_index)
            pitch_index = -self.variance_list[i] + (len(pitches) - 1 if self.variance_list[i] > 0 else 0)
            if pitch_index < 0:
                pitch_index = 0
            elif pitch_index >= len(pitches):
                pitch_index = len(pitches) - 1
            pitch = pitches[pitch_index]
            known_note = Note(pitch, self.actors[i].base_duration, self.actors[i].num_dots)
        return OrderedSet([known_note])


text:
package org.apache.lucene.analysis.hunspell;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Collections;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.KeywordTokenizer;
import org.apache.lucene.analysis.hunspell.Dictionary;
import org.apache.lucene.analysis.hunspell.HunspellStemFilter;
import org.apache.lucene.analysis.miscellaneous.SetKeywordMarkerFilter;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.util.IOUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;

public class TestHunspellStemFilter extends BaseTokenStreamTestCase {
  private static Dictionary dictionary;

  @BeforeClass
  public static void beforeClass() throws Exception {
    InputStream affixStream = TestStemmer.class.getResourceAsStream("simple.aff");
    InputStream dictStream = TestStemmer.class.getResourceAsStream("simple.dic");
    try {
      dictionary = new Dictionary(affixStream, dictStream);
    } finally {
      IOUtils.closeWhileHandlingException(affixStream, dictStream);
    }
  }

  @AfterClass
  public static void afterClass() {
    dictionary = null;
  }

  /** Simple test for KeywordAttribute */
  public void testKeywordAttribute() throws IOException {
    MockTokenizer tokenizer = new MockTokenizer(new StringReader("lucene is awesome"));
    tokenizer.setEnableChecks(true);
    HunspellStemFilter filter = new HunspellStemFilter(tokenizer, dictionary);
    assertTokenStreamContents(filter, new String[]{"lucene", "lucen", "is", "awesome"}, new int[] {1, 0, 1, 1});

    // assert with keyword marker
    tokenizer = new MockTokenizer(new StringReader("lucene is awesome"));
    CharArraySet set = new CharArraySet( Arrays.asList("Lucene"), true);
    filter = new HunspellStemFilter(new SetKeywordMarkerFilter(tokenizer, set), dictionary);
    assertTokenStreamContents(filter, new String[]{"lucene", "is", "awesome"}, new int[] {1, 1, 1});
  }

  /** simple test for longestOnly option */
  public void testLongestOnly() throws IOException {
    MockTokenizer tokenizer = new MockTokenizer(new StringReader("lucene is awesome"));
    tokenizer.setEnableChecks(true);
    HunspellStemFilter filter = new HunspellStemFilter(tokenizer, dictionary, true, true);
    assertTokenStreamContents(filter, new String[]{"lucene", "is", "awesome"}, new int[] {1, 1, 1});
  }

  /** blast some random strings through the analyzer */
  public void testRandomStrings() throws Exception {
    Analyzer analyzer = new Analyzer() {
      @Override
      protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
        return new TokenStreamComponents(tokenizer, new HunspellStemFilter(tokenizer, dictionary));
      }
    };
    checkRandomData(random(), analyzer, 1000*RANDOM_MULTIPLIER);
  }

  public void testEmptyTerm() throws IOException {
    Analyzer a = new Analyzer() {
      @Override
      protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        Tokenizer tokenizer = new KeywordTokenizer(reader);
        return new TokenStreamComponents(tokenizer, new HunspellStemFilter(tokenizer, dictionary));
      }
    };
    checkOneTerm(a, "", "");
  }

  public void testIgnoreCaseNoSideEffects() throws Exception {
    final Dictionary d;
    InputStream affixStream = TestStemmer.class.getResourceAsStream("simple.aff");
    InputStream dictStream = TestStemmer.class.getResourceAsStream("simple.dic");
    try {
      d = new Dictionary(affixStream, Collections.singletonList(dictStream), true);
    } finally {
      IOUtils.closeWhileHandlingException(affixStream, dictStream);
    }
    Analyzer a = new Analyzer() {
      @Override
      protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        Tokenizer tokenizer = new KeywordTokenizer(reader);
        return new TokenStreamComponents(tokenizer, new HunspellStemFilter(tokenizer, d));
      }
    };
    checkOneTerm(a, "NoChAnGy", "NoChAnGy");
  }
}


text:
require 'spec_helper'

describe Mongify::Mongoid::Printer do
  let(:output_dir){File.expand_path('../../../files/tmp', File.dirname(__FILE__))}
  subject(:printer){ Mongify::Mongoid::Printer.new([], output_dir) }
  it "should write" do
    expect { printer.write }.to_not raise_error
  end

  context "file output" do
    let(:model){Mongify::Mongoid::Model.new(table_name: "users", class_name: "User")}
    subject(:printer){ Mongify::Mongoid::Printer.new({user: model}, output_dir) }

    context "content" do
      before(:each) do
        printer.stub(:save_file)
      end
      it "should be include a class" do
        output = printer.send(:render_file, model)
        output.should include("class #{model.name}")
      end
      it "should have fields" do
        model.stub(:fields).and_return({first_name: Mongify::Mongoid::Model::Field.new("first_name", "String")})
        output = printer.send(:render_file, model)
        output.should include("field :first_name, type: String")
      end

      it "should have relations" do
        model.stub(:relations).and_return([Mongify::Mongoid::Model::Relation.new(:embedded_in, "posts")])
        output = printer.send(:render_file, model)
        output.should include("embedded_in :posts")
      end

      it "should sort relations" do
        model.stub(:relations).and_return([
          Mongify::Mongoid::Model::Relation.new(:embeds_many, "posts"),
          Mongify::Mongoid::Model::Relation.new(:has_many, "comments"),
          Mongify::Mongoid::Model::Relation.new(:embeds_many, "addons"),
          ])
        output = printer.send(:render_file, model)
        output.gsub(/^(\s+)/, "").should include(%q{
embeds_many :posts
embeds_many :addons
has_many :comments})
      end
    end

    it "should create a file" do
      printer.write
      Dir["#{output_dir}/*.rb"].count { |file| File.file?(file) }.should == printer.models.count
    end
  end
  after(:each) do
    FileUtils.rm  Dir["#{output_dir}/*.rb"]
  end
end


text:
package edu.latrobe.blaze.modules.generic

import edu.latrobe.blaze._
import edu.latrobe.blaze.modules._

object SReLU_Generic_Baseline_Description
  extends GenericModuleVariantDescriptionEx[SReLUBuilder] {

  override def generateBuilder(builder: SReLUBuilder, hints: BuildHints)
  : SequenceBuilder = {
    val a = {
      val tmp = AddValuesBuilder(
        TensorDomain.Batch,
        -builder.threshold
      )
      builder.copyTo(tmp)
      tmp
    }
    val b = {
      val tmp = ReLUBuilder()
      builder.copyTo(tmp)
      tmp
    }
    val c = {
      val tmp = AddValuesBuilder(
        TensorDomain.Batch,
        builder.threshold
      )
      builder.copyTo(tmp)
      tmp
    }
    SequenceBuilder(a, b, c, ChangePlatformPreferenceBuilder(hints.platform))
  }

}


text:
package com.hqw.bleproxy.protocol;

import android.util.Log;

import com.google.protobuf.InvalidProtocolBufferException;
import com.hqw.bleproxy.BLEHelper;
import com.hqw.bleproxy.LogUtil;
import com.hqw.bleproxy.StringUtil;
import com.hqw.bleproxy.net.ProxyServer;

/**
 * Created by Administrator on 2015/10/23.
 */
public class ProtocolHandler {

    private static final String TAG = ProtocolHandler.class.getSimpleName();

    private ProxyServer mProxyServer;
    private BLEHelper.OnBleListener mListener = new BLEHelper.OnBleListener() {
        @Override
        public void onScanResult(String deviceName, String address, int rssi) {
            LogUtil.d(TAG, "deviceName: " + deviceName + ", address: " + address + ", rssi: " + rssi);
            mProxyServer.send(ProtocolPacker.getInstance().getScanResultMsgBuff(deviceName, address,rssi));
        }

        @Override
        public void onConnectResult(boolean result, String address) {
            mProxyServer.send(ProtocolPacker.getInstance().getConnectResultMsgBuff(result, address, ""));
        }

        @Override
        public void onDisconnected() {
            mProxyServer.send(ProtocolPacker.getInstance().getBleDisconnectMsgBuff(""));
        }

        @Override
        public void onDataReceived(byte[] data) {
            LogUtil.d(TAG, "received: " + StringUtil.bytesToHexString(data));
            sendToClient(data);
        }
    };

    public ProtocolHandler(ProxyServer proxyServer) {
        BLEHelper.getInstance().setOnBleListener(mListener);
        mProxyServer = proxyServer;
    }

    private BleProxy.BleProxyMsg parseMsg(byte[] msgBuff) {
        try {
            BleProxy.BleProxyMsg bleProxyMsg = BleProxy.BleProxyMsg.parseFrom(msgBuff);
            return bleProxyMsg;
        } catch (InvalidProtocolBufferException e) {
            //e.printStackTrace();
            return null;
        }
    }

    public boolean handleMsg(byte[] msgBuff) {
        BleProxy.BleProxyMsg bleProxyMsg = parseMsg(msgBuff);
        if(bleProxyMsg == null) {
            LogUtil.e(TAG, "parseMsg error");
            return false;
        }

        LogUtil.d(TAG, "parseMsg success");
        switch (bleProxyMsg.getCmd().getNumber()) {
            case BleProxy.ProxyMsgCmd.CONTROL_VALUE:
                onControlMsg(bleProxyMsg.getControl());
                break;

            case BleProxy.ProxyMsgCmd.CONNECT_VALUE:
                onConnect(bleProxyMsg.getConnect());
                break;

            case BleProxy.ProxyMsgCmd.DISCONNECT_VALUE:
                onDisconnect(bleProxyMsg.getDisconnect());
                break;

            case BleProxy.ProxyMsgCmd.PROXY_DATA_VALUE:
                onSend(bleProxyMsg.getProxyData());
                break;

            default:
                break;
        }
        return true;
    }

    private void onControlMsg(final BleProxy.Control controlMsg) {
        LogUtil.d(TAG, "onControl");
        switch (controlMsg.getCmd().getNumber()) {
            case BleProxy.ControlCmd.START_SCAN_VALUE:
                onStartScan();
                break;

            case BleProxy.ControlCmd.STOP_SCAN_VALUE:
                onStopScan();
                break;
        }
    }

    private void onStartScan() {
        LogUtil.d(TAG, "on start scan");
        BLEHelper.getInstance().btStartScan();
    }

    private void onStopScan() {
        LogUtil.d(TAG, "on stop scan");
        BLEHelper.getInstance().btStopScan();
    }

    private void onConnect(BleProxy.Connect connectMsg) {
        LogUtil.d(TAG, "on connect device: " + connectMsg.getAddress());
        if(!BLEHelper.getInstance().btConnect(null, connectMsg.getAddress())) {
            mProxyServer.send(ProtocolPacker.getInstance().getConnectResultMsgBuff(false, connectMsg.getAddress(), ""));
        } else {
            // attention: even btConnect return true, we are not sure weather it's connected
            // we need broadcast
        }
    }

    private void onDisconnect(BleProxy.Disconnect disconnect) {
        LogUtil.d(TAG, "disconnect ble device: " + disconnect.getAddress());
        BLEHelper.getInstance().btDisconnect(disconnect.getAddress());
    }

    private void onSend(BleProxy.ProxyData proxyData) {
        LogUtil.d(TAG, "on Send");
        byte[] data = proxyData.getData().toByteArray();
        BLEHelper.getInstance().btSend(null, data);
    }

    private void sendToClient(byte[] data) {
        mProxyServer.send(ProtocolPacker.getInstance().getProxyDataMsgBuff(data));
    }
}


text:
YUI.add('app-regions', function (Y, NAME) {

var Lang = Y.Lang;

function AppRegions() { }

AppRegions.ATTRS = {
    regions: {
        setter: '_setRegions',
        value: false
    }
};

/*

*/
AppRegions.prototype = {
    initializer: function() {

    },
    //TODO: Not sure on the naming
    showView: function (view, config, options, callback) {
        /*jshint expr: true */

        var viewInfo, created, regions, region;
        regions = this.get('regions');
        options || (options = {});
        Y.log('showing Alt View' + view + ' in region ' + region);
        // Support the callback function being either the fourth or fifth arg.
        if (callback) {
            options = Y.merge(options, { callback: callback });
        } else if (Lang.isFunction(options)) {
            options = { callback: options };
        }

        if (Lang.isString(view)) {
            viewInfo = this.getViewInfo(view);
            if (viewInfo && viewInfo.preserve && viewInfo.instance) {
                view = viewInfo.instance;

                // Make sure there's a mapping back to the view metadata.
                this._viewInfoMap[Y.stamp(view, true)] = viewInfo;
            } else {
                view = this.createView(view, config);
                created = true;
            }
        }

        // Update the specified or preserved `view` when signaled to do so.
        // There's no need to updated a view if it was _just_ created.
        if (options.update && !created) {
            view.setAttrs(config);
        }
        if ('render' in options) {
            if (options.render) {
                view.render();
            }
        } else if (created) {
            view.render();
        }

        return this._set(region +'View', view, { options: options });
    },
    //TODO: Not sure on the naming
    showViewInRegion: function (region, view, config, options, callback) {
        /*jshint expr: true */
        Y.log('showing Alt View' + view + ' in region ' + region);
        var viewInfo, created;

        options || (options = {});

        // Support the callback function being either the fourth or fifth arg.
        if (callback) {
            options = Y.merge(options, { callback: callback });
        } else if (Lang.isFunction(options)) {
            options = { callback: options };
        }

        if (Lang.isString(view)) {
            viewInfo = this.getViewInfo(view);
            if (viewInfo && viewInfo.preserve && viewInfo.instance) {
                view = viewInfo.instance;

                // Make sure there's a mapping back to the view metadata.
                this._viewInfoMap[Y.stamp(view, true)] = viewInfo;
            } else {
                view = this.createView(view, config);
                created = true;
            }
        }

        // Update the specified or preserved `view` when signaled to do so.
        // There's no need to updated a view if it was _just_ created.
        if (options.update && !created) {
            view.setAttrs(config);
        }
        if ('render' in options) {
            if (options.render) {
                view.render();
            }
        } else if (created) {
            view.render();
        }

        return this._set(region +'View', view, { options: options });
    },
    _setRegions: function(regions) {
        var defRegions = this.regions;
        if (regions && regions === true) {
            return Y.merge(defRegions);
        }
        return regions;
    }
};

// -- Namespace ----------------------------------------------------------------
Y.App.AppRegions = AppRegions;
Y.Base.mix(Y.App, [AppRegions]);

}, '@VERSION@', {"requires": ["app-base"]});


text:
package com.castlemock.model.core.validation.validator;

import com.castlemock.model.core.Input;
import com.castlemock.model.core.Message;
import com.castlemock.model.core.Output;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * The Validator is used to check and enforce validation rules. The rules are applied to {@link Message} classes,
 * such as {@link Input} or {@link Output}.
 * @author Karl Dahlgren
 * @since 1.0
 * @see Message
 */
public abstract class Validator {

    private Class<? extends Annotation> validationType;
    protected Validator(Class<? extends Annotation> validationType){
        this.validationType = validationType;
    }

    /**
     * The method is responsible for checking if a message contains annotations that the validator is
     * responsible for validating or enforce.
     * @param message The message the will be validated.
     * @throws NullPointerException If the provided message is null
     */
    public void validateMessage(final Message message){
        if(message == null){
            throw new NullPointerException("The message cannot be null");
        }

        final Class<?> messageClass = message.getClass();
        for(Field field : messageClass.getDeclaredFields()){
            if(field.isAnnotationPresent(validationType)){
                validateMessage(message, field.getName());
            }
        }
    }

    /**
     * The method is responsible for validating a provided message and enforce the rule that the
     * validator is responsible for
     * @param message The message that will be validated
     * @param field The specific field that will be validated
     */
    protected abstract void validateMessage(final Message message, final String field);

}


text:
#include "StdAfx.h"
#include "FUTestBed.h"
#include "FUFileManager.h"
#include "FUUri.h"
#if defined(WIN32)
	#include <direct.h>
#endif // WIN32

inline bool PlatformEquivalent(fstring& f, const fchar* check)
{
#ifdef WIN32
    return IsEquivalent(f, check);
#else
    fstring p = check;
    p.replace('\\', '/');
    return IsEquivalent(f, p);
#endif // WIN32
}

TESTSUITE_START(FUFileManager)

TESTSUITE_TEST(0, Substrings)
const size_t testFilenameCount = 6;
const fchar* testFilenames[testFilenameCount] = {
    FC("C:\\TestFolder\\TestFile.dae"),
    FC("/UnixFolder/AbsoluteFile.dae"),
    FC("\\\\WindowsUNCPath/NetworkFolder/SomeFile.dae"),
    FC("file:///strangeURI"),
    FC("/UnixFolder/UnixFolder.AnnoyingExtension/SomeFileWithoutExtension"),
    FC("file://www.someweb.com/index")
};

for (size_t i = 0; i < testFilenameCount; ++i)
{
    // Check the ExtractNetworkHostname function
    fstring filename = testFilenames[i];
    fstring hostname = FUFileManager::ExtractNetworkHostname(filename);

    static const fchar* checkFilenameReferences[testFilenameCount] = {
        FC("C:\\TestFolder\\TestFile.dae"),
        FC("/UnixFolder/AbsoluteFile.dae"),
#ifdef WIN32
        FC("/NetworkFolder/SomeFile.dae"),
#else // WIN32
        FC("\\\\WindowsUNCPath/NetworkFolder/SomeFile.dae"),
#endif // WIN32
        FC("file:///strangeURI"),
        FC("/UnixFolder/UnixFolder.AnnoyingExtension/SomeFileWithoutExtension"),
        FC("file://www.someweb.com/index")
    };

#ifdef WIN32
    static const fchar* checkHostnames[testFilenameCount] =
    { FC(""), FC(""), FC("WindowsUNCPath"), FC(""), FC(""), FC("") };
#else // WIN32
    static const fchar* checkHostnames[testFilenameCount] =
    { FC(""), FC(""), FC(""), FC(""), FC(""), FC("") };
#endif // WIN32

    PassIf(IsEquivalent(filename, checkFilenameReferences[i]));
    PassIf(IsEquivalent(hostname, checkHostnames[i]));

    // Check the GetFileExtension function
    fstring extension = FUFileManager::GetFileExtension(testFilenames[i]);

    static const fchar* checkExtensions[testFilenameCount] =
    { FC("dae"), FC("dae"), FC("dae"), FC(""), FC(""), FC("") };
    PassIf(IsEquivalent(extension, checkExtensions[i]));

    // Check the StripFileFromPath function
    filename = FUFileManager::StripFileFromPath(testFilenames[i]);
    static const fchar* checkStrippedFile[testFilenameCount] =
    { FC("C:\\TestFolder\\"), FC("/UnixFolder/"), FC("\\\\WindowsUNCPath/NetworkFolder/"),
      FC("file:///"), FC("/UnixFolder/UnixFolder.AnnoyingExtension/"), FC("file://www.someweb.com/") };
    PassIf(IsEquivalent(filename, checkStrippedFile[i]));
}

TESTSUITE_TEST(1, BasicFileManagement)
FUFileManager manager;

// Verify that the 'localhost' hostname is dropped.
fstring f = FC("file://localhost/rootFolder/testFile.dae");
f = FUUri(f).GetAbsolutePath();
PassIf(PlatformEquivalent(f, FC("\\rootFolder\\testFile.dae")));

TESTSUITE_TEST(2, RelativePaths)
// Verify the relative file path generation for local files
FUFileManager manager;
manager.PushRootFile(FC("C:\\AFolder\\AFolder.D\\AFile"));
fstring f = manager.GetCurrentUri().MakeRelative(FC("D:\\BPath\\BFile"));
f = FUUri(f).GetAbsolutePath();
PassIf(PlatformEquivalent(f, FC("D:\\BPath\\BFile")));

f = manager.GetCurrentUri().MakeRelative(FC("\\BPath\\BFile"));
PassIf(PlatformEquivalent(f, FC("\\BPath\\BFile")));

#ifdef WIN32
// Verify drive-aware relative path generation.
f = manager.GetCurrentUri().MakeRelative(FC("\\AFolder\\AFolder.D\\BFile"));
PassIf(PlatformEquivalent(f, FC(".\\BFile")));

f = manager.GetCurrentUri().MakeRelative(FC("\\AFolder\\BFile"));
PassIf(PlatformEquivalent(f, FC("..\\BFile")));

f = manager.GetCurrentUri().MakeRelative(FC("..\\AFolder.D\\BFile"));
// [glaforte 21-07-2006] might be optimization possible, although the current output is not wrong.
PassIf(PlatformEquivalent(f, FC(".\\BFile")));
#endif

f = manager.GetCurrentUri().MakeRelative(FC("\\\\AFolder\\AFile"));
PassIf(PlatformEquivalent(f, FC("\\\\AFolder\\AFile")));

#ifndef WIN32
// Verify the relative file path generation with a Unix file as the root
manager.PopRootFile();
manager.PushRootFile(FC("/ARoot/AFolder/AFolder.D/AFile"));
f = manager.GetCurrentUri().MakeRelative(FC("/ARoot/AFolder/AFolder.D/FileG"));
PassIf(PlatformEquivalent(f, FC("./FileG")));

f = manager.GetCurrentUri().MakeRelative(FC("/ARoot/AFolder/TestOut.pdg"));
PassIf(PlatformEquivalent(f, FC("../TestOut.pdg")));
#endif // WIN32

// Verify the relative file path generation with a network file as the root
manager.PopRootFile();
manager.PushRootFile(FC("\\\\ANetwork\\AFolder\\AFolder.D\\AFile"));
FUUri uri(manager.GetCurrentUri().MakeRelative(FC("C:\\BLocal\\BFolder\\AFile")));
f = uri.GetAbsolutePath();
PassIf(PlatformEquivalent(f, FC("C:\\BLocal\\BFolder\\AFile")));

f = manager.GetCurrentUri().MakeRelative(FC("\\\\ANetwork\\AFolder\\BFile"));
PassIf(PlatformEquivalent(f, FC("..\\BFile")));

// Verify the relative file path generation when the root has no drive letter
manager.PushRootFile(FC("\\ARootFolder\\BFile"));
uri = FUUri(FC("A:\\ARootFolder\\CFile"));
f = uri.GetAbsolutePath();
PassIf(PlatformEquivalent(f, FC("A:\\ARootFolder\\CFile")));

f = manager.GetCurrentUri().MakeRelative(FC("BPureRelative\\CFile"));
PassIf(PlatformEquivalent(f, FC(".\\BPureRelative\\CFile")));

TESTSUITE_TEST(3, AbsolutePaths)
#ifdef WIN32
char currentPath[1024];
_getcwd(currentPath, 1023);
currentPath[1023] = 0;
fchar driveLetter = (fchar)toupper(currentPath[0]);
#endif // WIN32

// Verify the relative file path generation for local files
FUFileManager manager;
manager.PushRootFile(FC("C:\\AFolder\\AFolder.D\\AFile"));
fstring f = manager.GetCurrentUri().MakeAbsolute(FC(".\\BFile"));
#ifdef WIN32
PassIf(PlatformEquivalent(f, FC("C:\\AFolder\\AFolder.D\\BFile")));
#else
PassIf(PlatformEquivalent(f, FC("\\C:\\AFolder\\AFolder.D\\BFile")));
#endif // WIN32

manager.PopRootFile();
manager.PushRootFile(FC("\\AFolder\\AFolder.D\\AFile"));
f = manager.GetCurrentUri().MakeAbsolute(FC("..\\BFile.S"));
#ifdef WIN32
fstring check = FC("C:\\AFolder\\BFile.S");
check[0] = driveLetter;
PassIf(PlatformEquivalent(f, check.c_str()));
#else
PassIf(PlatformEquivalent(f, FC("\\AFolder\\BFile.S")));
#endif // WIN32

TESTSUITE_TEST(4, URI_Generation)
// Verify the URI generation with respect to a local file
FUFileManager manager;

#ifdef WIN32
manager.PushRootFile(FC("C:\\AFolder\\AFolder.D\\AFile"));
FUUri uri(FC("C:\\AFolder\\AFolder.D\\BFile"));
fstring f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("./BFile"));
uri = FUUri(FC("C:\\AFolder\\AFolder.D\\BFile"));
f = uri.GetAbsoluteUri();
PassIf(f == FC("file:///C:/AFolder/AFolder.D/BFile"));
#else
manager.PushRootFile(FC("/AFolder/AFolder.D/AFile"));
FUUri uri(FC("/AFolder/AFolder.D/BFile"));
fstring f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("./BFile"));
uri = FUUri(FC("/AFolder/AFolder.D/BFile"));
f = uri.GetAbsoluteUri();
//	fstring f1 = uri.GetAbsoluteUri();
//	wchar_t* blah = f1.c_str();
PassIf(f == FC("file:///AFolder/AFolder.D/BFile"));
#endif

#ifdef WIN32
uri = FUUri(FC("\\\\BNetwork\\BFolder\\BFile"));
f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("file://BNetwork/BFolder/BFile"));
uri = FUUri(FC("\\\\BNetwork\\BFolder\\BFile"));
f = uri.GetAbsoluteUri();
PassIf(f == FC("file://BNetwork/BFolder/BFile"));
#endif // WIN32

#ifdef WIN32
uri = FUUri(FC("file:///C:/AFolder/BFolder/BFile"));
f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("../BFolder/BFile"));
uri = FUUri(FC("file:///C:/AFolder/BFolder/BFile"));
f = uri.GetAbsoluteUri();
PassIf(f == FC("file:///C:/AFolder/BFolder/BFile"));
#else
uri = FUUri(FC("file:///AFolder/BFolder/BFile"));
f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("../BFolder/BFile"));
uri = FUUri(FC("file:///AFolder/BFolder/BFile"));
f = uri.GetAbsoluteUri();
PassIf(f == FC("file:///AFolder/BFolder/BFile"));
#endif // WIN32

#ifdef WIN32
// Verify the URI generation with respect to a networked file
manager.PushRootFile(FC("\\\\BNetwork\\BFolder\\BSubfolder\\BFile"));
uri = FUUri(FC("C:\\BFolder\\BSubfolder\\CFile"));
f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("file:///C:/BFolder/BSubfolder/CFile"));
uri = FUUri(FC("C:\\BFolder\\BSubfolder\\CFile"));
f = uri.GetAbsoluteUri();
PassIf(f == FC("file:///C:/BFolder/BSubfolder/CFile"));

uri = FUUri(FC("\\\\BNetwork\\BFolder\\CFile"));
f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("../CFile"));
uri = FUUri(FC("\\\\BNetwork\\BFolder\\CFile"));
f = uri.GetAbsoluteUri();
PassIf(f == FC("file://BNetwork/BFolder/CFile"));

uri = FUUri(FC("file://BNetwork/BFolder/BSubfolder/CFile"));
f = uri.GetRelativeUri(manager.GetCurrentUri());
PassIf(f == FC("./CFile"));
uri = FUUri(FC("file://BNetwork/BFolder/BSubfolder/CFile"));
f = uri.GetAbsoluteUri();
PassIf(f == FC("file://BNetwork/BFolder/BSubfolder/CFile"));
#endif // WIN32

TESTSUITE_TEST(5, BackwardCompatibility)

// Verify the handling of the file paths that we used to export.
#ifdef WIN32
FUFileManager manager;
manager.PushRootFile(FC("C:\\AFolder\\AFolder.D\\AFile"));
FUUri uri(FC("file://C|/AFolder/BFolder/BFile"));
fstring f = uri.GetAbsolutePath();
PassIf(PlatformEquivalent(f, FC("C:\\AFolder\\BFolder\\BFile")));

f = manager.GetCurrentUri().MakeRelative(FC("file://C|/AFolder/BFolder/BFile"));
PassIf(PlatformEquivalent(f, FC("..\\BFolder\\BFile")));
#else
PassIf(true);
#endif // WIN32

TESTSUITE_TEST(6, ApplicationFolderName)
fstring applicationFolderName = FUFileManager::GetApplicationFolderName();
FailIf(applicationFolderName.empty()); // really not much else I can test for..

#ifdef WIN32 // at the time of writing, only implemented for WIN32, else returns empty string
fstring moduleFolderName = FUFileManager::GetModuleFolderName();
FailIf(moduleFolderName.empty()); // really not much else I can test for..
#endif

TESTSUITE_END


text:
package at.rags.morpheus;

import com.google.gson.annotations.SerializedName;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import at.rags.morpheus.Annotations.Relationship;
import at.rags.morpheus.Exceptions.NotExtendingResourceException;

/**
 * Mapper will map all different top-level members and will
 * also map the relations.
 *
 * Includes will also mapped to matching relationship members.
 */
public class Mapper {

  private Deserializer deserializer;
  private Serializer serializer;
  private AttributeMapper attributeMapper;

  public Mapper() {
    deserializer = new Deserializer();
    serializer = new Serializer();
    attributeMapper = new AttributeMapper();
  }

  public Mapper(Deserializer deserializer, Serializer serializer, AttributeMapper attributeMapper) {
    this.deserializer = deserializer;
    this.serializer = serializer;
    this.attributeMapper = attributeMapper;
  }

  //TODO map href and meta (http://jsonapi.org/format/#document-links)
  /**
   * Will map links and return them.
   *
   * @param linksJsonObject JSONObject from link.
   * @return Links with mapped values.
   */
  public Links mapLinks(JSONObject linksJsonObject) {
    Links links = new Links();
    try {
      links.setSelfLink(linksJsonObject.getString("self"));
    } catch (JSONException e) {
      Logger.debug("JSON link does not contain self");
    }

    try {
      links.setRelated(linksJsonObject.getString("related"));
    } catch (JSONException e) {
      Logger.debug("JSON link does not contain related");
    }

    try {
      links.setFirst(linksJsonObject.getString("first"));
    } catch (JSONException e) {
      Logger.debug("JSON link does not contain first");
    }

    try {
      links.setLast(linksJsonObject.getString("last"));
    } catch (JSONException e) {
      Logger.debug("JSON link does not contain last");
    }

    try {
      links.setPrev(linksJsonObject.getString("prev"));
    } catch (JSONException e) {
      Logger.debug("JSON link does not contain prev");
    }

    try {
      links.setNext(linksJsonObject.getString("next"));
    } catch (JSONException e) {
      Logger.debug("JSON link does not contain next");
    }

    return links;
  }

  /**
   * Map the Id from json to the object.
   *
   * @param object Object of the class.
   * @param jsonDataObject JSONObject of the dataNode.
   * @return Object with mapped fields.
   * @throws NotExtendingResourceException Throws when the object is not extending {@link Resource}
   */
  public Resource mapId(Resource object, JSONObject jsonDataObject) throws NotExtendingResourceException {
    try {
      return deserializer.setIdField(object, jsonDataObject.get("id"));
    } catch (JSONException e) {
      Logger.debug("JSON data does not contain id.");
    }

    return object;
  }

  /**
   * Maps the attributes of json to the object.
   *
   * @param object Object of the class.
   * @param attributesJsonObject Attributes object inside the data node.
   * @return Object with mapped fields.
   */
  public Resource mapAttributes(Resource object, JSONObject attributesJsonObject) {
    if (attributesJsonObject == null) {
      return object;
    }

    for (Field field : object.getClass().getDeclaredFields()) {
      // get the right attribute name
      String jsonFieldName = field.getName();
      boolean isRelation = false;
      for (Annotation annotation : field.getAnnotations()) {
        if (annotation.annotationType() == SerializedName.class) {
          SerializedName serializeName = (SerializedName) annotation;
          jsonFieldName = serializeName.value();
        }
        if (annotation.annotationType() == Relationship.class) {
          isRelation = true;
        }
      }

      if (isRelation) {
        continue;
      }

      attributeMapper.mapAttributeToObject(object, attributesJsonObject, field, jsonFieldName);
    }

    return object;
  }

  /**
   * Loops through relation JSON array and maps annotated objects.
   *
   * @param object Real object to map.
   * @param jsonObject JSONObject.
   * @param included List of included resources.
   * @return Real object with relations.
   * @throws Exception when deserializer is not able to create instance.
   */
  public Resource mapRelations(Resource object, JSONObject jsonObject,
                                       List<Resource> included) throws Exception {
    HashMap<String, String> relationshipNames = getRelationshipNames(object.getClass());

    //going through relationship names annotated in Class
    for (String relationship : relationshipNames.keySet()) {
      JSONObject relationJsonObject = null;
      try {
        relationJsonObject = jsonObject.getJSONObject(relationship);
      } catch (JSONException e) {
        Logger.debug("Relationship named " + relationship + "not found in JSON");
        continue;
      }

      //map json object of data
      JSONObject relationDataObject = null;
      try {
        relationDataObject = relationJsonObject.getJSONObject("data");
        Resource relationObject = Factory.newObjectFromJSONObject(relationDataObject, null);

        relationObject = matchIncludedToRelation(relationObject, included);

        deserializer.setField(object, relationshipNames.get(relationship), relationObject);
      } catch (JSONException e) {
        Logger.debug("JSON relationship does not contain data");
      }

      //map json array of data
      JSONArray relationDataArray = null;
      try {
        relationDataArray = relationJsonObject.getJSONArray("data");
        List<Resource> relationArray = Factory.newObjectFromJSONArray(relationDataArray, null);

        relationArray = matchIncludedToRelation(relationArray, included);

        deserializer.setField(object, relationshipNames.get(relationship), relationArray);
      } catch (JSONException e) {
        Logger.debug("JSON relationship does not contain data");
      }
    }

    return object;
  }

  /**
   * Will check if the relation is included. If true included object will be returned.
   *
   * @param object Relation resources.
   * @param included List of included resources.
   * @return Relation of included resource.
   */
  public Resource matchIncludedToRelation(Resource object, List<Resource> included) {
    if (included == null) {
      return object;
    }

    for (Resource resource : included) {
      if (object.getId().equals(resource.getId()) && object.getClass().equals(resource.getClass())) {
        return resource;
      }
    }
    return object;
  }

  /**
   * Loops through relations and calls {@link #matchIncludedToRelation(Resource, List)}.
   *
   * @param relationResources List of relation resources.
   * @param included List of included resources.
   * @return List of relations and/or included resources.
   */
  public List<Resource> matchIncludedToRelation(List<Resource> relationResources, List<Resource> included) {
    List<Resource> matchedResources = new ArrayList<>();
    for (Resource resource : relationResources) {
      matchedResources.add(matchIncludedToRelation(resource, included));
    }
    return matchedResources;
  }

  public List<Error> mapErrors(JSONArray errorArray) {
    List<Error> errors = new ArrayList<>();

    for (int i = 0; errorArray.length() > i; i++) {
      JSONObject errorJsonObject;
      try {
        errorJsonObject = errorArray.getJSONObject(i);
      } catch (JSONException e) {
        Logger.debug("No index " + i + " in error json array");
        continue;
      }
      Error error = new Error();

      try {
        error.setId(errorJsonObject.getString("id"));
      } catch (JSONException e) {
        Logger.debug("JSON object does not contain id");
      }

      try {
        error.setStatus(errorJsonObject.getString("status"));
      } catch (JSONException e) {
        Logger.debug("JSON object does not contain status");
      }

      try {
        error.setCode(errorJsonObject.getString("code"));
      } catch (JSONException e) {
        Logger.debug("JSON object does not contain code");
      }

      try {
        error.setTitle(errorJsonObject.getString("title"));
      } catch (JSONException e) {
        Logger.debug("JSON object does not contain title");
      }

      try {
        error.setDetail(errorJsonObject.getString("detail"));
      } catch (JSONException e) {
        Logger.debug("JSON object does not contain detail");
      }

      JSONObject sourceJsonObject = null;
      try {
        sourceJsonObject = errorJsonObject.getJSONObject("source");
      }
      catch (JSONException e) {
        Logger.debug("JSON object does not contain source");
      }

      if (sourceJsonObject != null) {
        Source source = new Source();
        try {
          source.setParameter(sourceJsonObject.getString("parameter"));
        } catch (JSONException e) {
          Logger.debug("JSON object does not contain parameter");
        }
        try {
          source.setPointer(sourceJsonObject.getString("pointer"));
        } catch (JSONException e) {
          Logger.debug("JSON object does not contain pointer");
        }
        error.setSource(source);
      }

      try {
        JSONObject linksJsonObject = errorJsonObject.getJSONObject("links");
        ErrorLinks links = new ErrorLinks();
        links.setAbout(linksJsonObject.getString("about"));
        error.setLinks(links);
      }
      catch (JSONException e) {
        Logger.debug("JSON object does not contain links or about");
      }

      try {
        error.setMeta(attributeMapper.createMapFromJSONObject(errorJsonObject.getJSONObject("meta")));
      } catch (JSONException e) {
        Logger.debug("JSON object does not contain JSONObject meta");
      }

      errors.add(error);
    }

    return errors;
  }

  /**
   * Create data representation from resources.
   * This will return the representation of the resources as list of maps. Every item contains
   * a map with the resource's id, type and relationships (if any). Attributes are only included
   * when 'includeAttributes' is true.
   *
   * @param resources List of resources.
   * @param includeAttributes Add attributes map to representation.
   * @return ArrayList of Hashmaps<String, Object>.
   */
  public ArrayList<HashMap<String, Object>> createData(List<Resource> resources,
                                                       boolean includeAttributes) {
    String resourceName = null;
    try {
      resourceName = nameForResourceClass(resources.get(0).getClass());
    } catch (Exception e) {
      Logger.debug(e.getMessage());
      return null;
    }

    ArrayList<HashMap<String, Object>> dataArray = new ArrayList<>();

    for (Resource resource : resources) {
      HashMap<String, Object> attributes = serializer.getFieldsAsDictionary(resource);

      HashMap<String, Object> resourceRepresentation = new HashMap<>();
      resourceRepresentation.put("type", resourceName);
      resourceRepresentation.put("id", resource.getId());
      if (includeAttributes) {
        resourceRepresentation.put("attributes", attributes);
      }

      HashMap<String, Object> relationships = createRelationships(resource);
      if (relationships != null) {
        resourceRepresentation.put("relationships", relationships);
      }

      dataArray.add(resourceRepresentation);
    }

    return dataArray;
  }

  /**
   * Create data represenation from resource.
   * This will return the repersentation of the resource. The map contains the id, type and
   * relationships (if any). Attributes are only included when 'includeAttributes' is true.
   *
   * @param resource Resource to create data.
   * @param includeAttributes Add attributes map to representation.
   * @return Hashmaps<String, Object>.
   */
  public HashMap<String, Object> createData(Resource resource,
                                            boolean includeAttributes) {
    String resourceName = null;
    try {
      resourceName = nameForResourceClass(resource.getClass());
    } catch (Exception e) {
      Logger.debug(e.getMessage());
      return null;
    }

    HashMap<String, Object> resourceRepresentation = new HashMap<>();
    resourceRepresentation.put("type", resourceName);
    resourceRepresentation.put("id", resource.getId());
    if (includeAttributes) {
      HashMap<String, Object> attributes = serializer.getFieldsAsDictionary(resource);
      if (attributes != null) {
        resourceRepresentation.put("attributes", attributes);
      }
    }

    HashMap<String, Object> relationships = createRelationships(resource);
    if (relationships != null) {
      resourceRepresentation.put("relationships", relationships);
    }

    if (resource.getLinks() != null) {
      resourceRepresentation.put("links",
          createLinks(resource));
    }

    return resourceRepresentation;
  }

  /**
   * Creates the relationships represenation from an resource.
   * Will go through the relationships of a resource and return them as a map.
   * The keys of the returned map will be the resource type of the relationship and the value a map
   * of the data or a list of maps containing data of multiple relations.
   *
   * @param resource Resource to create relationships from.
   * @return HashMap of related resource names with their data.
   */
  public HashMap<String, Object> createRelationships(Resource resource) {
    HashMap<String, Object> relations = serializer.getRelationships(resource);
    HashMap<String, Object> relationships = new HashMap<>();

    for (String relationshipName : relations.keySet()) {
      Object relationObject = relations.get(relationshipName);

      if (relationObject instanceof Resource) {
        if (resource.getNullableRelationships().contains(relationshipName)) {
          HashMap<String, Object> dataObject = new HashMap<>();
          dataObject.put("data", null);
          relationships.put(relationshipName, dataObject);
          continue;
        }

        HashMap<String, Object> data = createData((Resource) relationObject, false);
        if (data != null) {
          HashMap<String, Object> dataObject = new HashMap<>();
          dataObject.put("data", data);
          relationships.put(relationshipName, dataObject);
        }
      }

      if (relationObject instanceof ArrayList) {
        if (resource.getNullableRelationships().contains(relationshipName)) {
          HashMap<String, Object> dataObject = new HashMap<>();
          dataObject.put("data", new ArrayList<Object>());
          relationships.put(relationshipName, dataObject);
          continue;
        }

        ArrayList dataArray = createData((List) relationObject, false);
        if (dataArray != null) {
          HashMap<String, Object> dataObject = new HashMap<>();
          dataObject.put("data", dataArray);
          relationships.put(relationshipName, dataObject);
        }
      }
    }

    if (relationships.isEmpty()) {
      relationships = null;
    }

    return relationships;
  }

  /**
   * Returns a resources links as a map.
   *
   * @param resource Resource to get links from.
   * @return Map of the links.
   */
  public HashMap<String, Object> createLinks(Resource resource) {
    HashMap<String, Object> links = null;

    Links resourceLinks = resource.getLinks();
    if (resourceLinks != null) {
      links = new HashMap<>();
      if (resourceLinks.getSelfLink() != null) {
        links.put("self", resourceLinks.getSelfLink());
      }
      if (resourceLinks.getRelated() != null) {
        links.put("related", resourceLinks.getRelated());
      }
      if (resourceLinks.getFirst() != null) {
        links.put("first", resourceLinks.getFirst());
      }
      if (resourceLinks.getLast() != null) {
        links.put("last", resourceLinks.getLast());
      }
      if (resourceLinks.getPrev() != null) {
        links.put("prev", resourceLinks.getPrev());
      }
      if (resourceLinks.getNext() != null) {
        links.put("next", resourceLinks.getNext());
      }
      if (resourceLinks.getAbout() != null) {
        links.put("about", resourceLinks.getAbout());
      }
    }

    return links;
  }

  /**
   * Create the included as list of maps.
   *
   * @param resource Resource with relations.
   * @return List of maps.
   */
  public ArrayList<HashMap<String, Object>> createIncluded(Resource resource) {
    HashMap<String, Object> relations = serializer.getRelationships(resource);
    ArrayList<HashMap<String, Object>> includes = new ArrayList<>();

    for (String relationshipName : relations.keySet()) {
      Object relationObject = relations.get(relationshipName);
      if (relationObject instanceof Resource) {
        HashMap<String, Object> data = createData((Resource) relationObject, true);
        if (data != null) {
          includes.add(data);
        }
      }

      if (relationObject instanceof ArrayList) {
        ArrayList dataArray = createData((List) relationObject, true);
        if (dataArray != null) {
          includes.addAll(dataArray);
        }
      }
    }

    return includes;
  }

  // helper

  /**
   * Get the annotated relationship names.
   *
   * @param clazz Class for annotation.
   * @return List of relationship names.
   */
  private HashMap<String, String> getRelationshipNames(Class clazz) {
    HashMap<String, String> relationNames = new HashMap<>();
    for (Field field : clazz.getDeclaredFields()) {
      String fieldName = field.getName();
      for (Annotation annotation : field.getDeclaredAnnotations()) {
        if (annotation.annotationType() == SerializedName.class) {
          SerializedName serializeName = (SerializedName)annotation;
          fieldName = serializeName.value();
        }
        if (annotation.annotationType() == Relationship.class) {
          Relationship relationshipAnnotation = (Relationship)annotation;
          relationNames.put(relationshipAnnotation.value(), fieldName);
        }
      }
    }

    return relationNames;
  }

  private String nameForResourceClass(Class clazz) throws Exception {
     for (String key : Deserializer.getRegisteredClasses().keySet()) {
      if (Deserializer.getRegisteredClasses().get(key) == clazz) {
        return key;
      }
    }

    throw new Exception("Class " + clazz.getSimpleName() + " not registered.");
  }

  // getter

  public Deserializer getDeserializer() {
    return deserializer;
  }

  public AttributeMapper getAttributeMapper() {
    return attributeMapper;
  }

  public Serializer getSerializer() {
    return serializer;
  }
}


text: [See the talk](http://tbekolay.github.io/scipy2013-quantities).


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Remote;
using Newtonsoft.Json;
using Roslyn.Utilities;
using StreamJsonRpc;

namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
    internal static class UnitTestingStreamExtensions
    {
        public static JsonRpc UnitTesting_CreateStreamJsonRpc(
            this Stream stream,
            object? target,
            TraceSource logger,
            IEnumerable<AggregateJsonConverter>? jsonConverters = null)
        {
            jsonConverters ??= SpecializedCollections.EmptyEnumerable<AggregateJsonConverter>();

            var jsonFormatter = new JsonMessageFormatter();
            jsonFormatter.JsonSerializer.Converters.AddRange(jsonConverters.Concat(AggregateJsonConverter.Instance));

            return new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter), target)
            {
                CancelLocallyInvokedMethodsWhenConnectionIsClosed = true,
                TraceSource = logger
            };
        }
    }
}


text:
CREATE TABLE `userrights` (
 `userid` int(11) NOT NULL,
 `siteid` varchar(40) COLLATE utf8_unicode_ci NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


text:
namespace base {

ThreadTestHelper::ThreadTestHelper(
    scoped_refptr<SequencedTaskRunner> target_sequence)
    : test_result_(false),
      target_sequence_(std::move(target_sequence)),
      done_event_(WaitableEvent::ResetPolicy::AUTOMATIC,
                  WaitableEvent::InitialState::NOT_SIGNALED) {}

bool ThreadTestHelper::Run() {
  if (!target_sequence_->PostTask(
          FROM_HERE, base::BindOnce(&ThreadTestHelper::RunOnSequence, this))) {
    return false;
  }
  base::ScopedAllowBaseSyncPrimitivesForTesting allow_wait;
  done_event_.Wait();
  return test_result_;
}

void ThreadTestHelper::RunTest() { set_test_result(true); }

ThreadTestHelper::~ThreadTestHelper() = default;

void ThreadTestHelper::RunOnSequence() {
  RunTest();
  done_event_.Signal();
}

}  // namespace base


text:
namespace base {
class CommandLine;
}

metrics::CallStackProfileParams::Process GetProfileParamsProcess(
    const base::CommandLine& command_line);

#endif  // CHROME_COMMON_PROFILER_PROCESS_TYPE_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.

-->
<Configuration status="WARN" name="XMLConfigTest">
  <Properties>
    <Property name="logDir">target/rolling-new-directory</Property>
  </Properties>

  <Appenders>
    <RollingFile name="RollingFile" filePattern="${logDir}/%d{yyyy_MM_dd-mm-ss}/messages-$${date:yyyy_MM_dd_HH_mm_ss_SSS}.log">
      <PatternLayout>
        <Pattern>%d{MM-dd-yy-HH-mm-ss} %p %C{1.} [%t] %m%n</Pattern>
      </PatternLayout>
      <TimeBasedTriggeringPolicy />
    </RollingFile>
  </Appenders>

  <Loggers>
    <Root level="info">
      <AppenderRef ref="RollingFile"/>
    </Root>
  </Loggers>

</Configuration>


text:
package models

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	log "gopkg.in/clog.v1"

	"github.com/lubanstudio/luban/pkg/setting"
)

var x *gorm.DB

func init() {
	var err error
	x, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
		setting.Database.User, setting.Database.Password, setting.Database.Host, setting.Database.Name))
	if err != nil {
		log.Fatal(4, "Fail to connect database: %s", err)
	}

	if err = x.Set("gorm:table_options", "ENGINE=InnoDB").
		AutoMigrate(new(User), new(Builder), new(Matrix), new(Task)).Error; err != nil {
		log.Fatal(4, "Fail to auto migrate database: %s", err)
	}
}

func releaseTransaction(tx *gorm.DB) {
	if tx.Error != nil {
		tx.Rollback()
	}
}

func IsErrRecordNotFound(err error) bool {
	return err == gorm.ErrRecordNotFound
}

func Count(bean interface{}) int64 {
	var count int64
	x.Model(bean).Count(&count)
	return count
}


text:
<!doctype html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<title>JAST: Just another Semantic Template: Demos: Tabs</title>
		<meta name="description" content="JAST is an HTML5 Semantic Boilerplate: Demos: Tabs">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="apple-touch-icon" href="../apple-touch-icon.png">
		<link rel="shortcut icon" href="../favicon.png">

		<link rel="stylesheet" href="../css/pure.css">
		<link rel="stylesheet" href="../css/pure.styles.css">

		<link rel="stylesheet" href="../css/nav.css">

		<link rel="stylesheet" href="../css/font-awesome.min.css">

		<link rel="stylesheet" href="../css/main.css">

JASTDemos

Home

						Demos

Tabs

TABs are section tags nested in an article element, the h2 title renders the tab label, the .jast-tabs class triggers the trasformations.

Lorem ipsum

Tabn °1 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra.
eleifend porta lorem eget scelerisque. Quisque suscipit sit amet libero pretium pharetra. Phasellus maximus leo non augue convallis, a egestas lacus dignissim. Ut non dictum nibh. Aliquam sit amet tincidunt neque, eu dapibus tortor. Nulla nibh justo, dapibus sit amet tincidunt malesuada, vehicula at purus.

In semper consequat

Tab n°2 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra.
					Phasellus aliquam suscipit nulla. Aenean malesuada ultricies egestas. Integer viverra maximus massa, quis tincidunt augue. Suspendisse pellentesque sapien sem, et maximus tortor vehicula vitae. Sed eleifend porta lorem eget scelerisque. Quisque suscipit sit amet libero pretium pharetra. Phasellus maximus leo non augue convallis, a egestas lacus dignissim. Ut non dictum nibh. Aliquam sit amet tincidunt neque, eu dapibus tortor. Nulla nibh justo, dapibus sit amet tincidunt malesuada, vehicula at purus.

Curabitur posuere

Tab n°3 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra.In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra.
					Phasellus aliquam suscipit nulla. Aenean malesuada ultricies egestas. Integer viverra maximus massa, quis tincidunt augue. Suspendisse pellentesque sapien sem, et maximus tortor vehicula vitae. Sed eleifend porta lorem eget scelerisque.

Thanks for all the fish

Footer No tab Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor.

JAST 2015 by Alfredo Cosco | MIT Licence


text:
package com.mentor.nucleus.bp.ui.graphics.handles;

import org.eclipse.gef.ConnectionEditPart;
import org.eclipse.gef.DragTracker;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.handles.BendpointCreationHandle;

import com.mentor.nucleus.bp.ui.graphics.trackers.SnappingBendpointTracker;

public class SnappingBendpointCreationHandle extends BendpointCreationHandle {

	public SnappingBendpointCreationHandle(ConnectionEditPart owner, int index,
			int locatorIndex) {
		super(owner, index, locatorIndex);
	}

	@Override
	public DragTracker getDragTracker() {
		SnappingBendpointTracker tracker = new SnappingBendpointTracker(
				(ConnectionEditPart) getOwner(), getIndex());
		tracker.setType(RequestConstants.REQ_CREATE_BENDPOINT);
		tracker.setDefaultCursor(getCursor());
		return tracker;
	}

}


text:
class Column

  LEFT  = :left unless defined?(LEFT)
  RIGHT = :right unless defined?(RIGHT)

  VALID_OPTIONS = [:name, :description, :size, :justification, :fixed_size] unless defined?(VALID_OPTIONS)

  attr_accessor :name, :description, :size, :justification, :fixed_size, :field, :link

  # Grid Column
  # === Options ===
  # * name
  # * description: defaults to +name+
  # * size: defaults to 0
  # * fixed_size: boolean, defaults to false
  # * justification: defaults to LEFT
  # * type: cast value to this Class
  def initialize(*options)
    if options
      options.flatten!
      options = options.first
    end
    options = {} if options.nil?

    for option in options.keys
      raise ArgumentError.new("#{option} is not a valid option") unless VALID_OPTIONS.include?(option)
    end

    @name          = options[:name] || ''
    @description   = options[:description] || @name
    @size          = options[:size] || 0
    @fixed_size    = options[:fixed_size] || false
    @justification = options[:justification] || LEFT

    set_field_from_name
    raise ArgumentError.new("size must be a number, but was '#{@size}'") unless @size.is_a?(Fixnum)
    raise ArgumentError.new("fixed_size must be a boolean, but was '#{@fixed_size}'") unless @fixed_size.is_a?(FalseClass) or @fixed_size.is_a?(TrueClass)
    raise ArgumentError.new("justification must LEFT or RIGHT, but was '#{@justification}") unless @justification == LEFT or @justification == RIGHT
  end

  def set_field_from_name
    unless self.name.blank?
      begin
        self.field = self.name.strip.to_sym
      rescue ArgumentError => error
        raise ArgumentError.new("#{error}: Can't create column with name '#{self.name}'")
      end
    end
  end

  def field=(value)
    case value
    when Symbol
      @field = value
    when NilClass
      @field = nil
    else
      begin
        @field = value.to_sym
      rescue ArgumentError => error
        raise ArgumentError.new("#{error}: Can't create column with name '#{value}'")
      end
    end
  end

  def size=(value)
    unless fixed_size?
      @size = value
    end
  end

  def fixed_size?
    fixed_size
  end

  def valid?
    !@field.nil?
  end

  def to_s
    name
  end
end


text:
#include <aws/lambda/model/AliasConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Lambda
{
namespace Model
{

AliasConfiguration::AliasConfiguration() :
    m_aliasArnHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_functionVersionHasBeenSet(false),
    m_descriptionHasBeenSet(false)
{
}

AliasConfiguration::AliasConfiguration(const JsonValue& jsonValue) :
    m_aliasArnHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_functionVersionHasBeenSet(false),
    m_descriptionHasBeenSet(false)
{
  *this = jsonValue;
}

AliasConfiguration& AliasConfiguration::operator =(const JsonValue& jsonValue)
{
  if(jsonValue.ValueExists("AliasArn"))
  {
    m_aliasArn = jsonValue.GetString("AliasArn");

    m_aliasArnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Name"))
  {
    m_name = jsonValue.GetString("Name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("FunctionVersion"))
  {
    m_functionVersion = jsonValue.GetString("FunctionVersion");

    m_functionVersionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Description"))
  {
    m_description = jsonValue.GetString("Description");

    m_descriptionHasBeenSet = true;
  }

  return *this;
}

JsonValue AliasConfiguration::Jsonize() const
{
  JsonValue payload;

  if(m_aliasArnHasBeenSet)
  {
   payload.WithString("AliasArn", m_aliasArn);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_functionVersionHasBeenSet)
  {
   payload.WithString("FunctionVersion", m_functionVersion);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  return payload;
}

} // namespace Model
} // namespace Lambda
} // namespace Aws


text:
<?php

namespace Madef\UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\Table(name="users")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function getRolesDescriptions($rolesDescriptions)
    {
        $descriptions = array();
        foreach ($this->getRoles() as $role) {
            if (!isset($rolesDescriptions[$role])) {
                continue;
            }
            $descriptions[] = $rolesDescriptions[$role];
        }

        return $descriptions;
    }
}


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using Marketplace.Domain.Models.Security;

namespace Marketplace.Data.Mappings.Security
{
    internal sealed class FeatureMap : EntityTypeConfiguration<Feature>
    {
        public FeatureMap()
        {
            ToTable("Features");

            #region Key

            HasKey(i => i.Id);

            Property(i => i.Id)
                .HasColumnName("Id")
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            #endregion

            #region Fields

            Property(i => i.Name)
                .HasColumnName("Name");

            Property(i => i.Detail)
                .HasColumnName("Detail");

            Property(i => i.Path)
                .HasColumnName("Path");

            Property(i => i.ParentId)
                .HasColumnName("ParentId");

            #endregion

            #region Relationships

            HasOptional(s => s.Parent)
                .WithMany(d => d.Children)
                .HasForeignKey(i => i.ParentId);

            #endregion
        }
    }
}


text:
package com.example.administrator.coolweather.db;

import org.litepal.crud.DataSupport;

/**
 * Created by Administrator on 2017/6/18.
 */

public class County extends DataSupport{
    private int id;
    private String countyName;
    private String weatherId;

    public int getId() {
        return id;
    }

    public String getCountyName() {
        return countyName;
    }
    public String getWeatherId() {
        return weatherId;
    }

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

    public void setCountyName(String countyName) {
        this.countyName = countyName;
    }

    public void setWeatherId(String weatherId) {
        this.weatherId = weatherId;
    }

}