text:
<?php

namespace Knp\Doctrine\MongoDB\Event;

use Doctrine\ODM\MongoDB\Event\LoadClassMetadataEventArgs;

/**
 *
 * LoadClassMetadaEventListener listens to Doctrine\ODM
 * to dynamically add a discrimator map in the BaseBlock class metadata
 * @author fklein
 *
 */
class LoadClassMetadaEventListener
{
    private $map = array();
    private $className;

    /**
     * @param string $clasName the full class name to map
     */
    public function __construct($className)
    {
        $this->className = $className;
    }

    /**
     * This method is called to populate available Documents thanks to a CompilerPass
     *
     * @see Knp\BlockBundle\DependencyExtension\Compiler\AddBlockTypesPass
     * @param string $alias
     * @param string $className
     */
    public function addDiscriminatorMapping($alias, $className)
    {
        $this->map[$alias] = $className;
    }

    /**
     *
     * This event listener handles automagically the DiscriminatorMap configuration of BaseBlock
     *
     * @param LoadClassMetadataEventArgs $eventArgs
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        $classMetadata = $eventArgs->getClassMetadata();
        if ($classMetadata->getName() == $this->className) {
            $classMetadata->setDiscriminatorMap($this->map);
        }
    }
}


text:
package uk.ac.ebi.eva.commons.jpa.models.metadata;

import org.junit.Test;

import java.util.Set;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;

/**
 * Created by parce on 07/10/15.
 */
public class FileTest {

    @Test
    public void testAddSample() throws Exception {
        // create a file without samples
        File file = new File("file1.vcf", File.Type.VCF, "7s6efgwe78748");
        assertThat(file.getSamples(), empty());
        assertThat(file.getFileGenerators(), empty());

        // add one file to the sample
        Sample sample1 = new Sample("alias1", "sample1", null, null, null, null, null, null, null, null, null, null);
        file.addSample(sample1);
        checkFileHasSamples(file, sample1);
        checkFileInSamples(file, sample1);

        // add the same file object to the sample
        file.addSample(sample1);
        checkFileHasSamples(file, sample1);
        checkFileInSamples(file, sample1);

        // add a different object containing the same file
        Sample anotherSample1 = new Sample("anotherAlias", "sample1", null, null, null, null, null, null, null, null, null, null);
        file.addSample(anotherSample1);
        checkFileHasSamples(file, sample1);
        checkFileHasSamples(file, anotherSample1);
        checkFileInSamples(file, sample1, anotherSample1);

        // add a diferent sample to the file
        Sample sample2 = new Sample("alias2", "sample2", null, null, null, null, null, null, null, null, null, null);
        file.addSample(sample2);
        checkFileHasSamples(file, sample1, sample2);
        checkFileInSamples(file, sample1, sample2);
    }

    private void checkFileHasSamples(File file, Sample... samples) {
        Set<Sample> fileSamples = file.getSamples();
        assertThat(fileSamples, hasSize(samples.length));
        assertThat(fileSamples, contains(samples));
    }

