text:
class BuildingType < ApplicationRecord
  has_many :buildings, dependent: :nullify
  validates :name, presence: true, length: { maximum: 255 }
  RESIDENCE = 3
end

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const markdownIt = require('markdown-it')
const markdownItAnchor = require('markdown-it-anchor')
const markdownItClass = require('@toycode/markdown-it-class')

module.exports = function configureMarkdown (config) {
  // configure markdown
  const mdClassesMapping = {
    h2: ['title', 'is-2'],
    h3: ['title', 'is-3']
  }
  config.setLibrary('md',
    markdownIt({
      html: true,
      linkify: true
    })
      .use(markdownItAnchor)
      .use(markdownItClass, mdClassesMapping)
  )
}


text:
import { Observable } from '../Observable';
import { MonoTypeOperatorFunction, OperatorFunction } from '../types';
/** @deprecated Deprecated in favor of static race. */
export declare function race<T>(observables: Array<Observable<T>>): MonoTypeOperatorFunction<T>;
/** @deprecated Deprecated in favor of static race. */
export declare function race<T, R>(observables: Array<Observable<T>>): OperatorFunction<T, R>;
/** @deprecated Deprecated in favor of static race. */
export declare function race<T>(...observables: Array<Observable<T> | Array<Observable<T>>>): MonoTypeOperatorFunction<T>;
/** @deprecated Deprecated in favor of static race. */
export declare function race<T, R>(...observables: Array<Observable<any> | Array<Observable<any>>>): OperatorFunction<T, R>;


text:
<?php

// C:\xampp\htdocs\dobervich\src\Acme\DemoBundle/Resources/views\Welcome\index.html.twig
return array (
);


text:
package org.ripple.power.txns.btc;

import java.io.EOFException;
import java.util.ArrayList;
import java.util.List;

import org.ripple.power.Helper;

/**
 *

 * A Merkle branch is a data structure that contains proofs of block inclusion
 * for one or more transactions in an efficient manner.
 *

 *
 *

 * The encoding works as follows: we traverse the tree in depth-first order,
 * storing a bit for each traversed node, signifying whether the node is the
 * parent of at least one matched leaf txid (or a matched txid itself). In case
 * we are at the leaf level, or this bit is 0, its Merkle node hash is stored,
 * and its children are not explored further. Otherwise, no hash is stored, but
 * we recurse into both (or the only) child branches. During decoding, the same
 * depth-first traversal is performed, consuming bits and hashes as they were
 * written during encoding.
 *

 *
 *

 * The serialization is fixed and provides a hard guarantee about the encoded
 * size, <tt>SIZE LE 10 + ceil(32.25*N)</tt> where N represents the number of
 * leaf nodes of the partial tree. N itself is bounded by:
 *

 *
 *

 * N LE total_transactions

 * N LE 1 + matched_transactions*tree_height
 *

 *
 *

 * Merkle Branch
 *

 *
 *

 *   Size       Field           Description
 *   ====       =====           ===========
 *   4 bytes    txCount         Number of transactions in the block
 *   VarInt     hashCount       Number of hashes
 *   Variable   hashes          Hashes in depth-first order
 *   VarInt     flagCount       Number of bytes of flag bits
 *   Variable   flagBits        Flag bits packed 8 per byte, least significant bit first
 *

 */
public class MerkleBranch implements ByteSerializable {

	/** Bits used while traversing the tree */
	private int bitsUsed;

	/** Hashes used while traversing the tree */
	private int hashesUsed;

	/** Transaction count */
	private final int txCount;

	/** Merkle branch node hashes in big-endian format */
	private List<byte[]> nodeHashes;

	/** Merkle branch node flags */
	private byte[] nodeFlags;

	/**
	 * Creates a new Merkle branch from the serialized byte stream
	 *
	 * @param inBuffer
	 *            Input buffer
	 * @throws EOFException
	 *             End-of-data processing input stream
	 * @throws VerificationException
	 *             Verification error
	 */
	public MerkleBranch(SerializedBuffer inBuffer) throws EOFException, VerificationException {
		//
		// Get the transaction count
		//
		txCount = inBuffer.getInt();
		if (txCount < 1 || txCount > NetParams.MAX_BLOCK_SIZE / 60)
			throw new VerificationException(String.format("Transaction count %d is not valid", txCount),
					RejectMessage.REJECT_INVALID);
		//
		// Get the node hashes
		//
		int hashCount = inBuffer.getVarInt();
		if (hashCount < 0 || hashCount > txCount)
			throw new VerificationException(String.format("Hash count %d is not valid", hashCount),
					RejectMessage.REJECT_INVALID);
		nodeHashes = new ArrayList<>(hashCount);
		for (int i = 0; i < hashCount; i++)
			nodeHashes.add(Helper.reverseBytes(inBuffer.getBytes(32)));
		//
		// Get the node flags
		//
		int flagCount = inBuffer.getVarInt();
		if (flagCount < 1)
			throw new VerificationException(String.format("Flag count %d is not valid", flagCount),
					RejectMessage.REJECT_INVALID);
		nodeFlags = inBuffer.getBytes(flagCount);
	}

	/**
	 * Creates a new Merkle branch for the supplied transactions. The
	 * transaction list must be sorted by transaction index. The Merkle tree
	 * starts with the leaf nodes and ends with the root node.
	 *
	 * @param txCount
	 *            Total number of transactions in the block
	 * @param txList
	 *            Matched transaction index list
	 * @param merkleTree
	 *            Merkle tree
	 */
	public MerkleBranch(int txCount, List<Integer> txList, List<byte[]> merkleTree) {
		this.txCount = txCount;
		//
		// Calculate the tree height based on the total transaction count. Each
		// node in the tree has two descendants (the last node in a level may
		// have
		// just one descendant)
		//
		int height = 0;
		int nodeCount = 1;
		int width;
		while ((width = getTreeWidth(height)) > 1) {
			height++;
			nodeCount += width;
		}
		//
		// Allocate the hash list and flag array (we will adjust the flag array
		// size
		// when we are done)
		//
		nodeHashes = new ArrayList<>(nodeCount);
		nodeFlags = new byte[(nodeCount * 2 + 7) / 8];
		//
		// Create the paths to reach each matched transaction. Each tree level
		// has
		// an array of node indexes representing the next node for each
		// transaction.
		// The paths are arranged from the first transaction index to the
		// last index, so the tree is traversed from left to right.
		//
		int[][] nodePath = new int[height][txList.size()];
		for (int i = 0; i < txList.size(); i++) {
			int pos = 0;
			int index = txList.get(i);
			for (int pHeight = height - 1; pHeight >= 0; pHeight--) {
				int p2 = 1 << pHeight;
				pos = pos * 2 + index / p2;
				nodePath[pHeight][i] = pos;
				index = index % p2;
			}
		}
		//
		// Build the Merkle branch starting at the Merkle root and continuing
		// down to the leaf transactions. Remember that the tree is upside down
		// with
		// the leaf nodes first and the Merkle root last. We flag the root node
		// as a match since you always start at the root.
		//
		// We have a special case if there are no transactions supplied. In this
		// case, we will create a Merkle branch with the Merkle root as the only
		// nodeHashes element and no matches will be set in nodeFlags.
		//
		// We have another special case if the block contains just the coinbase
		// transaction
		// and this is also the matched transaction. In this case, we will
		// create
		// a Merkle branch with the coinbase transaction set in nodeFlags. Note
		// that
		// the merkle root is the same as the coinbase transaction hash in this
		// case.
		//
		if (txList.isEmpty()) {
			bitsUsed++;
			nodeHashes.add(merkleTree.get(merkleTree.size() - 1));
		} else if (txCount == 1) {
			Helper.setBitLE(nodeFlags, bitsUsed++);
			nodeHashes.add(merkleTree.get(merkleTree.size() - 1));
		} else {
			Helper.setBitLE(nodeFlags, bitsUsed++);
			buildBranch(height - 1, 0, nodePath, merkleTree.size() - 1, merkleTree);
		}
		//
		// Resize nodeFlags based on the actual number of bits used
		//
		byte[] newFlags = new byte[(bitsUsed + 7) / 8];
		System.arraycopy(nodeFlags, 0, newFlags, 0, newFlags.length);
		nodeFlags = newFlags;
	}

	/**
	 * Write the serialized Merkle branch to the output buffer
	 *
	 * @param outBuffer
	 *            Output buffer
	 * @return Output buffer
	 */
	@Override
	public SerializedBuffer getBytes(SerializedBuffer outBuffer) {
		outBuffer.putInt(txCount).putVarInt(nodeHashes.size());
		for (byte[] hash : nodeHashes)
			outBuffer.putBytes(Helper.reverseBytes(hash));
		outBuffer.putVarInt(nodeFlags.length).putBytes(nodeFlags);
		return outBuffer;
	}

	/**
	 * Get the serialized byte array
	 *
	 * @return Serialized byte array
	 */
	@Override
	public byte[] getBytes() {
		return getBytes(new SerializedBuffer(nodeHashes.size() * 32 + nodeFlags.length + 12)).toByteArray();
	}

	/**
	 * Traverse the Merkle branch down to the leaf transaction. Return the leaf
	 * transaction hashes and the calculated Merkle root hash. The matchedHash
	 * list will be cleared before starting.
	 *
	 * @param matchedHashes
	 *            Return the hashes of the matched leaf transactions
	 * @return Merkle root
	 * @throws VerificationException
	 *             Malformed Merkle branch
	 */
	public Sha256Hash calculateMerkleRoot(List<Sha256Hash> matchedHashes) throws VerificationException {
		matchedHashes.clear();
		bitsUsed = 0;
		hashesUsed = 0;
		//
		// Start at the root and travel down to the leaf node
		//
		int height = 0;
		while (getTreeWidth(height) > 1)
			height++;
		byte[] merkleRoot = parseBranch(height, 0, matchedHashes);
		//
		// Verify that all bits and hashes were consumed
		//
		if ((bitsUsed + 7) / 8 != nodeFlags.length)
			throw new VerificationException("Merkle branch did not use all of its bits");
		if (hashesUsed != nodeHashes.size())
			throw new VerificationException(
					String.format("Merkle branch used %d of %d hashes", hashesUsed, nodeHashes.size()),
					RejectMessage.REJECT_INVALID);
		return new Sha256Hash(merkleRoot);
	}

