text:
namespace DTML.EduBot.Dialogs
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.Bot.Builder.Dialogs;
    using Microsoft.Bot.Builder.Luis;
    using Microsoft.Bot.Builder.Luis.Models;
    using DTML.EduBot.Common;
    using DTML.EduBot.Constants;
    using DTML.EduBot.Extensions;

    public partial class ChitChatDialog : QnaLuisDialog <Object>
    {
        [LuisIntent("UserEmotion")]
        public async Task HandleIAmIntent(IDialogContext context, LuisResult result)
        {
           await context.PostTranslatedAsync(BotPersonality.GetRandomGenericResponse());
        }
    }
}


text:
package com.synopsys.integration.blackduck.api;

import static org.junit.jupiter.api.Assertions.*;

import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import com.synopsys.integration.bdio.SimpleBdioFactory;
import com.synopsys.integration.bdio.model.externalid.ExternalId;
import com.synopsys.integration.blackduck.TimingExtension;
import com.synopsys.integration.blackduck.api.generated.enumeration.ComplexLicenseType;
import com.synopsys.integration.blackduck.api.generated.view.ComplexLicenseView;
import com.synopsys.integration.blackduck.rest.IntHttpClientTestHelper;
import com.synopsys.integration.blackduck.service.BlackDuckServicesFactory;
import com.synopsys.integration.blackduck.service.LicenseService;

@Tag("integration")
@ExtendWith(TimingExtension.class)
public class LicenseDataServiceTestIT {
    private final IntHttpClientTestHelper intHttpClientTestHelper = new IntHttpClientTestHelper();

    @Test
    public void testGettingLicenseFromComponentVersion() throws Exception {
        BlackDuckServicesFactory blackDuckServicesFactory = intHttpClientTestHelper.createBlackDuckServicesFactory();
        LicenseService licenseService = blackDuckServicesFactory.createLicenseService();

        SimpleBdioFactory simpleBdioFactory = new SimpleBdioFactory();
        ExternalId guavaExternalId = simpleBdioFactory.createMavenExternalId("com.google.guava", "guava", "20.0");
        Optional<ComplexLicenseView> optionalComplexLicense = licenseService.getComplexLicenseItemFromComponent(guavaExternalId);
        ComplexLicenseView complexLicense = optionalComplexLicense.get();

        assertEquals("Apache License 2.0", complexLicense.getLicenseDisplay());
        assertEquals(ComplexLicenseType.DISJUNCTIVE, complexLicense.getType());
        assertEquals(1, complexLicense.getLicenses().size());

        ComplexLicenseView embeddedLicense = complexLicense.getLicenses().get(0);
        assertTrue(StringUtils.isNotBlank(embeddedLicense.getLicense()));
        assertEquals("Apache License 2.0", embeddedLicense.getLicenseDisplay());
        assertEquals("Apache License 2.0", embeddedLicense.getName());
        assertEquals("OPEN_SOURCE", embeddedLicense.getOwnership());
        assertNull(embeddedLicense.getType());
        assertEquals(0, embeddedLicense.getLicenses().size());

        System.out.println(complexLicense);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.code.pomelo.design.pattern.command.common.expression;

/**
 * Created by ruyin on 2018/1/29.
 *
 * 一个命令抽象类,命令指定一个接收执行者
 */
public abstract class Command {

    protected Receiver receiver;

    public Command(Receiver receiver) {
        this.receiver = receiver;
    }

    abstract public void executeCommand();
}


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

using Dice.AST;

namespace Dice
{
    /// <summary>
    /// Represents the context of a function call, such as the parameters
    /// and what die expression it is attached to.
    /// </summary>
    public class FunctionContext
    {
        /// <summary>
        /// The scope of this function call.
        /// </summary>
        public FunctionScope Scope { get; private set; }

        /// <summary>
        /// The function name, in the case it was defined.
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// The arguments to the function.
        /// </summary>
        public IReadOnlyList<DiceAST> Arguments { get; private set; }

        /// <summary>
        /// RollData attached to this function execution.
        /// </summary>
        public RollData Data { get; private set; }

        /// <summary>
        /// The dice expression this function is attached to, or null
        /// if this is a global function call.
        /// </summary>
        public DiceAST? Expression { get; internal set; }

        /// <summary>
        /// The result of this function call.
        /// </summary>
        public decimal Value { get; set; }

        /// <summary>
        /// What sort of value the function call returns.
        /// </summary>
        public ResultType ValueType { get; set; }

        /// <summary>
        /// If dice rolls need to be exposed, set Values to them.
        /// If null, the underlying dice rolls of Expression (if any) are used.
        /// </summary>
        public IEnumerable<DieResult>? Values { get; set; }

        /// <summary>
        /// Number of extra rolls performed during function execution.
        /// </summary>
        internal long NumRolls { get; set; }

        /// <summary>
        /// When evaluating, the root node of the AST.
        /// </summary>
        internal DiceAST? Root { get; set; }

        /// <summary>
        /// When evaluating, the current evaluation depth as of the time of this function call.
        /// </summary>
        internal int? Depth { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="FunctionContext"/> class.
        /// </summary>
        /// <param name="scope">Scope the function is attached to.</param>
        /// <param name="name">Function name.</param>
        /// <param name="arguments">Arguments passed to the function.</param>
        /// <param name="data">Roll configuration.</param>
        internal FunctionContext(FunctionScope scope, string name, IReadOnlyList<DiceAST> arguments, RollData data)
        {
            Scope = scope;
            Name = name;
            Arguments = arguments;
            Expression = null!;
            Value = Decimal.MinValue;
            ValueType = ResultType.Total;
            Values = null;
            Data = data;
            NumRolls = 0;
        }

        /// <summary>
        /// Roll an extra die as part of the function execution.
        /// </summary>
        /// <param name="rollType">Type of roll to perform.</param>
        /// <param name="numSides">Number of sides to roll.</param>
        /// <returns>The result of the die roll.</returns>
        public DieResult RollExtra(RollType rollType, int numSides)
        {
            NumRolls++;
            return RollNode.DoRoll(Data, rollType, numSides, DieFlags.Extra);
        }

        /// <summary>
        /// Rerolls the given die.
        /// </summary>
        /// <param name="die">A DieResult representing a basic roll or group roll.</param>
        /// <returns>The result of the reroll.</returns>
        public DieResult Reroll(DieResult die)
        {
            if (Expression == null)
            {
                throw new InvalidOperationException("Cannot reroll from a global function call");
            }

            if (Root == null || Depth == null)
            {
                throw new InvalidOperationException("Cannot reroll when not evaluating a roll");
            }

            if (die.DieType == DieType.Group)
            {
                if (die.Data == null)
                {
                    throw new InvalidOperationException("Grouped die roll is missing group key");
                }

                var group = Data.InternalContext.GetGroupExpression(die.Data);
                NumRolls += group.Reroll(Data, Root, Depth.Value + 1);

                return new DieResult()
                {
                    DieType = DieType.Group,
                    NumSides = 0,
                    Value = group.Value,
                    // maintain any crit/fumble flags from the underlying dice, combining them together
                    Flags = group.Values
                            .Where(d => d.DieType != DieType.Special && !d.Flags.HasFlag(DieFlags.Dropped))
                            .Select(d => d.Flags & (DieFlags.Critical | DieFlags.Fumble))
                            .Aggregate((d1, d2) => d1 | d2) | DieFlags.Extra,
                    Data = die.Data
                };
            }
            else
            {
                var rt = die.DieType switch
                {
                    DieType.Normal => RollType.Normal,
                    DieType.Fudge => RollType.Fudge,
                    _ => throw new InvalidOperationException("Unsupported die type in reroll"),
                };

                return RollExtra(rt, die.NumSides);
            }
        }
    }
}


text:
@interface BilinearInterpolation : NSObject {

}

//- (void) test;
+ (CGPoint)BilinearInterpolationOfPoints:(CGPoint[100])points WithParameter:(CGPoint)parameters;
+ (CGPoint)InverseBilinearInterpolationOfPoints:(CGPoint[100])points WithPoint:(CGPoint)point;

int fuzzTestInvBilerp( int num_trials );
int inverseBilerp( double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3, double x, double y, double* sout, double* tout, double* s2out, double* t2out );
int bilerp( double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3, double s, double t, double* x, double* y );

@end


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: May 19, 2011
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  VHAISWWERFEJ
  Description:

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */
package gov.va.med.server.tomcat;

import gov.va.med.imaging.tomcat.vistarealm.RealmErrorContext;

import java.io.IOException;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.deploy.LoginConfig;
import org.apache.log4j.Logger;

/**
 * This extends the Basic authentication valve for Tomcat and checks for values on thread local to add as response headers.
 * This allows a client to know why an authentication failed
 *
 * @author VHAISWWERFEJ
 *
 */
public class TomcatBasicAuthenticatorValve
extends org.apache.catalina.authenticator.BasicAuthenticator
{
	private final static Logger logger = Logger.getLogger(TomcatBasicAuthenticatorValve.class);
	public final static String httpHeaderAuthenticateErrorMessage = "xxx-authenticate-error-message";
	public final static String httpHeaderAuthenticateErrorName = "xxx-authenticate-error-name";

	public TomcatBasicAuthenticatorValve()
	{
		super();
		logger.info("TomcatBasicAuthenticatorValve <ctor>");
	}

	@Override
	public boolean authenticate(Request request, Response response, LoginConfig loginConfig)
			throws IOException
	{
		// must clear before calling to ensure not using a previous attempts data (since threads are recycled)
		RealmErrorContext.clear();
		logger.debug("TomcatBaiscAuthenticatorValve.authenticate(Request, Response, LoginConfig)");
		boolean result = super.authenticate(request, response, loginConfig);
		if(!result)
		{
			String errorMessage = RealmErrorContext.getProperty(RealmErrorContext.realmErrorContextExceptionMessage);
			String exceptionClass = RealmErrorContext.getProperty(RealmErrorContext.realmErrorContextExceptionName);
			logger.debug("authentication failed with error '" + (exceptionClass == null ? "<null>" : exceptionClass) + "' and message '" + (errorMessage == null ? "<null>" : errorMessage) + "'.");
			if(errorMessage != null)
				response.addHeader(httpHeaderAuthenticateErrorMessage, errorMessage);
			if(exceptionClass != null)
				response.addHeader(httpHeaderAuthenticateErrorName, exceptionClass);
		}
		RealmErrorContext.unsetRealmErrorContext();
		return result;
	}

}


text:
/*
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     (1) Redistributions of source code must retain the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer.
 *
 *     (2) Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *     (3) Neither the name of the copyright holder nor the names of
 *     its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written
 *     permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#pragma once

#include <inttypes.h>
#include <string.h>
//#include <pthread.h>
#include <vector>
#include <string>

#ifdef HAVE_CONFIG_H
    #include "ac_config.h"
#endif
#include "stdlib/local_db/sqlite3.h"

class PartialMessage {
public:
	PartialMessage()
		: length(0),
		  msg_type(NULL),
		  part_msg(NULL),
		  ttl{0,0}
		{
		};

	~PartialMessage()
		{
			free(msg_type);
			free(part_msg);
		};

	uint32_t length;
	char *msg_type;
	uint8_t *part_msg;
	struct timeval ttl;
};

class PartialMessageList {
public:
	~PartialMessageList()
		{
			unsigned int n;

			for (n = 0; n < list_.size(); ++n)
				delete list_[n];
		};

	size_t size(void) const
		{
			return list_.size();
		};

	void push_back(PartialMessage *pmsg)
		{
			list_.push_back(pmsg);
		};

	/*
	 * Returns message number n. If the message in question has
	 * exceeded its time to live, then a NULL will be
	 * returned. NULL will also be returned if n >= size().
	 */
	PartialMessage *get_at(const unsigned int n)
		{
			if (n > (list_.size() - 1))
				return NULL;

			return list_[n];
		};

private:
	std::vector<PartialMessage*> list_;
};

class MsgDB {
public:

        MsgDB(void)
		: db_(NULL),
		  db_path_(NULL),
		  insert_recv_msg_statement_(NULL),
		  insert_sent_msg_statement_(NULL),
		  max_recv_seqnum_statement_(NULL),
		  max_sent_seqnum_statement_(NULL)
                {
                };

        ~MsgDB()
                {
                        this->close();
                        free(db_path_);
                };

        /*
         * Does whatever needs doing to get the database initialized
         * and ready for action.
         *
         * Returns 1 (one) if all is well, 0 (zero) if not.
         */
        int open(void);

        /*
         * On-disk database file path
         */
        int set_db_path(const char * const db_path)
                {
                        free(db_path_);
                        db_path_ = strdup(db_path);

                        return (NULL != db_path_);
                }

        /*
         * Returns when the underlying store is closed. Blocks
         * potentially for a long(-ish) time.
         *
         * Returns 1 (one) if all is well, 0 (zero) if not.
         */
        int close(void);

        /*
         * Stores outgoing partial messages.
         *
         * seqnum: Sequence number
         * msg: The partial message
         * len: Number of bytes in msg
         *
         * Returns 1 (one) if all is well, 0 (zero) otherwise.
         */
        int store_sent_msg(const uint64_t seqnum,
                           const uint64_t len,
			   const uint64_t ttl_tv_sec,
			   const uint64_t ttl_tv_usec,
                           const uint8_t * const msg,
                           const char * const msg_type);

        /*
         * Stores incoming complete messages.
         *
         * seqnum: Sequence number
         * msg: The complete message
         * len: Number of bytes in msg
         *
         * Returns 1 (one) if all is well, 0 (zero) otherwise.
         */
        int store_recv_msg(const uint64_t seqnum,
                           const uint64_t len,
                           const uint8_t * const msg);

        /*
         * Returns the sequence number of last recieved message or 0
         * if the session is new.
         *
         * Returns 1 (one) if all is well, 0 (zero) otherwise.
         */
        int get_latest_recv_seqnum(uint64_t & seqnum) const;

        /*
         * Returns the sequence number of last transmitted message or
         * 0 if the session is new.
         *
         * Returns 1 (one) if all is well, 0 (zero) otherwise.
         */
        int get_latest_sent_seqnum(uint64_t & seqnum) const;

        /*
         * Returns a vector of previously sent partial messages ready
         * to be re-sent starting with sequence number "start" and
         * ending with sequence number "end", both included.
         *
         * If "end" is larger than the largest sequence number, or 0
         * (zero), then all messages, starting with "start", is
         * returned.
         *
         * This method is not performance critical (re-sending is a
         * fairly rare occurrence) and the implementation reflects
         * that.
	 *
	 * Only messages within their respective TTL will be
	 * returned. Messages which has exceeded their time to live
	 * will be returned as NULL.
	 *
	 * Memory allocation errors will result in NULL being returned.
         */
        PartialMessageList *get_sent_msgs(uint64_t start, uint64_t end) const;

        /*
         * Returns a vector of previously recieved complete messages
         * starting with sequence number "start" and ending with
         * sequence number "end", both included.
         *
         * If "end" is larger than the largest sequence number then
         * all messages, starting with "start", is returned.
         *
         * This method is not performance critical and the
         * implementation reflects that.
         */
        std::vector<std::vector<uint8_t> > *get_recv_msgs(uint64_t start, uint64_t end) const;

private:
        sqlite3 *db_;
        char *db_path_;
        sqlite3_stmt *insert_recv_msg_statement_;
        sqlite3_stmt *insert_sent_msg_statement_;
        sqlite3_stmt *max_recv_seqnum_statement_;
        sqlite3_stmt *max_sent_seqnum_statement_;
};


text:
This chapter outlines the general research methodology of this thesis,
and explains different choices. The methodology of this thesis is
generally based on the guidelines proposed by
\citet{article:casestudies} for conducting a case study. An objective is
defined and a literature study is conducted in order to establish a
theoretical base. A case study is then conducted in order to evaluate
the theory by applying it in a real-life application context. Finally,
the result is analyzed in order to draw conclusions about the theory.


text:
package org.apache.activemq.transport;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.BrokerTest;
import org.apache.activemq.broker.StubConnection;
import org.apache.activemq.broker.TransportConnector;

public abstract class TransportBrokerTestSupport extends BrokerTest {

    protected TransportConnector connector;
    private ArrayList<StubConnection> connections = new ArrayList<StubConnection>();

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    @Override
    protected BrokerService createBroker() throws Exception {
        BrokerService service = super.createBroker();
        connector = service.addConnector(getBindLocation());
        return service;
    }

    protected abstract String getBindLocation();

    @Override
    protected void tearDown() throws Exception {
        for (Iterator<StubConnection> iter = connections.iterator(); iter.hasNext();) {
            try {
                StubConnection connection = iter.next();
                connection.stop();
                iter.remove();
            } catch (Exception ex) {
            }
        }

        if (connector != null) {
            try {
                connector.stop();
            } catch (Exception ex) {
            }
        }

        super.tearDown();
    }

    protected URI getBindURI() throws URISyntaxException {
        return new URI(getBindLocation());
    }

    @Override
    protected StubConnection createConnection() throws Exception {
        URI bindURI = getBindURI();

        // Note: on platforms like OS X we cannot bind to the actual hostname, so we
        // instead use the original host name (typically localhost) to bind to

        URI actualURI = connector.getServer().getConnectURI();
        URI connectURI = new URI(actualURI.getScheme(), actualURI.getUserInfo(), bindURI.getHost(), actualURI.getPort(), actualURI.getPath(), bindURI
                .getQuery(), bindURI.getFragment());

        Transport transport = TransportFactory.connect(connectURI);
        StubConnection connection = new StubConnection(transport);
        connections.add(connection);
        return connection;
    }

}


text:
<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        // poner el nombre de la tabla en singular la cual se ejecutara con el comando de artisan
        $this->call(TagTableSeeder::class);
    }
}