    private void checkFileInSamples(File file, Sample... samples) {
        for (Sample sample : samples) {
            Set<File> sampleFiles = sample.getFiles();
            assertThat(sampleFiles, hasSize(1));
            assertThat(sampleFiles, contains(file));
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>REST Services and Reports — CasperJS  documentation</title>

    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/jsdemo.css" type="text/css" />
    <link rel="stylesheet" href="../_static/sphinxcontrib-images/LightBox2/lightbox2/css/lightbox.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/casperjs-favicon.ico"/>
    <link rel="top" title="CasperJS  documentation" href="../index.html" />
    <link rel="up" title="Features - Core" href="$_02-core.html" />
    <link rel="next" title="International Data and Methods" href="$_02-core-13-internationalization.html" />
    <link rel="prev" title="Nutrition Mathematics" href="$_02-core-11-mathematics.html" />
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Asap:400,700,400italic,700italic&subset=latin,latin-ext">
    <link rel="stylesheet" title="Dark theme" href="../_static/casperjs-dark.css">
    <link rel="alternate stylesheet" title="Light theme" href="../_static/casperjs-light.css">

Navigation

          index

          next |

          previous |

CasperJS  documentation »

Features - Core »

REST Services and Reports¶

This section addresses:

:USDA #6:¶

Permit export of composition and analytical data and conversion of composition data to an application development format.

:USDA #10:¶

Permit assembly of ad hoc databases to suit individual needs.

:USDA #11:¶

Permit export of ad hoc data.

Table of Contents¶

General Structure of REST API

Query Parameters: Input Specification

Query Parameters: Operation Specification

Query Parameters: Output Specification

Request: Food property tables

Return food property table

Variation: Return Nutrient Fact Panel <NFP_type>

Variation: Return dates

Variation: Return Cross References <xrefs>

Quality Control using Provenance Ontology and REST

Label project € data will be available to investigators € via REST € (Representational State Transfer) services. REST is a simple stateless architecture that runs over HTTP. REST service reads a designated Web page that contains an XML file in RDF format. XML/RDF file describes and includes label project data. Data is returned to investigator in JSON-LD € format.

General Structure of REST API¶

Structure of a USDA REST conversation € :

Structure of the USDA REST API is:

http://usda.ars.gov/rest/<input specification>/<operation specification>/[<output specification>]/[<operation options>]

Example: “retrieve food description using food identifier [USDA_fid] and item number 2244”

http://usda.ars.gov/rest/food/USDA_fid/2244/JSON

Query Parameters: Input Specification¶

Input portion of URL tells service which records to use as subject of query.

This is further subdivided into two or more locations in URL “path” as follows:

<col class="field-name" />
<col class="field-body" />

query parameter title:

 	input specification

query parameter domain:

 	values may include food, compound, Nutrient Fact Panel (NFP) values and other inputs

For example:

                           1          2            3
<input_specification> = <domain>/<namespace>/<identifiers>

                2.1     2.2        2.3             2.4
1   <domain> = food | compound | NFP_values | <other inputs>

                                                   2.n.1                                              2.n.2
2.1    food domain <namespace> = USDA_fid | sourceid/<source name> | sourceall/<source name> | name | <xref>

2.2    compound domain <namespace> = PC_cid | name | inchikey | <xref>

                                                   2.n.3
2.3    NFP_values domain <namespace> = NFP_id | type/<NFP type> | sourceall/<source name> | activity/<activity column name> | {_to_be_specified_}

2.n.1     <source_name> = any valid Branded Food depositor name

2.n.2     <xref> = xref / {RegistryID | RN | NCBI_ProteinGI | NCBI_TaxonomyID }

2.n.3     <NFP_type> = all | panel | summary | {_to_be_specified_}

2.4    <other_inputs_to_be_specified_> = sources / [substance, assay] | conformers

3    <identifiers> = comma-separated list of positive integers (e.g. PC_cid, USDA_fid, NFP_id) or identifier strings (source, inchikey)

Query Parameters: Operation Specification¶

Operation part of URL tells service what to do with input records - such as to retrieve whole record or specific properties of a food.

Construction of this part of “path” will depend on Operation Specification. If no operation is specified, default is to retrieve entire record.

Available operations dependent on Input Specification. For example, certain operations are applicable only to foods, compounds and not NFP_values.

For example:

                                                         1.n.1                                                             1.n.2
1.1  food domain <operation_specification> = record | <food_property> | synonyms | PC_cids | NFP_values | classification | <xrefs> | description

1.n.1    <food_property> = property / [comma-separated list of property tags]

1.n.2    <xrefs> = xrefs / [comma-separated list of xrefs tags]

1.3  NFP domain <operation_specification> = record | NFP_ids | USDA_fids | PC_cids | description | summary | classification | xrefs

Query Parameters: Output Specification¶

Final portion of URL tells service what output format is desired.

Output format also can be specified in HTTP Accept field of request header.

For example:

<output:specification> = JSON | CSV | TXT

Request: Food property tables¶

Request properties for a food (USDA_fid) or compound (PC_cid).

http://usda.ars.gov/rest/food/USDA_fid/3114/property/JSON

Return food property table¶

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

Property
Notes

to_be_specified
to_be_specified

to_be_specified
to_be_specified

Variation: Return Nutrient Fact Panel <NFP_type>¶

<colgroup>
<col width="33%" />
<col width="33%" />
<col width="33%" />
</colgroup>

Options
Allowed Values
meaning

NFP_type
all, primary, secondary
Type of NFP to return given, USDA_fids, PC_cids

Variation: Return dates¶

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

Date
Meaning

Deposition
when an USDA_fid or NFP_id first appeared

Modification
when an USDA_fid or NFP_id was last modified

Hold
when an USDA_fid or NFP_id will be released

Creation
when a USDA_fid or NFP_id first appeared

Deprecation
when a USDA_fid or NFP_id is no longer active

Variation: Return Cross References <xrefs>¶

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

Cross Reference
Meaning

RegistryID
external registry identifier

PubMedID
NCBI PubMed identifier

DBURL
external database home page URL

TaxonomyID
NCBI taxonomy identifier

SourceName
external depositor name

SourceCategory
depositor category(ies)

Quality Control using Provenance Ontology and REST¶

Several conversation € types will be supported.

For example, Ontomatica imports € the Provenance Ontology [prov].

The following illustrates a curator € using [prov]:

Alanna wishes to verify that a new data set correctly addresses previous error.

David [ex:David] documents Alanna’s instructions [ex:instructions] in a plan [prov:Plan].

David then generates a new dataset [ex:dataset2] that implements correction activity [ex:correct1].

Alanna confirms [prov:Plan] and executes a diff (difference) to contrast [ex:dataset2] with [ex:dataset1].

Curator uses a REST conversation to implement the example above.

See also

Model sites that implement REST

ChemAxon concepts

ChemAxon application programming interface (APIs)

Return to top

Document Outline

REST Services and Reports

Table of Contents

General Structure of REST API

Query Parameters: Input Specification

Query Parameters: Operation Specification

Query Parameters: Output Specification

Request: Food property tables

Return food property table

Variation: Return Nutrient Fact Panel <NFP_type>

Variation: Return dates

Variation: Return Cross References <xrefs>

Quality Control using Provenance Ontology and REST

Previous topic

Nutrition Mathematics

Next topic

International Data and Methods

Index

Thesaurus

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

CasperJS  documentation »

Features - Core »

        © Copyright 2011-2015 Nicolas Perriault and contributors. CasperJS logo by Jeremy Forveille.
      Created using Sphinx 1.3.1.


text: oc cluster up --metrics=true --host-data-dir=/var/lib/origin/data --use-existing-config


text:
var introspect = require( 'introspect' );
var os = require( 'os' );
var _ = require( 'lodash' );

//Deferring load of output and fp module until end of file to resolve circular dependency

//Placeholders for the cmd and readlineInterface objects from ncline
var cmdObject = {};
var readlineInterface = {};

module.exports = {

    spaceReplacement: '@#Sp#@',
    semicolonReplacement: '@#Semi#@',

    getModulePath: function( dirname ) {
        if( os.platform() == 'win32' ) {
            return dirname.split( '\\' )[ ( dirname.split( '\\' ).length - 1 ) ];
        } else {
            return dirname.split( '/' )[ ( dirname.split( '/' ).length - 1 ) ];
        }
    },

    generateCommandPrompt: function() {
        var promptText;
        if( fp.hooks.getSourceAlias() != undefined ) {
            promptText = 'source -> ' + fp.hooks.getSourceAlias() + ', ';
        } else {
            promptText = '';
        }
        promptText += 'target -> ' + fp.hooks.getTargetAlias() + ' >>';
        return promptText;
    },

    escapeRegExp: function( str ) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    },

    isBoolean: function( str ) {
        if( str == 0 || str == 1 ) {
            return true;
        } else if ( str.constructor == Number ) {
            return false;
        }

        if( str.trim().match(/^(T|t)rue$/) || str.trim().match(/^(F|f)alse$/) ) {
            return true;
        }
        if( str.trim().match(/^(Y|y)es$/) || str.trim().match(/^(N|n)o$/) ) {
            return true;
        }
        if( str.trim().match(/^(Y|y)$/) || str.trim().match(/^(N|n)$/) ) {
            return true;
        }
        if( str.trim() == '1' || str.trim() == '0') {
            return true;
        }
        return false;
    },

    booleanValue: function( str ) {
        if( typeof( str ) == "boolean" ) {
            return str;
        }

        if( str.constructor == Number ) {
            return str == 1 ? true : false;
        }
        switch( str.trim() ) {
            case "true":
            case "True":
            case "yes":
            case "Yes":
            case "y":
            case "Y":
            case "1":
                return true;
                break;
            default:
                return false;
        }
    },

    //Adapted from https://gist.github.com/colingourlay/82506396503c05e2bb94
    sortObjectProperties: function( obj ) {
        var keys = _.sortBy( _.keys( obj ), function ( key ) {
            return key;
        });

        var objectWithSortedProperties =  _.zipObject( keys, _.map( keys, function ( key ) {
            return obj[ key ];
        }));

        return objectWithSortedProperties;
    },

    transformQuotedValues: function( argumentString ) {
        var rawQuotes,
            revisedQuote,
            quoteRegExp;

        //Find any values enclosed in double-quote marks
        rawQuotes = argumentString.match( /"[^"]*"/g );
        if( rawQuotes ) {

            for( var i = 0; i < rawQuotes.length; i++ ) {
                revisedQuote = rawQuotes[ i ].replace( /\s/g, this.spaceReplacement );
                //Make a RegExp out of the original quote, escaping any special RegExp characters in the quote
                quoteRegExp = new RegExp( this.escapeRegExp( rawQuotes[ i ] ) );
                //Use the RegExp to replace the original quote with the revised one
                argumentString = argumentString.replace( quoteRegExp, revisedQuote );
            }
        }

        //Remove all of the " marks from the argument string before returning it:
        argumentString = argumentString.replace( /\"/g, "" );
        return argumentString;
    },

    parseNamedArguments: function( cmdArgumentsArray, cmdFunction ) {
        var methodArgumentsObject = {},
            parsedArgumentsArray = [];

        //Use the introspect module to return an array of the argument names of the targeted function
        var methodArgumentsArray = introspect( cmdFunction );

        //Transform that data into a value object, with the position of each argument stored under the argument name
        methodArgumentsArray.forEach( function( value, index ) {
            methodArgumentsObject[ value ] = index;
        } );

        //Replace the first colon in each command argument array element (perserving any colons in the argument value)
        for( var i = 0; i < cmdArgumentsArray.length; i++ ) {
            cmdArgumentsArray[ i ] = cmdArgumentsArray[ i ].replace(/\:/, this.semicolonReplacement );
            var paramArray = cmdArgumentsArray[ i ].split( this.semicolonReplacement );
            if( methodArgumentsObject.hasOwnProperty( paramArray[ 0 ] ) ) {
                //The argument value will be placed at the index location in the parsedArgumentArray that matches the
                //corresponding method argument position.
                parsedArgumentsArray[ methodArgumentsObject[ paramArray[ 0 ] ] ] = paramArray[ 1 ];
            }
        }

        //Now loop through the methodArgumentsObject, and make sure any array position represented in the object that didn't
        //get populated in the parsedArgumentsArray gets a null value:
        for( var arg in methodArgumentsObject ) {
            if( parsedArgumentsArray[ methodArgumentsObject[ arg ] ] == undefined ) {
                parsedArgumentsArray[ methodArgumentsObject[ arg ] ] = null;
            }
        }

        return parsedArgumentsArray;
    },

    generateArgumentsArray: function( argumentString, cmdFunction ) {
        var namedArguments = false,
            initialArgumentsArray = [],
            spaceReplacementRegExp = new RegExp( this.spaceReplacement, 'g' ),
            argumentsArray = [];

        argumentString = argumentString.trim();
        argumentString = this.transformQuotedValues( argumentString );

        //If the argument string is enclosed in [] or {}, it indicates named parameters being used
        if( argumentString.match(/^\[.*\]$/) || argumentString.match(/^\{.*\}$/) ) {
            namedArguments = true;
            //Remove the brackets
            argumentString = argumentString.slice(0, -1).slice(1, argumentString.length-1);
        }

        //Now the arguments can be split into an array based on the remaining spaces
        initialArgumentsArray = argumentString.trim().split(' ');

        if( namedArguments ) {
            initialArgumentsArray = this.parseNamedArguments( initialArgumentsArray, cmdFunction );
        }

        //Loop through the arguments, restoring any spaces and transforming any 'null' values to true null
        initialArgumentsArray.forEach( function( value ) {
            //Process any null argument values, whether a string or an actual null
            if( value == 'null' || value == null ) {
                argumentsArray.push( null );
            } else if ( value != null ) {
                //Make sure all spaces are restored
                argumentsArray.push( value.replace( spaceReplacementRegExp, ' ' ) );
            }
        });

        return argumentsArray;
    },

    renderSignature: function( cmdName, cmdFunction ) {
        var argumentArray = introspect( cmdFunction )
        if( argumentArray.length > 0 ) {
            return cmdName + '( ' + introspect( cmdFunction ).join(', ') + ' )';
        } else {
            return cmdName + '()';
        }
    },

    createTerminalExecutionPrefix: function( path, title ) {
        switch( os.platform() ) {
            case "win32":
                var driveLetter = path.match(/\S{1}\:/);
                if( driveLetter != undefined ) {
                    var cdPath = path.replace(/\S{1}\:/, '');
                    return 'start "' + title + '" cmd /k "' + driveLetter + ' & cd ' + cdPath;
                } else {
                    return 'start "' + title + '" cmd /k "cd ' + path;
                }
                break;
            case "darwin":
                return 'open -a Terminal "' + path ;
            default:
                output.throwError( 'Currently only executes on Windows and Macintosh operating systems.' );
                break;
        }
    },

    setCmdObject: function ( cmd ) {
        cmdObject = cmd;
    },

    getCmdObject: function() {
        return cmdObject;
    },

    setReadlineInterface: function( rl ) {
        readlineInterface = rl;
    },

    getReadlineInterface: function() {
        return readlineInterface;
    }

};

//Load needed core files
var output = require( './output' );

//Load any need core command modules
var fp = require( '../cmdModules/core/filePath/commands' );


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Context.Interfaces.Services;

namespace Context.Interfaces.Logging
{
    [Guid("0B627327-D170-452c-90A9-10F62CD29AD2")]
    public interface ILogService
    {
        bool Enabled { get; set; }

        void Log(LogLevel level, IContext context, IFormatProvider formatProvider, string message, params object[] args);

        void Log(LogLevel level, IContext context, string message, params object[] args);

        void Log(LogLevel level, IFormatProvider formatProvider, string message, params object[] args);

        void Log(LogLevel level, string message, params object[] args);

        ILog GetLog(IContext context, IFormatProvider formatProvider);

        void Flush(TimeSpan timeout);

        void Flush();
    }
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.security;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.http.FilterContainer;
import org.apache.hadoop.http.HttpServer2;
import org.apache.hadoop.yarn.server.security.http.RMAuthenticationFilter;
import org.apache.hadoop.yarn.server.security.http
    .RMAuthenticationFilterInitializer;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 * Test RM Auth filter.
 */
public class TestRMAuthenticationFilter {

  @SuppressWarnings("unchecked")
  @Test
  public void testConfiguration() throws Exception {
    Configuration conf = new Configuration();
    conf.set("hadoop.http.authentication.foo", "bar");
    conf.set("hadoop.proxyuser.user.foo", "bar1");

    conf.set(HttpServer2.BIND_ADDRESS, "barhost");

    FilterContainer container = Mockito.mock(FilterContainer.class);
    Mockito.doAnswer(new Answer() {
      @Override
      public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        Object[] args = invocationOnMock.getArguments();

        assertEquals("RMAuthenticationFilter", args[0]);

        assertEquals(RMAuthenticationFilter.class.getName(), args[1]);

        Map<String, String> conf = (Map<String, String>) args[2];
        assertEquals("/", conf.get("cookie.path"));

        assertEquals("simple", conf.get("type"));
        assertEquals("36000", conf.get("token.validity"));
        assertNull(conf.get("cookie.domain"));
        assertEquals("true", conf.get("simple.anonymous.allowed"));
        assertEquals("HTTP/barhost@LOCALHOST", conf.get("kerberos.principal"));
        assertEquals(System.getProperty("user.home") + "/hadoop.keytab",
            conf.get("kerberos.keytab"));
        assertEquals("bar", conf.get("foo"));
        assertEquals("bar1", conf.get("proxyuser.user.foo"));

        return null;
      }
    }).when(container).addFilter(Mockito.<String>anyObject(),
        Mockito.<String>anyObject(), Mockito.<Map<String, String>>anyObject());

    new RMAuthenticationFilterInitializer().initFilter(container, conf);
  }
}


text:
require 'spec_helper'

describe Chef::Resource::Deploy do

  class << self
    def resource_has_a_string_attribute(attr_name)
      it "has a String attribute for #{attr_name.to_s}" do
        @resource.send(attr_name, "this is a string")
        @resource.send(attr_name).should eql("this is a string")
        lambda {@resource.send(attr_name, 8675309)}.should raise_error(ArgumentError)
      end
    end

    def resource_has_a_boolean_attribute(attr_name, opts={:defaults_to=>false})
      it "has a Boolean attribute for #{attr_name.to_s}" do
        @resource.send(attr_name).should eql(opts[:defaults_to])
        @resource.send(attr_name, !opts[:defaults_to])
        @resource.send(attr_name).should eql( !opts[:defaults_to] )
      end
    end

    def resource_has_a_callback_attribute(attr_name)
      it "has a Callback attribute #{attr_name}" do
        callback_block = lambda { :noop }
        lambda {@resource.send(attr_name, &callback_block)}.should_not raise_error
        @resource.send(attr_name).should == callback_block
        callback_file = "path/to/callback.rb"
        lambda {@resource.send(attr_name, callback_file)}.should_not raise_error
        @resource.send(attr_name).should == callback_file
        lambda {@resource.send(attr_name, :this_is_fail)}.should raise_error(ArgumentError)
      end
    end
  end

  before do
    @resource = Chef::Resource::Deploy.new("/my/deploy/dir")
  end

  resource_has_a_string_attribute(:repo)
  resource_has_a_string_attribute(:deploy_to)
  resource_has_a_string_attribute(:role)
  resource_has_a_string_attribute(:restart_command)
  resource_has_a_string_attribute(:migration_command)
  resource_has_a_string_attribute(:user)
  resource_has_a_string_attribute(:group)
  resource_has_a_string_attribute(:repository_cache)
  resource_has_a_string_attribute(:copy_exclude)
  resource_has_a_string_attribute(:revision)
  resource_has_a_string_attribute(:remote)
  resource_has_a_string_attribute(:git_ssh_wrapper)
  resource_has_a_string_attribute(:svn_username)
  resource_has_a_string_attribute(:svn_password)
  resource_has_a_string_attribute(:svn_arguments)
  resource_has_a_string_attribute(:svn_info_args)

  resource_has_a_boolean_attribute(:migrate, :defaults_to=>false)
  resource_has_a_boolean_attribute(:enable_submodules, :defaults_to=>false)
  resource_has_a_boolean_attribute(:shallow_clone, :defaults_to=>false)

  it "uses the first argument as the deploy directory" do
    @resource.deploy_to.should eql("/my/deploy/dir")
  end

  # For git, any revision, branch, tag, whatever is resolved to a SHA1 ref.
  # For svn, the branch is included in the repo URL.
  # Therefore, revision and branch ARE NOT SEPARATE THINGS
  it "aliases #revision as #branch" do
    @resource.branch "stable"
    @resource.revision.should eql("stable")
  end

  it "takes the SCM resource to use as a constant, and defaults to git" do
    @resource.scm_provider.should eql(Chef::Provider::Git)
    @resource.scm_provider Chef::Provider::Subversion
    @resource.scm_provider.should eql(Chef::Provider::Subversion)
  end

  it "allows scm providers to be set via symbol" do
    @resource.scm_provider.should == Chef::Provider::Git
    @resource.scm_provider :subversion
    @resource.scm_provider.should == Chef::Provider::Subversion
  end

  it "allows scm providers to be set via string" do
    @resource.scm_provider.should == Chef::Provider::Git
    @resource.scm_provider "subversion"
    @resource.scm_provider.should == Chef::Provider::Subversion
  end

  it "has a boolean attribute for svn_force_export defaulting to false" do
    @resource.svn_force_export.should be_false
    @resource.svn_force_export true
    @resource.svn_force_export.should be_true
    lambda {@resource.svn_force_export(10053)}.should raise_error(ArgumentError)
  end

  it "takes arbitrary environment variables in a hash" do
    @resource.environment "RAILS_ENV" => "production"
    @resource.environment.should == {"RAILS_ENV" => "production"}
  end

  it "takes string arguments to environment for backwards compat, setting RAILS_ENV, RACK_ENV, and MERB_ENV" do
    @resource.environment "production"
    @resource.environment.should == {"RAILS_ENV"=>"production", "RACK_ENV"=>"production","MERB_ENV"=>"production"}
  end

  it "sets destination to $deploy_to/shared/$repository_cache" do
    @resource.destination.should eql("/my/deploy/dir/shared/cached-copy")
  end

  it "sets shared_path to $deploy_to/shared" do
    @resource.shared_path.should eql("/my/deploy/dir/shared")
  end

  it "sets current_path to $deploy_to/current" do
    @resource.current_path.should eql("/my/deploy/dir/current")
  end

  it "gets the current_path correct even if the shared_path is set (regression test)" do
    @resource.shared_path
    @resource.current_path.should eql("/my/deploy/dir/current")
  end

  it "gives #depth as 5 if shallow clone is true, nil otherwise" do
    @resource.depth.should be_nil
    @resource.shallow_clone true
    @resource.depth.should eql("5")
  end

  it "aliases repo as repository" do
    @resource.repository "git@github.com/opcode/cookbooks.git"
    @resource.repo.should eql("git@github.com/opcode/cookbooks.git")
  end

  it "aliases git_ssh_wrapper as ssh_wrapper" do
    @resource.ssh_wrapper "git_my_repo.sh"
    @resource.git_ssh_wrapper.should eql("git_my_repo.sh")
  end

  it "has an Array attribute purge_before_symlink, default: log, tmp/pids, public/system" do
    @resource.purge_before_symlink.should == %w{ log tmp/pids public/system }
    @resource.purge_before_symlink %w{foo bar baz}
    @resource.purge_before_symlink.should == %w{foo bar baz}
  end

  it "has an Array attribute create_dirs_before_symlink, default: tmp, public, config" do
    @resource.create_dirs_before_symlink.should == %w{tmp public config}
    @resource.create_dirs_before_symlink %w{foo bar baz}
    @resource.create_dirs_before_symlink.should == %w{foo bar baz}
  end

  it 'has a Hash attribute symlinks, default: {"system" => "public/system", "pids" => "tmp/pids", "log" => "log"}' do
    default = { "system" => "public/system", "pids" => "tmp/pids", "log" => "log"}
    @resource.symlinks.should == default
    @resource.symlinks "foo" => "bar/baz"
    @resource.symlinks.should == {"foo" => "bar/baz"}
  end

  it 'has a Hash attribute symlink_before_migrate, default "config/database.yml" => "config/database.yml"' do
    @resource.symlink_before_migrate.should == {"config/database.yml" => "config/database.yml"}
    @resource.symlink_before_migrate "wtf?" => "wtf is going on"
    @resource.symlink_before_migrate.should == {"wtf?" => "wtf is going on"}
  end

  resource_has_a_callback_attribute :before_migrate
  resource_has_a_callback_attribute :before_symlink
  resource_has_a_callback_attribute :before_restart
  resource_has_a_callback_attribute :after_restart

  it "aliases restart_command as restart" do
    @resource.restart "foobaz"
    @resource.restart_command.should == "foobaz"
  end

  it "takes a block for the restart parameter" do
    restart_like_this = lambda {p :noop}
    @resource.restart(&restart_like_this)
    @resource.restart.should == restart_like_this
  end

  it "defaults to using the Deploy::Timestamped provider" do
    @resource.provider.should == Chef::Provider::Deploy::Timestamped
  end

  it "allows providers to be set with a full class name" do
    @resource.provider Chef::Provider::Deploy::Timestamped
    @resource.provider.should == Chef::Provider::Deploy::Timestamped
  end

  it "allows deploy providers to be set via symbol" do
    @resource.provider :revision
    @resource.provider.should == Chef::Provider::Deploy::Revision
  end

  it "allows deploy providers to be set via string" do
    @resource.provider "revision"
    @resource.provider.should == Chef::Provider::Deploy::Revision
  end

  it "defaults keep_releases to 5" do
    @resource.keep_releases.should == 5
  end

  it "allows keep_releases to be set via integer" do
    @resource.keep_releases 10
    @resource.keep_releases.should == 10
  end

  it "enforces a minimum keep_releases of 1" do
    @resource.keep_releases 0
    @resource.keep_releases.should == 1
  end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaleromyces occidentalis Thaxt.

### Remarks
null


text:
#import "KGPDFObject_identifier.h"
#import <string.h>
#import <Foundation/NSString.h>

KGPDFIdentifier KGPDFClassifyIdentifier(const char *bytes,unsigned length) {
   char name[length+1];

   strncpy(name,bytes,length);
   name[length]='\0';

   if(strcmp(name,"true")==0)
    return KGPDFIdentifier_true;
   if(strcmp(name,"false")==0)
    return KGPDFIdentifier_false;
   if(strcmp(name,"null")==0)
    return KGPDFIdentifier_null;

   if(strcmp(name,"f")==0)
    return KGPDFIdentifier_f;
   if(strcmp(name,"n")==0)
    return KGPDFIdentifier_n;
   if(strcmp(name,"R")==0)
    return KGPDFIdentifier_R;
   if(strcmp(name,"xref")==0)
    return KGPDFIdentifier_xref;
   if(strcmp(name,"trailer")==0)
    return KGPDFIdentifier_trailer;
   if(strcmp(name,"startxref")==0)
    return KGPDFIdentifier_startxref;
   if(strcmp(name,"obj")==0)
    return KGPDFIdentifier_obj;
   if(strcmp(name,"endobj")==0)
    return KGPDFIdentifier_endobj;
   if(strcmp(name,"stream")==0)
    return KGPDFIdentifier_stream;
   if(strcmp(name,"endstream")==0)
    return KGPDFIdentifier_endstream;

   //NSLog(@"KGPDFClassifyIdentifier UNKNOWN [%s]",name);

   return KGPDFIdentifierUnknown;
}

@implementation KGPDFObject_identifier

-initWithIdentifier:(KGPDFIdentifier)identifier name:(const char *)bytes length:(unsigned)length {
   _identifier=identifier;
   _length=length;
   _bytes=NSZoneMalloc(NULL,_length+1);
   strncpy(_bytes,bytes,_length);
   _bytes[_length]='\0';
   return self;
}

-(void)dealloc {
   NSZoneFree(NULL,_bytes);
   [super dealloc];
}

+pdfObjectWithIdentifier:(KGPDFIdentifier)identifier name:(const char *)bytes length:(unsigned)length {
   return [[[self alloc] initWithIdentifier:identifier name:bytes length:length] autorelease];
}

-(KGPDFObjectType)objectType {
   return KGPDFObjectType_identifier;
}

-(KGPDFIdentifier)identifier {
   return _identifier;
}

-(const char *)name {
   return _bytes;
}

-(NSString *)description {
   return [NSString stringWithFormat:@"<%@ %d %s",isa,_identifier,_bytes];
}
@end


text:
import SlidingPages from "../base/SlidingPages.js";

/**
 * SlidingPages component in the Plain reference design system
 *
 * @inherits SlidingPages
 */
class PlainSlidingPages extends SlidingPages {}

export default PlainSlidingPages;


text:
require 'singleton'
	class ToE::ToECache
	  include Singleton

	  def initialize
	    super

	    @documents = []
	    @events = []

	    @step = 0

    end

	  def cached?(toe_document)
	    #@todo (med) return true if this document is in the cache already
    end

    def add_document(toe_document)

    end

    # finds events according to given properties
    #
    # :value  :: String, Regexp, Hash
    #
    def find(params={})

    end

    def step
      @step = @step + 1
      @step
    end

	end


text:
package com.mwronski.codejam2015.qualification.io

/**
 * Parser for standing ovation input data.
 *
 * The first line of the input gives the number of test cases, T.
 * T test cases follow. Each consists of one line with Smax, the maximum shyness level of the shyest person in the audience,
 * followed by a string of Smax + 1 single digits. The kth digit of this string (counting starting from 0) represents
 * how many people in the audience have shyness level k. For example, the string "409" would mean that there were
 * four audience members with Si = 0 and nine audience members with Si = 2 (and none with Si = 1 or any other value).
 * Note that there will initially always be between 0 and 9 people with each shyness level.
 *
 * The string will never end in a 0. Note that this implies that there will always be at least one person in the audience.
 *
 * @see https://code.google.com/codejam/contest/6224486/dashboard
 * @author Michal Wronski
 */
object StandingOvationTask {

  /**
   * Parse task data
   * @param data data with tasks
   * @return non-nullable iterator with parsing results
   */
  def apply(data: Iterator[String]): Iterator[Either[String, StandingOvationTask]] = {
    data.next() //skip first line with number of test cases
    data.map(
      row => {
        val data = row.split(" ")
        if (data.length != 2) {
          Left("Unexpected line format: %s".format(row))
        } else {
          try {
            val maxShyness = data(0).toInt
            val audience = data(1).toCharArray.map(_.asDigit)
            val expectedAudience = audience.length - 1
            if (maxShyness != expectedAudience) {
              Left("Couldn't parse line '%s' - max shyness level '%d' different then audience length '%d'".format(row, maxShyness, expectedAudience))
            } else {
              Right(new StandingOvationTask(maxShyness, audience))
            }
          } catch {
            case t: Throwable => Left("Error while parsing line: %s, error: %s".format(row, t))
          }
        }
      }
    )
  }

}

/**
 * Single task related for standing ovation
 * @param maxShyness the maximum shyness level of the shyest person in the audience
 * @param audience people grouped by shyness level (index: shyness level, value: number of persons with given shyness)
 */
sealed case class StandingOvationTask(maxShyness: Int, audience: Array[Int])


text:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

public class ImageMovePanel extends JPanel
{
    // To make this class serializable
    private static final long serialVersionUID = 1L;

	private BufferedImage img;
	private Rectangle selection;
    private double rotationAngle;

    public ImageMovePanel()
    {
        setOpaque(false);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        setRotationAngle(0);
    }

	public void setImage(Point p, BufferedImage i)
	{
		img = i;

        int w = 0;
        int h = 0;

        if (img != null)
        {
            w = img.getWidth();
            h = img.getHeight();
        }

		selection = new Rectangle(p.x, p.y, w, h);

		repaint();
	}

    public void setRotationAngle(double angle)
    {
        rotationAngle = angle;
    }

	public void setSelectionBounds(Rectangle rect)
	{
		selection = rect;
		repaint();
	}

	public void paintComponent(Graphics gr)
	{
        // Convert the Graphics object to a Graphics2D object
        Graphics2D g2d = (Graphics2D)gr;

        // Rotate the image
        g2d.rotate(Math.toRadians(rotationAngle),
                   img.getWidth()/2, img.getHeight()/2);

		if ((img != null) && (selection != null))
		{
            // Declare variables
            int dx1 = selection.x;
            int dy1 = selection.y;
            int dx2 = selection.x + selection.width;
            int dy2 = selection.y + selection.height;

            // Draw the image
			g2d.drawImage(img,
                          dx1,             //dx1
                          dy1,             //dy1
                          dx2,             //dx2
                          dy2,             //dy2
                          0,               //sx1
                          0,               //sy1
                          img.getWidth(),  //sx2
                          img.getHeight(), //sy2
                          this);
		}
	}
}


text:
/**
 * Requires placing keywords on a new line.
 *
 * Type: `Array`
 *
 * Values: Array of quoted keywords
 *
 * #### Example
 *
 * ```js
 * "requireKeywordsOnNewLine": ["else"]
 * ```
 *
 * ##### Valid
 *
 * ```js
 * if (x < 0) {
 *     x++;
 * }
 * else {
 *     x--;
 * }
 * ```
 *
 * ##### Invalid
 *
 * ```js
 * if (x < 0) {
 *     x++;
 * } else {
 *     x--;
 * }
 * ```
 */

var assert = require('assert');

module.exports = function() {};

module.exports.prototype = {

    configure: function(keywords) {
        assert(Array.isArray(keywords), 'requireKeywordsOnNewLine option requires array value');
        this._keywordIndex = {};
        for (var i = 0, l = keywords.length; i < l; i++) {
            this._keywordIndex[keywords[i]] = true;
        }
    },

    getOptionName: function() {
        return 'requireKeywordsOnNewLine';
    },

    check: function(file, errors) {
        var keywordIndex = this._keywordIndex;

        file.iterateTokensByType('Keyword', function(token) {
            if (keywordIndex[token.value]) {
                errors.assert.differentLine({
                    token: file.getPrevToken(token),
                    nextToken: token
                });
            }
        });
    }

};


text:
import { connect } from 'react-redux'
import React, { Component, PropTypes } from 'react'
import Playlist from '../components/Playlist'

class PlaylistContainer extends Component {
  render() {
    return <Playlist {...this.props} />
  }
}

function mapStateToProps(state) {
  const { channel } = state.playlist
  const { songIndex } = state.player
  const { open } = state.environment
  const playlistSongs = state.playlist[channel] ? state.playlist[channel] : []

  return {
    channel,
    playlistSongs,
    songIndex,
    open
  }
}

export default connect(
  mapStateToProps
)(PlaylistContainer)


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

<title>S-Index</title>
<meta name="date" content="2016-02-21">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

C E G I J M N S

S

setVidas(int) - Method in class com.codizer.Naves

Set vidas

C E G I J M N S

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
var express = require('express');
var jade = require('jade');
var mongo = require('mongoskin');
var nodemailer = require('nodemailer');
var config = require('./config')

var mdb = mongo.db('paramaggarwal:' + config.mongodb_pass + '@staff.mongohq.com:10085/meyouapp');

mdb.bind('users');
mdb.bind('messages');

var app = express();
app.set('view engine', 'jade');
app.set('view options', {layout: false});

app.use(express.logger());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: config.express_secret }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
app.use(express.favicon());
//app.use(express.errorHandler());

app.get('/', function(request, response) {
        if (request.session.user) {
        mdb.messages
        .find({receipient: request.session.user})
        .toArray(function(err, doc) {
                 response.render('user', {user: request.session.user, messages: doc} );
                 });
        } else {
        response.render('index');
        }
        });

app.get('/all', function(request, response) {
		mdb.messages
		.find()
		.toArray(function(err, doc) {
				 response.write('');
				 for(var i=0; i < doc.length; i++) {
				 response.write('Message from ' + doc[i].sender + ' for ' + doc[i].receipient + ': ' + doc[i].message + '
');
				 }
				 response.write('

');
				 mdb.users
				 .find()
				 .toArray(function(err, doc) {
						  for(var i=0; i < doc.length; i++) {
						  response.write('Username: ' + doc[i].nickname + ' and password: ' + doc[i].password + '
');
						  }
						  response.write('');
						  response.end();
						  });
				 });
		});

app.post('/register', function(request, response){
         var data = request.body;
         mdb.users
		 .find({nickname: data.nickname})
		 .toArray(function(err, doc) {
				  if(doc != 0) {
				  response.render('index', {flash: 'Nickname is in use'});

				  } else if(data.password != data.confirm_password) {
				  response.render('index', {flash: 'Password does not match'});

				  } else {
				  delete data.confirm_password;
				  mdb.users
				  .save(data,
						function(db_err, db_res) {
						request.session.user = data.nickname;
                        response.redirect('/');
						});
				  }
				  });
         });

app.post('/login', function(request, response){
         var data = request.body;
         mdb.users
		 .find({nickname: data.nickname})
		 .toArray(function(err, doc) {
				  if(!(doc != 0)) {
				  response.render('index', {flash: 'No user found'});
				  } else if(doc[0].password != data.password) {
				  response.render('index', {flash: 'Wrong password'});
				  } else {
                  request.session.user = doc[0].nickname;
                  response.redirect('/');
				  }
                  });
         });

app.post('/logout', function(request, response){
         request.session.destroy();
         response.redirect('/');
         });

app.post('/save', function(request, response){
         var data = request.body;

         var userid = '2';
         var time = String (new Date().getTime());
         var messagesArray = new Array(time);

         data.time = time;
         mdb.messages.save(data);
		 response.redirect('/');
         });

nodemailer.SMTP = {
host: 'smtp.mailgun.org',
port: 465,
ssl: true,
use_authentication: true,
user: 'postmaster@paramaggarwal.mailgun.org',
pass: config.smtp_pass
}

app.get('/email', function(request, response) {
        nodemailer
		.send_mail({
				   sender: 'ourapp@ourapp.com',
				   to:'paramaggarwal@gmail.com',
				   subject:'Hello!',
				   html: '
Hi, how are you doing?
',
				   body:'Hi, how are you doing?'
				   },function(error, success){
				   console.log('Message ' + success ? 'sent' : 'failed');
				   }
				   );
        response.end();
        });

var port = process.env.PORT || 3000;
app.listen(port, function() {
           console.log("Listening on " + port);
           });


text:
package gitbase

import (
	"bytes"
	"fmt"
	"io"
	"strings"

	"github.com/src-d/go-mysql-server/sql"

	"gopkg.in/src-d/go-git.v4/plumbing"
	"gopkg.in/src-d/go-git.v4/plumbing/storer"
)

type referencesTable struct {
	checksumable
	partitioned
	filters []sql.Expression
	index   sql.IndexLookup
}

// RefsSchema is the schema for the refs table.
var RefsSchema = sql.Schema{
	{Name: "repository_id", Type: sql.Text, Nullable: false, Source: ReferencesTableName},
	{Name: "ref_name", Type: sql.Text, Nullable: false, Source: ReferencesTableName},
	{Name: "commit_hash", Type: sql.VarChar(40), Nullable: false, Source: ReferencesTableName},
}

func newReferencesTable(pool *RepositoryPool) *referencesTable {
	return &referencesTable{checksumable: checksumable{pool}}
}

var _ Table = (*referencesTable)(nil)
var _ Squashable = (*referencesTable)(nil)

func (referencesTable) isSquashable()   {}
func (referencesTable) isGitbaseTable() {}

func (r referencesTable) String() string {
	return printTable(
		ReferencesTableName,
		RefsSchema,
		nil,
		r.filters,
		r.index,
	)
}

func (referencesTable) Name() string {
	return ReferencesTableName
}

func (referencesTable) Schema() sql.Schema {
	return RefsSchema
}

func (r *referencesTable) WithFilters(filters []sql.Expression) sql.Table {
	nt := *r
	nt.filters = filters
	return &nt
}

func (r *referencesTable) WithIndexLookup(idx sql.IndexLookup) sql.Table {
	nt := *r
	nt.index = idx
	return &nt
}

func (r *referencesTable) IndexLookup() sql.IndexLookup { return r.index }
func (r *referencesTable) Filters() []sql.Expression    { return r.filters }

func (r *referencesTable) PartitionRows(
	ctx *sql.Context,
	p sql.Partition,
) (sql.RowIter, error) {
	repo, err := getPartitionRepo(ctx, p)
	if err != nil {
		return nil, err
	}

	span, ctx := ctx.Span("gitbase.ReferencesTable")
	iter, err := rowIterWithSelectors(
		ctx, RefsSchema, ReferencesTableName,
		r.filters,
		r.handledColumns(),
		func(selectors selectors) (sql.RowIter, error) {
			var hashes []string
			hashes, err = selectors.textValues("commit_hash")
			if err != nil {
				return nil, err
			}

			var names []string
			names, err = selectors.textValues("ref_name")
			if err != nil {
				return nil, err
			}

			for i := range names {
				names[i] = strings.ToLower(names[i])
			}

			var indexValues sql.IndexValueIter
			if r.index != nil {
				if indexValues, err = r.index.Values(p); err != nil {
					return nil, err
				}
			}

			return &refRowIter{
				hashes:        stringsToHashes(hashes),
				repo:          repo,
				names:         names,
				index:         indexValues,
				skipGitErrors: shouldSkipErrors(ctx),
			}, nil
		},
	)

	if err != nil {
		span.Finish()
		return nil, errorWithRepo(repo, err)
	}

	return sql.NewSpanIter(span, newRepoRowIter(repo, iter)), nil
}

func (referencesTable) HandledFilters(filters []sql.Expression) []sql.Expression {
	return handledFilters(ReferencesTableName, RefsSchema, filters)
}

func (referencesTable) handledColumns() []string { return []string{"commit_hash", "ref_name"} }

// IndexKeyValues implements the sql.IndexableTable interface.
func (r *referencesTable) IndexKeyValues(
	ctx *sql.Context,
	colNames []string,
) (sql.PartitionIndexKeyValueIter, error) {
	return newTablePartitionIndexKeyValueIter(
		ctx,
		newReferencesTable(r.pool),
		ReferencesTableName,
		colNames,
		new(refRowKeyMapper),
	)
}

type refRowKeyMapper struct{}

func (refRowKeyMapper) fromRow(row sql.Row) ([]byte, error) {
	if len(row) != 3 {
		return nil, errRowKeyMapperRowLength.New(3, len(row))
	}

	repo, ok := row[0].(string)
	if !ok {
		return nil, errRowKeyMapperColType.New(0, repo, row[0])
	}

	name, ok := row[1].(string)
	if !ok {
		return nil, errRowKeyMapperColType.New(1, name, row[1])
	}

	commit, ok := row[2].(string)
	if !ok {
		return nil, errRowKeyMapperColType.New(2, commit, row[2])
	}

	var buf bytes.Buffer
	writeString(&buf, repo)
	writeString(&buf, name)

	if err := writeHash(&buf, commit); err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

func (refRowKeyMapper) toRow(data []byte) (sql.Row, error) {
	var buf = bytes.NewBuffer(data)

	repo, err := readString(buf)
	if err != nil {
		return nil, fmt.Errorf("can't read ref repository: %s", err)
	}

	name, err := readString(buf)
	if err != nil {
		return nil, fmt.Errorf("can't read ref name: %s", err)
	}

	commit, err := readHash(buf)
	if err != nil {
		return nil, fmt.Errorf("can't read ref hash: %s", err)
	}

	return sql.Row{repo, name, commit}, nil
}

type refRowIter struct {
	repo          *Repository
	hashes        []plumbing.Hash
	names         []string
	index         sql.IndexValueIter
	skipGitErrors bool

	head   *plumbing.Reference
	iter   storer.ReferenceIter
	mapper refRowKeyMapper
}

func (i *refRowIter) Next() (sql.Row, error) {
	if i.index != nil {
		return i.nextFromIndex()
	}

	return i.next()
}

func (i *refRowIter) init() error {
	var err error
	i.iter, err = i.repo.References()
	if err != nil {
		return err
	}

	i.head, err = i.repo.Head()
	if err != nil && err != plumbing.ErrReferenceNotFound {
		return err
	}

	return nil
}

var (
	refRefNameIdx = RefsSchema.IndexOf("ref_name", ReferencesTableName)
	refHashIdx    = RefsSchema.IndexOf("commit_hash", ReferencesTableName)
)

func (i *refRowIter) nextFromIndex() (sql.Row, error) {
	for {
		key, err := i.index.Next()
		if err != nil {
			return nil, err
		}

		row, err := i.mapper.toRow(key)
		if err != nil {
			return nil, err
		}

		hash := plumbing.NewHash(row[refHashIdx].(string))
		if len(i.hashes) > 0 && !hashContains(i.hashes, hash) {
			continue
		}

		refName := strings.ToLower(row[refRefNameIdx].(string))
		if len(i.names) > 0 && !stringContains(i.names, refName) {
			continue
		}

		return row, nil
	}
}

func (i *refRowIter) next() (sql.Row, error) {
	for {
		if i.iter == nil {
			if err := i.init(); err != nil {
				if i.skipGitErrors {
					return nil, io.EOF
				}

				return nil, err
			}
		}

		if i.head != nil {
			o := i.head
			i.head = nil

			if len(i.hashes) > 0 && !hashContains(i.hashes, o.Hash()) {
				continue
			}

			if len(i.names) > 0 && !stringContains(i.names, "head") {
				continue
			}

			return sql.NewRow(
				i.repo.ID(),
				"HEAD",
				o.Hash().String(),
			), nil
		}

		o, err := i.iter.Next()
		if err != nil {
			return nil, err
		}

		if isIgnoredReference(o) {
			continue
		}

		if len(i.hashes) > 0 && !hashContains(i.hashes, o.Hash()) {
			continue
		}

		if len(i.names) > 0 && !stringContains(i.names, strings.ToLower(o.Name().String())) {
			continue
		}

		return referenceToRow(i.repo.ID(), o), nil
	}
}

func (i *refRowIter) Close() error {
	if i.iter != nil {
		i.iter.Close()
	}

	if i.repo != nil {
		i.repo.Close()
	}

	if i.index != nil {
		return i.index.Close()
	}

	return nil
}

func referenceToRow(repositoryID string, c *plumbing.Reference) sql.Row {
	hash := c.Hash().String()

	return sql.NewRow(
		repositoryID,
		c.Name().String(),
		hash,
	)
}

func isIgnoredReference(r *plumbing.Reference) bool {
	return r.Type() != plumbing.HashReference
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Matt & Yana | Timeline</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Rokkitt' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Playfair+Display+SC:700,400' rel='stylesheet' type='text/css'>
        <link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet">

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

        <link rel="stylesheet" href="css/portfolio.css">
        <link rel="stylesheet" href="css/component.css">

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

MENU

Home

Timeline

Travel

Recipes

            M&Y

Our Timeline

        <time>December 2017</time> Sign contract for a new construction house.

        <time>November 2016</time> Begin house shopping!

        <time>October 2016</time> Honeymoon trip to Iceland.

        <time>October 8, 2016</time> Wedding Day.

         <time>August 2015</time> We get a 3rd cat (what's one more when a cute gray tabby needs a home, eh?)

         <time>January 15, 2015</time> Matt pops the Big Question! (Yana says "YES").

        <time>July 2014</time> Our second international trip - to Costa Rica.  Yana got to pet a sloth (major life milestone).

        <time>March 2014</time> Move into a rental house.

        <time>March 2013</time> We move in together into an apartment that was way too small for our computers, workout stuff, and two cats.

        <time>August 2011</time> Our first trip out of the country together, to Mexico.  We were both very worried we'd hate each other by the end of it, but instead we realized we are the best travel buddies!

        <time>May 11, 2011</time> The official first date!  We went to see the movie Thor.

        <time>2009</time> First time we met.  Yana messaged Matt on OkCupid.  That's not the actual start of the story, though, as it was not meant-to-be for a little while...

© All Rights Reserved, Made with


text:
import React, { Component } from 'react'
import styled from 'styled-components'
import { observer } from 'mobx-react'
import { Text } from '../utils/'

const Button = styled.button`
  border: none;
  width 50px;
  padding: 10px 0;
  background: #EEE4DA;
  color: #776E65;
  border-radius: 2px;
  box-shadow: 0 2px 5px 0 rgba(0,0,0,.18), 0 1px 5px 0 rgba(0,0,0,.15);
  margin-left: 8px;
  cursor: pointer;
  outline: none;
  font-weight: bold;
  transition: box-shadow .4s ease-out,-webkit-box-shadow .4s ease-out;

  &:hover {
    box-shadow: 0 5px 11px 0 rgba(0,0,0,.18), 0 4px 15px 0 rgba(0,0,0,.15);
    background: #EDE0C8;
  }
`
interface ContollerProps {
  className?: string
  onReset: () => void
  onPrev: () => void
}
@observer
class Contoller extends Component<ContollerProps> {
  render() {
    const { className } = this.props
    return (
      <div className={className}>
        <Button onClick={this.props.onPrev}>{Text.undo}</Button>
        <Button onClick={this.props.onReset}>{Text.reset}</Button>
      </div>
    )
  }
}

const StyledContoller = styled(Contoller)`
  width: 120px;
  margin: 0 auto 20px auto;
`

export default StyledContoller


text:
import { MenuManager } from "./../../browser/src/Services/Menu"

export const mockMenuShow = jest.fn()
const MockMenu = jest.fn<MenuManager>().mockImplementation(() => ({
    create() {
        return {
            show: mockMenuShow,
            setItems(items: {}) {
                return items
            },
            onItemSelected: {
                subscribe: jest.fn(),
            },
        }
    },
}))

export default MockMenu


text:
id: a6b0bb188d873cb2c8729495
title: Convierte entidades HTML
challengeType: 5
forumTopicId: 16007
dashedName: convert-html-entities
---

# --description--

Convierte los caracteres `&`, `<`, `>`, `"` (dobles comillas), y `'` (apóstrofo), en un cadena con su correspondiente entidad HTML.

# --hints--

`convertHTML("Dolce & Gabbana")` debe devolver la cadena `Dolce & Gabbana`.

```js
assert.match(convertHTML('Dolce & Gabbana'), /Dolce & Gabbana/);
```

`convertHTML("Hamburgers < Pizza < Tacos")` debe devolver la cadena `Hamburgers < Pizza < Tacos`.

```js
assert.match(
  convertHTML('Hamburgers < Pizza < Tacos'),
  /Hamburgers < Pizza < Tacos/
);
```

`convertHTML("Sixty > twelve")` debe devolver la cadena `Sixty > twelve`.

```js
assert.match(convertHTML('Sixty > twelve'), /Sixty > twelve/);
```

`convertHTML('Stuff in "quotation marks"')` debe devolver la cadena `Stuff in "quotation marks"`.

```js
assert.match(
  convertHTML('Stuff in "quotation marks"'),
  /Stuff in "quotation marks"/
);
```

`convertHTML("Schindler's List")` debe devolver la cadena `Schindler's List`.

```js
assert.match(convertHTML("Schindler's List"), /Schindler's List/);
```

`convertHTML("<>")` debe devolver la cadena `<>`.

```js
assert.match(convertHTML('<>'), /<>/);
```

`convertHTML("abc")` debe devolver la cadena `abc`.

```js
assert.strictEqual(convertHTML('abc'), 'abc');
```

# --seed--

## --seed-contents--

```js
function convertHTML(str) {
  return str;
}

convertHTML("Dolce & Gabbana");
```

# --solutions--

```js
var MAP = { '&': '&',
            '<': '<',
            '>': '>',
            '"': '"',
            "'": '''};

function convertHTML(str) {
  return str.replace(/[&<>"']/g, function(c) {
    return MAP[c];
  });
}
```


text:
#pragma once
#include <af/defines.h>

typedef void * af_features;

#ifdef __cplusplus
namespace af
{
    class array;

    class AFAPI features {
    private:
        af_features feat;

    public:
        features();
        features(const size_t n);
        features(af_features f);

        ~features();

        features& operator= (const features& f);

        size_t getNumFeatures() const;
        array getX() const;
        array getY() const;
        array getScore() const;
        array getOrientation() const;
        array getSize() const;
        af_features get() const;
    };

}
#endif

#ifdef __cplusplus
extern "C" {
#endif

    AFAPI af_err af_create_features(af_features *feat, dim_t num);

    AFAPI af_err af_retain_features(af_features *out, const af_features feat);

    AFAPI af_err af_get_features_num(dim_t *num, const af_features feat);

    AFAPI af_err af_get_features_xpos(af_array *out, const af_features feat);

    AFAPI af_err af_get_features_ypos(af_array *out, const af_features feat);

    AFAPI af_err af_get_features_score(af_array *score, const af_features feat);

    AFAPI af_err af_get_features_orientation(af_array *orientation, const af_features feat);

    AFAPI af_err af_get_features_size(af_array *size, const af_features feat);

    // Destroy af_features
    AFAPI af_err af_release_features(af_features feat);

#ifdef __cplusplus
}
#endif


text:
package com.ctrip.zeus.model.report;

public class CmsResponse {
    private Boolean m_success;

    private String m_message;

    private Result m_result;

    public CmsResponse() {
    }

    protected boolean equals(Object o1, Object o2) {
        if (o1 == null) {
            return o2 == null;
        } else if (o2 == null) {
            return false;
        } else {
            return o1.equals(o2);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof CmsResponse) {
            CmsResponse _o = (CmsResponse) obj;

            if (!equals(m_success, _o.getSuccess())) {
                return false;
            }

            if (!equals(m_message, _o.getMessage())) {
                return false;
            }

            if (!equals(m_result, _o.getResult())) {
                return false;
            }

            return true;
        }

        return false;
    }

    public String getMessage() {
        return m_message;
    }

    public Result getResult() {
        return m_result;
    }

    public Boolean getSuccess() {
        return m_success;
    }

    @Override
    public int hashCode() {
        int hash = 0;

        hash = hash * 31 + (m_success == null ? 0 : m_success.hashCode());
        hash = hash * 31 + (m_message == null ? 0 : m_message.hashCode());
        hash = hash * 31 + (m_result == null ? 0 : m_result.hashCode());

        return hash;
    }

    public boolean isSuccess() {
        return m_success != null && m_success.booleanValue();
    }

    public CmsResponse setMessage(String message) {
        m_message = message;
        return this;
    }

    public CmsResponse setResult(Result result) {
        m_result = result;
        return this;
    }

    public CmsResponse setSuccess(Boolean success) {
        m_success = success;
        return this;
    }

}


text:
package com.ebay.jetstream.event.support;

import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;

import com.ebay.jetstream.event.BatchEventSink;
import com.ebay.jetstream.event.BatchEventSource;
import com.ebay.jetstream.event.EventException;
import com.ebay.jetstream.event.EventMetaInfo;
import com.ebay.jetstream.event.EventSink;
import com.ebay.jetstream.event.JetstreamErrorCodes;
import com.ebay.jetstream.event.JetstreamEvent;

/**
 * @author xiaojuwu1
 */
public abstract class AbstractBatchEventSource extends AbstractEventSource
		implements BatchEventSource {

	private final Collection<BatchEventSink> m_batchSinks = new CopyOnWriteArrayList<BatchEventSink>();

	protected void fireSendEvents(Collection<JetstreamEvent> events,
			EventMetaInfo meta)  throws EventException {
		if (m_batchSinks.isEmpty()) {
			throw new EventException("All Event Sinks are paused",
					JetstreamErrorCodes.EVENT_SINKS_PAUSED.toString());
		}
		for (BatchEventSink b : m_batchSinks) {
			b.sendEvents(events, meta);
		}
	}

	@Override
	public void addBatchEventSink(BatchEventSink target) {
		m_batchSinks.add(target);
	}

	@Override
	public Collection<BatchEventSink> getBatchEventSinks() {
		return m_batchSinks;
	}

	@Override
	public void removeBatchEventSink(BatchEventSink target) {
		m_batchSinks.remove(target);
	}

	@Override
	public void setBatchEventSinks(Collection<BatchEventSink> sinks) {
		if (sinks != null && !sinks.isEmpty()) {
			m_batchSinks.clear();
			m_batchSinks.addAll(sinks);
		}
	}

	@Override
	public void addEventSink(EventSink sink) {
		if (sink instanceof BatchEventSink) {
			addBatchEventSink((BatchEventSink) sink);
		} else {
			super.addEventSink(sink);
		}
	}

	@Override
	public void setEventSinks(Collection<EventSink> sinks) {
		for (EventSink s : sinks) {
			if (s instanceof BatchEventSink) {
				addBatchEventSink((BatchEventSink) s);
			} else {
				addEventSink(s);
			}
		}
	}

}


text:
<?php

class ChargeBee_ListResult implements Countable, ArrayAccess, Iterator
{

	private $response;

  private $nextOffset;

	protected $_items;

	private $_index;

  function __construct($response, $nextOffset)
  {
		$this->response = $response;
		$this->nextOffset = $nextOffset;
    $this->_items = array();
    $this->_initItems();
  }

	private function _initItems()
	{
		foreach($this->response as $r)
		{
			array_push($this->_items, new ChargeBee_Result($r));
		}
	}

	public function nextOffset()
	{
	  return $this->nextOffset;
	}

	public function count()
	{
		return count($this->_items);
	}

	//Implementation for ArrayAccess functions
	public function offsetSet($k, $v)
  {
    $this->$k = $v;
  }

  public function offsetExists($k)
  {
    return isset($this->$k);
  }

  public function offsetUnset($k)
  {
    unset($this->$k);
  }

  public function offsetGet($k)
  {
    return isset($this->list[$k]) ? $this->list[$k] : null;
  }

  //Implementation for Iterator functions
  public function current()
  {
      return $this->_items[$this->_index];
  }

  public function key()
  {
      return $this->_index;
  }

  public function next()
  {
      ++$this->_index;
  }

  public function rewind()
  {
      $this->_index = 0;
  }

  public function valid()
  {
      if ($this->_index < count($this->_items)) {
          return true;
      } else {
          return false;
      }
  }

  public function toJson() {
       return json_encode($this->response);
  }

}

?>


text:
require('./polyfills');

var CONST = require('./const');
var Extend = require('./utils/object/Extend');

/**
 * @namespace Phaser
 */

/**
 * The root types namespace.
 *
 * @namespace Phaser.Types
 * @since 3.17.0
 */

var Phaser = {

    Animations: require('./animations'),
    Cache: require('./cache'),
    Cameras: { Scene2D: require('./cameras/2d') },
    Core: require('./core'),
    Class: require('./utils/Class'),
    Data: require('./data'),
    Display: { Masks: require('./display/mask') },
    Events: require('./events'),
    Game: require('./core/Game'),
    GameObjects: {
        DisplayList: require('./gameobjects/DisplayList'),
        GameObjectCreator: require('./gameobjects/GameObjectCreator'),
        GameObjectFactory: require('./gameobjects/GameObjectFactory'),
        UpdateList: require('./gameobjects/UpdateList'),
        Components: require('./gameobjects/components'),
        BuildGameObject: require('./gameobjects/BuildGameObject'),
        BuildGameObjectAnimation: require('./gameobjects/BuildGameObjectAnimation'),
        GameObject: require('./gameobjects/GameObject'),
        Graphics: require('./gameobjects/graphics/Graphics.js'),
        Image: require('./gameobjects/image/Image'),
        Sprite: require('./gameobjects/sprite/Sprite'),
        Text: require('./gameobjects/text/static/Text'),
        Factories: {
            Graphics: require('./gameobjects/graphics/GraphicsFactory'),
            Image: require('./gameobjects/image/ImageFactory'),
            Sprite: require('./gameobjects/sprite/SpriteFactory'),
            Text: require('./gameobjects/text/static/TextFactory')
        },
        Creators: {
            Graphics: require('./gameobjects/graphics/GraphicsCreator'),
            Image: require('./gameobjects/image/ImageCreator'),
            Sprite: require('./gameobjects/sprite/SpriteCreator'),
            Text: require('./gameobjects/text/static/TextCreator')
        }
    },
    Input: require('./input'),
    Loader: {
        FileTypes: {
            AnimationJSONFile: require('./loader/filetypes/AnimationJSONFile'),
            AtlasJSONFile: require('./loader/filetypes/AtlasJSONFile'),
            AudioFile: require('./loader/filetypes/AudioFile'),
            AudioSpriteFile: require('./loader/filetypes/AudioSpriteFile'),
            HTML5AudioFile: require('./loader/filetypes/HTML5AudioFile'),
            ImageFile: require('./loader/filetypes/ImageFile'),
            JSONFile: require('./loader/filetypes/JSONFile'),
            MultiAtlasFile: require('./loader/filetypes/MultiAtlasFile'),
            PluginFile: require('./loader/filetypes/PluginFile'),
            ScriptFile: require('./loader/filetypes/ScriptFile'),
            SpriteSheetFile: require('./loader/filetypes/SpriteSheetFile'),
            TextFile: require('./loader/filetypes/TextFile'),
            XMLFile: require('./loader/filetypes/XMLFile')
        },
        File: require('./loader/File'),
        FileTypesManager: require('./loader/FileTypesManager'),
        GetURL: require('./loader/GetURL'),
        LoaderPlugin: require('./loader/LoaderPlugin'),
        MergeXHRSettings: require('./loader/MergeXHRSettings'),
        MultiFile: require('./loader/MultiFile'),
        XHRLoader: require('./loader/XHRLoader'),
        XHRSettings: require('./loader/XHRSettings')
    },
    Math: {
        Between: require('./math/Between'),
        DegToRad: require('./math/DegToRad'),
        FloatBetween: require('./math/FloatBetween'),
        RadToDeg: require('./math/RadToDeg'),
        Vector2: require('./math/Vector2')
    },
    Plugins: require('./plugins'),
    Renderer: require('./renderer'),
    Scale: require('./scale'),
    Scene: require('./scene/Scene'),
    Scenes: require('./scene'),
    Structs: require('./structs'),
    Textures: require('./textures'),
    Time: require('./time'),
    Tweens: require('./tweens')
};

//   Merge in the consts

Phaser = Extend(false, Phaser, CONST);

//  Export it

if (typeof FEATURE_SOUND)
{
    Phaser.Sound = require('./sound');
}

module.exports = Phaser;

global.Phaser = Phaser;

/*
 * "Documentation is like pizza: when it is good, it is very, very good;
 * and when it is bad, it is better than nothing."
 *  -- Dick Brandon
 */


text:
package com.obsidian.compiler.StaticCodeAnalyzer.Errors;

import com.obsidian.compiler.Lava.LvRangeInFile;
import com.obsidian.compiler.StaticCodeAnalyzer.ScaErrorSource;

public class FunctionBodyIsNonPure extends CompileError {

	private final LvRangeInFile arrowSource;
	private final LvRangeInFile firstNonPureNode;

	public FunctionBodyIsNonPure(LvRangeInFile arrowSource, LvRangeInFile firstNonPureNode) {
		super();
		this.arrowSource = arrowSource;
		this.firstNonPureNode = firstNonPureNode;
	}

	@Override
	public String getTitle() {
		return null;
	}

	@Override
	public ScaErrorSource getFirstSource() {
		return new ScaErrorSource(arrowSource, "Function declared pure, declare with => for impure");
	}

	@Override
	public ScaErrorSource getSecondSource() {
		return new ScaErrorSource(firstNonPureNode, "Impure operation found here");
	}

}


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

	<title>Area Manager - Unit Tests</title>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec ante eros, dignissim quis, facilisis nec, euismod vitae, metus. Nunc dolor sapien, euismod eget, consectetuer id, egestas ut, neque.


text:
package org.panterose.narniaa;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.Random;

import org.junit.Test;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.FastInput;
import com.esotericsoftware.kryo.io.FastOutput;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class NarniaaDBBench {
	private final String location = "F:\\Dev\\data";
	private final long millisInDay = 24 * 60 * 60 * 1000;

	private final ByteBuffer IntBuff = ByteBuffer.allocate(4);
	private final Path path = Paths.get(location, "docs");

	private static final Kryo kryo = new Kryo();
	private static final byte[] data = new byte[1_000_000];
	private static final Random r = new Random(0);
	private static final Document doci = new Document();
	private static final LocalDate date = LocalDate.of(2015, 3, 1);
	private static final byte[] docbytes = new byte[1_000_020];
	{
		r.nextBytes(data);
		doci.setId(0);
		doci.setSym("0");
		doci.setTimestamp(epoch(date));
		doci.setData(data);
		kryo.register(Document.class);
		Output ko = new FastOutput(data.length + 512, 1 << 26);
		ko.setBuffer(docbytes);
		kryo.writeObject(ko, doci);
		ko.flush();
		ko.position();
	}

	@Test
	public void insert() throws IOException, ClassNotFoundException {
		try (NarniaaDB db = new NarniaaDB(path, 1 << 26)) {
			write(0, 5000, db);
			read(1000, 3000, db);
		}
	}

	public void write(int start, int end, NarniaaDB db) throws IOException {
		long nbbytes = 0;
		//byte[] out = new byte[data.length + 2048];

		long startTime = System.currentTimeMillis();

		System.out.print("writing: ");
		Output ko = new FastOutput(data.length + 512, 1 << 26);
		for (int i = start; i < end; i++) {
			try {

				//System.out.print(" " + i);
				Document doc = new Document();
				doc.setId(i);
				doc.setSym((i % 10) + "");
				doc.setTimestamp(epoch(date.plus(i / 1000, ChronoUnit.DAYS)));
				doc.setData(data);

				kryo.writeObject(ko, doc);
				ko.flush();
				byte[] ser = ko.toBytes();
				db.put(IntBuff.putInt(i).array(), ser);
				//db.put(IntBuff.putInt(i).array(), docbytes);
				nbbytes += ser.length;
				//nbbytes += docbytes.length;
				if (ko.getBuffer().length > data.length * 2) {
					System.out.println("Buffer size :" + ko.getBuffer().length);
				}
				if (i % 1000 == 0) {
					System.out.print(".");
				}
				ko.clear();
				IntBuff.clear();
			} catch (RuntimeException e) {
				System.out.println("error for " + i);
				e.printStackTrace();
				throw e;
			}
		}
		long time = System.currentTimeMillis() - startTime + 1;
		System.out.printf("%n %,d B done at %,d MB /s %n", nbbytes, nbbytes / 1000 / time);

	}

	public void read(int start, int end, NarniaaDB db) throws IOException {
		long nbbytes = 0;
		long startTime = System.currentTimeMillis();
		System.out.print("reading: ");
		for (int i = start; i < end; i++) {
			try {
				//System.out.print(" " + i);
				byte[] bytes = db.get(IntBuff.putInt(i).array());

				//assertArrayEquals(docbytes, bytes);
				Input ki = new FastInput(bytes);
				Document doc = kryo.readObject(ki, Document.class);
				nbbytes += bytes.length;
				// oos.reset();
				// baos.reset();

				assertEquals(i, doc.getId());
				//assertEquals(0, doc.getId());

				// assertEquals(start, d.getTimestamp());
				assertEquals((i % 10) + "", doc.getSym());
				//assertEquals("0", doc.getSym());

				assertArrayEquals(data, doc.getData());
				if (i % 1000 == 0) {
					System.out.print(".");
				}
				IntBuff.clear();
			} catch (RuntimeException e) {
				System.out.println("error for " + i);
				e.printStackTrace();
				throw e;
			}
		}
		long time = System.currentTimeMillis() - startTime;
		System.out.printf("%n %,d B done at %,d MB /s %n", nbbytes, nbbytes / 1000 / time);
	}

	protected long epoch(LocalDate date) {
		return date.getLong(ChronoField.EPOCH_DAY) * millisInDay;
	}

}


text:
#ifndef TENSORFLOW_CORE_KERNELS_DATA_SPLIT_UTILS_H_
#define TENSORFLOW_CORE_KERNELS_DATA_SPLIT_UTILS_H_

#include "tensorflow/core/framework/dataset.h"

namespace tensorflow {
namespace data {

// A class which produces splits for a dataset of size N that can be indexed
// into.
class IndexSplitProvider : public SplitProvider {
 public:
  explicit IndexSplitProvider(int64 n);
  Status GetNext(Tensor* split, bool* end_of_splits) override;
  Status Reset() override;
  Status Save(std::function<std::string(std::string)> full_name,
              IteratorStateWriter* writer) override;
  Status Restore(std::function<std::string(std::string)> full_name,
                 IteratorStateReader* reader) override;

 private:
  mutex mu_;
  int64 i_ GUARDED_BY(mu_);
  const int64 n_;
};

// A SplitProvider which wraps another split provider, but drops all splits
// where `index != shard_index % num_shards`
class ShardingSplitProvider : public SplitProvider {
 public:
  ShardingSplitProvider(int64 num_shards, int64 shard_index,
                        std::shared_ptr<SplitProvider> split_provider);

  Status GetNext(Tensor* split, bool* end_of_splits) override;
  Status Reset() override;
  Status Save(std::function<std::string(std::string)> full_name,
              IteratorStateWriter* writer) override;
  Status Restore(std::function<std::string(std::string)> full_name,
                 IteratorStateReader* reader) override;

 private:
  const int64 num_shards_;
  const int64 shard_index_;
  mutex mu_;
  std::shared_ptr<SplitProvider> split_provider_ TF_GUARDED_BY(mu_);
  int64 num_to_skip_ TF_GUARDED_BY(mu_);
};

}  // namespace data
}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_KERNELS_DATA_SPLIT_UTILS_H_


text:
import React, { useEffect, useRef, useState } from 'react';
import { Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import useNotification from '../../hooks/useNotification';
import useRBACProvider from '../../hooks/useRBACProvider';
import hasPermissions from '../../utils/hasPermissions';
import LoadingIndicatorPage from '../LoadingIndicatorPage';

const CheckPagePermissions = ({ permissions, children }) => {
  const abortController = new AbortController();
  const { signal } = abortController;
  const { allPermissions } = useRBACProvider();
  const toggleNotification = useNotification();

  const [state, setState] = useState({ isLoading: true, canAccess: false });
  const isMounted = useRef(true);

  useEffect(() => {
    const checkPermission = async () => {
      try {
        setState({ isLoading: true, canAccess: false });

        const canAccess = await hasPermissions(allPermissions, permissions, signal);

        if (isMounted.current) {
          setState({ isLoading: false, canAccess });
        }
      } catch (err) {
        if (isMounted.current) {
          console.error(err);

          toggleNotification({
            type: 'warning',
            message: { id: 'notification.error' },
          });

          setState({ isLoading: false });
        }
      }
    };

    checkPermission();

    return () => {
      abortController.abort();
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [permissions]);

  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []);

  if (state.isLoading) {
    return <LoadingIndicatorPage />;
  }

  if (!state.canAccess) {
    return <Redirect to="/" />;
  }

  return children;
};

CheckPagePermissions.defaultProps = {
  permissions: [],
};

CheckPagePermissions.propTypes = {
  children: PropTypes.node.isRequired,
  permissions: PropTypes.array,
};

export default CheckPagePermissions;


text:
<?php

namespace Magento\Framework\ObjectManager;

class DefinitionFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $filesystemDriverMock;

    /**
     * @var \Magento\Framework\ObjectManager\DefinitionFactory
     */
    protected $model;

    /**
     * @var string
     */
    protected $sampleContent;

    protected function setUp()
    {
        $this->sampleContent = serialize([1, 2, 3]);
        $this->filesystemDriverMock = $this->getMock(
            'Magento\Framework\Filesystem\Driver\File',
            [],
            [],
            '',
            false
        );
        $this->model = new \Magento\Framework\ObjectManager\DefinitionFactory(
            $this->filesystemDriverMock,
            'DefinitionDir',
            'GenerationDir',
            'serialized'
        );
    }

    public function testCreateDefinitionsReadsCompiledDefinitions()
    {
        $this->filesystemDriverMock->expects($this->once())->method('isReadable')->will($this->returnValue(false));
        $this->assertInstanceOf(
            '\Magento\Framework\ObjectManager\Definition\Runtime',
            $this->model->createClassDefinition(null, true)
        );
        $autoloadFunctions = spl_autoload_functions();
        spl_autoload_unregister(array_pop($autoloadFunctions));
    }

    public function testCreateDefinitionsDoesNotReadCompiledDefinitionsIfUseCompiledIsFalse()
    {
        $this->filesystemDriverMock->expects($this->never())->method('isReadable');
        $this->assertInstanceOf(
            '\Magento\Framework\ObjectManager\Definition\Runtime',
            $this->model->createClassDefinition(null, false)
        );
        $autoloadFunctions = spl_autoload_functions();
        spl_autoload_unregister(array_pop($autoloadFunctions));
    }

    public function testCreateClassDefinitionFromString()
    {
        $this->assertInstanceOf(
            '\Magento\Framework\ObjectManager\Definition\Compiled\Serialized',
            $this->model->createClassDefinition($this->sampleContent)
        );
    }

    /**
     * @param string $path
     * @param string $callMethod
     * @param string $expectedClass
     * @dataProvider createPluginsAndRelationsReadableDataProvider
     */
    public function testCreatePluginsAndRelationsReadable($path, $callMethod, $expectedClass)
    {
        $this->filesystemDriverMock->expects($this->once())->method('isReadable')
            ->with($path)
            ->will($this->returnValue(true));
        $this->filesystemDriverMock->expects($this->once())->method('fileGetContents')
            ->with($path)
            ->will($this->returnValue($this->sampleContent));
        $this->assertInstanceOf($expectedClass, $this->model->$callMethod());
    }

    public function createPluginsAndRelationsReadableDataProvider()
    {
        return [
            'relations' => [
                'DefinitionDir/relations.php',
                'createRelations',
                '\Magento\Framework\ObjectManager\Relations\Compiled',
            ],
            'plugins' => [
                'DefinitionDir/plugins.php',
                'createPluginDefinition',
                '\Magento\Framework\Interception\Definition\Compiled',
            ],
        ];
    }

    /**
     * @param string $path
     * @param string $callMethod
     * @param string $expectedClass
     * @dataProvider createPluginsAndRelationsNotReadableDataProvider
     */
    public function testCreatePluginsAndRelationsNotReadable($path, $callMethod, $expectedClass)
    {
        $this->filesystemDriverMock->expects($this->once())->method('isReadable')
            ->with($path)
            ->will($this->returnValue(false));
        $this->assertInstanceOf($expectedClass, $this->model->$callMethod());
    }

    public function createPluginsAndRelationsNotReadableDataProvider()
    {
        return [
            'relations' => [
                'DefinitionDir/relations.php',
                'createRelations',
                '\Magento\Framework\ObjectManager\Relations\Runtime',
            ],
            'plugins' => [
                'DefinitionDir/plugins.php',
                'createPluginDefinition',
                '\Magento\Framework\Interception\Definition\Runtime',
            ],
        ];
    }
}


text:
from __future__ import print_function, unicode_literals
import tordoc
from tornado.web import RequestHandler, Application
from tornado import httpserver, options, ioloop
from tornado.options import define, options
define('port', type="int", default=1234)

API_MODULE_DOC = '测试登录'

class ApiLoginHandler(RequestHandler):
    def post(self):
        """
        restapi: 登录账号
        warning: 必须要输入正常哦
        request:
            username: 用户名
            password: 密码
        response:
            uid: 用户uid
        """
        username = self.get_body_argument('username')
        password = self.get_body_argument('password')
        self.write({'code': 0, 'uid': 111})

if __name__ == "__main__":
    options.parse_command_line()

    debug_handler = tordoc.router('/', {'public_response_params':{
        'code': 'api响应状态码'}}) # 这里的'/' 表示url前缀。也就是/debug就是本插件的页面地址。比如是/api,那本插件的页面地址就是/api/debug

    app = Application([('/api/login', ApiLoginHandler)] + debug_handler,
            debug = True)
    server = httpserver.HTTPServer(app, xheaders = True)
    server.listen(options.port)
    ioloop.IOLoop().instance().start()


text:
require 'benchmark'

# Major migration to create hierarchy of answer objects.
class MoveToNewAnswerHierarchy < ActiveRecord::Migration[4.2]
  def up
    ActiveRecord::Migration.suppress_messages do
      @new_rows = {}
      @parent_rows = {}

      without_trigger do
        delete_leaf_nodes
        create_hierarchy_nodes
        fix_ranks
      end
    end
  end

  private

  def without_trigger
    execute("ALTER TABLE answers DISABLE TRIGGER answers_before_insert_update_row_tr")
    yield
    execute("ALTER TABLE answers ENABLE TRIGGER answers_before_insert_update_row_tr")
  end

  def delete_leaf_nodes
    # Delete all existing non-Answer-type rows, making this script idempotent, since it only
    # creates this type of rows.
    puts("Deleting any old non-leaf nodes")
    execute("DELETE FROM answers WHERE type != 'Answer'")
  end

  # Creates the nodes required to represent the new hierarchy system.
  def create_hierarchy_nodes
    # The basic idea here is, for each existing answer, to recursively find or create its parents
    # and then 1. set the parent_id on the row and 2. create the appropriate rows in the hierarchies table.
    # We do in batches of 10,000 so we can report progress.
    puts "Creating hierarchy nodes"
    puts "  Running main SELECT query"
    result = execute("SELECT id, response_id, questioning_id, inst_num, rank, type
      FROM answers WHERE deleted_at IS NULL")
    total_slices = (leaf_node_count.to_f / 10_000).ceil
    result.each_slice(10_000).with_index do |slice, i|
      @inserts = []
      @updates = []
      puts("  Processing slice #{i + 1}/#{total_slices}")
      run_and_print_time(2) do
        puts("    Building trees in memory")
        run_and_print_time(4) { slice.each { |row| find_or_create_parent_row(row) } }
        puts("    Inserting new ResponseNodes")
        run_and_print_time(4) { do_inserts }
        puts("    Updating existing Answers")
        run_and_print_time(4) { do_updates }
      end
    end
  end

  # Finds or creates the parent row for the given row.
  # Associates the given row with it.
  # If the given row is a top level node, then this amounts to finding/creating
  # the root node for the response.
  # Returns the ID of the found/created row.
  def find_or_create_parent_row(row, inst_num: nil)
    orig_row = row.dup

    form_item = form_items_by_id[row["questioning_id"]]

    raise "No FormItem found with ID #{row['questioning_id']}" if form_item.nil?

    # Terminate the recursion if we reach the root.
    if form_item["ancestry"].nil?
      row["new_rank"] = 0
      return nil
    end

    # If given row is an AnswerGroup that references a repeatable QingGroup, find/create AnswerGroupSet.
    if row["type"] == "AnswerGroup" && (form_item["repeatable"] == "t" || form_item["repeatable"] == true)
      parent_row = row.slice("questioning_id", "response_id")
        .merge("type" => "AnswerGroupSet", "inst_num" => 1)
      row["new_rank"] = inst_num
    # Else if it references a question with a multilevel option set, find/create AnswerSet.
    elsif row["type"] == "Answer" && form_item["level_names"].present?
      parent_row = row.slice("questioning_id", "inst_num", "response_id").merge("type" => "AnswerSet")
      row["new_rank"] = row["rank"]
    # Else just find/create its parent AnswerGroup.
    else
      parent_row = row.slice("inst_num", "response_id").merge(
        "type" => "AnswerGroup",
        "questioning_id" => form_item["ancestry"].split("/").last
      )
    end

    # We can set the new_rank on the row here since the recursion happens before the insertion.
    # Another way to do this would be to load the parent form_item in the previous call and set it there.
    row["new_rank"] ||= form_item["rank"]

    # Short circuit if we've seen this arg before.
    if (pid = @parent_rows[[orig_row, inst_num]])
      return pid
    end

    # Recursive call.
    parent_row["parent_id"] = find_or_create_parent_row(parent_row, inst_num: row["inst_num"])

    # Now that we have the parent's parent_id, we can do the find/insert.
    parent_id = find_or_insert_hash(parent_row)

    # Answer rows are preexisting so we need to update them with parent_id and rank instead of
    # setting them on creation.
    update_answer(row["id"], parent_id, row["new_rank"]) if row["type"] == "Answer"

    # Save in hash for faster lookup and return
    @parent_rows[[orig_row, inst_num]] = parent_id
  end

  def form_items_by_id
    @form_items_by_id ||= execute("SELECT fi.id, ancestry, ancestry_depth, repeatable, level_names, rank
      FROM form_items fi
      LEFT OUTER JOIN questions q ON fi.question_id = q.id
      LEFT OUTER JOIN option_sets os ON os.id = q.option_set_id")
      .to_a.index_by { |r| r["id"] }
  end

  def find_or_insert_hash(hash)
    unless (hash.keys - %w[questioning_id response_id type inst_num new_rank parent_id]).empty?
      raise "Invalid keys: #{hash.keys}"
    end

    if (found = @new_rows[hash])
      found
    else
      id = SecureRandom.uuid
      @new_rows[hash] = id
      insert_answer_parent(id, hash)
      id
    end
  end

  def update_answer(id, parent_id, new_rank)
    @updates << "('#{id}', #{id_str(parent_id)}, '#{new_rank}')"
  end

  def insert_answer_parent(id, hash)
    @inserts << "('#{id}','#{hash['questioning_id']}','#{hash['response_id']}','#{hash['type']}',"\
      "'#{hash['inst_num']}','#{hash['new_rank']}',#{id_str(hash['parent_id'])},NOW(),NOW())"
  end

  def id_str(val)
    val.nil? ? "NULL" : "'#{val}'"
  end

  def do_inserts
    batched_insert(
      "answers",
      "id,questioning_id,response_id,type,inst_num,new_rank,parent_id,created_at,updated_at",
      @inserts
    )
  end

  def do_updates
    ensure_empty_tmp_table
    batched_insert("ansupdates", "id,parent_id,new_rank", @updates)
    execute("UPDATE answers AS a SET parent_id = u.parent_id, new_rank = u.new_rank
      FROM ansupdates u WHERE a.id = u.id")
  end

  def batched_insert(tbl, cols, rows)
    rows.each_slice(1000) do |slice|
      execute("INSERT INTO #{tbl} (#{cols})
        VALUES #{slice.join(',')}")
    end
  end

  def fix_ranks
    puts("Fixing ranks")
    puts("  Non-leaf node count: #{non_leaf_node_count}")
    result = execute("SELECT id FROM answers WHERE type != 'Answer' AND deleted_at IS NULL")
    total_slices = (non_leaf_node_count.to_f / 1_000).ceil
    result.each_slice(1_000).with_index do |slice, i|
      puts("  Processing slice #{i + 1}/#{total_slices}")
      run_and_print_time(2) do
        slice.each { |row| execute(rank_fix_sql(row["id"])) }
      end
    end
  end

  def rank_fix_sql(parent_id)
    <<~SQL
      UPDATE answers
        SET new_rank = t.seq
        FROM (
          SELECT id, row_number() OVER(ORDER BY new_rank) - 1 AS seq
          FROM answers
          WHERE parent_id = '#{parent_id}' AND deleted_at IS NULL
        ) AS t
        WHERE answers.id = t.id AND answers.new_rank != t.seq;
    SQL
  end

  def leaf_node_count
    @leaf_node_count ||= execute("SELECT COUNT(*) FROM answers WHERE deleted_at IS NULL")
      .to_a.first["count"].to_i
  end

  def non_leaf_node_count
    @non_leaf_node_count ||= execute("SELECT COUNT(*) FROM answers WHERE type != "\
      "'Answer' AND deleted_at IS NULL").to_a.first["count"].to_i
  end

  def run_and_print_time(indent, &block)
    t = Benchmark.realtime(&block)
    puts("#{' ' * indent}Took #{format('%.3f', t)}s")
  end

  def ensure_empty_tmp_table
    unless @tmp_created
      execute("CREATE TEMPORARY TABLE ansupdates (id uuid primary key, parent_id uuid, new_rank integer)")
      @tmp_created = true
    end
    execute("TRUNCATE ansupdates")
  end
end


text:
using ConsoleScraper.Enums;

namespace ConsoleScraper.Models
{
	public interface IWikiEntry
	{
		#region Properties
		string Title { get; set; }
		string Url { get; set; }
		VehicleTypeEnum VehicleType { get; set; }
		GroundVehicle GroundVehicleInfo { get; set; }
		AviationVehicle AviationVehicleInfo { get; set; }
		#endregion
	}

	public class WikiEntry : IWikiEntry
	{
		public string Title { get; set; }
		public string Url { get; set; }
		public VehicleTypeEnum VehicleType { get; set; }
		public GroundVehicle GroundVehicleInfo { get; set; }
		public AviationVehicle AviationVehicleInfo { get; set; }
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>pro.redsoft.iframework</groupId>
        <artifactId>iframework</artifactId>
        <version>0.4.2-SNAPSHOT</version>
    </parent>
    <artifactId>iframework-core</artifactId>
    <packaging>pom</packaging>

    <modules>
        <module>iframework-gwtpx</module>
        <module>iframework-gwtpx-servlet</module>
    </modules>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>gwtpx</artifactId>
                <version>${project.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>gwtpx-servlet</artifactId>
                <version>${project.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- Dependencies that are inherited by sub-modules -->
    <dependencies>

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>iframework-build-tools</artifactId>
        </dependency>

        <!-- Google Web Toolkit -->
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
            <version>${gwt.version}</version>
        </dependency>

        <!-- GWT-Platform -->
        <dependency>
            <groupId>com.gwtplatform</groupId>
            <artifactId>gwtp-mvp-client</artifactId>
            <version>${gwtp.version}</version>
        </dependency>

        <!-- DI -->
        <dependency>
            <groupId>com.google.gwt.inject</groupId>
            <artifactId>gin</artifactId>
            <version>${gin.version}</version>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jukito</groupId>
            <artifactId>jukito</artifactId>
            <version>${jukito.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

        <dependency>
            <groupId>name.pehl</groupId>
            <artifactId>piriti-user</artifactId>
            <version>${piriti.version}</version>
        </dependency>

        <!--     <dependency> -->
        <!--       <groupId>name.pehl</groupId> -->
        <!--       <artifactId>piriti-dev</artifactId> -->
        <!--       <version>${piriti.version}</version> -->
        <!--     </dependency> -->

        <dependency>
            <groupId>name.pehl</groupId>
            <artifactId>totoe</artifactId>
            <version>${totoe.version}</version>
        </dependency>

        <dependency>
            <groupId>pro.redsoft.iframework</groupId>
            <artifactId>iframework-jaxbx</artifactId>
            <version>${project.version}</version>
        </dependency>

    </dependencies>

</project>