	/**
	 * Recursively build the Merkle branch setting the node flags to indicate
	 * the branches we have taken. For each node, follow the left branch as long
	 * as it leads to the next leaf transaction. Then switch to the right branch
	 * to continue. At each node junction, set the appropriate node flag to
	 * indicate which branch we took. For each branch that we don't take, add
	 * the hash for that path to the node hash list.
	 *
	 * @param height
	 *            Current height
	 * @param levelPos
	 *            Current position within level
	 * @param nodePath
	 *            Transaction paths
	 * @param treePos
	 *            Current position within the tree
	 * @param merkleTree
	 *            Merkle tree
	 */
	private void buildBranch(int height, int levelPos, int[][] nodePath, int treePos, List<byte[]> merkleTree) {
		//
		// Determine which branch to take to reach the current transaction
		//
		// hashesUsed tracks our position within nodePath and bitsUsed tracks
		// our
		// position within nodeFlags
		//
		int levelWidth = getTreeWidth(height);
		int nextLevelPos = levelPos * 2;
		int leftTreePos = treePos - levelWidth + nextLevelPos;
		int nextNode = nodePath[height][hashesUsed];
		if (height > 0) {
			//
			// We are not at a leaf node yet, so follow the left or right branch
			// to the next level of the tree.
			//
			if (nextNode == nextLevelPos) {
				//
				// We need to follow the left branch
				//
				Helper.setBitLE(nodeFlags, bitsUsed++);
				buildBranch(height - 1, nextLevelPos, nodePath, treePos - levelWidth, merkleTree);
				//
				// We have found the current transaction, so update nextNode and
				// see if
				// we should now follow the right branch. If not, add the hash
				// for the
				// right path to nodeHashes.
				//
				if (nextLevelPos + 1 < getTreeWidth(height)) {
					if (hashesUsed < nodePath[height].length) {
						nextNode = nodePath[height][hashesUsed];
						if (nextNode == nextLevelPos + 1) {
							Helper.setBitLE(nodeFlags, bitsUsed++);
							buildBranch(height - 1, nextLevelPos + 1, nodePath, treePos - levelWidth, merkleTree);
						} else {
							nodeHashes.add(merkleTree.get(leftTreePos + 1));
							bitsUsed++;
						}
					} else {
						nodeHashes.add(merkleTree.get(leftTreePos + 1));
						bitsUsed++;
					}
				}
			} else if (nextNode == nextLevelPos + 1) {
				//
				// We need to follow the right branch, so add the hash for the
				// left node
				// and then recurse
				//
				nodeHashes.add(merkleTree.get(leftTreePos));
				Helper.setBitLE(nodeFlags, bitsUsed + 1);
				bitsUsed += 2;
				buildBranch(height - 1, nextLevelPos + 1, nodePath, treePos - levelWidth, merkleTree);
			} else {
				throw new IllegalStateException(
						String.format("Next node %d at height %d is not valid", nextNode, height));
			}
		} else {
			//
			// We are at the leaf nodes, so our choice is simple: left node or
			// right node
			//
			if (nextNode == nextLevelPos) {
				//
				// The desired transaction is the left leaf
				//
				Helper.setBitLE(nodeFlags, bitsUsed++);
				nodeHashes.add(merkleTree.get(leftTreePos));
				hashesUsed++;
				//
				// We always add the hash for the right leaf node to nodeHashes.
				// Update nextNode and see if we also have another match.
				//
				if (nextLevelPos + 1 < getTreeWidth(height)) {
					nodeHashes.add(merkleTree.get(leftTreePos + 1));
					if (hashesUsed < nodePath[height].length) {
						nextNode = nodePath[height][hashesUsed];
						if (nextNode == nextLevelPos + 1) {
							Helper.setBitLE(nodeFlags, bitsUsed);
							hashesUsed++;
						}
					}
					bitsUsed++;
				}
			} else if (nextNode == nextLevelPos + 1) {
				//
				// The desired transaction is the right leaf. Add the hashes
				// for both leaves to nodeHashes and indicate the right leaf
				// is a match.
				//
				Helper.setBitLE(nodeFlags, bitsUsed + 1);
				bitsUsed += 2;
				nodeHashes.add(merkleTree.get(leftTreePos));
				nodeHashes.add(merkleTree.get(leftTreePos + 1));
				hashesUsed++;
			} else {
				throw new IllegalStateException(
						String.format("Next node %d at height %d is not valid", nextNode, height));
			}
		}
	}

	/**
	 * Recursively traverse the tree nodes as dictated by the node flags,
	 * getting missing hashes from the node hash list for branches not on our
	 * path. Matching leaf hashes are added to matchesHashes.
	 *
	 * @param height
	 *            Current height
	 * @param pos
	 *            Current position within the level
	 * @param matchedHashes
	 *            Matched hashes from the leaf node
	 * @return Node hash
	 * @throws VerificationException
	 */
	private byte[] parseBranch(int height, int pos, List<Sha256Hash> matchedHashes) throws VerificationException {
		if (bitsUsed >= nodeFlags.length * 8)
			throw new VerificationException("Merkle branch overflowed the bits array", RejectMessage.REJECT_INVALID);
		boolean parentOfMatch = Helper.checkBitLE(nodeFlags, bitsUsed++);
		if (height == 0 || !parentOfMatch) {
			//
			// If at height 0 or nothing interesting below, use the stored hash
			// and do not descend
			// to the next level. If we have a match at height 0, it is a
			// matching transaction.
			//
			if (hashesUsed >= nodeHashes.size())
				throw new VerificationException("Merkle branch overflowed the hash array",
						RejectMessage.REJECT_INVALID);
			if (height == 0 && parentOfMatch)
				matchedHashes.add(new Sha256Hash(nodeHashes.get(hashesUsed)));
			return nodeHashes.get(hashesUsed++);
		}
		//
		// Continue down to the next level
		//
		byte[] right;
		byte[] left = parseBranch(height - 1, pos * 2, matchedHashes);
		if (pos * 2 + 1 < getTreeWidth(height - 1))
			right = parseBranch(height - 1, pos * 2 + 1, matchedHashes);
		else
			right = left;
		//
		// Calculate the node hash from the left and right branches. We need to
		// reverse the bytes for the digest calculation and then reverse the
		// result to match the way Sha256Hash stores the hash bytes.
		//
		return Helper.reverseBytes(
				Helper.doubleDigestTwoBuffers(Helper.reverseBytes(left), 0, 32, Helper.reverseBytes(right), 0, 32));
	}

	/**
	 * Calculate the Merkle tree width for a given height based upon the total
	 * transaction count
	 *
	 * @param height
	 *            Tree height
	 * @return Tree width
	 */
	private int getTreeWidth(int height) {
		return (txCount + (1 << height) - 1) >> height;
	}
}


text:
package com.dmdirc.addons.ui_swing.wizard;

/**
 * Wizard interface, notifications on change of step and closing.
 */
public interface WizardListener {

    /**
     * Called when the wizard finishes.
     */
    void wizardFinished();

    /**
     * Called when the wizard is cancelled.
     */
    void wizardCancelled();

}


text:
module FriendlyId
  # The configuration parameters passed to {Base#friendly_id} will be stored in
  # this object.
  class Configuration

    attr_writer :base

    # The default configuration options.
    attr_reader :defaults

    # The modules in use
    attr_reader :modules

    # The model class that this configuration belongs to.
    # @return ActiveRecord::Base
    attr_accessor :model_class

    # The module to use for finders
    attr_accessor :finder_methods

    def initialize(model_class, values = nil)
      @model_class    = model_class
      @defaults       = {}
      @modules        = []
      @finder_methods = FriendlyId::FinderMethods
      set values
    end

    # Lets you specify the addon modules to use with FriendlyId.
    #
    # This method is invoked by {FriendlyId::Base#friendly_id friendly_id} when
    # passing the `:use` option, or when using {FriendlyId::Base#friendly_id
    # friendly_id} with a block.
    #
    # @example
    #   class Book < ActiveRecord::Base
    #     extend FriendlyId
    #     friendly_id :name, :use => :slugged
    #   end
    #
    # @param [#to_s,Module] modules Arguments should be Modules, or symbols or
    #   strings that correspond with the name of an addon to use with FriendlyId.
    #   By default FriendlyId provides `:slugged`, `:history`, `:simple_i18n`,
    #   and `:scoped`.
    def use(*modules)
      modules.to_a.flatten.compact.map do |object|
        mod = get_module(object)
        mod.setup(@model_class) if mod.respond_to?(:setup)
        @model_class.send(:include, mod) unless uses? object
      end
    end

    # Returns whether the given module is in use.
    def uses?(mod)
      @model_class < get_module(mod)
    end

    # The column that FriendlyId will use to find the record when querying by
    # friendly id.
    #
    # This method is generally only used internally by FriendlyId.
    # @return String
    def query_field
      base.to_s
    end

    # The base column or method used by FriendlyId as the basis of a friendly id
    # or slug.
    #
    # For models that don't use {FriendlyId::Slugged}, this is the column that
    # is used to store the friendly id. For models using {FriendlyId::Slugged},
    # the base is a column or method whose value is used as the basis of the
    # slug.
    #
    # For example, if you have a model representing blog posts and that uses
    # slugs, you likely will want to use the "title" attribute as the base, and
    # FriendlyId will take care of transforming the human-readable title into
    # something suitable for use in a URL.
    #
    # If you pass an argument, it will be used as the base. Otherwise the current
    # value is returned.
    #
    # @param value A symbol referencing a column or method in the model. This
    #   value is usually set by passing it as the first argument to
    #   {FriendlyId::Base#friendly_id friendly_id}.
    def base(*value)
      if value.empty?
        @base
      else
        self.base = value.first
      end
    end

    private

    def get_module(object)
      Module === object ? object : FriendlyId.const_get(object.to_s.titleize.camelize.gsub(/\s+/, ''))
    end

    def set(values)
      values and values.each {|name, value| self.send "#{name}=", value}
    end
  end
end


text:
const test = (true) ?
Broken Color
 :
Also Broken Color


text:
using System;
using System.IO;
using System.Windows;
using FirstFloor.ModernUI.Presentation;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using java.util;
using java.util.concurrent;
using Metrobit.Shell.Messages;
using Metrobit.Shell.Models;
using Metrobit.Shell.Properties;
using Microsoft.Practices.ServiceLocation;

namespace Metrobit.Shell
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static App()
        {
            DispatcherHelper.Initialize();
        }

        public static string AppDataDirectory { get; private set; }

        protected override void OnStartup(StartupEventArgs e)
        {
            AppDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "Metrobit");

            AppDomain.CurrentDomain.SetData("DataDirectory", AppDataDirectory);

            base.OnStartup(e);

            AppearanceManager.Current.ThemeSource = Settings.Default.ThemeSource;
            AppearanceManager.Current.AccentColor = Settings.Default.AccentColor;

            Messenger.Default.Register<ShutdownNotificationMessage>(this, message =>
            {
                var appKit = ServiceLocator.Current.GetInstance<MetrobitWalletAppKit>();

                try
                {
                    appKit.wallet().shutdownAutosaveAndWait();
                    appKit.stopAsync();
                    appKit.awaitTerminated(1, TimeUnit.SECONDS);
                }
                catch (Exception exception)
                {
                    _log.Error("Failed to shutdown wallet gracefully.", exception);
                }
                finally
                {
                    java.lang.System.exit(0);
                    DispatcherHelper.CheckBeginInvokeOnUI(Shutdown);
                }
            });
        }
    }
}