text:
<?php

namespace MobileCart\FedexBundle\Api\RateV10\SimpleType;

/**
 * CM = centimeters, IN = inches
 *
 *
 */
class LinearUnits extends SimpleTypeAbstract
{
    const CM = 'CM';

    const IN = 'IN';

    static function getUnits()
    {
        return [
            self::CM,
            self::IN,
        ];
    }
}


text:
#ifndef EEPROMEX_h
#define EEPROMEX_h

#include <EEPROM.h>

#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <inttypes.h>
#include <avr/eeprom.h>

// Boards with ATmega328, Duemilanove, Uno, UnoSMD, Lilypad - 1024 bytes (1 kilobyte)
// Boards with ATmega1280 or 2560, Arduino Mega series – 4096 bytes (4 kilobytes)
// Boards with ATmega168, Lilypad, old Nano, Diecimila  – 512 bytes (1/2 kilobyte)

#define EEPROMSizeATmega168   512
#define EEPROMSizeATmega328   1024
#define EEPROMSizeATmega1280  4096

#define EEPROMSizeUno         EEPROMSizeATmega328
#define EEPROMSizeUnoSMD      EEPROMSizeATmega328
#define EEPROMSizeLilypad     EEPROMSizeATmega328
#define EEPROMSizeDuemilanove EEPROMSizeATmega328
#define EEPROMSizeMega        EEPROMSizeATmega1280
#define EEPROMSizeDiecimila   EEPROMSizeATmega168
#define EEPROMSizeNano        EEPROMSizeATmega168

class EEPROMClassEx
{

  public:
	EEPROMClassEx();
	bool 	 isReady();
	int 	 writtenBytes();
    void 	 setMemPool(int base, int memSize);
	void  	 setMaxAllowedWrites(int allowedWrites);
	int 	 getAddress(int noOfBytes);

	uint8_t  read(int);
	bool 	 readBit(int, byte);
	uint8_t  readByte(int);
    uint16_t readInt(int);
    uint32_t readLong(int);
	float    readFloat(int);
	double   readDouble(int);

    bool     write(int, uint8_t);
	bool 	 writeBit(int , uint8_t, bool);
	bool     writeByte(int, uint8_t);
	bool 	 writeInt(int, uint16_t);
	bool 	 writeLong(int, uint32_t);
	bool 	 writeFloat(int, float);
	bool 	 writeDouble(int, double);

	bool     update(int, uint8_t);
	bool 	 updateBit(int , uint8_t, bool);
	bool     updateByte(int, uint8_t);
	bool 	 updateInt(int, uint16_t);
	bool 	 updateLong(int, uint32_t);
	bool 	 updateFloat(int, float);
	bool 	 updateDouble(int, double);

    // Use template for other data formats

	template <class T> int readBlock(int address, const T value[], int items)
	{
		if (!isWriteOk(address+items*sizeof(T))) return 0;
		unsigned int i;
		for (i = 0; i < items; i++)
			readBlock<T>(address+(i*sizeof(T)),value[i]);
		return i;
	}

	template <class T> int readBlock(int address, const T& value)
	{
		eeprom_read_block((void*)&value, (const void*)address, sizeof(value));
		return sizeof(value);
	}

	template <class T> int writeBlock(int address, const T value[], int items)
	{
		if (!isWriteOk(address+items*sizeof(T))) return 0;
		unsigned int i;
		for (i = 0; i < items; i++)
			  writeBlock<T>(address+(i*sizeof(T)),value[i]);
		return i;
	}

	template <class T> int writeBlock(int address, const T& value)
	{
		if (!isWriteOk(address+sizeof(value))) return 0;
		eeprom_write_block((void*)&value, (void*)address, sizeof(value));
		return sizeof(value);
	}

	template <class T> int updateBlock(int address, const T value[], int items)
	{
		int writeCount=0;
		if (!isWriteOk(address+items*sizeof(T))) return 0;
		unsigned int i;
		for (i = 0; i < items; i++)
			  writeCount+= updateBlock<T>(address+(i*sizeof(T)),value[i]);
		return writeCount;
	}

	template <class T> int updateBlock(int address, const T& value)
	{
		int writeCount=0;
		if (!isWriteOk(address+sizeof(value))) return 0;
		const byte* bytePointer = (const byte*)(const void*)&value;
		for (unsigned int i = 0; i < sizeof(value); i++) {
			if (read(address)!=*bytePointer) {
				write(address, *bytePointer);
				writeCount++;
			}
			address++;
			*bytePointer++;
		}
		return writeCount;
	}

private:
	//Private variables
	static int _base;
	static int _memSize;
	static int _nextAvailableaddress;
	static int _writeCounts;
	int _allowedWrites;
	bool checkWrite(int base,int noOfBytes);
	bool isWriteOk(int address);
	bool isReadOk(int address);
};

extern EEPROMClassEx EEPROM;

#endif


text:
using System.Runtime.CompilerServices;
namespace AutoMapper.Configuration;

public interface ICtorParamConfigurationExpression
{
    /// <summary>
    /// Specify the source member(s) to map from.
    /// </summary>
    /// <param name="sourceMembersPath">Property name referencing the source member to map against. Or a dot separated member path.</param>
    void MapFrom(string sourceMembersPath);
}
public interface ICtorParamConfigurationExpression<TSource> : ICtorParamConfigurationExpression
{
    /// <summary>
    /// Map constructor parameter from member expression
    /// </summary>
    /// <typeparam name="TMember">Member type</typeparam>
    /// <param name="sourceMember">Member expression</param>
    void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember);

    /// <summary>
    /// Map constructor parameter from custom func that has access to <see cref="ResolutionContext"/>
    /// </summary>
    /// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
    /// <param name="resolver">Custom func</param>
    void MapFrom<TMember>(Func<TSource, ResolutionContext, TMember> resolver);
}
public interface ICtorParameterConfiguration
{
    string CtorParamName { get; }
    void Configure(TypeMap typeMap);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public class CtorParamConfigurationExpression<TSource, TDestination> : ICtorParamConfigurationExpression<TSource>, ICtorParameterConfiguration
{
    public string CtorParamName { get; }
    public Type SourceType { get; }

    private readonly List<Action<ConstructorParameterMap>> _ctorParamActions = new List<Action<ConstructorParameterMap>>();

    public CtorParamConfigurationExpression(string ctorParamName, Type sourceType)
    {
        CtorParamName = ctorParamName;
        SourceType = sourceType;
    }

    public void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember) =>
        _ctorParamActions.Add(cpm => cpm.MapFrom(sourceMember));

    public void MapFrom<TMember>(Func<TSource, ResolutionContext, TMember> resolver)
    {
        Expression<Func<TSource, TDestination, TMember, ResolutionContext, TMember>> resolverExpression = (src, dest, destMember, ctxt) => resolver(src, ctxt);
        _ctorParamActions.Add(cpm => cpm.SetResolver(new FuncResolver(resolverExpression)));
    }

    public void MapFrom(string sourceMembersPath)
    {
        var sourceMembers = ReflectionHelper.GetMemberPath(SourceType, sourceMembersPath);
        _ctorParamActions.Add(cpm => cpm.MapFrom(sourceMembersPath, sourceMembers));
    }

    public void Configure(TypeMap typeMap)
    {
        var ctorMap = typeMap.ConstructorMap;
        if (ctorMap == null)
        {
            throw new AutoMapperConfigurationException($"The type {typeMap.DestinationType.Name} does not have a constructor.\n{typeMap.DestinationType.FullName}");
        }
        var parameter = ctorMap[CtorParamName];
        if (parameter == null)
        {
            throw new AutoMapperConfigurationException($"{typeMap.DestinationType.Name} does not have a matching constructor with a parameter named '{CtorParamName}'.\n{typeMap.DestinationType.FullName}.{CheckRecord(ctorMap.Ctor)}");
        }
        foreach (var action in _ctorParamActions)
        {
            action(parameter);
        }
        return;
        static string CheckRecord(ConstructorInfo ctor) => ctor.IsFamily && ctor.Has<CompilerGeneratedAttribute>() ?
            " When mapping to records, consider excluding non-public constructors. See https://docs.automapper.org/en/latest/Construction.html." : null;
    }
}


text:
<?php

declare(strict_types=1);

namespace Humus\Amqp\Driver\PhpAmqpLib;

use Humus\Amqp\Channel as ChannelInterface;
use Humus\Amqp\ConnectionOptions;
use PhpAmqpLib\Connection\AMQPLazySocketConnection as BaseLazySocketConnection;
use Traversable;

final class LazySocketConnection extends AbstractConnection
{
    /**
     * @param ConnectionOptions|array|Traversable $options
     */
    public function __construct($options)
    {
        if (! $options instanceof ConnectionOptions) {
            $options = new ConnectionOptions($options);
        }

        $this->options = $options;
        $this->connection = new BaseLazySocketConnection(
            $options->host(),
            $options->port(),
            $options->login(),
            $options->password(),
            $options->vhost(),
            false,
            'AMQPLAIN',
            null,
            'en_US',
            $options->readTimeout() ?: $options->writeTimeout(),
            $options->heartbeat() > 0
        );
    }

    public function newChannel(): ChannelInterface
    {
        $method = new \ReflectionMethod($this->connection, 'connect');
        $method->setAccessible(true);
        $method->invoke($this->connection);

        return parent::newChannel();
    }
}


text:
example1:
  id: addition-calc
  title: Addition
example2:
  id: subtraction-calc
  title: Subtraction
---
<script src="scripts/calculator.js"></script>

#Calculator

The calculator is our contrived sample component. It carries out simple arithmetic on two inputted values. It is configurable by passing context into it.