text:
using Cresce.Models.Interfaces;

namespace Cresce.Datasources.Sql.Internal
{
    internal class ContractedAppointment : IIdenfiable
    {
        public string Id { get; set; }
        public string AppointmentId { get; set; }
        public string ContractId { get; set; }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Physalis spruceana Hunz.

### Remarks
null


text:
#include <aws/grafana/model/ValidationExceptionReason.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace ManagedGrafana
  {
    namespace Model
    {
      namespace ValidationExceptionReasonMapper
      {

        static const int UNKNOWN_OPERATION_HASH = HashingUtils::HashString("UNKNOWN_OPERATION");
        static const int CANNOT_PARSE_HASH = HashingUtils::HashString("CANNOT_PARSE");
        static const int FIELD_VALIDATION_FAILED_HASH = HashingUtils::HashString("FIELD_VALIDATION_FAILED");
        static const int OTHER_HASH = HashingUtils::HashString("OTHER");

        ValidationExceptionReason GetValidationExceptionReasonForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == UNKNOWN_OPERATION_HASH)
          {
            return ValidationExceptionReason::UNKNOWN_OPERATION;
          }
          else if (hashCode == CANNOT_PARSE_HASH)
          {
            return ValidationExceptionReason::CANNOT_PARSE;
          }
          else if (hashCode == FIELD_VALIDATION_FAILED_HASH)
          {
            return ValidationExceptionReason::FIELD_VALIDATION_FAILED;
          }
          else if (hashCode == OTHER_HASH)
          {
            return ValidationExceptionReason::OTHER;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ValidationExceptionReason>(hashCode);
          }

          return ValidationExceptionReason::NOT_SET;
        }

        Aws::String GetNameForValidationExceptionReason(ValidationExceptionReason enumValue)
        {
          switch(enumValue)
          {
          case ValidationExceptionReason::UNKNOWN_OPERATION:
            return "UNKNOWN_OPERATION";
          case ValidationExceptionReason::CANNOT_PARSE:
            return "CANNOT_PARSE";
          case ValidationExceptionReason::FIELD_VALIDATION_FAILED:
            return "FIELD_VALIDATION_FAILED";
          case ValidationExceptionReason::OTHER:
            return "OTHER";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace ValidationExceptionReasonMapper
    } // namespace Model
  } // namespace ManagedGrafana
} // namespace Aws


text:
{: #enable-push-ios-notifications-register}

Debe registrar una aplicación (app) con APNs para recibir notificaciones remotas, que normalmente se producen después de instalar la app en un dispositivo. Después de que la app reciba la señal de dispositivo que ha generado APNs, debe volver a pasarse al Servicio de notificaciones Push.

Para registrar las aplicaciones y los dispositivos de iOS:

1. Cree una aplicación de fondo
2. Pase la señal a las Notificaciones Push

##Cree una aplicación de fondo

Cree una aplicación de fondo en el catálogo Bluemix® de la sección de Contenedores modelo, que enlaza automáticamente el servicio Push a esta aplicación. Si ya ha creado una app de fondo, asegúrese de que enlace la app al Servicio de notificaciones Push.

###Objective-C

```
	//Para Objective-C
	- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
	    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:categories]];
	    [[UIApplication sharedApplication] registerForRemoteNotifications];
	    }
	    else{
	    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
	    (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
	    }
	    return YES;
	}
```

###Swift

```
	//For Swift
	func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
		let notificationTypes: UIUserNotificationType = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound
		let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: categories)
		application.registerUserNotificationSettings(notificationSettings)
		application.registerForRemoteNotifications()
	}
```

##Pase la señal a las Notificaciones Push

Después de recibir la señal desde APNs, pase la señal a Notificaciones Push como parte del método `registerDevice:withDeviceToken`.

###Objective-C

```
//Para Objective-C
-( void) application:( UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:( NSData *)deviceToken{

   IMFClient *client = [IMFClient sharedInstance];

 [client initializeWithBackendRoute:@"your-backend-route-here" backendGUID:@"Your-backend-GUID-here"];

 // get Push instance
IMFPushClient* push = [IMFPushClient sharedInstance];
[push registerDeviceToken:deviceToken completionHandler:^(IMFResponse *response,  NSError *error) {
   if (error){
     [ self  updateMessage:error .description];
  }  else {
    [ self updateMessage:response .responseJson .description];
}
}];
```

###Swift

Después de recibir la señal desde APNS, pase la señal a Notificaciones Push como parte del método `didRegisterForRemoteNotificationsWithDeviceToken`.

```
func application (application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
   let push =  BMSPushClient.sharedInstance
   push.registerDeviceToken(deviceToken) { (response, statusCode, error) -> Void in
        if error.isEmpty {
            print( "Response during device registration : \(response)")
            print( "status code during device registration : \(statusCode)")
        }
        else{
            print( "Error during device registration \(error) ")
            Print( "Error during device registration \n  - status code: \(statusCode) \n Error :\(error) \n")
        }
    }

}
```


text:
package org.deeplearning4j.spark.earlystopping;

import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.deeplearning4j.earlystopping.EarlyStoppingConfiguration;
import org.deeplearning4j.earlystopping.EarlyStoppingResult;
import org.deeplearning4j.earlystopping.listener.EarlyStoppingListener;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.spark.api.TrainingMaster;
import org.deeplearning4j.spark.impl.graph.SparkComputationGraph;
import org.deeplearning4j.spark.impl.graph.dataset.DataSetToMultiDataSetFn;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.MultiDataSet;

public class SparkEarlyStoppingGraphTrainer extends BaseSparkEarlyStoppingTrainer<ComputationGraph> {

    private SparkComputationGraph sparkNet;

    public SparkEarlyStoppingGraphTrainer(SparkContext sc, TrainingMaster trainingMaster,
                    EarlyStoppingConfiguration<ComputationGraph> esConfig, ComputationGraph net,
                    JavaRDD<MultiDataSet> train, int examplesPerFit, int totalExamples) {
        this(new JavaSparkContext(sc), trainingMaster, esConfig, net, train, null);
    }

    public SparkEarlyStoppingGraphTrainer(JavaSparkContext sc, TrainingMaster trainingMaster,
                    EarlyStoppingConfiguration<ComputationGraph> esConfig, ComputationGraph net,
                    JavaRDD<MultiDataSet> train, int examplesPerFit, int totalExamples) {
        this(sc, trainingMaster, esConfig, net, train, null);
    }

    public SparkEarlyStoppingGraphTrainer(SparkContext sc, TrainingMaster trainingMaster,
                    EarlyStoppingConfiguration<ComputationGraph> esConfig, ComputationGraph net,
                    JavaRDD<MultiDataSet> train) {
        this(new JavaSparkContext(sc), trainingMaster, esConfig, net, train, null);
    }

    public SparkEarlyStoppingGraphTrainer(JavaSparkContext sc, TrainingMaster trainingMaster,
                    EarlyStoppingConfiguration<ComputationGraph> esConfig, ComputationGraph net,
                    JavaRDD<MultiDataSet> train) {
        this(sc, trainingMaster, esConfig, net, train, null);
    }

    public SparkEarlyStoppingGraphTrainer(JavaSparkContext sc, TrainingMaster trainingMaster,
                    EarlyStoppingConfiguration<ComputationGraph> esConfig, ComputationGraph net,
                    JavaRDD<MultiDataSet> train, EarlyStoppingListener<ComputationGraph> listener) {
        super(sc, esConfig, net, null, train, listener);
        this.sparkNet = new SparkComputationGraph(sc, net, trainingMaster);
    }

    @Override
    protected void fit(JavaRDD<DataSet> data) {
        fitMulti(data.map(new DataSetToMultiDataSetFn()));
    }

    @Override
    protected void fitMulti(JavaRDD<MultiDataSet> data) {
        sparkNet.fitMultiDataSet(data);
    }

    @Override
    protected double getScore() {
        return sparkNet.getScore();
    }

    @Override
    public EarlyStoppingResult<ComputationGraph> pretrain() {
        throw new UnsupportedOperationException("Not supported");
    }
}


text:
<?php

$message->setProtocolVersion('1.1');


text:
BASE="$(cd `dirname "$0"` && pwd)"

main () {
    local cmd="$1"
    case $cmd in
        'setup')
            shift
            setup "$@"
            ;;
        'test')
            shift
            run_tests "$@"
            ;;
        'clean')
            shift
            clean "$@"
            ;;
        * )
            echo "
Exiting without running any operations.
Possible operations include:

  setup - Install dependencies.
    Usage: ./manage.sh setup

  test  - Run 'setup' and then test.
    Usage: ./manage.sh test <username:password@domain:port>

  clean - Remove everything generated by this script.
    Usage: ./manage.sh clean
            "
            ;;
    esac
}

setup () {
    if ! [ -d "$BASE/node_modules" ]; then
        cd "$BASE/"
        npm install
    fi
}

run_tests () {
    hostname="$1"

    if [ -z "$hostname" ]; then
        echo "<uri> argument is required."
        exit
    fi

    setup
    cd "$BASE/"
    node $BASE/bin/run_tests.js "$hostname" test/
}

clean () {
    rm -rf "$BASE/node_modules/"
}

main "$@"


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Something is coming"
        />

</LinearLayout>


text:
using OnlineExamPrep.Common;
using OnlineExamPrep.Models.Common;
using OnlineExamPrep.Models.Common.ParamsModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OnlineExamPrep.Service.Common
{
    public interface IExamService
    {
        Task<List<dynamic>> GetPageWithQuestionsAndTestingAreaAsync(PagingParams pagingParams);
        Task<List<IExam>> GetCollectionAsync(PagingParams pagingParams);
        Task<dynamic> GetExamDataForSimulationAsync(string examId);
        Task<IExamParams> GetExamForUpdateAsync(string examId);
        Task<dynamic> GetExamQuestionsAsync(string examId);
        Task<int> InsertAsync(IExam exam);
        Task<int> UpdateAsync(IExam exam);
        Task<int> DeleteAsync(string examId);
        Task<int> UpdateQuestionOrderAsync(string examId, IExamQuestion[] examQuestions);
    }
}


text:
package com.intel.oap.vectorized;

/** ArrowBufBuilder. */
public class NativeSerializableObject {
  public int[] size;
  public long[] memoryAddress;

  /**
   * Create an instance for NativeSerializableObject.
   *
   * @param memoryAddress native ArrowBuf data addr.
   * @param size ArrowBuf size.
   */
  public NativeSerializableObject(long[] memoryAddress, int[] size) {
    this.memoryAddress = memoryAddress;
    this.size = size;
  }
}


text:
<?php
namespace OPNsense\Tor;

use OPNsense\Base\BaseModel;

class HiddenService extends BaseModel
{
}