##Example 1
Adding two numbers
{{#example1}}
  {{> calculator}}
{{/example1}}

<script>
  new Calculator(document.getElementById('{{example1.id}}'), {
    modifier: '+'
  });
</script>

##Example 2
Subtracting two numbers
{{#preview:html}}
  {{#example2}}
    {{> calculator}}
  {{/example2}}
{{/preview:html}}
{{#preview:js}}
  <script>
    new Calculator(document.getElementById('{{example2.id}}'), {
      modifier: '-'
    });
  </script>
{{/preview:js}}


text:
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <exception>
#include <stdexcept>

#include <boost/shared_ptr.hpp>

#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdint.h>
#include <memory.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>

#include "shared.h"
#include "onl_database.h"

#include "onlcrd_reservation.h"
#include "onlcrd_session.h"
#include "onlcrd_component.h"
#include "onlcrd_session_manager.h"
#include "onlcrd_globals.h"
#include "onlcrd_requests.h"
#include "onlcrd_responses.h"
#include "onlcrd_session_sharing.h"

using namespace onlcrd;

reservation::reservation(uint32_t rid, std::string username, nccp_connection* nc)
{
  id = int2str(rid).c_str();
  user = username;
  nccpconn = nc;

  cleared = false;

  pthread_mutex_init(&req_lock, NULL);
}

reservation::~reservation()
{
  clear();

  pthread_mutex_destroy(&req_lock);
}

void
reservation::set_begin_request(begin_reservation_req* req)
{
  autoLockDebug rlock(req_lock, "reservation::set_begin_request(): req_lock");
  write_log("reservation::set_begin_request user:" + user + " id:" + id);
  begin_req = req;
}

void
reservation::add_component(reservation_add_component_req* req)
{
  autoLockDebug rlock(req_lock, "reservation::add_component(): req_lock");
  write_log("reservation::add_component user:" + user + " id:" + id + " component:" + req->getComponent().getLabel());
  component_reqs.push_back(req);
}

void
reservation::add_cluster(reservation_add_cluster_req* req)
{
  autoLockDebug rlock(req_lock, "reservation::add_cluster(): req_lock");
  write_log("reservation::add_cluster user:" + user + " id:" + id + " component:" + req->getComponent().getLabel());
  cluster_reqs.push_back(req);
}

void
reservation::add_link(reservation_add_link_req* req)
{
  autoLockDebug rlock(req_lock, "reservation::add_link(): req_lock");
  write_log("reservation::add_link user:" + user + " id:" + id + " component:" + req->getComponent().getLabel());
  link_reqs.push_back(req);
}

void
reservation::commit()
{
  autoLockDebug rlock(req_lock, "reservation::commit(): req_lock");
  write_log("reservation::commit user:" + user + " id:" + id);
  if(cleared) return;

  uint32_t num_reqs = begin_req->getNumRequests();
  uint32_t num_reqs_rxed = component_reqs.size() + cluster_reqs.size() + link_reqs.size();
  write_log("reservation::commit(): user:" + user + " id:" + id + " expecting " + int2str(num_reqs) + " requests rxed:" + int2str(num_reqs_rxed));
  uint32_t num_attempts = 0;
  while(num_reqs_rxed < num_reqs)
  {
    // check every 50ms until all reqs received or it's been 1 minute
    if(num_attempts > 1200) { return; }
    num_attempts++;
    rlock.unlock();
    struct timespec ts;
    ts.tv_sec = 0;
    ts.tv_nsec = 50000000;
    nanosleep(&ts, NULL);
    rlock.lock();
    num_reqs_rxed = component_reqs.size() + cluster_reqs.size() + link_reqs.size();  }

  while(!cluster_reqs.empty())
  {
    session_add_cluster_req* req = (session_add_cluster_req*)cluster_reqs.front();
    cluster_reqs.pop_front();

    component c = req->getComponent();
    NCCP_StatusType stat = NCCP_Status_Fine;
    onl::onldb_resp r = topology.add_node(c.getType(), c.getID(), c.getParent());
    if(r.result() < 1)
    {
      stat = NCCP_Status_AllocFailed;
    }

    cluster_response* resp = new cluster_response(req, stat);
    resp->send();
    delete resp;
    delete req;
  }

  while(!component_reqs.empty())
  {
    session_add_component_req* req = (session_add_component_req*)component_reqs.front();
    component_reqs.pop_front();

    component c = req->getComponent();
    NCCP_StatusType stat = NCCP_Status_Fine;
    onl::onldb_resp r = topology.add_node(c.getType(), c.getID(), c.getParent(), false, req->getCores(), req->getMemory(), req->getNumInterfaces(), req->getInterfaceBW());
    if(r.result() < 1)
    {
      stat = NCCP_Status_AllocFailed;
    }
    else if(c.getCP() != "")
    {
      the_session_manager->fix_component(&topology, c.getID(), c.getCP());
    }

    component_response* resp = new component_response(req, stat);
    resp->send();
    delete resp;
    delete req;
  }

  while(!link_reqs.empty())
  {
    session_add_link_req* req = (session_add_link_req*)link_reqs.front();
    link_reqs.pop_front();

    component c = req->getComponent();
    NCCP_StatusType stat = NCCP_Status_Fine;

    std::string n1type = topology.get_type(req->getFromComponent().getID());
    int n1port = req->getFromPort();
    int n1cap = req->getFromCapacity();
    std::string n2type = topology.get_type(req->getToComponent().getID());
    int n2port = req->getToPort();
    int n2cap = req->getToCapacity();

    bool hascap = true;
    if (req->get_version() <= 0x75) hascap = false;

    if(n1type == "vgige" && n2type == "vgige")
    {
      // we could try to calculate the max capacity here instead..
      n1cap = MAX_INTERCLUSTER_CAPACITY;
      n2cap = MAX_INTERCLUSTER_CAPACITY;
    }
    else if(n1type == "vgige")
    {
      if (!hascap)
	{
	  n2cap = the_session_manager->get_capacity(n2type,n2port);
	}
      n1cap = n2cap;
    }
    else if(n2type == "vgige")
    {
      if (!hascap)
	{
	  n1cap = the_session_manager->get_capacity(n1type,n1port);
	}
      n2cap = n1cap;
    }
    else if (!hascap)
    {
      n1cap = the_session_manager->get_capacity(n1type,n1port);
      n2cap = the_session_manager->get_capacity(n2type,n2port);
    }

    if(n1cap == -1 || n2cap == -1 || (!hascap && n1cap != n2cap))
    {
      stat = NCCP_Status_AllocFailed;
    }
    else
    {
      onl::onldb_resp r = topology.add_cap_link(c.getID(), n1cap, req->getFromComponent().getID(), n1port, n1cap, req->getToComponent().getID(), n2port, n2cap);
      if(r.result() < 1)
      {
        stat = NCCP_Status_AllocFailed;
      }
    }

    rlicrd_response* resp = new rlicrd_response(req, stat);
    resp->send();
    delete resp;
    delete req;
  }

  // now assign the physical resources to the virtual topology
  if(!the_session_manager->make_reservation(this, user, begin_req->getEarlyStart(), begin_req->getLateStart(), begin_req->getDuration(), &topology))
  {
    begin_req->commit_done(false, errmsg, "");
  }
  else
  {
    begin_req->commit_done(true, "Reservation Request Succeeded", errmsg);
  }

  delete begin_req;
  begin_req = NULL;
}

void
reservation::clear()
{
  autoLockDebug rlock(req_lock, "reservation::clear(): req_lock");
  if(cleared) return;
  cleared = true;

  write_log("reservation::clear(): clearing reservation " + user + "," + id);

  while(!cluster_reqs.empty())
  {
    reservation_add_cluster_req* req = cluster_reqs.front();
    cluster_reqs.pop_front();

    cluster_response* resp = new cluster_response(req, NCCP_Status_Failed);
    resp->set_more_message(true);
    resp->send();
    delete resp;
    delete req;
  }

  while(!component_reqs.empty())
  {
    reservation_add_component_req* req = component_reqs.front();
    component_reqs.pop_front();

    component_response* resp = new component_response(req, NCCP_Status_Failed);
    resp->set_more_message(true);
    resp->send();
    delete resp;
    delete req;
  }

  while(!link_reqs.empty())
  {
    reservation_add_link_req* req = link_reqs.front();
    link_reqs.pop_front();

    rlicrd_response* resp = new rlicrd_response(req, NCCP_Status_Failed);
    resp->set_more_message(true);
    resp->send();
    delete resp;
    delete req;
  }

  if(begin_req != NULL)
  {
    begin_req->commit_done(false, "Reservation failed.", "");
  }
  delete begin_req;
  begin_req = NULL;
}


text:
package org.bitcoins.core.util

import org.bitcoins.core.crypto.{ ECPrivateKey, ECPublicKey }
import org.bitcoins.core.script.bitwise.{ OP_EQUALVERIFY, OP_OR }
import org.bitcoins.core.script.constant._
import org.bitcoins.core.script.crypto._
import org.bitcoins.core.script.flag.ScriptVerifyWitnessPubKeyType
import org.bitcoins.core.script.locktime.OP_CHECKLOCKTIMEVERIFY
import org.bitcoins.core.script.reserved.{ OP_NOP, OP_RESERVED }
import org.bitcoins.core.script.result.ScriptErrorWitnessPubKeyType
import org.bitcoins.core.script.stack.OP_DUP
import org.scalatest.{ FlatSpec, MustMatchers }

/**
 * Created by chris on 3/2/16.
 */
class BitcoinScriptUtilTest extends FlatSpec with MustMatchers {

  //from b30d3148927f620f5b1228ba941c211fdabdae75d0ba0b688a58accbf018f3cc
  val asm = TestUtil.p2pkhScriptPubKey.asm
  val expectedHex = TestUtil.rawP2PKHScriptPubKey
  "BitcoinScriptUtil" must "give us the correct hexadecimal value of an asm script" in {

    BitcoinScriptUtil.asmToHex(asm) must be(asm.flatMap(_.hex).mkString)
  }

  it must "give us the correct byte representation of an asm script" in {
    BitcoinScriptUtil.asmToBytes(asm) must be(asm.flatMap(_.bytes))
  }

  it must "filter out all of the push operations in a scriptSig" in {
    BitcoinScriptUtil.filterPushOps(Seq(OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4) ++
      BytesToPushOntoStack.operations).isEmpty must be(true)
  }

  it must "determine if a script op count towards the bitcoin script op code limit" in {
    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_1) must be(false)
    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_16) must be(false)
    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_RESERVED) must be(false)

    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_NOP) must be(true)
    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_CHECKLOCKTIMEVERIFY) must be(true)
  }

  it must "not count script constants towards the script count limit" in {
    BitcoinScriptUtil.countsTowardsScriptOpLimit(ScriptConstant("1234")) must be(false)
  }

  it must "not count OP_PUSHDATA operations towards the script count" in {
    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_PUSHDATA1) must be(false)
    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_PUSHDATA2) must be(false)
    BitcoinScriptUtil.countsTowardsScriptOpLimit(OP_PUSHDATA4) must be(false)
  }

  it must "count 0 sigops where there are none in a script" in {
    val script = Seq()
    BitcoinScriptUtil.countSigOps(script) must be(0)
    BitcoinScriptUtil.countSigOps(Seq(OP_1, OP_2, ScriptConstant("1234")))
  }

  it must "count n sigops when we have n occurrences OP_CHECKSIG or OP_CHECKSIGVERIFY in a script" in {
    BitcoinScriptUtil.countSigOps(Seq(OP_CHECKSIG)) must be(1)
    BitcoinScriptUtil.countSigOps(Seq(OP_CHECKSIGVERIFY)) must be(1)

    BitcoinScriptUtil.countSigOps(Seq(OP_CHECKSIG, OP_CHECKSIG, OP_CHECKSIG, OP_CHECKSIG, OP_CHECKSIG)) must be(5)
    BitcoinScriptUtil.countSigOps(Seq(OP_CHECKSIGVERIFY, OP_CHECKSIGVERIFY,
      OP_CHECKSIGVERIFY, OP_CHECKSIGVERIFY, OP_CHECKSIGVERIFY)) must be(5)
  }

  it must "count n sigops when have n possible signatures in a OP_CHECKMULTISIG or OP_CHECKMULTISIGVERIFY" in {
    BitcoinScriptUtil.countSigOps(Seq(OP_0, OP_CHECKMULTISIG)) must be(0)
    BitcoinScriptUtil.countSigOps(Seq(OP_0, OP_CHECKMULTISIGVERIFY)) must be(0)

    BitcoinScriptUtil.countSigOps(Seq(OP_1, OP_CHECKMULTISIG)) must be(1)
    BitcoinScriptUtil.countSigOps(Seq(OP_1, OP_CHECKMULTISIGVERIFY)) must be(1)

    BitcoinScriptUtil.countSigOps(Seq(OP_16, OP_CHECKMULTISIG)) must be(16)
    BitcoinScriptUtil.countSigOps(Seq(OP_16, OP_CHECKMULTISIGVERIFY)) must be(16)
  }

  it must "count n sigops when have n possible signatures with multiple occurrences OP_CHECKMULTISIG or OP_CHECKMULTISIGVERIFY in a script" in {
    BitcoinScriptUtil.countSigOps(Seq(OP_0, OP_CHECKMULTISIG, OP_0, OP_CHECKMULTISIG)) must be(0)
    BitcoinScriptUtil.countSigOps(Seq(OP_0, OP_CHECKMULTISIGVERIFY, OP_0, OP_CHECKMULTISIGVERIFY)) must be(0)

    BitcoinScriptUtil.countSigOps(Seq(OP_1, OP_CHECKMULTISIG, OP_1, OP_CHECKMULTISIG)) must be(2)
    BitcoinScriptUtil.countSigOps(Seq(OP_1, OP_CHECKMULTISIGVERIFY, OP_1, OP_CHECKMULTISIGVERIFY)) must be(2)

    BitcoinScriptUtil.countSigOps(Seq(OP_16, OP_CHECKMULTISIG, OP_16, OP_CHECKMULTISIG)) must be(32)
    BitcoinScriptUtil.countSigOps(Seq(OP_16, OP_CHECKMULTISIGVERIFY, OP_16, OP_CHECKMULTISIG)) must be(32)
  }

  it must "determine if the empty script is push only" in {
    BitcoinScriptUtil.isPushOnly(Seq()) must be(true)
    BitcoinScriptUtil.isPushOnly(Seq(OP_0)) must be(true)
  }

  it must "determine that script is not push only if it contains any operation whose op code is > OP_16.opCode" in {
    BitcoinScriptUtil.isPushOnly(Seq(OP_NOP, OP_0, OP_0, OP_0)) must be(false)
  }

  it must "determine that a script is not push only if it contains a ScriptConstant" in {
    BitcoinScriptUtil.isPushOnly(Seq(OP_NOP, BytesToPushOntoStack(1), ScriptConstant("51"))) must be(false)
  }

  it must "determine that the script is not push only if it contains an script number operation" in {
    BitcoinScriptUtil.isMinimalPush(BytesToPushOntoStack(1), OP_1) must be(false)
  }

  it must "determine that a script is push only if it only contains pushing an empty script constant" in {
    BitcoinScriptUtil.isMinimalPush(OP_0, ScriptConstant("")) must be(true)
  }

  it must "determine that a script is not push only if it uses an OP_PUSHDATA operation while pushing < 75 bytes" in {
    BitcoinScriptUtil.isMinimalPush(OP_PUSHDATA1, OP_0) must be(false)
  }

  it must "determine that a OP_PUSHDATA1 operation is the minimal push op for a 76 byte script constant" in {
    val byteConstantSize = 76
    val byteConstant = for { x <- 0 to byteConstantSize } yield 0x0.toByte
    val scriptConstant = ScriptConstant(byteConstant)
    BitcoinScriptUtil.isMinimalPush(OP_PUSHDATA1, scriptConstant) must be(true)
  }

  it must "determine that a OP_PUSHDATA1 operation is NOT the minimal push op for a 75 byte script constant" in {
    val byteConstantSize = 75
    val byteConstant = for { x <- 0 until byteConstantSize } yield 0x0.toByte
    val scriptConstant = ScriptConstant(byteConstant)
    BitcoinScriptUtil.isMinimalPush(OP_PUSHDATA1, scriptConstant) must be(false)
  }

  it must "determine that a OP_PUSHDATA2 operation is NOT the minimal push op for a 255 byte script constant" in {
    val byteConstantSize = 255
    val byteConstant = for { x <- 0 until byteConstantSize } yield 0x0.toByte
    val scriptConstant = ScriptConstant(byteConstant)
    BitcoinScriptUtil.isMinimalPush(OP_PUSHDATA2, scriptConstant) must be(false)
  }

  it must "determine that a OP_PUSHDATA2 operation is the minimal push op for a 256 byte script constant" in {
    val byteConstantSize = 256
    val byteConstant = for { x <- 0 until byteConstantSize } yield 0x0.toByte
    val scriptConstant = ScriptConstant(byteConstant)
    BitcoinScriptUtil.isMinimalPush(OP_PUSHDATA2, scriptConstant) must be(true)
  }

  it must "determine that a OP_PUSHDATA4 operation is NOT the minimal push op for a 65535 byte script constant" in {
    val byteConstantSize = 65535
    val byteConstant = for { x <- 0 until byteConstantSize } yield 0x0.toByte
    val scriptConstant = ScriptConstant(byteConstant)
    BitcoinScriptUtil.isMinimalPush(OP_PUSHDATA4, scriptConstant) must be(false)
  }

  it must "determine that a OP_PUSHDATA4 operation is the minimal push op for a 65536 byte script constant" in {
    val byteConstantSize = 65536
    val byteConstant = for { x <- 0 until byteConstantSize } yield 0x0.toByte
    val scriptConstant = ScriptConstant(byteConstant)
    BitcoinScriptUtil.isMinimalPush(OP_PUSHDATA4, scriptConstant) must be(true)
  }

  it must "determine if a number is encoded in the shortest way possible" in {
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("00")) must be(false)
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("0000")) must be(false)

    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("0100")) must be(false)
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("80")) must be(false)
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("0080")) must be(false)

    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("0500")) must be(false)
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("050000")) must be(false)

    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("0580")) must be(false)
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("050080")) must be(false)

    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("ff7f80")) must be(false)
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("ff7f00")) must be(false)

    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("ffff7f80")) must be(false)
    BitcoinScriptUtil.isShortestEncoding(ScriptConstant("ffff7f00")) must be(false)
  }

  it must "check a public key's encoding" in {
    //pubkeys must be compressed or uncompressed or else that are not validly encoded
    val key = ECPublicKey("00")
    val program = TestUtil.testProgram
    BitcoinScriptUtil.checkPubKeyEncoding(key, program) must be(false)
  }

  it must "determine if script number is correctly minimally-encoded" in {
    val scriptNum100 = ScriptNumber(100)
    val scriptNum10 = ScriptNumber(10)
    val scriptNumZero = ScriptNumber(0)
    val scriptNum16 = ScriptNumber(16)
    val scriptNum17 = ScriptNumber(17)
    BitcoinScriptUtil.minimalScriptNumberRepresentation(scriptNum100) must be(scriptNum100)
    BitcoinScriptUtil.minimalScriptNumberRepresentation(scriptNum10) must be(OP_10)
    BitcoinScriptUtil.minimalScriptNumberRepresentation(scriptNumZero) must be(OP_0)
    BitcoinScriptUtil.minimalScriptNumberRepresentation(scriptNum16) must be(OP_16)
    BitcoinScriptUtil.minimalScriptNumberRepresentation(scriptNum17) must be(scriptNum17)
    BitcoinScriptUtil.minimalScriptNumberRepresentation(ScriptNumber(-1)) must be(OP_1NEGATE)
    BitcoinScriptUtil.minimalScriptNumberRepresentation(ScriptNumber(-2)) must be(ScriptNumber(-2))
  }

  it must "determine if a segwit pubkey is compressed" in {
    val key = ECPrivateKey(false)
    val pubKey = key.publicKey
    val flags = Seq(ScriptVerifyWitnessPubKeyType)
    BitcoinScriptUtil.isValidPubKeyEncoding(pubKey, flags) must be(Some(ScriptErrorWitnessPubKeyType))

    val key2 = ECPrivateKey(true)
    val pubKey2 = key2.publicKey
    BitcoinScriptUtil.isValidPubKeyEncoding(pubKey2, flags) must be(None)
  }

  it must "remove the signatures from a p2sh scriptSig" in {
    val p2shScriptSig = TestUtil.p2sh2Of3ScriptSig
    val signatures = p2shScriptSig.signatures
    val asmWithoutSigs = BitcoinScriptUtil.removeSignaturesFromScript(signatures, p2shScriptSig.asm)
    val sigExists = signatures.map(sig => asmWithoutSigs.exists(_ == ScriptConstant(sig.hex)))
    sigExists.exists(_ == true) must be(false)
  }

  it must "cast a script token to a boolean value" in {
    BitcoinScriptUtil.castToBool(ScriptConstant("")) must be(false)
    BitcoinScriptUtil.castToBool(ScriptConstant(Seq(0x80.toByte))) must be(false)
    BitcoinScriptUtil.castToBool(ScriptConstant("000000")) must be(false)
    BitcoinScriptUtil.castToBool(ScriptConstant("00000080")) must be(false)

    BitcoinScriptUtil.castToBool(ScriptConstant("01")) must be(true)
    BitcoinScriptUtil.castToBool(ScriptConstant("80000000")) must be(true)
    BitcoinScriptUtil.castToBool(ScriptConstant("00008000")) must be(true)
  }
}


text:
"""
Packer specific errors
"""

class PackerError(Exception):
    """
    Generic Packer exception
    """

class PackerUnknownFormatType(PackerError):
    """
    Packer error raised when an unknown format type is specified
    """

class PackerMalformedDataError(PackerError):
    """
    Packer error raised for malformed data
    """


text:
package trekindiamobile.trekindia.ui;

/**
 * Created by rajesh on 26/5/15.
 */

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.parse.Parse;

import trekindiamobile.trekindia.R;
import trekindiamobile.trekindia.common.Utils;
import trekindiamobile.trekindia.service.UtilityService;

/**
 * The main tourist attraction activity screen which contains a list of
 * attractions sorted by distance.
 */
public class AttractionListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new AttractionListFragment())
                    .commit();
        }
        Parse.initialize(this, "yG1e1QYeC1Iw3k9BGo5LAjSSueqFX3QrzZifZ5KG", "PUOyDMcc1XyPfBFNQFmGf5NEFnlV9VgVVmj9B4o6");
//        TouristAttractions obj = new TouristAttractions();
//        obj.getAttractionListFromParse();
        UtilityService.addGeofences(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        UtilityService.requestLocation(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.test_notification:
                UtilityService.triggerWearTest(this, false);
                showDebugDialog(R.string.action_test_notification,
                        R.string.action_test_notification_dialog);
                return true;
            case R.id.test_microapp:
                UtilityService.triggerWearTest(this, true);
                showDebugDialog(R.string.action_test_microapp,
                        R.string.action_test_microapp_dialog);
                return true;
            case R.id.test_toggle_geofence:
                boolean geofenceEnabled = Utils.getGeofenceEnabled(this);
                Utils.storeGeofenceEnabled(this, !geofenceEnabled);
                Toast.makeText(this, geofenceEnabled ?
                        "Debug: Geofencing trigger disabled" :
                        "Debug: Geofencing trigger enabled", Toast.LENGTH_SHORT).show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Show a basic debug dialog to provide more info on the built-in debug
     * options.
     */
    private void showDebugDialog(int titleResId, int bodyResId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(titleResId)
                .setMessage(bodyResId)
                .setPositiveButton(android.R.string.ok, null);
        builder.create().show();
    }
}


text:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <!-- Place this tag in your head or just before your close body tag. -->
        <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
        <!-- Place this tag where you want the widget to render. -->
        <div class="g-post" data-href="https://plus.google.com/113677283818712334483/posts/2siuofuqkRt"
             >
        </div>
    </body>
</html>


text:
var express = require('express');
var router = express.Router();
var db = require('../server_modules/db.js');

router.get('/', function(req,res){
	db.query('SELECT * FROM trash_project.Location', function(err, result){
		if(err){
			res.status(400).send(err);
		} else {
			res.json(result);
		}
	});
});

module.exports = router;


text:
package azkaban.spi;

import static java.util.Objects.requireNonNull;

import java.util.Objects;

public class ProjectStorageMetadata {

  private final int projectId;
  private final int version;
  private final String uploader;
  private final byte[] hash;
  private final String uploaderIPAddr;

  public ProjectStorageMetadata(final int projectId, final int version, final String uploader,
      final byte[] hash, final String uploaderIPAddr) {
    this.projectId = projectId;
    this.version = version;
    this.uploader = requireNonNull(uploader);
    this.hash = hash;
    this.uploaderIPAddr = uploaderIPAddr;
  }

  @Override
  public String toString() {
    return "StorageMetadata{" + "projectId='" + this.projectId + '\'' + ", version='" + this.version
        + '\''
        + '}';
  }

  public int getProjectId() {
    return this.projectId;
  }

  public int getVersion() {
    return this.version;
  }

  public String getUploader() {
    return this.uploader;
  }

  public byte[] getHash() {
    return this.hash;
  }

  public String getUploaderIPAddr() {
    return this.uploaderIPAddr;
  }

  @Override
  public boolean equals(final Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    final ProjectStorageMetadata that = (ProjectStorageMetadata) o;
    return Objects.equals(this.projectId, that.projectId) &&
        Objects.equals(this.version, that.version) &&
        Objects.equals(this.uploader, that.uploader);
  }

  @Override
  public int hashCode() {
    return Objects.hash(this.projectId, this.version, this.uploader);
  }
}


text:
using System.Windows;
using EnvDTE;
using ReviewPal.Core;
using MessageBox = System.Windows.MessageBox;
using Window = System.Windows.Window;

namespace ReviewPal.ReviewPal2012.UI
{
    /// <summary>
    /// Interaction logic for ReviewEditor.xaml
    /// </summary>
    public partial class ReviewEditor : Window
    {
        #region Private members

        /// <summary>
        /// reviewId currently being edited.
        /// </summary>
        private int _reviewId;

        private bool _isNew;

        private Review _review;

        private readonly ReviewRepository _reviewRepo;

        #endregion

        #region Public members

        /// <summary>
        /// Initializes a new instance of the <see cref="ReviewEditor"/> class.
        /// </summary>
        /// <param name="reviewRepo"></param>
        public ReviewEditor(ReviewRepository reviewRepo)
        {
            InitializeComponent();
            _reviewRepo = reviewRepo;
        }

        /// <summary>
        /// Sets the review properties in the ReviewEditor window.
        /// </summary>
        /// <param name="rev">The rev.</param>
        public void SetReview(Review rev)
        {
            //if this a new addition, passed in Review will be null
            if(rev == null)
            {
                _isNew = true;
                // TODO: this needs to be moved into the VSIDEHelper
                TextSelection textSelection = (TextSelection)VSIDEHelper.VisualStudioInstance.ActiveDocument.Selection;
                int line = textSelection.CurrentLine;
                int col = textSelection.CurrentColumn;
                string file = VSIDEHelper.VisualStudioInstance.ActiveDocument.Name;
                string project = VSIDEHelper.VisualStudioInstance.ActiveDocument.ProjectItem.ContainingProject.Name;

                rev = new Review()
                {
                    ReviewId = _reviewRepo.GetNextReviewId(),
                    Project = project,
                    File = file,
                    Line = line
                };
            }
            else
            {
                _isNew = false;
            }
            _reviewId = rev.ReviewId;
            grpReview.Header = "Review ID : " + _reviewId;
            if (!_isNew)
            {
                UIHelper.SelectByString(cmbComment, rev.Comment);
                UIHelper.SelectByString(cmbStatus, rev.Status);
                UIHelper.SelectByString(cmbReExamined, rev.ReExamined);
                UIHelper.SelectByString(cmbSeverity, rev.Severity);
                UIHelper.SelectByString(cmbDefectType, rev.DefectType);
                UIHelper.SelectByString(cmbInjectedPhase, rev.InjectedPhase);
            }

            txtDescription.Text = rev.Description;
            txtRevieweeComments.Text = rev.RevieweeComment;
            txtReviewerComments.Text = rev.ReviewerComment;

            stsProject.Text = "Project : " + rev.Project;
            stsFile.Text = "File: " + rev.File;
            stsLine.Text = "Line : " + rev.Line;

            _review = rev;
        }

        /// <summary>
        /// Updates the review properties.
        /// </summary>
        /// <param name="review">The review.</param>
        private void UpdateReview(Review review)
        {
            review.Comment = cmbComment.Text;
            review.Status = cmbStatus.Text;

            review.ReExamined = cmbReExamined.Text;
            review.Severity = cmbSeverity.Text;
            review.DefectType = cmbDefectType.Text;
            review.InjectedPhase = cmbInjectedPhase.Text;

            review.Description = txtDescription.Text;
            review.RevieweeComment = txtRevieweeComments.Text;
            review.ReviewerComment = txtReviewerComments.Text;

            review.Line = int.Parse(stsLine.Text.Substring(6));
            review.File = stsFile.Text.Substring(6);
            review.Project = stsProject.Text.Substring(10);
        }

        #endregion

        #region Event handlers

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (txtDescription.Text.Length > 0)
            {
                UpdateReview(_review);
                if (_isNew)
                {
                    _reviewRepo.Add(_review);
                }
                this.Close();
            }
            else
            {
                MessageBox.Show("Please input description.", Utils.AssemblyTitle);
            }
        }

        #endregion
    }
}