text:
var EJSON = require('meteor/ejson')
var _ = require('meteor/underscore')
var Meteor = require('meteor/meteor')
var Deps = require('meteor/deps')
// XXX come up with a serialization method which canonicalizes object key
// order, which would allow us to use objects as values for equals.
var stringify = function (value) {
  if (value === undefined)
    return 'undefined';
  return EJSON.stringify(value);
};
var parse = function (serialized) {
  if (serialized === undefined || serialized === 'undefined')
    return undefined;
  return EJSON.parse(serialized);
};

// migrationData, if present, should be data previously returned from
// getMigrationData()
var ReactiveDict = module.exports = function (migrationData) {
  this.keys = migrationData || {}; // key -> value
  this.keyDeps = {}; // key -> Dependency
  this.keyValueDeps = {}; // key -> Dependency
};

_.extend(ReactiveDict.prototype, {
  set: function (key, value) {
    var self = this;

    value = stringify(value);

    var oldSerializedValue = 'undefined';
    if (_.has(self.keys, key)) oldSerializedValue = self.keys[key];
    if (value === oldSerializedValue)
      return;
    self.keys[key] = value;

    var changed = function (v) {
      v && v.changed();
    };

    changed(self.keyDeps[key]);
    if (self.keyValueDeps[key]) {
      changed(self.keyValueDeps[key][oldSerializedValue]);
      changed(self.keyValueDeps[key][value]);
    }
  },

  setDefault: function (key, value) {
    var self = this;
    // for now, explicitly check for undefined, since there is no
    // ReactiveDict.clear().  Later we might have a ReactiveDict.clear(), in which case
    // we should check if it has the key.
    if (self.keys[key] === undefined) {
      self.set(key, value);
    }
  },

  get: function (key) {
    var self = this;
    self._ensureKey(key);
    self.keyDeps[key].depend();
    return parse(self.keys[key]);
  },

  equals: function (key, value) {
    var self = this;

    // XXX hardcoded awareness of the 'mongo-livedata' package is not ideal
    var ObjectID = Meteor.Collection && Meteor.Collection.ObjectID;

    // We don't allow objects (or arrays that might include objects) for
    // .equals, because JSON.stringify doesn't canonicalize object key
    // order. (We can make equals have the right return value by parsing the
    // current value and using EJSON.equals, but we won't have a canonical
    // element of keyValueDeps[key] to store the dependency.) You can still use
    // "EJSON.equals(reactiveDict.get(key), value)".
    //
    // XXX we could allow arrays as long as we recursively check that there
    // are no objects
    if (typeof value !== 'string' &&
        typeof value !== 'number' &&
        typeof value !== 'boolean' &&
        typeof value !== 'undefined' &&
        !(value instanceof Date) &&
        !(ObjectID && value instanceof ObjectID) &&
        value !== null)
      throw new Error("ReactiveDict.equals: value must be scalar");
    var serializedValue = stringify(value);

    if (Deps.active) {
      self._ensureKey(key);

      if (! _.has(self.keyValueDeps[key], serializedValue))
        self.keyValueDeps[key][serializedValue] = new Deps.Dependency;

      var isNew = self.keyValueDeps[key][serializedValue].depend();
      if (isNew) {
        Deps.onInvalidate(function () {
          // clean up [key][serializedValue] if it's now empty, so we don't
          // use O(n) memory for n = values seen ever
          if (! self.keyValueDeps[key][serializedValue].hasDependents())
            delete self.keyValueDeps[key][serializedValue];
        });
      }
    }

    var oldValue = undefined;
    if (_.has(self.keys, key)) oldValue = parse(self.keys[key]);
    return EJSON.equals(oldValue, value);
  },

  _ensureKey: function (key) {
    var self = this;
    if (!(key in self.keyDeps)) {
      self.keyDeps[key] = new Deps.Dependency;
      self.keyValueDeps[key] = {};
    }
  },

  // Get a JSON value that can be passed to the constructor to
  // create a new ReactiveDict with the same contents as this one
  getMigrationData: function () {
    // XXX sanitize and make sure it's JSONible?
    return this.keys;
  }
});


text:
<?php
namespace Chaos\ORM\Relationship;

use Traversable;
use Lead\Set\Set;
use Chaos\ORM\Document;

/**
 * The `HasMany` relationship.
 */
class HasMany extends \Chaos\ORM\Relationship
{
    /**
     * Indicates whether the relation is a junction table or not.
     *
     * @var boolean
     */
    protected $_junction = false;

    /**
     * Constructs an object that represents a relationship between two model classes.
     *
     * @see Chaos\ORM\Relationship
     * @param array $config The relationship's configuration, which defines how the two models in
     *                      question are bound. The available options are:
     *                      - `'junction'` _boolean_ : Indicates whether the relation is a junction table or not.
     *                                                 If `true`, associative entities are removed when unsetted.
     *                                                 All `hasMany` relations used aby an `hasManyThrough` relation will
     *                                                 have their junction attribute set to `true`. Default to `false`.
     */
    public function __construct($config = [])
    {
        $defaults = [
            'junction' => false
        ];

        $config += $defaults;

        parent::__construct($config);

        $this->_junction = $config['junction'];
    }

    /**
     * Sets the behavior of associative entities. If a hasMany relation is marked as a "junction table",
     * associative entities will be removed once a foreign key is unsetted. When a hasMany relation is
     * not marked as a "junction table", associative entities will simply have their foreign key unsetted.
     *
     * @param  boolean $boolean The junction value to set or none to get it.
     * @return object           Returns `$this` on set and the junction value on get.
     */
    public function junction($boolean = null)
    {
        if (func_num_args()) {
            $this->_junction = $boolean;
            return $this;
        }
        return $this->_junction;
    }

    /**
     * Expands a collection of entities by adding their related data.
     *
     * @param  mixed $collection The collection to expand.
     * @param  array $options    The embedging options.
     * @return array             The collection of related entities.
     */
    public function embed(&$collection, $options = [])
    {
        $indexes = $this->_index($collection, $this->keys('from'));
        $related = $this->_find(array_keys($indexes), $options);

        $name = $this->name();
        $this->_cleanup($collection);

        foreach ($related as $index => $entity) {
            $values = is_object($entity) ? $entity->{$this->keys('to')} : $entity[$this->keys('to')];
            $values = is_array($values) || $values instanceof Traversable ? $values : [$values];
            foreach ($values as $value) {
                $value = (string) $value;
                if (isset($indexes[$value])) {
                    if (is_object($collection[$indexes[$value]])) {
                        $source = $collection[$indexes[$value]];
                        if ($entity instanceof Document) {
                            $source->__get($name)->push($entity); // Too Many Magic Kill The Magic.
                        } else {
                            $source->{$name}[] = $entity;
                        }
                    } else {
                        $collection[$indexes[$value]][$name][] = &$related[$index];
                    }
                }
            }
        }
        return $related;
    }

    /**
     * Saves a relation.
     *
     * @param  object  $entity  The relation's entity
     * @param  array   $options Saving options.
     * @return boolean
     */
    public function save($entity, $options = [])
    {
        if ($this->link() !== static::LINK_KEY) {
            return true;
        }

        $name = $this->name();
        if (!isset($entity->{$name})) {
            return true;
        }

        $conditions = $this->match($entity) + $this->conditions();
        $to = $this->to();
        $previous = $to::all(['conditions' => $conditions]);

        $indexes = $this->_index($previous, $this->keys('from'));
        $result = true;

        foreach ($entity->{$name} as $item) {
            $item->sync();
            $value = (string) $item->id();
            if ($item->exists() && isset($indexes[$value])) {
                unset($previous[$indexes[$value]]);
            }
            $item->set($conditions);
            $result = $result && $item->save($options);
        }

        $junction = $this->junction();

        if ($junction) {
            foreach ($previous as $deprecated) {
                $deprecated->delete();
            }
        } else {
            $toKey = $this->keys('to');
            foreach ($previous as $deprecated) {
                unset($deprecated->{$toKey});
                $deprecated->save();
            }
        }

        return $result;
    }
}


text:
package com.google.cloud.tools.eclipse.appengine.localserver;

import com.google.cloud.tools.eclipse.test.util.BasePluginXmlTest;

public class PluginXmlTest extends BasePluginXmlTest {

}