text:
<?php
/**
 * base class for all strategies which operate on form inputs. Generally, they
 * all need to know about the form input they are operating on.
 */
abstract class EE_Form_Input_Strategy_Base{
	/**
	 * Form Input to display
	 * @var EE_Form_Input_Base
	 */
	protected $_input;

	function __construct(){

	}

	/**
	 * The form input on which this strategy is to perform
	 * @param EE_Form_Input_Base $form_input
	 */
	function _construct_finalize(EE_Form_Input_Base $form_input){
		$this->_input = $form_input;
	}

	/**
	 * Gets this strategy's input
	 * @return EE_Form_Input_Base
	 */
	public function get_input() {
		return $this->_input;
	}
}


text:
import authorsData from '../../data/authors.json';
import { loadConfig } from '../config';
import { AuthorData } from './types';

export function loadAuthors(): AuthorData[] {
  const authors = authorsData as AuthorData[];
  const config = loadConfig();
  return authors.map((author) => ({
    ...author,
    url: `${config.url}/authors/${author.slug}`,
  }));
}

export function loadAuthor(slug: string): AuthorData | undefined {
  return loadAuthors().find((author) => author.slug === slug);
}


text:
package edu.ur.ir.person;

import java.util.List;

import edu.ur.dao.CountableDAO;
import edu.ur.dao.CrudDAO;
import edu.ur.dao.NameListDAO;
import edu.ur.dao.UniqueNameDAO;
import edu.ur.dao.UniqueSystemCodeDAO;

/**
 * Interface for persisting a contributor type.
 *
 * @author Nathan Sarr
 *
 */
public interface ContributorTypeDAO extends CountableDAO,
CrudDAO<ContributorType>, NameListDAO, UniqueNameDAO<ContributorType>, UniqueSystemCodeDAO<ContributorType>
{
	/**
	 * Get the list of contributor types.
	 *
	 *
	 * @param rowStart - start position
	 * @param numberOfResultsToShow - number of rows to grab.
	 * @param sortType - sort order(Asc/desc)
	 *
	 * @return list of contributor type found.
	 */
	public List<ContributorType> getContributorTypes(final int rowStart,
    		final int numberOfResultsToShow, final String sortType);

	/**
	 * Get the contributor type by it's unique system code.
	 *
	 * @param systemCode
	 * @return the contributor type or null if a contributor type is not found.
	 */
	public ContributorType getByUniqueSystemCode(String systemCode);

}


text:
package com.msun.luckyBlog.support;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author zxc Dec 1, 2016 5:45:25 PM
 */
public class MSUNUtils {

    private static final Calendar CALENDAR = Calendar.getInstance();

    /**
     * 获取当前月往前数前两个月的月份
     */
    public static String last2Month() {
        Date date = new Date();// 当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 格式化对象
        CALENDAR.setTime(date);// 设置当前日期
        CALENDAR.add(Calendar.MONTH, -2);
        return sdf.format(CALENDAR.getTime());
    }

    /**
     * 返回年份
     *
     * @param date 日期
     * @return 返回年份
     */
    public static int getYear(Date date) {
        CALENDAR.setTime(date);
        return CALENDAR.get(Calendar.YEAR);
    }

    public static String getEdate(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMM dd", Locale.UK);
        df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }

    public static String getYearMonthOfNow() {
        CALENDAR.setTime(new Date());
        int year = CALENDAR.get(Calendar.YEAR);
        int month = CALENDAR.get(Calendar.MONTH);
        return year + "" + month;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Create a category — Sonata ~ Ecommerce  documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

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

    <link rel="top" title="Sonata ~ Ecommerce  documentation" href="../../index.html"/>
        <link rel="up" title="Introduction" href="index.html"/>
        <link rel="next" title="Create a collection" href="create-collection.html"/>
        <link rel="prev" title="Introduction" href="index.html"/>

         Sonata ~ Ecommerce

  <form id ="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

 Installation

Quick install

Manual installation

 Bundles

Product

Price

Customer

Basket

Delivery

Order

Payment

Invoice

 Architecture

Technical Choices

Going in depths

 API

Setup

Serialization

 Tutorials

 Create a category

 Create a collection

 Create a product

 Basic options for product providers

 Create a delivery method

 Create a payment method

 Extend the e-commerce part of Sonata

 Interact with other bundles

        Sonata ~ Ecommerce

Docs »

Introduction »

Create a category

           View page source

Create a category¶

Category¶

Browse the Sonata demo and go to the admin dashboard (/admin/dashboard).
Default login and password are <tt class="docutils literal">admin</tt>/<tt class="docutils literal">admin</tt>.

In the <tt class="docutils literal">Classification</tt> menu, select <tt class="docutils literal">Categories</tt>,

On the top right of the page, click on the <tt class="docutils literal">Add new</tt> button.

Fill in the form with at least a name and a media.

Note

If you don’t specify the <tt class="docutils literal">position</tt> for a category, categories will be displayed in the order they are created.

We will then create a root category named Dishes and enable it.

Sub-category¶

Repeat the process explained below providing the parent category for two sub-categories:

Bowl

Spoon

Once again, don’t forget to enable them and then check that everything is properly displayed in the frontoffice.

        Next

         Previous

        © Copyright 2010-2014, Thomas Rabaix.

  Sphinx theme provided by Read the Docs


text:
package tutorial;
import jgame.*;
import jgame.platform.*;

/** Tutorial example 1: a minimal program.  A "bare skeleton" program
 * displaying a moving text "hello world".
 *
 * In order to run as both applet and application, you need to define a main()
 * method (this is the entry point for an application) and a parameterless
 * constructor (this is the entry point for an applet).  We use a second
 * constructor with a size parameter to initialise the engine as an
 * application.
 */
public class Example1 extends JGEngine {

	public static void main(String [] args) {
		// We start the engine with a fixed window size (which happens to
		// be twice the size of the defined playfield, scaling the playfield
		// by a factor 2).  Normally, you'd want this size to be configurable,
		// for example by means of command line parameters.
		new Example1(new JGPoint(640,480));
	}

	/** The parameterless constructor is called by the browser, in case we're
	 * an applet. */
	public Example1() {
		// This inits the engine as an applet.
		initEngineApplet();
	}

	/** We use a separate constructor for starting as an application. */
	public Example1(JGPoint size) {
		// This inits the engine as an application.
		initEngine(size.x,size.y);
	}

	/** This method is called by the engine when it is ready to intialise the
	 * canvas (for an applet, this is after the browser has called init()).
	 * Note that applet parameters become available here and not
	 * earlier (don't try to access them from within the parameterless
	 * constructor!).  Use isApplet() to check if we started as an applet.
	 */
	public void initCanvas() {
		// The only thing we need to do in this method is to tell the engine
		// what canvas settings to use.  We should not yet call any of the
		// other game engine methods here!
		setCanvasSettings(
			20,  // width of the canvas in tiles
			15,  // height of the canvas in tiles
			16,  // width of one tile
			16,  // height of one tile
			     //    (note: total size = 20*16=320  x  15*16=240)
			null,// foreground colour -> use default colour white
			null,// background colour -> use default colour black
			null // standard font -> use default font
		);
	}

	/** This method is called when the engine has finished initialising and is
	 * ready to produce frames.  Note that the engine logic runs in its own
	 * thread, separate from the AWT event thread, which is used for painting
	 * only.  This method is the first to be called from within its thread.
	 * During this method, the game window shows the intro screen. */
	public void initGame() {
		// We can set the frame rate, load graphics, etc, at this point.
		// (note that we can also do any of these later on if we wish)
		setFrameRate(
			35,// 35 = frame rate, 35 frames per second
			2  //  2 = frame skip, skip at most 2 frames before displaying
			   //      a frame again
		);
	}

	/** A timer used to animate the "hello world" text. */
	double texttimer=0;

	/** Game logic is done here.  No painting can be done here, define
	* paintFrame to do that. */
	public void doFrame() {
		// Increment the angle of the moving text.
		texttimer += 0.05;
	}

	/** Any graphics drawing beside objects or tiles should be done here.
	 * Usually, only status / HUD information needs to be drawn here. */
	public void paintFrame() {
		setColor(JGColor.yellow);
		// Draw a text that moves around in a circle.
		// Note: viewWidth returns the width of the view;
		//       viewHeight the height.
		drawString("Hello world",
			viewWidth()/2  + 50*Math.sin(texttimer), // xpos
			viewHeight()/2 + 50*Math.cos(texttimer), // ypos
			0 // the text alignment
			  // (-1 is left-aligned, 0 is centered, 1 is right-aligned)
		);
	}
}


text:
<?php namespace Hdphp\Session;

use Hdphp\Session\Session;
use Hdphp\Kernel\ServiceProvider;

class SessionServiceProvider extends ServiceProvider
{

    //延迟加载
    public $defer = false;

    public function boot()
    {
        \Session::make();

    }

    public function register()
    {
        $this->app->single(
            'Session', function ($app)
        {
            return new Session($app);
        }
        );
    }
}


text:
using UnityEditor;
using UnityEngine;

using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;

using Re = System.Text.RegularExpressions;
using Debug = UnityEngine.Debug;

/*
 *
 */

public class ImportText : AssetPostprocessor {

    enum TextFileExtentions {
        cs,
        txt,
        xml,
        lua,
    }

	static Re.Regex SourcesPattern = new Re.Regex(@"\.(cs|txt|xml|lua)");
	// static byte[] Bom = new byte[]{0xef, 0xbb, 0xbf};

	static void OnPostprocessAllAssets(
		string[] imported,
		string[] deleted,
		string[] moved,
		string[] movedFromAssetPaths)
	{
		var decoder = Encoding.GetEncoding("UTF-8",
			EncoderFallback.ReplacementFallback,
			new DecoderExceptionFallback());

		foreach (var file in imported) {
			// ファイル名確認
			if (!SourcesPattern.IsMatch(file)) {
				continue;
			}

			// エンコード確認
			var bytes = File.ReadAllBytes(file);

			// ASCIIチェック
			var b = true;
			for (var i = 0; b && i < bytes.Length; ++i) {
				if (bytes[i] >= 0x80) {
					b = false;
					break;
				}
			}

			// UTF8チェック
			try {
				decoder.GetString(bytes);
			}
			catch (DecoderFallbackException) {
				Debug.LogError("UTF8にデコード出来ません : " + file + ":1");
				continue;
			}

			// // BOMチェック
			// var head = bytes.Take(Bom.Length).ToArray();
			// if (!Bom.SequenceEqual(head)) {
			// 	Information.LogWarning("[xest] BOMが有りません : " + file + ":1");
			// }
		}
	}
}


text:
/*jshint esnext: true */
"use strict";

/* HTTP Routing */
const express = require("express");
const router = express.Router();
const db = require("../db");
const dotenv = require("dotenv").config();
const app = require("../app");
const Yelp = require("yelp");

/* Setup Yelp Authentication */
var yelp = new Yelp({
  consumer_key: process.env.YELP_CONS_KEY,
  consumer_secret: process.env.YELP_CONS_SECRET,
  token: process.env.YELP_TOK,
  token_secret: process.env.YELP_TOK_SECRET,
});

/* Home Page */
router.get("/", function(request, response) {
  response.render("home", { title: "Map the Night | Social Nightlife Tracker" });
});

//return yelp API data plus current user information
router.get("/api/location/:area", function(request, response) {
  let areaInput = request.params.area;
  let yelpObj = { term: "bar", location: areaInput };

  db.returnReservations().then(function(userData) {
    yelp.search(yelpObj).then(function(yelpData) {

      //parse location data into an object and then add user data
      let parsedData = yelpData.businesses.map(function(d) {
        let users = 0;

        // adds the user information to the yelp data
        if(userData) {
          for(let i = 0; i < userData.length; i++) {
            if(d.id === userData[i].name) {
              users = userData[i].users;
              break;
            }
          }
        }
        return {
          id: d.id,
          name: d.name,
          url: d.url,
          image: d.image_url,
          address: d.location.display_address,
          users: users
        };
      });
      response.setHeader("Content-Type", "application/json");
      response.json(parsedData);

    }).catch(function(error) {
      console.error("YELP SEARCH ERROR", error);
    });
  }, function(error) {
    console.error("MONGO USER FETCHING FAILED", error);
  });
});

//handle a new reservation
router.post("/api/save", function(request, response) {
  let data = request.body;
  db.saveReservation(data.location, function(result) {
    if(result !== "Saved") { console.error("ERROR SAVING RESERVATION", result); }
    response.end("Success");
  });
});

module.exports = router;


text:
import React from 'react'
import { connect } from 'react-redux'
import { Button } from 'react-toolbox/lib/button'
import { push } from 'react-router-redux'
import autoBind from 'react-autobind'
import rValues from 'ramda/src/values'

import ListWithBars from '../../components/ListWithBars/ListWithBars'
import AddTaskBtnDialog from '../../components/AddTaskBtnDialog/AddTaskBtnDialog'
import { getJsonTasks, makeTaskCurrent } from '../../redux/modules/tasks/tasks'

class TaskList extends React.Component {

  static propTypes = {
    tasks: React.PropTypes.object,
    getTasks: React.PropTypes.func.isRequired,
    makeCurrentTask: React.PropTypes.func,
    currentTask: React.PropTypes.number,
  }

  constructor(props) {
    super(props)
    autoBind(this)
  }

  componentWillMount() {
    this.props.getTasks()
  }

  makeArrFromObj(object) {
    return rValues(object)
  }

  // makeCurrent() {
  //   console.log('blah')
  // }

  render() {
    const { tasks, currentTask, getTasks, makeCurrentTask } = this.props
    return (

        <Button raised primary onClick={getTasks}>Get Tasks</Button>   <AddTaskBtnDialog />

        <ListWithBars data={this.makeArrFromObj(tasks)} currentTask={currentTask} makeCurrent={makeCurrentTask} extension />

    )
  }
}

// Get the value of the tasks propetry from the store. And pass to to props as tasks
const mapStateToProps = ({ tasks }) => ({ tasks: tasks.tasks, currentTask: tasks.current })

// Get the dispatch func and pass a prop called getTasks as a func that dispatches the getJsonTaks action creator
const mapDispatchToProps = (dispatch) => ({
  getTasks: () => { dispatch(getJsonTasks())},
  makeCurrentTask: (clickedComponentsProps) => {
    dispatch(makeTaskCurrent(clickedComponentsProps.id))
    dispatch(push(`/tasks/${clickedComponentsProps.id}`))
  },
})

export default connect(mapStateToProps, mapDispatchToProps)(TaskList)


text:
app-basic
=========

Basic App for MPF Framework (work in progress)


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

ConsoleNamespaceFunction(Graphics, captureBegin, ConsoleVoid, 1, 1, (""))
{
   Graphics::captureBegin();
}

ConsoleNamespaceFunction(Graphics, captureEnd, ConsoleVoid, 1, 1, (""))
{
   Graphics::captureEnd();
}

ConsoleNamespaceFunction(Graphics, saveScreenshot, ConsoleVoid, 1, 1, (""))
{
   Graphics::saveScreenshot();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPaint.Services;

namespace WebPaint.Controllers
{
    public class DrawingsController : Controller
    {
        //
        // GET: /Drawings/

        public ActionResult Index()
        {
            var drawingsService = new DrawingsService();
            var model = new DrawingsViewModel(drawingsService.GetAll());
            return View(model);
        }

    }
}


text:
'use babel';

module.exports = {
    render: function(){
      return `

{{data.length}} plugins found

            {{#each data}}

                    {{#each rating}}

                      {{formatRating this}}
                    {{/each}}

                      {{name}}

                      {{version}}

                    {{description}}

                    Last update {{formatLastUpdate lastUpdate}}

                      {{url}}

                        <button type="button" class="btn btn-info icon icon-cloud-download install-button" btn-install-plugin pluginId="{{name}}">Install</button>

            {{/each}}

`}
}

/**

  295,041

{{#each description}}

{{this}}

{{/each}}
**/


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Church extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('smi/church_m', 'church');
	}

	public function index()
	{
		$this->data['churches'] = $this->church->get_churches();

		$this->data['subview'] = 'smi/church/index';
		$this->load->view('admin/_layout_main', $this->data);
	}

	public function edit($pk = NULL)
	{
		is_ajax();

		// Fetch a church or set a new one
		if ($pk) {
			$this->data['church'] = $this->church->find($pk);
			count($this->data['church']) || $this->data['errors'][] = 'church could no be found';
		} else {
			$this->data['church'] = $this->church->get_new();
		}

		// Set up the form
		$rules = $this->church->rules;

		$this->form_validation->set_rules($rules);

		// Process the form
		if ($this->form_validation->run() == TRUE) {
			$data = $this->input->post();
			$data['area'] = (int) $data['area'];
			$this->church->save($data, $pk);
			echo $pk ? 'UPDATE' : 'CREATE';
		} else {
			// Load the view
			$this->load->view('smi/church/edit', $this->data);
		}
	}

	public function delete_selected()
	{
		is_ajax();

		echo $this->church->deleteItems($this->input->post('pks'))?"OK":lang('error_deleted_records');
	}

	public function set_state($id_church)
	{
		is_ajax();

		echo $this->church->save(array('state' => $this->input->post('state')), $id_church);
	}
}

/* End of file church.php */
/* Location: ./application/modules/admin/controllers/church.php */


text:
A timestamp in ISO 8601 format which specifies a date after the current time and up to 180 days in the future to send the letter off for production. Setting a send date overrides the default [cancellation window](#section/Cancellation-Windows) applied to the mailpiece. Until the `send_date` has passed, the mailpiece can be canceled. If a date in the format `2017-11-01` is passed, it will evaluate to midnight UTC of that date (`2017-11-01T00:00:00.000Z`). If a datetime is passed, that exact time will be used. A `send_date` passed with no time zone will default to UTC, while a `send_date` passed with a time zone will be converted to UTC.

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------


text:
import React, { useEffect, useState } from 'react'

import getString from '../../lib/strings'
import copyIcon from '../../assets/images/copy.svg'
import styles from './Usage.module.css'

const Usage = () => {
  const [isValueCopied, setIsValueCopied] = useState(false)
  const usageValue = `https://http.cat/[${getString('USAGE_PARAM')}]`

  const copyValue = async () => {
    if (!isValueCopied) {
      await navigator.clipboard.writeText(usageValue)
      setIsValueCopied(true)
    }
  }

  useEffect(() => {
    if (isValueCopied) {
      setTimeout(() => {
        setIsValueCopied(false)
      }, 3000)
    }
  }, [isValueCopied])

  return (

{getString('USAGE_TITLE')}:

        {usageValue}
        {'clipboard' in navigator && (
          <button onClick={copyValue} title='Copy to clipboard'>
            {isValueCopied ? getString('COPIED') : }
          </button>
        )}

        {getString('USAGE_NOTE_LABEL')}: {getString('USAGE_NOTE_TEXT')}{' '}.jpg.

  )
}

export default Usage


text:
if [ ! -d "/app" ];then
	echo "Creating app from repo $REPO/$BRANCH"

	git clone $REPO --branch $BRANCH --single-branch /app
	cd /app

	# get all the gems and stuff
	bundle install

else
	echo "Updating app from repo $REPO"

	cd /app
	git pull origin $BRANCH

	bundle install
fi

# start the app server
RACK_ENV=$RACK_ENV bundle exec rackup -o 0.0.0.0


text:
import { Injectable } from '@angular/core';
import { Logger } from '../../providers/logger/logger';

// Providers
import { AppProvider } from '../../providers/app/app';
import { BwcProvider } from '../../providers/bwc/bwc';
import { DownloadProvider } from '../../providers/download/download';
import { ProfileProvider } from '../../providers/profile/profile';
import { ConfigProvider } from '../config/config';
import { KeyProvider } from '../key/key';

@Injectable()
export class BackupProvider {
  constructor(
    private appProvider: AppProvider,
    private bwcProvider: BwcProvider,
    private configProvider: ConfigProvider,
    private downloadProvider: DownloadProvider,
    private logger: Logger,
    private profileProvider: ProfileProvider,
    private keyProvider: KeyProvider
  ) {
    this.logger.debug('BackupProvider initialized');
  }

  public walletDownload(
    walletId: string,
    opts,
    password?: string
  ): Promise<any> {
    return new Promise((resolve, reject) => {
      let config = this.configProvider.get();

      let wallet = this.profileProvider.getWallet(walletId);
      let ew = this.walletExport(walletId, opts, password);
      if (!ew) return reject('Could not create backup');

      let walletName =
        wallet.credentials.walletName || wallet.credentials.walletId;

      let alias =
        config.aliasFor && config.aliasFor[wallet.credentials.walletId];

      if (alias) {
        walletName = alias + ' [' + walletName + ']';
      }

      if (opts.noSign) walletName = walletName + '-noSign';
      let filename =
        walletName + '-' + this.appProvider.info.nameCase + 'backup.aes.json';
      this.downloadProvider.download(ew, filename).then(() => {
        return resolve();
      });
    });
  }

  public walletExport(walletId: string, opts, password?: string) {
    if (!password) {
      return null;
    }

    let wallet = this.profileProvider.getWallet(walletId);
    try {
      opts = opts ? opts : {};
      let b: any = {};

      b.credentials = JSON.parse(wallet.toString(opts));
      if (b.credentials.keyId && opts.noSign) {
        delete b.credentials.keyId;
      }
      if (wallet.canSign && !opts.noSign) {
        const k = this.keyProvider.getKey(wallet.credentials.keyId).toObj();
        if (opts.password) {
          const k1 = this.keyProvider.get(
            wallet.credentials.keyId,
            opts.password
          );
          k.mnemonic = k1.mnemonic;
          k.xPrivKey = k1.xPrivKey;
          delete k.xPrivKeyEncrypted;
          delete k.mnemonicEncrypted;
        }
        b.key = k;
      }
      if (opts.addressBook) b.addressBook = opts.addressBook;
      b = JSON.stringify(b);

      return this.bwcProvider.getSJCL().encrypt(password, b, {
        iter: 10000
      });
    } catch (err) {
      this.logger.error('Error exporting wallet: ', err);
      return null;
    }
  }
}


text:
* Remove useless .bind()

## 0.2.0

* Update to react 0.12.0

#### Fixes

* Issue with embedCss
* Fix keys to removes react warnings
* Add a `setTimeout(resetTriggers, 1000)` which might sometimes fix issues with stylesheet loading latency


text:
package gw.plugin.ij.actions;

import com.intellij.ide.util.PackageUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import com.intellij.util.IncorrectOperationException;
import gw.plugin.ij.framework.GosuTestCase;
import org.jetbrains.annotations.Nullable;

import java.io.File;

public class CreateTemplateActionTest extends GosuTestCase {
  public void testTemplateCreation() {
    try {
      File testRootDir = createTempDirectory();
      final PsiDirectory rootDir = PsiDirectoryFactory.getInstance(getProject()).createDirectory(getVirtualFile(testRootDir));
      final PsiDirectory pkgDir = PackageUtil.findOrCreateDirectoryForPackage(getModule(), "test.pkg", rootDir, false);
      final String className = "TestTemplateOne";
      final String templateName = "GosuTemplate.gst";

      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          TestAction action = new TestAction(pkgDir, className, templateName);
          action.runTest();
        }
      });

      // verify result
      PsiFile pfile = pkgDir.findFile("TestTemplateOne.gst");
      byte[] content = pfile.getVirtualFile().contentsToByteArray();
      String result = new String(content);
      assertEquals("", "<%@ params( myParam: String ) %>\n" +
          "\n" +
          "The content of my param is: ${myParam}\n" +
          "\n" +
          "Note you can render this template from a class or program\n" +
          "simply by calling one of its render methods:\n" +
          "\n" +
          "  TestTemplateOne.renderToString( \"wow\" )", result.trim());
    } catch (Exception e) {
      fail(e.getMessage());
      e.printStackTrace();
    }
  }

  public void testDuplicateTemplateCreation() {
    try {
      File testRootDir = createTempDirectory();
      final PsiDirectory rootDir = PsiDirectoryFactory.getInstance(getProject()).createDirectory(getVirtualFile(testRootDir));
      final PsiDirectory pkgDir = PackageUtil.findOrCreateDirectoryForPackage(getModule(), "test.pkg", rootDir, false);
      final String className = "TestTemplateUnique";
      final String templateName = "GosuTemplate.gst";
      final Throwable[] caught = new Throwable[1];
      caught[0] = null;

      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          try {
            TestAction action = new TestAction(pkgDir, className, templateName);
            action.runTest();
            action.runTest();  // run create a second time on purpose
          } catch (Throwable t) {
            caught[0] = t;
          }
        }
      });
      assertNotNull(caught[0]);
      assertTrue(caught[0] instanceof IncorrectOperationException);
      assertTrue(caught[0].getMessage().contains("File already exists"));
    } catch (Exception e) {
      fail(e.getMessage());
      e.printStackTrace();
    }
  }

  public void testTemplateCreationWithJavaConflict() {
    try {
      File testRootDir = createTempDirectory();
      final PsiDirectory rootDir = PsiDirectoryFactory.getInstance(getProject()).createDirectory(getVirtualFile(testRootDir));
      final PsiDirectory pkgDir = PackageUtil.findOrCreateDirectoryForPackage(getModule(), "test.pkg", rootDir, false);
      final String className = "TestTemplateUnique";
      final String templateName = "GosuTemplate.gst";
      final Throwable[] caught = new Throwable[1];
      caught[0] = null;

      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          try {
            TestAction action = new TestAction(pkgDir, className, templateName);
            pkgDir.createFile(className + ".java");
            action.runTest();
          } catch (Throwable t) {
            caught[0] = t;
          }
        }
      });
      assertNotNull(caught[0]);
      assertTrue(caught[0] instanceof IncorrectOperationException);
      assertTrue(caught[0].getMessage().contains("Cannot create TestTemplateUnique.gst. A Java class with the same name already exists."));
    } catch (Exception e) {
      fail(e.getMessage());
      e.printStackTrace();
    }
  }

  public void testTemplateCreationWithTypeConflict() {
    try {
      File testRootDir = createTempDirectory();
      final PsiDirectory rootDir = PsiDirectoryFactory.getInstance(getProject()).createDirectory(getVirtualFile(testRootDir));
      final PsiDirectory pkgDir = PackageUtil.findOrCreateDirectoryForPackage(getModule(), "test.pkg", rootDir, false);
      final String className = "TemplateEnhancementNameConflict";
      final String templateName = "GosuTemplate.gst";
      final Throwable[] caught = new Throwable[1];
      caught[0] = null;

      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          try {
            TestAction action = new TestAction(pkgDir, className, templateName);
            pkgDir.createFile(className + ".gsx");
            action.runTest();
          } catch (Throwable t) {
            caught[0] = t;
          }
        }
      });
      assertNotNull(caught[0]);
      assertTrue(caught[0] instanceof IncorrectOperationException);
      assertTrue(caught[0].getMessage().contains("Cannot create TemplateEnhancementNameConflict.gst. A type with the same name already exists."));
    } catch (Exception e) {
      fail(e.getMessage());
      e.printStackTrace();
    }
  }

  private class TestAction extends CreateTemplateAction {

    @Nullable
    PsiDirectory _dir = null;
    @Nullable
    String _className = null;
    @Nullable
    String _templateName = null;

    public TestAction(PsiDirectory dir, String className, String templateName) {
      super();
      _dir = dir;
      _className = className;
      _templateName = templateName;

    }

    public void runTest() {
      checkBeforeCreate(_className, _templateName, _dir);
      createFile(_className, _templateName, _dir);
    }
  }
}


text:
package jp.ac.nii.prl.mape.autoscaling;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import jp.ac.nii.prl.mape.autoscaling.controller.DeploymentNotFoundException;

@ControllerAdvice
public class RestErrorHandler {

	@ExceptionHandler(DeploymentNotFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public void handleDeploymentNotFoundException(final DeploymentNotFoundException ex) {

	}
}


text:
module Liquid

  # Assign sets a variable in your template.
  #
  #   {% assign foo = 'monkey' %}
  #
  # You can then use the variable later in the page.
  #
  #  {{ foo }}
  #
  class Assign < Tag
    Syntax = /(#{VariableSignature}+)\s*=\s*(.*)\s*/o

    def initialize(tag_name, markup, tokens)
      if markup =~ Syntax
        @to = $1
        @from = Variable.new($2)
      else
        raise SyntaxError.new("Syntax Error in 'assign' - Valid syntax: assign [var] = [source]")
      end

      super
    end

    def render(context)
      val = @from.render(context)
      context.scopes.last[@to] = val
      context.resource_limits[:assign_score_current] += (val.respond_to?(:length) ? val.length : 1)
      ''
    end

  end

  Template.register_tag('assign', Assign)
end