text:
<?php echo Form::open(array("class"=>"form-horizontal")); ?>

	<fieldset>

			<?php echo Form::label('Server id', 'server_id', array('class'=>'control-label')); ?>

				<?php echo Form::input('server_id', Input::post('server_id', isset($group) ? $group->server_id : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Server id')); ?>

			<?php echo Form::label('Name', 'name', array('class'=>'control-label')); ?>

				<?php echo Form::input('name', Input::post('name', isset($group) ? $group->name : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Name')); ?>

			<?php echo Form::label('Current article', 'current_article', array('class'=>'control-label')); ?>

				<?php echo Form::input('current_article', Input::post('current_article', isset($group) ? $group->current_article : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Current article')); ?>

			<?php echo Form::label('Active', 'active', array('class'=>'control-label')); ?>

				<?php echo Form::input('active', Input::post('active', isset($group) ? $group->active : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Active')); ?>

			<?php echo Form::submit('submit', 'Save', array('class' => 'btn btn-primary')); ?>

	</fieldset>
<?php echo Form::close(); ?>


text: Import-Html "https://en.wikipedia.org/wiki/List_of_Star_Trek:_The_Original_Series_episodes" 2


text:
[![testling badge](https://ci.testling.com/thlorenz/translocator.png)](https://ci.testling.com/thlorenz/translocator)

Convert line-column locations to ranges and vice-versa.

```js
var assert = require('assert');

var text = [
    'line0'
  , 'line1'
].join('\n');

var translocator = require('../')(text);

var locations = { start: { line: 0, column: 2 }, end: { line: 1, column: 3 } };
var range     = translocator.range(locations.start, locations.end)

console.dir({ range: range, subtext: text.slice(range[0], range[1]) });

assert.deepEqual(translocator.locations(range), locations);

// => { range: [ 2, 9 ], subtext: 'ne0\nlin' }
```

## Installation

    npm install translocator

## API

translocator(text) → {Translocator}

Creates a translocator for the given text.

Parameters:

Name
Type
Description

text

string

Source:

index.js
,
lineno 5

Returns:

translocator

Type

Translocator

translocator::index(loc) → {number}

Finds the index in the text that matches the given location.

Parameters:

Name
Type
Description

loc

Object

location of format: { line: number, column: number }

Source:

index.js
,
lineno 23

Throws:

when the given location is outside of the text

Type

Error

Returns:

the index of the given location in the text

Type

number

translocator::location(index) → {Object}

Finds the location of the character in the text at the given index.

Parameters:

Name
Type
Description

index

number

the index of the character in the text to locate

Source:

index.js
,
lineno 60

Throws:

when the given index is outside of the text

Type

Error

Returns:

location of format: { line: number, column: number }

Type

Object

translocator::locations(range) → {Object}

Finds the start and end locations for the given range

Parameters:

Name
Type
Description

range

Array.<number>

start and end indexes of the format [ start, end ]

Source:

index.js
,
lineno 84

Throws:

when the given index is outside of the text

Type

Error

Returns:

locations of the format { start: { line: number, column, number }, end: { line: number, column: number } }

Type

Object

translocator::range(locs, to) → {Arrary.<number>}

Finds start and end index for the given locations.

Parameters:

Name
Type
Description

locs

Object

start and end locationx of format:
{ start: { line: number, column, number }, end: { line: number, column: number } }

to

Object

end location of format: { line: number, column: number }

Source:

index.js
,
lineno 45

Throws:

when the given location is outside of the text

Type

Error

Returns:

the range of the locations within the text of format [ start, end ]

Type

Arrary.<number>

*generated with [docme](https://github.com/thlorenz/docme)*

## License

MIT


text:
package main

import (
	"net/http"
	"time"

	"github.com/codegangsta/martini"
	"github.com/codegangsta/martini-contrib/binding"
	"github.com/codegangsta/martini-contrib/render"
	"github.com/dgrijalva/jwt-go"
)

// User model
type User struct {
	UserId   string `form:"userid" json:"userid" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

// Field validator
func (u *User) Validate(errors *binding.Errors, req *http.Request) {

	if len(u.UserId) < 4 {
		errors.Fields["userid"] = "Too short; minimum 4 characters"
	}
}

const (
	ValidUser = "John"
	ValidPass = "Doe"
	SecretKey = "WOW,MuchShibe,ToDogge"
)

func main() {

	m := martini.Classic()

	m.Use(martini.Static("static"))
	m.Use(render.Renderer())

	m.Get("/", func(r render.Render) {
		r.HTML(201, "index", nil)
	})

	// Authenticate user
	m.Post("/auth", binding.Bind(User{}), func(user User, r render.Render) {

		if user.UserId == ValidUser && user.Password == ValidPass {

			// Create JWT token
			token := jwt.New(jwt.GetSigningMethod("HS256"))
			token.Claims["userid"] = user.UserId
			// Expire in 5 mins
			token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix()
			tokenString, err := token.SignedString([]byte(SecretKey))
			if err != nil {
				r.HTML(201, "error", nil)
				return
			}

			data := map[string]string{

				"token": tokenString,
			}

			r.HTML(201, "success", data)
		} else {
			r.HTML(201, "error", nil)
		}

	})

	// Check Key is ok
	m.Get("/debug/:token", func(params martini.Params, r render.Render) string {
		token, err := jwt.Parse(params["token"], func(token *jwt.Token) ([]byte, error) {
			return []byte(SecretKey), nil
		})
		if err == nil && token.Valid {
			return "User id: " + token.Claims["userid"].(string)
		} else {
			return "Invalid"
		}
	})

	// Only accesible if authenticated
	m.Post("/secret", func() {

	})

	m.Run()
}


text:
.. The Web Modeling Tool execution server documentation master file, created by
   sphinx-quickstart on Wed Jul  6 16:16:08 2016.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

The WMT Execution Server
==================================================================

:Release: |release|
:Date: |today|

The WMT Execution Server,
part of the `CSDMS Web Modeling Tool <http://csdms.colorado.edu/wiki/WMT_portal/>`_,
provides tools to configure and run stand-alone or coupled models
on a computational resource.
The source for this package can be found on GitHub at
`https://github.com/csdms/wmt-exe <https://github.com/csdms/wmt-exe/>`_.

Contents
========

The `wmtexe` package:

.. toctree::

   wmtexe.audit
   wmtexe.config
   wmtexe.env
   wmtexe.formatting
   wmtexe.launcher
   wmtexe.reporter
   wmtexe.slave
   wmtexe.task

The `wmtexe.cmd` subpackage contains code for console scripts:

.. toctree::

   wmtexe.cmd.activate
   wmtexe.cmd.audit
   wmtexe.cmd.exe
   wmtexe.cmd.get
   wmtexe.cmd.info
   wmtexe.cmd.quickstart
   wmtexe.cmd.run
   wmtexe.cmd.script
   wmtexe.cmd.slave

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
#ifndef _CORECRYPTO_CCMD5_H_
#define _CORECRYPTO_CCMD5_H_

#include <corecrypto/ccdigest.h>

#define CCMD5_BLOCK_SIZE   64
#define CCMD5_OUTPUT_SIZE  16
#define CCMD5_STATE_SIZE   16

extern const uint32_t ccmd5_initial_state[4];

/* Selector */
const struct ccdigest_info *ccmd5_di(void);

/* Implementations */
extern const struct ccdigest_info ccmd5_ltc_di;

#endif /* _CORECRYPTO_CCMD5_H_ */


text:
package com.github.paolorotolo.appintro;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

class DefaultIndicatorController implements IndicatorController {
    private Context mContext;
    private LinearLayout mDotLayout;
    private List<ImageView> mDots;
    private int mSlideCount;

    private static final int FIRST_PAGE_NUM = 0;

    @Override
    public View newInstance(@NonNull Context context) {
        mContext = context;
        mDotLayout = (LinearLayout) View.inflate(context, R.layout.default_indicator, null);
        return mDotLayout;
    }

    @Override
    public void initialize(int slideCount) {
        mDots = new ArrayList<>();
        mSlideCount = slideCount;
        mDotLayout.removeAllViews();

        for (int i = 0; i < slideCount; i++) {
            ImageView dot = new ImageView(mContext);
            dot.setImageDrawable(ResourceUtils.getDrawable(mContext, R.drawable.indicator_dot_grey));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            mDotLayout.addView(dot, params);
            mDots.add(dot);
        }

        selectPosition(FIRST_PAGE_NUM);
    }

    @Override
    public void selectPosition(int index) {
        for (int i = 0; i < mSlideCount; i++) {
            int drawableId = (i == index) ? (R.drawable.indicator_dot_white) : (R.drawable.indicator_dot_grey);
            Drawable drawable = ResourceUtils.getDrawable(mContext, drawableId);
            mDots.get(i).setImageDrawable(drawable);
        }
    }
}


text:
This repository is a clone of the Spring 2017 deep reinforcement
learning [class](http://rll.berkeley.edu/deeprlcourse/) at Berkeley.
We've cloned it for the purpose of having a collaborative study group
watching the lectures and working on the problem sets.

# Resources.
## Lecture Material

- Google's deep learning Udacity [course](https://www.udacity.com/course/deep-learning--ud730) seems like a good introduction.

- Professor Bertsekas's Dynamic Programming [lectures](https://www.youtube.com/playlist?list=PLiCLbsFQNFAxOmVeqPhI5er1LGf2-L9I4) seem like a good supplement to these lectures.

## Papers

- Yann Lecun's [paper](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) discusses
  tricks for normalization and initialization.

## Blog Posts etc.

- A [post](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) describing RNNs.
- A [post](http://colah.github.io/posts/2015-08-Understanding-LSTMs/) explaining LSTMs.
- A pair of posts on [seq2seq](https://indico.io/blog/sequence-modeling-neuralnets-part1/)
  and [attention](https://indico.io/blog/sequence-modeling-neuralnets-part1/).
- A [post](http://karpathy.github.io/2016/05/31/rl/) giving general background on RL and diving into score function gradient estimators.

## Books

- [The Deep Learning Book](http://www.deeplearningbook.org/).

## Software

### Tensorflow

- [Tutorials](https://www.tensorflow.org/tutorials/mandelbrot)

- [Tensorboard](https://www.tensorflow.org/get_started/summaries_and_tensorboard) seems like a good way to instrument training algorithms.

- [Supervisor](https://www.tensorflow.org/programmers_guide/supervisor)

- [Threading and queues](https://www.tensorflow.org/programmers_guide/threading_and_queues)

- [TF Slim](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/slim) might save time.

### Other

- [Pudb](https://pypi.python.org/pypi/pudb) seems like a useful debug tool.

## Other courses
- [Stanford CS class CS231n: Convolutional Neural Networks for Visual Recognition](http://cs231n.github.io) - another class more focused on convnets


text:
	<title>BOOST_PP_ENUM_TRAILING</title>
	<link rel="stylesheet" type="text/css" href="../styles.css">

		The BOOST_PP_ENUM_TRAILING macro generates a comma-separated list with a leading comma.

Usage

			BOOST_PP_ENUM_TRAILING(count, macro, data)

Arguments

count

				The number of repetitious calls to macro.
				Valid values range from 0 to BOOST_PP_LIMIT_REPEAT.

macro

				A ternary operation of the form macro(z, n, data).
				This macro is expanded by BOOST_PP_ENUM with the next available repetition depth,
				the current repetition number, and the auxiliary data argument.

data

				Auxiliary data passed to macro.

Remarks

			This macro expands to the comma-separated sequence:

				, macro(z, 0, data), macro(z, 1, data), ... macro(z, count - 1, data)

			The z value that is passed to macro represents the next available repetition dimension.
			Other macros that have _Z suffix variants internally use BOOST_PP_REPEAT--for example, BOOST_PP_ENUM_PARAMS and BOOST_PP_ENUM_PARAMS_Z.
			Using these _Z versions is not strictly necessary, but passing the z value (that is passed to macro) to these macros allows them to reenter BOOST_PP_REPEAT with maximum efficiency.

			To directly use this z value, rather than simply passing it to another macro, see BOOST_PP_ENUM_TRAILING_z.

See Also

BOOST_PP_ENUM_TRAILING_z

BOOST_PP_LIMIT_REPEAT

Requirements

			Header:  <boost/preprocessor/repetition/enum_trailing.hpp>

Sample Code

#include <boost/preprocessor/repetition/enum_trailing.hpp>

#define TEXT(z, n, text) text

template<class BOOST_PP_ENUM_TRAILING(3, TEXT, class)>
class X { };
/*
   expands to...

template<class, class, class, class>
class X { };
*/

		© Copyright Housemarque Oy 2002

© Copyright Paul Mensonides 2002

Distributed under the Boost Software License, Version 1.0. (See
		accompanying file LICENSE_1_0.txt or
		copy at www.boost.org/LICENSE_1_0.txt)


text:
@implementation ClassRollsClient

+(void)getInstructorScheduleWithYearTerm:(YearTerm *)yearTerm andCallBack:(void (^)(InstructorSchedule *, ByuError *))callback {
    [ByuCredentialManager getPersonSummaryWithCallback:^(PersonSummary *personSummary, ByuError *error) {
        if (personSummary) {
            ByuRequest *request = [ByuRequest requestWithMethod:GET andUrl:[self urlWithBaseUrl:INSTRUCTOR_SCHEDULE_BASE_URL andPathParams:@[personSummary.personId, yearTerm.code]]];
            request.acceptType = JSON;
            request.authMethod = OAUTH;
            [[ByuRequestManagerObjC instance] makeRequest:request withCallback:^(ByuResponse *response) {
                if (response.failed) {
                    callback(nil, response.error);
                } else {
                    callback([InstructorSchedule instructorScheduleWithPersonId:personSummary.personId yearTerm:yearTerm andDictionary:[response getDataJson]], nil);
                }
            }];
        } else {
            callback(nil, [[ByuError alloc] initWithError:nil readableMessage:@"Failed to load personal information." debugMessage:nil]);
            return;
        }
    }];
}

+(void)getClassRollWithCurriculumId:(NSString *)curriculumId titleCode:(NSString *)titleCode sectionNumber:(NSString *)sectionNumber yearTerm:(NSString *)yearTerm andCallBack:(void (^)(NSArray<InstructorScheduleClassStudent *> *, ByuError *))callback {
    if (!curriculumId || !titleCode || !sectionNumber || !yearTerm) {
        callback(nil, [[ByuError alloc] initWithError:nil readableMessage:@"Unable to load Instructor's course information." debugMessage:nil]);
        return;
    }
    ByuRequest *request = [ByuRequest requestWithMethod:GET andUrl:[self urlWithBaseUrl:CLASS_ROLL_BASE_URL andPathParams:@[curriculumId, titleCode, sectionNumber, yearTerm]]];
    request.acceptType = JSON;
    request.authMethod = OAUTH;
    [[ByuRequestManagerObjC instance] makeRequest:request withCallback:^(ByuResponse *response) {
        if (response.failed) {
            callback(nil, response.error);
        } else {
            NSArray *students = [[response getDataJson] nullSafeObjectForKeyPath:@"ClassRollService.response.students"];
            students = [students transformWithBlock:^id(id value) {
                return [InstructorScheduleClassStudent studentWithDictionary:value yearTerm:yearTerm curriculumId:curriculumId titleCode:titleCode andSectionNumber:sectionNumber];
            }];
            callback(students, nil);
        }
    }];
}

@end


text:
@interface EezdropperModule : BSModule
+ (EezdropperModule *)module;
@end


text:
Get Youtube thumbnails via Youtube API

## Before you start

Follow the official Google tutorial to [obtain API KEY](https://developers.google.com/youtube/v3/getting-started#before-you-start)

 1. You need a [Google Account](https://www.google.com/accounts/NewAccount) to access the Google API Console, request an API key, and register your application.
 2. Create a project in the [Google Developers Console](https://console.developers.google.com) and [obtain authorization credentials](https://developers.google.com/youtube/registering_an_application) so your application can submit API requests.
 3. After creating your project, make sure the YouTube Data API is one of the services that your application is registered to use:

     - Go to the [Developers Console](https://console.developers.google.com/) and select the project that you just registered.
     - [Open the API Library](https://console.developers.google.com/apis/library?project=_) in the Google Developers Console. If prompted, select a project or create a new one. In the list of APIs, make sure the status is ON for the YouTube Data API v3.
 4. In Credentials in left menu you can generate your API key

## Instalation
```sh
$ npm install youtube-api-thumbnails
```
## Usage

Call the module
```javascript
var thumbnails = require('youtube-api-thumbnails');
```
Configuration
```javascript
thumbnails.config({
  	key: "<your Youtube API key>",	// required
    returnAsArray: true,			// optional, default is false
	onlyHighestRes: true,			// optional, default is false
	getResolutions: true			// optional, default is false
})
```
Get Youtube video thumbnails
```javascript
thumbnails.get(id, callback);
```
#### id
Array of youtube videos ID

#### callback( err, thumbnails )
If error appears err contains error message else is null.

thumbnails is an object with videos ID and links to their thumbnails. Check examples for more information

## Examples
```javascript
thumbnails.get([ 'aaa' , 'Z0ZUwh8GOo0' , 'Rh9a1ICbIJE' ], function (err, thumbnails) {
    if(err){
      console.log(err);
      return;
    }

    console.log(thumbnails);
});
```

Only existing videos will appear in result so video ID **'aaa'** will be missing

#### Result
With default configuration ( only key set )
```
[
	Z0ZUwh8GOo0: {
    	default: 'https://i.ytimg.com/vi/Z0ZUwh8GOo0/default.jpg',
    	medium: 'https://i.ytimg.com/vi/Z0ZUwh8GOo0/mqdefault.jpg',
    	high: 'https://i.ytimg.com/vi/Z0ZUwh8GOo0/hqdefault.jpg',
    	standard: 'https://i.ytimg.com/vi/Z0ZUwh8GOo0/sddefault.jpg' },
  	Rh9a1ICbIJE: {
  		default: 'https://i.ytimg.com/vi/Rh9a1ICbIJE/default.jpg',
    	medium: 'https://i.ytimg.com/vi/Rh9a1ICbIJE/mqdefault.jpg',
    	high: 'https://i.ytimg.com/vi/Rh9a1ICbIJE/hqdefault.jpg',
    	standard: 'https://i.ytimg.com/vi/Rh9a1ICbIJE/sddefault.jpg',
    	maxres: 'https://i.ytimg.com/vi/Rh9a1ICbIJE/maxresdefault.jpg' }
]

```

If **returnAsArray** is set to true in config

```
[
	Z0ZUwh8GOo0: [
    	'https://i.ytimg.com/vi/Z0ZUwh8GOo0/default.jpg',
    	'https://i.ytimg.com/vi/Z0ZUwh8GOo0/mqdefault.jpg',
    	'https://i.ytimg.com/vi/Z0ZUwh8GOo0/hqdefault.jpg',
    	'https://i.ytimg.com/vi/Z0ZUwh8GOo0/sddefault.jpg' ],
  	Rh9a1ICbIJE: [
    	'https://i.ytimg.com/vi/Rh9a1ICbIJE/default.jpg',
    	'https://i.ytimg.com/vi/Rh9a1ICbIJE/mqdefault.jpg',
    	'https://i.ytimg.com/vi/Rh9a1ICbIJE/hqdefault.jpg',
    	'https://i.ytimg.com/vi/Rh9a1ICbIJE/sddefault.jpg',
    	'https://i.ytimg.com/vi/Rh9a1ICbIJE/maxresdefault.jpg' ]
]
```

If **onlyHighestRes** and **getResolutions** are set to true in config

```
[
	Z0ZUwh8GOo0: {
    	url: 'https://i.ytimg.com/vi/Z0ZUwh8GOo0/sddefault.jpg',
    	width: 640,
   		height: 480 },
  	Rh9a1ICbIJE: {
    	url: 'https://i.ytimg.com/vi/Rh9a1ICbIJE/maxresdefault.jpg',
    	width: 1280,
    	height: 720 }
]
```
### Version
1.0.1
### License
MIT


text:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

mongoose.connect('mongodb://192.168.99.100:27017/wepay');

//CONFIGURA
var porta = 8081;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

var router = express.Router();

router.get('/', function (req, res) {
    res.json({ message: 'bem vindo a api do wepay' });
});

app.use('/api', router);

//==================
// REGISTRO DE ROTAS
//==================

//USUARIO
var usuario = require('./app/api/usuarioapi');
app.use('/api', usuario);

//TRANSACAO
var transacao = require('./app/api/transacaoapi');
app.use('/api', transacao);

//ENTRADA
var entrada = require('./app/api/entradaapi');
app.use('/api', entrada);

// INICIA SERVIDOR
app.listen(porta);
console.log('Servidor wepay rodando na porta:' + porta);


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textViewAlreadyRead"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_marginBottom="3dip"
    android:background="@color/transparent"
    android:text="已读"
    android:textColor="#666666"
    android:textSize="12sp"
    android:visibility="gone" />


text:
package org.springframework.transaction.interceptor;

import org.springframework.beans.TestBean;

/**
 * Test for CGLIB proxying that implements no interfaces
 * and has one dependency.
 *
 * @author Rod Johnson
 */
public class ImplementsNoInterfaces {

	private TestBean testBean;

	public void setDependency(TestBean testBean) {
		this.testBean = testBean;
	}

	public String getName() {
		return testBean.getName();
	}

	public void setName(String name) {
		testBean.setName(name);
	}

}


text:
package lexek.wschat.db.model;

import java.util.List;

public class DataPage<T> {
    private final List<T> data;
    private final int page;
    private final int pageCount;

    public DataPage(List<T> data, int page, int pageCount) {
        this.data = data;
        this.page = page;
        this.pageCount = pageCount;
    }

    public List<T> getData() {
        return data;
    }

    public int getPage() {
        return page;
    }

    public int getPageCount() {
        return pageCount;
    }
}


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
/*
<rules>: <rule>
<rules>: [<rule>]
<rule>: {
	resource: {
		test: <condition>,
		include: <condition>,
		exclude: <condition>,
	},
	resource: <condition>, -> resource.test
	test: <condition>, -> resource.test
	include: <condition>, -> resource.include
	exclude: <condition>, -> resource.exclude
	resourceQuery: <condition>,
	compiler: <condition>,
	issuer: <condition>,
	use: "loader", -> use[0].loader
	loader: <>, -> use[0].loader
	loaders: <>, -> use
	options: {}, -> use[0].options,
	query: {}, -> options
	parser: {},
	use: [
		"loader" -> use[x].loader
	],
	use: [
		{
			loader: "loader",
			options: {}
		}
	],
	rules: [
		<rule>
	],
	oneOf: [
		<rule>
	]
}

<condition>: /regExp/
<condition>: function(arg) {}
<condition>: "starting"
<condition>: [<condition>] // or
<condition>: { and: [<condition>] }
<condition>: { or: [<condition>] }
<condition>: { not: [<condition>] }
<condition>: { test: <condition>, include: <condition>, exclude: <condition> }

normalized:

{
	resource: function(),
	resourceQuery: function(),
	compiler: function(),
	issuer: function(),
	use: [
		{
			loader: string,
			options: string,
			<any>: <any>
		}
	],
	rules: [<rule>],
	oneOf: [<rule>],
	<any>: <any>,
}

*/

"use strict";

module.exports = class RuleSet {
	constructor(rules) {
		this.references = Object.create(null);
		this.rules = RuleSet.normalizeRules(rules, this.references, "ref-");
	}

	static normalizeRules(rules, refs, ident) {
		if(Array.isArray(rules)) {
			return rules.map((rule, idx) => {
				return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`);
			});
		} else if(rules) {
			return [RuleSet.normalizeRule(rules, refs, ident)];
		} else {
			return [];
		}
	}

	static normalizeRule(rule, refs, ident) {
		if(typeof rule === "string")
			return {
				use: [{
					loader: rule
				}]
			};
		if(!rule)
			throw new Error("Unexcepted null when object was expected as rule");
		if(typeof rule !== "object")
			throw new Error("Unexcepted " + typeof rule + " when object was expected as rule (" + rule + ")");

		let newRule = {};
		let useSource;
		let resourceSource;
		let condition;

		if(rule.test || rule.include || rule.exclude) {
			checkResourceSource("test + include + exclude");
			condition = {
				test: rule.test,
				include: rule.include,
				exclude: rule.exclude
			};
			try {
				newRule.resource = RuleSet.normalizeCondition(condition);
			} catch(error) {
				throw new Error(RuleSet.buildErrorMessage(condition, error));
			}
		}

		if(rule.resource) {
			checkResourceSource("resource");
			try {
				newRule.resource = RuleSet.normalizeCondition(rule.resource);
			} catch(error) {
				throw new Error(RuleSet.buildErrorMessage(rule.resource, error));
			}
		}

		if(rule.resourceQuery) {
			try {
				newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery);
			} catch(error) {
				throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error));
			}
		}

		if(rule.compiler) {
			try {
				newRule.compiler = RuleSet.normalizeCondition(rule.compiler);
			} catch(error) {
				throw new Error(RuleSet.buildErrorMessage(rule.compiler, error));
			}
		}

		if(rule.issuer) {
			try {
				newRule.issuer = RuleSet.normalizeCondition(rule.issuer);
			} catch(error) {
				throw new Error(RuleSet.buildErrorMessage(rule.issuer, error));
			}
		}

		if(rule.loader && rule.loaders)
			throw new Error(RuleSet.buildErrorMessage(rule, new Error("Provided loader and loaders for rule (use only one of them)")));

		const loader = rule.loaders || rule.loader;
		if(typeof loader === "string" && !rule.options && !rule.query) {
			checkUseSource("loader");
			newRule.use = RuleSet.normalizeUse(loader.split("!"), ident);
		} else if(typeof loader === "string" && (rule.options || rule.query)) {
			checkUseSource("loader + options/query");
			newRule.use = RuleSet.normalizeUse({
				loader: loader,
				options: rule.options,
				query: rule.query
			}, ident);
		} else if(loader && (rule.options || rule.query)) {
			throw new Error(RuleSet.buildErrorMessage(rule, new Error("options/query cannot be used with loaders (use options for each array item)")));
		} else if(loader) {
			checkUseSource("loaders");
			newRule.use = RuleSet.normalizeUse(loader, ident);
		} else if(rule.options || rule.query) {
			throw new Error(RuleSet.buildErrorMessage(rule, new Error("options/query provided without loader (use loader + options)")));
		}

		if(rule.use) {
			checkUseSource("use");
			newRule.use = RuleSet.normalizeUse(rule.use, ident);
		}

		if(rule.rules)
			newRule.rules = RuleSet.normalizeRules(rule.rules, refs, `${ident}-rules`);

		if(rule.oneOf)
			newRule.oneOf = RuleSet.normalizeRules(rule.oneOf, refs, `${ident}-oneOf`);

		const keys = Object.keys(rule).filter((key) => {
			return ["resource", "resourceQuery", "compiler", "test", "include", "exclude", "issuer", "loader", "options", "query", "loaders", "use", "rules", "oneOf"].indexOf(key) < 0;
		});
		keys.forEach((key) => {
			newRule[key] = rule[key];
		});

		function checkUseSource(newSource) {
			if(useSource && useSource !== newSource)
				throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one result source (provided " + newSource + " and " + useSource + ")")));
			useSource = newSource;
		}

		function checkResourceSource(newSource) {
			if(resourceSource && resourceSource !== newSource)
				throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one resource source (provided " + newSource + " and " + resourceSource + ")")));
			resourceSource = newSource;
		}

		if(Array.isArray(newRule.use)) {
			newRule.use.forEach((item) => {
				if(item.ident) {
					refs[item.ident] = item.options;
				}
			});
		}

		return newRule;
	}

	static buildErrorMessage(condition, error) {
		const conditionAsText = JSON.stringify(condition, (key, value) => {
			return value === undefined ? "undefined" : value;
		}, 2);
		return error.message + " in " + conditionAsText;
	}

	static normalizeUse(use, ident) {
		if(Array.isArray(use)) {
			return use
				.map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`))
				.reduce((arr, items) => arr.concat(items), []);
		}
		return [RuleSet.normalizeUseItem(use, ident)];
	}

	static normalizeUseItemFunction(use, data) {
		const result = use(data);
		if(typeof result === "string") {
			return RuleSet.normalizeUseItem(result);
		}
		return result;
	}

	static normalizeUseItemString(useItemString) {
		const idx = useItemString.indexOf("?");
		if(idx >= 0) {
			return {
				loader: useItemString.substr(0, idx),
				options: useItemString.substr(idx + 1)
			};
		}
		return {
			loader: useItemString
		};
	}

	static normalizeUseItem(item, ident) {
		if(typeof item === "function")
			return item;

		if(typeof item === "string") {
			return RuleSet.normalizeUseItemString(item);
		}

		let newItem = {};

		if(item.options && item.query)
			throw new Error("Provided options and query in use");

		if(!item.loader)
			throw new Error("No loader specified");

		newItem.options = item.options || item.query;

		if(typeof newItem.options === "object" && newItem.options) {
			if(newItem.options.ident)
				newItem.ident = newItem.options.ident;
			else
				newItem.ident = ident;
		}

		const keys = Object.keys(item).filter(function(key) {
			return ["options", "query"].indexOf(key) < 0;
		});

		keys.forEach(function(key) {
			newItem[key] = item[key];
		});

		return newItem;
	}

	static normalizeCondition(condition) {
		if(!condition)
			throw new Error("Expected condition but got falsy value");
		if(typeof condition === "string") {
			return str => str.indexOf(condition) === 0;
		}
		if(typeof condition === "function") {
			return condition;
		}
		if(condition instanceof RegExp) {
			return condition.test.bind(condition);
		}
		if(Array.isArray(condition)) {
			const items = condition.map(c => RuleSet.normalizeCondition(c));
			return orMatcher(items);
		}
		if(typeof condition !== "object")
			throw Error("Unexcepted " + typeof condition + " when condition was expected (" + condition + ")");

		let matchers = [];
		Object.keys(condition).forEach(key => {
			const value = condition[key];
			switch(key) {
				case "or":
				case "include":
				case "test":
					if(value)
						matchers.push(RuleSet.normalizeCondition(value));
					break;
				case "and":
					if(value) {
						const items = value.map(c => RuleSet.normalizeCondition(c));
						matchers.push(andMatcher(items));
					}
					break;
				case "not":
				case "exclude":
					if(value) {
						const matcher = RuleSet.normalizeCondition(value);
						matchers.push(notMatcher(matcher));
					}
					break;
				default:
					throw new Error("Unexcepted property " + key + " in condition");
			}
		});
		if(matchers.length === 0)
			throw new Error("Excepted condition but got " + condition);
		if(matchers.length === 1)
			return matchers[0];
		return andMatcher(matchers);
	}

	exec(data) {
		const result = [];
		this._run(data, {
			rules: this.rules
		}, result);
		return result;
	}

	_run(data, rule, result) {
		// test conditions
		if(rule.resource && !data.resource)
			return false;
		if(rule.resourceQuery && !data.resourceQuery)
			return false;
		if(rule.compiler && !data.compiler)
			return false;
		if(rule.issuer && !data.issuer)
			return false;
		if(rule.resource && !rule.resource(data.resource))
			return false;
		if(data.issuer && rule.issuer && !rule.issuer(data.issuer))
			return false;
		if(data.resourceQuery && rule.resourceQuery && !rule.resourceQuery(data.resourceQuery))
			return false;
		if(data.compiler && rule.compiler && !rule.compiler(data.compiler))
			return false;

		// apply
		const keys = Object.keys(rule).filter((key) => {
			return ["resource", "resourceQuery", "compiler", "issuer", "rules", "oneOf", "use", "enforce"].indexOf(key) < 0;
		});
		keys.forEach((key) => {
			result.push({
				type: key,
				value: rule[key]
			});
		});

		if(rule.use) {
			rule.use.forEach((use) => {
				result.push({
					type: "use",
					value: typeof use === "function" ? RuleSet.normalizeUseItemFunction(use, data) : use,
					enforce: rule.enforce
				});
			});
		}

		if(rule.rules) {
			for(let i = 0; i < rule.rules.length; i++) {
				this._run(data, rule.rules[i], result);
			}
		}

		if(rule.oneOf) {
			for(let i = 0; i < rule.oneOf.length; i++) {
				if(this._run(data, rule.oneOf[i], result))
					break;
			}
		}

		return true;
	}

	findOptionsByIdent(ident) {
		const options = this.references[ident];
		if(!options) throw new Error("Can't find options with ident '" + ident + "'");
		return options;
	}
};

function notMatcher(matcher) {
	return function(str) {
		return !matcher(str);
	};
}

function orMatcher(items) {
	return function(str) {
		for(let i = 0; i < items.length; i++) {
			if(items[i](str))
				return true;
		}
		return false;
	};
}

function andMatcher(items) {
	return function(str) {
		for(let i = 0; i < items.length; i++) {
			if(!items[i](str))
				return false;
		}
		return true;
	};
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="hello">Hello World, SendSms!</string>
	<string name="app_name">发送短信</string>
	<string name="number">收件人号码:</string>
	<string name="content">短信内容:</string>
	<string name="send">发送</string>
</resources>


text:
package dev;

public class PROJECT_Quack {
    /*
     * Where should filter placement happen? BGP reordering?
     *
     *  Define a lifecycle.
     *    "reorder" BGP -> BGP
     *    Place filters.
     *    Reorder
     *    Place filters.
     *
OpExecutor
  OpExecutorBlockFilter         <<- rename?
    + OpExecutorBlock           <<-
    |   OpExecutorStage
    |     OpExecutorStageMain   <<- Node space, old style
    + OpExecutorRowsMain        <<- Node space, rows
    + OpExecutorTDBBase
    |   OpExecutorQuackTDB

    When to go to X space?

    BlockExecutors for BGP excution (replaces StageGenerator
    public interface BlockExecutor
    {
        public QueryIterator execute(BasicPattern pattern, QueryIterator input, ExecutionContext execCxt) ;
    }

    Where does reordering go?
    Needs a PeekIterator.

    */

    /*
     * OpExecLib
     */

    // Incorportate reordering of BGPs.  Add a defualt of "fixed"

    // Detailed tests for Accessor(TBD)
    // Benchmark setup.

    // Creating ExecutionContexts
    //    QC.createExecutionContext(dsg)

    // Iterator -> RowSource = Iterator + isReady()

    // Java8-isation.

    // Caching in substitution
    //   Same binding (row) -> same output
    //   Use array for output, sized to max prev seen.

    // BindingBuilder

    // Scope tracker.

    // Drop support for TDB/OpExecutorQuack on anything but datasets - not individual graphs.
    // OpExecutorTDBBase.isForThisExecutor
    // EecutionContext.getExecutor() is not a factory.

    // BSBM Q5 ****
    // Reorder: adjacent same-subject
    //   Do and don't break up by filter reorder.
    //   StepPredicateObjectList is simpler.
    // * TransformReorder
    // * TransformFilterPlacement <-- Spilt this
    // What does Quack do current?
    // What does TDB do current?

    // Design:
    //   Extend Quack to Sequence/Join/LeftJoin/Conditional
    //    AccessorGraph not trigger fully by test suite.
    //    OpExecutorRowsMain not using PredObjList

    // TDB
    // Setting factory needs to set the global choice
    //   QC.execute in: QueryIterUnion, QueryIterOptionalIndex,
    //                  ExprFunctionOp,
    //                  QueryIterGraph.QueryIterGraphInner,
    // Only need change at OpGraph boundaries.
    // ExecutionContext.getCurrentOpExec(), not factory

    // ** Sort out wiring.
    //   OpExecutorQuackTDB has an indirection.
    //   QueryEngineQuack does set the context factory.
    //   Add getOpExecutor to ExecutionContext?  Currently return the factory.

    // ** Initial inputs and accessors
    // RowVarBinding - a fixed array version.

    // Quack: Tuple<Slot> == Slots? Pattern? TuplePattern? TPattern

    // BGP reorder by Transform.
    // Not working for graphs ?g ?

    // Optimizer
    //   reorder BGPs then do filter placement optimization.
    // Scan with filter (between X Y)
    //   Links to jump start on merge join?
    // Do we need a bottom up executor c.f. OpExecutor and Evaluator (ref engine).

    // OpExecutorGeneral == OpExecutorMain2?
    //   Document as extension point - roll out to ARQ, remove StageGenerators.

    // BindingNodeId (read-only part) as interface so a Row<NodeId> can project it.
    // RowBuilder that is Tuples<NodeId> to Row<NodeId>
    // RowBuilder fixed width rows.

    // Fixed width Rows
    // Row implementation which is a a fixed width, fixed variable (for small N)
    // e.g. a [] of Var and a [] of results.

    // Efficient Tuples and Bindings.
    //   Test whether fixed width whole pattern bindings make sense.
    //   Tuple.make/1,2,3
    //   Binding.make/1,2,3 or Binding Builder

    // MergeJoin
    //   Jumpstart right. Needs per X code via Accessor?
    //   Small left, large right ==> merge or substitute?

    // == TDB
    // StorageTDB = indexes + node table.
    // + SystemParams2 / SystemParamsBuilder
    //     + Setting default system params or building dataset
    //     + Location sensitive?

    // + idx tools
    //   + Index copy to do location to location
    //    DBcopy to do location to location (compression!)
    //   + idxinfo
    //   + idxdump
}


text:
name             'deploy'
maintainer       'Joseph Bridgwater-Rowe'
maintainer_email 'joe@westernmilling.com'
license          'All rights reserved'
description      'Creates and configures a passwordless deployment user.'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'

depends 'apt'
depends 'user'


text:
import $ from 'jquery'
import EventEmitter from 'events'

export default class Player extends EventEmitter {
  jFrame

  constructor(pathToSwf) {
    super()

    this.jFrame = $('div')
    this.initPlayer(pathToSwf)
    this.initBindings()
  }

  initPlayer(pathToSwf) {
    this.jFrame.jPlayer({
      swfPath: pathToSwf,
      supplied: 'mp3',
      solution: 'html',
    })
  }

  initBindings() {
    this.jFrame.bind($.jPlayer.event.ready, (event) => this.emit('ready', event))
    this.jFrame.bind($.jPlayer.event.play, (event) => this.emit('play', event))
    this.jFrame.bind($.jPlayer.event.pause, (event) => this.emit('pause', event))
    this.jFrame.bind($.jPlayer.event.waiting, (event) => this.emit('waiting', event))
    this.jFrame.bind($.jPlayer.event.playing, (event) => this.emit('playing', event))
    this.jFrame.bind($.jPlayer.event.canplay, (event) => this.emit('canplay', event))
    this.jFrame.bind($.jPlayer.event.seeking, (event) => this.emit('seeking', event))
    this.jFrame.bind($.jPlayer.event.seeked, (event) => this.emit('seeked', event))
    this.jFrame.bind($.jPlayer.event.ended, (event) => this.emit('ended', event))
    this.jFrame.bind($.jPlayer.event.volumechange, (event) => this.emit('volumechange', event))
    this.jFrame.bind($.jPlayer.event.timeupdate, (event) =>
      this.emit('timeupdate', event.jPlayer.status.currentTime, event),
    )
  }

  async load(url) {
    this.jFrame.jPlayer('setMedia', { mp3: url })
  }

  async play(position) {
    this.jFrame.jPlayer('play', position)
  }

  async pause() {
    this.jFrame.jPlayer('pause')
  }

  async stop() {
    this.jFrame.jPlayer('stop')
  }

  async close() {
    this.jFrame.jPlayer('clearMedia')
  }

  async seek(position) {
    this.jFrame.jPlayer('playHead', position)
  }

  async volume(volume) {
    this.jFrame.jPlayer('volume', volume)
  }
}


text:
<?php

namespace TelegramBot\Types;

/**
 * Represents the {@see https://core.telegram.org/bots/api#botcommandscope scope}
 * of bot commands, covering all private chats.
 *
 * @see https://core.telegram.org/bots/api#botcommandscopeallprivatechats
 */
class BotCommandScopeAllPrivateChats
{
    /**
     * Scope type, must be all_private_chats
     * @var string $type
     */
    public $type;
}


text:
package com.zrlog.admin.business.rest.response;

import com.zrlog.common.vo.Version;

import java.io.Serializable;

public class CheckVersionResponse implements Serializable {

    private Boolean upgrade;
    private Version version;

    public Boolean getUpgrade() {
        return upgrade;
    }

    public void setUpgrade(Boolean upgrade) {
        this.upgrade = upgrade;
    }

    public Version getVersion() {
        return version;
    }

    public void setVersion(Version version) {
        this.version = version;
    }
}


text:
<?php
header('Access-Control-Allow-Origin: *');
$client_id = '725594625403-tu1r5phvui0rf2l9094p4ont101cuq15.apps.googleusercontent.com';
$Email_address = 'gaaccess@kl82-bigquery-streaming.iam.gserviceaccount.com';
$KEY_FILE_LOCATION = 'KL82-bigquery-streaming-542cbda95a62.json';
$projectId='kl82-bigquery-streaming'; //bigQuery project id
# Imports the Google Cloud client library
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\BigQuery\BigQueryClient;
# Instantiates a client
$bigquery = new BigQueryClient(['projectId' => $projectId]);
//var_dump($_POST["data"]);
# The name for the new dataset
$datasetName = 'gadataset';
$tableName = 'my_table';
/*# Creates the new dataset
$dataset = $bigquery->createDataset($datasetName);
echo 'Dataset ' . $dataset->id() . ' created.';*/
// $dataset->createTable("sometable");
$dataset = $bigquery->dataset($datasetName);
$table = $dataset->table($tableName);
 /*$fields = array(
        array('name' => 'user_id', 'type' => 'integer', 'mode' => 'required'),
        array('name' => 'order_id', 'type' => 'integer', 'mode' => 'required'),
        array('name' => 'status', 'type' => 'integer', 'mode' => 'nullable'),
        array('name' => 'timestamp', 'type' => 'timestamp', 'mode' => 'nullable')
    );
    $table_reference = new Google_Service_Bigquery_TableReference();
    $table_reference->setProjectId($projectId);
    $table_reference->setDatasetId($datasetName);
    $table_reference->setTableId($tableName);
   // $schema = new Google_Service_Bigquery_TableSchema();
  //  $schema->setFields($fields);
  //  $table = new Google_Service_Bigquery_Table();
    $table_reference->setSchema($fields);
   $table->setSchema($schema);
    try {
        return $bigquery->tables->insert($project_id, $dataset_id, $table);
    } catch (Google_Service_Exception $e) {
        $this->setErrors($e->getErrors())->setErrorMessage($e->getMessage());
        throw $e;
    }*/

$data= json_decode($_POST["data"], true);
$ready_data;
foreach ($data as $key => $value) {

   switch ($key) {
    case (preg_match('/^cd[0-9]*/',$key)? true : false) :
		$ready_data['dimensions'][$key]=$value;
		unset($data[$key]);
        break;
    case (preg_match('/^cm[0-9]*/',$key)? true : false) :
		$ready_data['metrics'][$key]=$value;
		unset($data[$key]);
        break;
	case (preg_match('/^cg[0-9]*/',$key)? true : false) :
		$ready_data['contentGroups'][$key]=$value;
		unset($data[$key]);
        break;
	case (preg_match('/^il[0-9].*/',$key)? true : false) :
		switch ($key) {
			case (preg_match('/^il[0-9]*pi[0-9]*/',$key)? true : false) :
			$pr=explode("pi",$key);
			preg_match('/^[0-9]*/', $pr[1], $match);
			$param=str_replace ($match[0],"",$pr[1]);
			 if(preg_match('/^cd[0-9]*/',$param))
			{
				$ready_data['products'][$match[0]-1]["dimensions"][$param]=$value;
				unset($data[$key]);
			}else if(preg_match('/^cm[0-9]*/',$param))
			{
				$ready_data['products'][$match[0]-1]["metrics"][$param]=$value;
				unset($data[$key]);
			}else{
				$ready_data['products'][$match[0]-1][$param]=$value;
				unset($data[$key]);
			}
			$ready_data['products'][$match[0]-1]['action']['name']="impression";
			break;
		}
        break;

			case (preg_match('/^pr[0-9]*/',$key)? true : false) :
			$pr=substr ($key,2);
			preg_match('/^[0-9]*/', $pr, $match);
			$param=str_replace ($match[0],"",$pr);
			 if(preg_match('/^cd[0-9]*/',$param))
			{
				$ready_data['products'][$match[0]-1]["dimensions"][$param]=$value;
				unset($data[$key]);
			}else if(preg_match('/^cm[0-9]*/',$param))
			{
				$ready_data['products'][$match[0]-1]["metrics"][$param]=$value;
				unset($data[$key]);
			}else{
				$ready_data['products'][$match[0]-1][$param]=$value;
				unset($data[$key]);
			}
			$ready_data['products'][$match[0]-1]['action']['name']=$data["pa"];
			$ready_data['products'][$match[0]-1]['action']['step']=$data["cos"];
			break;

    default:
	if($key!="pa"&&$key!="cos"){
        $ready_data[$key]=$value;
		unset($data[$key]);
	}
        break;
}
}
//var_dump($ready_data);
$insertResponse = $table->insertRows([
        [ 'data' =>$ready_data],
        // additional rows can go here
    ]);
    if ($insertResponse->isSuccessful()) {
      //  print('Data streamed into BigQuery successfully' . PHP_EOL);
    } else {
        foreach ($insertResponse->failedRows() as $row) {
            foreach ($row['errors'] as $error) {
				var_dump($error);
                printf('%s: %s' . PHP_EOL, $error['reason'], $error['message']);
            }
        }
    }
?>