text:
import miscTCGA
import tsvIO

import sys

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

NA_VALUE = -999999

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
# the input is a data dictionary which should have 4 keys:
# 'dataType'	single string, eg 'GEXP'
# 'rowLabels'	vector of feature labels
# 'colLabels'	vector of column (sample) labels
# 'dataMatrix'	matrix of values
# the output is a data dictionary with the same # of rows, but some columns
# may have been removed if they do not represent tumor samples ... also the
# TCGA barcodes are stripped down to the point where they uniquely identify
# tumor samples
#
# FIXME: this should be modified to take a list of rows or columns to remove
# and then return a new dataD ... (put that into tsvIO???)

def removeNonTumorSamples(dataD):

    ## miscTCGA.lookAtBarcodes ( dataD['colLabels'] )
    numCol = len(dataD['colLabels'])
    keepCols = [0] * numCol
    tumorList = []
    numOutCol = 0

    for jj in range(numCol):
        aCode = dataD['colLabels'][jj]
        tumorCode = ''

        # if the barcode is not even long enough to specify the sample type,
        # we will just assume that we keep it ...
        if (len(aCode) < 15):
            tumorCode = aCode

        else:
            # if the barcode is at least 15 characters long, then we parse it
            # ...
            aCode = miscTCGA.fixTCGAbarcode(aCode)
            (site, patient, sample, vial, portion, analyte,
             plate, center) = miscTCGA.parseTCGAbarcode(aCode)
            try:
                iSample = int(sample)
            except:
                iSample = -1
                if (sample != aCode):
                    print " what is going on here ??? ", aCode
                    sys.exit(-1)
            if (iSample > 0 and iSample < 10):
                tumorCode = miscTCGA.sampleLevelCode(aCode)

        if (tumorCode != ''):
            if (tumorCode not in tumorList):
                tumorList += [tumorCode]
                keepCols[jj] = 1
                numOutCol += 1
            else:
                print " WARNING: in removeNonTumorSamples ... multiple columns for the same tumor sample ??? "
                print aCode, tumorCode
                # print tumorList
                print "          --> keeping only the first one "
                # sys.exit(-1)

    rmColList = []
    for jj in range(numCol):
        if (keepCols[jj] == 0):
            rmColList += [jj]
            print "             will remove sample <%s> " % dataD['colLabels'][jj]

    # filter out the columns we don't want ...
    dataD = tsvIO.filter_dataMatrix(dataD, [], rmColList)
    print " back from filter_dataMatrix ... ", dataD['colLabels'][:5]

    # NOTE: this next bit may no longer be necessary ...
    # and also set the shortened TCGA barcodes as labels ...
    if (len(tumorList) != len(dataD['dataMatrix'][0])):
        print " ERROR !!! length of tumorList does not correspond to size of dataMatrix !!! "
        print len(tumorList)
        tsvIO.lookAtDataD(dataD)
        sys.exit(-1)

    dataD['colLabels'] = tumorList
    print " now using shortened barcodes .. ", dataD['colLabels'][:5]

    return (dataD)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

def dropSampleTypeFromBarcodes(dataD):

    ## miscTCGA.lookAtBarcodes ( dataD['colLabels'] )
    numCol = len(dataD['colLabels'])
    codeList = []
    for jj in range(numCol):
        aCode = dataD['colLabels'][jj]
        if (aCode > 12):
            aCode = aCode[:12]
            dataD['colLabels'][jj] = aCode
        if (aCode not in codeList):
            codeList += [aCode]
        else:
            print " WARNING in dropSampleTypeFromBarcodes ... duplicates ??? ", aCode
            # print codeList
            # sys.exit(-1)

    return (dataD)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

def intersectLists(aList, bList):
    cList = []
    for aToken in aList:
        if (aToken in bList):
            cList += [aToken]

    return (cList)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

def unionLists(aList, bList):

    for bToken in bList:
        if (bToken not in aList):
            aList += [bToken]

    return (aList)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

def getMappingVector(unionLabels, curLabels):

    mapVec = [-1] * len(curLabels)
    for ii in range(len(curLabels)):
        aLabel = curLabels[ii]
        if (aLabel.startswith("TCGA-")):
            aLabel = miscTCGA.sampleLevelCode(aLabel)
        try:
            jj = unionLabels.index(aLabel)
            mapVec[ii] = jj
        except:
            print " ERROR ... did not find <%s> in union labels ... " % aLabel
            print unionLabels
            sys.exit(-1)

    print "                 mapping vector from %d into %d ... " % (len(curLabels), len(unionLabels))
    print "                 ", mapVec[:20]
    # print curLabels[:20]
    # print unionLabels[:20]
    print " "

    return (mapVec)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

def makeDataTypeString(dTypeList, fTypeList):

    # print " in makeDataTypeString ... "
    # print dTypeList
    # print fTypeList

    if ("MISC" in fTypeList):
        dTypeString = "M:MISC"
        return (dTypeString)

    if (len(dTypeList) == 1):
        dTypeString = dTypeList[0]
    else:
        dTypeString = "M"

    dTypeString += ":"
    for aType in fTypeList:
        if (dTypeString[-1] != ":"):
            dTypeString += "+"
        dTypeString += aType

    print " output data type string : <%s> " % dTypeString

    return (dTypeString)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

def readSampleListFromFile(sampleFile):

    try:
        fh = file(sampleFile)
    except:
        print " FAILED to read input list from <%s> " % sampleFile
        return ([])

    sampleList = []

    for aLine in fh:
        aLine = aLine.strip()
        if (aLine.startswith("TCGA")):
            sampleList += [aLine]
        elif (len(aLine) > 0):
            print "     NOT USING this input line : <%s> " % aLine

    fh.close()

    return (sampleList)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

def is_in_list(tmpLabel, sampleList, aFlag):

    # so the input sampleList may have variable length barcodes,
    # eg TCGA-BR-4184-11A-01D-1130-01
    # TCGA-BR-4186

    # while the tmpLabel is either a 'patient' barcode, or a 'sample'
    # barcode, or a full-length barcode ...

    lowerT = tmpLabel.lower()

    for aSample in sampleList:
        lowerA = aSample.lower()
        if (aFlag == "strict"):
            if (lowerA == lowerT):
                return (1)
        else:
            if (lowerT.startswith(lowerA)):
                return (1)

    return (0)

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

if __name__ == "__main__":

    if (1):
        # there must be 2 + 3N parameters, where N is the # of sample-lists
        # being used for filtering ...
        if (len(sys.argv) < 6):
            print " Usage : %s <input file> <output file> <sample-list> <{black,white}> <{loose,strict}> " % sys.argv[0]
            print " "
            print " Notes : a BLACK list means samples that any samples in this list must be removed "
            print "         from the input file, and this is generally done with LOOSE filtering "
            print "         so that if a patient barcode is given, then all other barcodes that "
            print "         even just partially match that barcode will also be BLACKed out. "
            print " "
            print "         a WHITE list means that ONLY samples that are in this list can be included "
            print "         in the output file, and this is generally done with STRICT filtering so that "
            print "         if the methylation data from a particular sample is in the white list, that "
            print "         does not necessarily mean that the microRNA data from the same sample can "
            print "         automatically be included as well -- it must be listed explicitly. "
            print " "
            print " ERROR -- bad command line arguments "
            sys.exit(-1)

        inFile = sys.argv[1]
        outFile = sys.argv[2]

        ii = 3
        listInfo = []
        while (len(sys.argv) >= (ii + 2)):
            listInfo += [sys.argv[ii:ii + 3]]
            ii += 3
        if (len(listInfo) < 1):
            print " ERROR ??? no sample-list information provided ??? "
            sys.exit(-1)

    print " "
    print " in filterTSVbySampList.py ... "
    print "         input file  : ", inFile
    print "         output file : ", outFile
    print "         list info   : ", listInfo
    print " "

    # print " "
    # print " ***************************************************************** "
    # print " calling readTSV ... ", inFile
    dataD = tsvIO.readTSV(inFile)
    if (dataD == {}):
        sys.exit(-1)

    tsvIO.lookAtDataD(dataD)

    # print " "
    # print " reading sample list ... "
    numLists = len(listInfo)
    listDetails = [0] * numLists
    listBW = [0] * numLists
    listLS = [0] * numLists
    for iList in range(numLists):
        print " --> loading sample list #%d from <%s> " % ((iList + 1), listInfo[iList][0])
        listDetails[iList] = readSampleListFromFile(listInfo[iList][0])
        listBW[iList] = listInfo[iList][1]
        listLS[iList] = listInfo[iList][2]
        if (len(listDetails[iList]) > 0):
            print "     %4d samples found, eg <%s> " % (len(listDetails[iList]), listDetails[iList][0])
        else:
            print "        0 samples found "
            if (listLS[iList] == "strict"):
                print "             --> NO strict filtering can/will be applied "

    # now we need to figure out which columns we will keep/remove ...
    colLabels = dataD['colLabels']
    dataMatrix = dataD['dataMatrix']
    numCol = len(dataMatrix[0])
    if (numCol != len(colLabels)):
        print " mismatched sizes ??? ", numCol, len(colLabels)
        sys.exit(-1)

    print " "
    print "     %4d samples in input data matrix " % numCol
    print " debug : colLabels  : ", colLabels[1:5]

    print " "
    print " building up skipColList ... "
    skipColList = []

    ## first, we loop over the black-lists and check each column
    ## label to see if it should be added to the skipColList ...
    numSkip = 0
    print " "
    print " FIRST checking black lists ... "
    for iList in range(numLists):
        bwFlag = listBW[iList]
        if ( bwFlag != "black" ): continue

        sampleList = listDetails[iList]
        if (len(sampleList) == 0): continue

        lsFlag = listLS[iList]
        print "         examining list #%d (%d,%s,%s) " % ((iList + 1), len(sampleList), bwFlag, lsFlag)

        for iCol in range(numCol):
            # print colLabels[iCol], sampleList[1:5]
            tmpLabel = colLabels[iCol]
            # print tmpLabel

            # if this column has already been added to the skip-list,
            # we don't need to add it again ...
            if (iCol in skipColList):
                print "     <%s> is ALREADY in the skip-list (list #%d) " % (tmpLabel, (iList + 1))
                continue

            if (is_in_list(tmpLabel, sampleList, lsFlag)):
                skipColList += [iCol]
                numSkip += 1

        print "         --> %d additional samples to be skipped " % numSkip, listInfo[iList][0], bwFlag, lsFlag

    ## now we're going to loop over the column labels and see if they
    ## are in any of the white lists ...
    print " "
    print " NOW checking white lists ... "
    for iCol in range(numCol):
        tmpLabel = colLabels[iCol]

        ## initialize the isWhite flag to TRUE
        isWhite = 1

        for iList in range(numLists):
            bwFlag = listBW[iList]
            if ( bwFlag == "black" ): continue

            sampleList = listDetails[iList]
            if (len(sampleList) == 0): continue

            ## if we get to here, then we have at least one white list
            ## so reset the isWhite flag to FALSE
            isWhite = 0

            lsFlag = listLS[iList]
            print "         examining list #%d (%d,%s,%s) " % ((iList + 1), len(sampleList), bwFlag, lsFlag)

            if (is_in_list(tmpLabel, sampleList, lsFlag)):
                isWhite = 1

        ## once we get back to here, if isWhite is FALSE, then add to skipColList
        if ( iCol in skipColList):
            print "     <%s> is ALREADY in the skip-list (list #%d) " % (tmpLabel, (iList + 1))
            continue

        if ( isWhite == 0 ):
            skipColList += [iCol]
            numSkip += 1

    print "         --> %d additional samples to be skipped " % numSkip

    # print skipColList

    print " "
    print " number of columns to be skipped : ", len(skipColList)
    print " --> number of columns remaining : ", (numCol - len(skipColList))

    if (0):
        if (len(skipColList) == 1):
            print "     for example ", colLabels[skipColList[0]]
        elif (len(skipColList) > 1):
            print "     for example ", colLabels[skipColList[0]], colLabels[skipColList[-1]]

    else:
        print " "
        print " "
        for iCol in range(len(skipColList)):
            print "    REMOVING SAMPLE %s " % colLabels[skipColList[iCol]]
        print " "
        print " "

    if (len(skipColList) > int(0.90 * numCol)):
        print " "
        print " WARNING !!! more than 90% of the data is going to be lost ??? !!! "
        print " "
        # sys.exit(-1)

    # print " "
    # print " calling filter_dataMatrix ... "
    outD = tsvIO.filter_dataMatrix(dataD, [], skipColList)

    # make sure that we are not left with any features that are all-NA ...
    dataMatrix = outD['dataMatrix']
    numRow = len(dataMatrix)
    numCol = len(dataMatrix[0])
    skipRowList = []
    for iRow in range(numRow):
        allNA = 1
        iCol = 0
        while (allNA == 1 and iCol < numCol):
            if (dataMatrix[iRow][iCol] != NA_VALUE):
                allNA = 0
            iCol += 1
        if (allNA):
            skipRowList += [iRow]

    if (len(skipRowList) > 0):
        print " after checking for all-NA features ... "
        print " number of rows to be skipped : ", len(skipRowList)
        print " --> number of rows remaining : ", (numRow - len(skipRowList))
        outD2 = tsvIO.filter_dataMatrix(outD, skipRowList, [])
        outD = outD2

    # set up sorting options ...
    sortRowFlag = 0
    sortColFlag = 0
    rowOrder = []
    colOrder = []

    # print " "
    # print " calling writeTSV_dataMatrix ... ", outFile
    tsvIO.writeTSV_dataMatrix(outD, sortRowFlag, sortColFlag, outFile, rowOrder, colOrder)

    print " "
    print " DONE "
    print " "

# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#


text:
all:	install
install:
	install -d /opt/kernelchip
	install -m 755 rele-turn.sh /opt/kernelchip
	install -m 755 rele-switch.sh /opt/kernelchip
	install -m 644 logrotate /etc/logrotate.d/kernelchip

redpajama_set_name: RedPajamaGithub


text:
/*global define:false, Backbone:false, _:false, $:false */
var app = app || {};

define(["skills/skill"], function() {
    "use strict";

    app.SkillView = Backbone.View.extend({

        tagName: 'div',

        events: {
            'click button.del'             : 'removeSkill',
            "change input[type='text']"    : "updateSkill",
            "change select"                : "updateSkill",
            "click input[type='checkbox']" : "toggleSchoolSkill"
        },

        template: _.template($('#skill-template').html()),

        initialize: function() {
            _.bindAll(this, 'render', 'removeSkill', 'unRender', 'updateSkill');

            this.model.bind('change', this.render);
            this.model.bind('remove', this.unRender);
        },

        render: function () {
            $(this.el).html(this.template(this.model.attributes));
            return this;
        },

        unRender: function () {
            $(this.el).remove();
        },

        removeSkill: function() {
            this.model.destroy();
        },

        updateRoll: function() {
            this.model.set('roll', 1 );//needs access to the rings, and to get the dropdown working first.
        },

        updateSkill: function(e) {
            //this.updateRoll();
            this.model.set(e.target.dataset.name, e.target.value);
        },

        toggleSchoolSkill: function() {
            this.model.toggle();
        }

    });

});


text:
package org.wmaop.util.logger;

import com.wm.util.JournalLogger;

/*
 * Place holder until correct server log handling figured out
 */
public class WmLogger {

	private static final int CODE = 3;
	private static final int FAC = JournalLogger.FAC_UTIL;

	private static final String PFX = "]>]> ";

	public void info(String message) {
		log(JournalLogger.INFO, message);
	}

	public boolean isDebugEnabled() {
		return JournalLogger.isLogEnabled(CODE, FAC, JournalLogger.DEBUG);
	}

	public void debug(String message) {
		log(JournalLogger.DEBUG, message);
	}

	public void error(String message, Exception e) {
		JournalLogger.log(CODE, FAC, JournalLogger.ERROR, PFX + message, e);
	}

	private void log(int level, String message) {
		JournalLogger.log(CODE, FAC, level, PFX + message);
	}

	public void warn(String message) {
		log(JournalLogger.WARNING, message);
	}
}


text:
#include "common.h"

#include <fribidi-bidi-types.h>

#include "bidi-types.h"

enum FriBidiCharTypeLinearEnum
{
# define _FRIBIDI_ADD_TYPE(TYPE,SYMBOL) TYPE,
# include "fribidi-bidi-types-list.h"
# undef _FRIBIDI_ADD_TYPE
  _FRIBIDI_NUM_TYPES
};

#include "bidi-type.tab.i"

/* Map FriBidiCharTypeLinearEnum to FriBidiCharType. */
static const FriBidiCharType linear_enum_to_char_type[] = {
# define _FRIBIDI_ADD_TYPE(TYPE,SYMBOL) FRIBIDI_TYPE_##TYPE,
# include "fribidi-bidi-types-list.h"
# undef _FRIBIDI_ADD_TYPE
};

FRIBIDI_ENTRY FriBidiCharType
fribidi_get_bidi_type (
  /* input */
  FriBidiChar ch
)
{
  return linear_enum_to_char_type[FRIBIDI_GET_BIDI_TYPE (ch)];
}

FRIBIDI_ENTRY void
fribidi_get_bidi_types (
  /* input */
  const FriBidiChar *str,
  const FriBidiStrIndex len,
  /* output */
  FriBidiCharType *btypes
)
{
  register FriBidiStrIndex i = len;
  for (; i; i--)
    {
      *btypes++ = linear_enum_to_char_type[FRIBIDI_GET_BIDI_TYPE (*str)];
      str++;
    }
}

FRIBIDI_ENTRY const char *
fribidi_get_bidi_type_name (
  /* input */
  FriBidiCharType t
)
{
  switch (t)
    {
#   define _FRIBIDI_ADD_TYPE(TYPE,SYMBOL) case FRIBIDI_TYPE_##TYPE: return STRINGIZE(TYPE);
#   define _FRIBIDI_ALL_TYPES
#   include "fribidi-bidi-types-list.h"
#   undef _FRIBIDI_ALL_TYPES
#   undef _FRIBIDI_ADD_TYPE
    default:
      return "?";
    }
}

#if DEBUG+0

char
fribidi_char_from_bidi_type (
  /* input */
  FriBidiCharType t
)
{
  switch (t)
    {
#   define _FRIBIDI_ADD_TYPE(TYPE,SYMBOL) case FRIBIDI_TYPE_##TYPE: return SYMBOL;
#   define _FRIBIDI_ALL_TYPES
#   include "fribidi-bidi-types-list.h"
#   undef _FRIBIDI_ALL_TYPES
#   undef _FRIBIDI_ADD_TYPE
    default:
      return '?';
    }
}

#endif /* DEBUG */

/* Editor directions:
 * vim:textwidth=78:tabstop=8:shiftwidth=2:autoindent:cindent
 */


text:
package vtgate

const (
	// ExecutorTemplate is the HTML template to display ExecutorStats.
	ExecutorTemplate = `

QPS

  Health

  Current Query Log

  Query Plan Stats

  Query Plans

  Scatter Query Statistics

`
)


text:
=begin
#The Plaid API

#The Plaid REST API. Please see https://plaid.com/docs/api for more details.

The version of the OpenAPI document: 2020-09-14_1.205.3

Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.1

=end

require 'date'
require 'time'

module Plaid
  # Defines the request schema for `/transfer/refund/create`
  class TransferRefundCreateRequest
    # Your Plaid API `client_id`. The `client_id` is required and may be provided either in the `PLAID-CLIENT-ID` header or as part of a request body.
    attr_accessor :client_id

    # Your Plaid API `secret`. The `secret` is required and may be provided either in the `PLAID-SECRET` header or as part of a request body.
    attr_accessor :secret

    # The ID of the transfer to refund.
    attr_accessor :transfer_id

    # The amount of the refund (decimal string with two digits of precision e.g. \"10.00\").
    attr_accessor :amount

    # A random key provided by the client, per unique refund. Maximum of 50 characters.  The API supports idempotency for safely retrying requests without accidentally performing the same operation twice. For example, if a request to create a refund fails due to a network connection error, you can retry the request with the same idempotency key to guarantee that only a single refund is created.
    attr_accessor :idempotency_key

    # Attribute mapping from ruby-style variable name to JSON key.
    def self.attribute_map
      {
        :'client_id' => :'client_id',
        :'secret' => :'secret',
        :'transfer_id' => :'transfer_id',
        :'amount' => :'amount',
        :'idempotency_key' => :'idempotency_key'
      }
    end

    # Returns all the JSON keys this model knows about
    def self.acceptable_attributes
      attribute_map.values
    end

    # Attribute type mapping.
    def self.openapi_types
      {
        :'client_id' => :'String',
        :'secret' => :'String',
        :'transfer_id' => :'String',
        :'amount' => :'String',
        :'idempotency_key' => :'String'
      }
    end

    # List of attributes with nullable: true
    def self.openapi_nullable
      Set.new([
      ])
    end

    # Initializes the object
    # @param [Hash] attributes Model attributes in the form of hash
    def initialize(attributes = {})
      if (!attributes.is_a?(Hash))
        fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::TransferRefundCreateRequest` initialize method"
      end

      # check to see if the attribute exists and convert string to symbol for hash key
      attributes = attributes.each_with_object({}) { |(k, v), h|
        if (!self.class.attribute_map.key?(k.to_sym))
          fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::TransferRefundCreateRequest`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
        end
        h[k.to_sym] = v
      }

      if attributes.key?(:'client_id')
        self.client_id = attributes[:'client_id']
      end

      if attributes.key?(:'secret')
        self.secret = attributes[:'secret']
      end

      if attributes.key?(:'transfer_id')
        self.transfer_id = attributes[:'transfer_id']
      end

      if attributes.key?(:'amount')
        self.amount = attributes[:'amount']
      end

      if attributes.key?(:'idempotency_key')
        self.idempotency_key = attributes[:'idempotency_key']
      end
    end

    # Show invalid properties with the reasons. Usually used together with valid?
    # @return Array for valid properties with the reasons
    def list_invalid_properties
      invalid_properties = Array.new
      if @transfer_id.nil?
        invalid_properties.push('invalid value for "transfer_id", transfer_id cannot be nil.')
      end

      if @amount.nil?
        invalid_properties.push('invalid value for "amount", amount cannot be nil.')
      end

      if @idempotency_key.nil?
        invalid_properties.push('invalid value for "idempotency_key", idempotency_key cannot be nil.')
      end

      if @idempotency_key.to_s.length > 50
        invalid_properties.push('invalid value for "idempotency_key", the character length must be smaller than or equal to 50.')
      end

      invalid_properties
    end

    # Check to see if the all the properties in the model are valid
    # @return true if the model is valid
    def valid?
      return false if @transfer_id.nil?
      return false if @amount.nil?
      return false if @idempotency_key.nil?
      return false if @idempotency_key.to_s.length > 50
      true
    end

    # Custom attribute writer method with validation
    # @param [Object] idempotency_key Value to be assigned
    def idempotency_key=(idempotency_key)
      if idempotency_key.nil?
        fail ArgumentError, 'idempotency_key cannot be nil'
      end

      if idempotency_key.to_s.length > 50
        fail ArgumentError, 'invalid value for "idempotency_key", the character length must be smaller than or equal to 50.'
      end

      @idempotency_key = idempotency_key
    end

    # Checks equality by comparing each attribute.
    # @param [Object] Object to be compared
    def ==(o)
      return true if self.equal?(o)
      self.class == o.class &&
          client_id == o.client_id &&
          secret == o.secret &&
          transfer_id == o.transfer_id &&
          amount == o.amount &&
          idempotency_key == o.idempotency_key
    end

    # @see the `==` method
    # @param [Object] Object to be compared
    def eql?(o)
      self == o
    end

    # Calculates hash code according to all attributes.
    # @return [Integer] Hash code
    def hash
      [client_id, secret, transfer_id, amount, idempotency_key].hash
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def self.build_from_hash(attributes)
      new.build_from_hash(attributes)
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def build_from_hash(attributes)
      return nil unless attributes.is_a?(Hash)
      self.class.openapi_types.each_pair do |key, type|
        if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
          self.send("#{key}=", nil)
        elsif type =~ /\AArray<(.*)>/i
          # check to ensure the input is an array given that the attribute
          # is documented as an array but the input is not
          if attributes[self.class.attribute_map[key]].is_a?(Array)
            self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
          end
        elsif !attributes[self.class.attribute_map[key]].nil?
          self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
        end
      end

      self
    end

    # Deserializes the data based on type
    # @param string type Data type
    # @param string value Value to be deserialized
    # @return [Object] Deserialized data
    def _deserialize(type, value)
      case type.to_sym
      when :Time
        Time.parse(value)
      when :Date
        Date.parse(value)
      when :String
        value.to_s
      when :Integer
        value.to_i
      when :Float
        value.to_f
      when :Boolean
        if value.to_s =~ /\A(true|t|yes|y|1)\z/i
          true
        else
          false
        end
      when :Object
        # generic object (usually a Hash), return directly
        value
      when /\AArray<(?<inner_type>.+)>\z/
        inner_type = Regexp.last_match[:inner_type]
        value.map { |v| _deserialize(inner_type, v) }
      when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
        k_type = Regexp.last_match[:k_type]
        v_type = Regexp.last_match[:v_type]
        {}.tap do |hash|
          value.each do |k, v|
            hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
          end
        end
      else # model
        # models (e.g. Pet) or oneOf
        klass = Plaid.const_get(type)
        klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
      end
    end

    # Returns the string representation of the object
    # @return [String] String presentation of the object
    def to_s
      to_hash.to_s
    end

    # to_body is an alias to to_hash (backward compatibility)
    # @return [Hash] Returns the object in the form of hash
    def to_body
      to_hash
    end

    # Returns the object in the form of hash
    # @return [Hash] Returns the object in the form of hash
    def to_hash
      hash = {}
      self.class.attribute_map.each_pair do |attr, param|
        value = self.send(attr)
        if value.nil?
          is_nullable = self.class.openapi_nullable.include?(attr)
          next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
        end

        hash[param] = _to_hash(value)
      end
      hash
    end

    # Outputs non-array value in the form of hash
    # For object, use to_hash. Otherwise, just return the value
    # @param [Object] value Any valid value
    # @return [Hash] Returns the value in the form of hash
    def _to_hash(value)
      if value.is_a?(Array)
        value.compact.map { |v| _to_hash(v) }
      elsif value.is_a?(Hash)
        {}.tap do |hash|
          value.each { |k, v| hash[k] = _to_hash(v) }
        end
      elsif value.respond_to? :to_hash
        value.to_hash
      else
        value
      end
    end

  end

end


text:
import Evaluator from './evaluator.js';
import {Rules} from "../ivx-js/rules.js";

/**
 * Generates an iVXio Rules function that allows navigation and
 * rule evaluation based on both experience data and progress.
 */
export class iVXioRules extends Rules {

    /**
     * Attaches the current experience to this class to help
     * process both data and progress informaiton.
     *
     * @param {iVXioExperiece} experience - iVXio Experience object
     * containing all the information for these rules to evaluate on.
     */
    constructor(experience, customEvaluator) {
        super(experience, customEvaluator);
        this.evaluator = new Evaluator(experience, customEvaluator);
    }
}


text:
//  Created by Loïc Gardiol on 20.07.14.

@class MoodleFolder2;

@interface MoodleFolderViewController : UITableViewController

- (instancetype)initWithFolder:(MoodleFolder2*)folder;

@property (nonatomic, strong, readonly) MoodleFolder2* folder;

@end


text:
libgl-elf-tricks-demo
=====================

There are several ELF-level problems mentioned in my new Linux OpenGL
ABI straw-man proposal.  The files here demonstrate some ways those
problems could be solved.

Problem 1: Symbol Collisions
--------------

OpenGL ES is speced such that most of its entry points have the same
names as entry points in (non-ES) OpenGL.  The OpenGL and OpenGL ES
symbols are provided by separate libraries (e.g., libOpenGL.so.1 and
libGLESv2.so.1, respectively).  It may be possible for applications to
have both libraries loaded at the same time (often indirectly, through
chains of DSO dependencies).  Multiple symbols with the same name will
cause ambiguity over which symbol should be used where.  Calling the
wrong symbol could lead to incorrect behavior.

One solution to this problem is to use ELF symbol versioning to stamp each
symbol with a version that indicates which library provides it.  When an
application is linked with -lOpenGL or -lGLESv2, the symbol's version
will be recorded in the application.  At run time, only the symbol with
the correct version will be used to resolve the symbol in the application.

This solution is not entirely satisfying: the version of the symbol
is defined at _link_ time, so each linked object can only reference
symbols from one of libOpenGL or libGLESv2.  For an application to
have run-time selection of OpenGL vs OpenGL ES, it would need to
abstract its usage of those two APIs into separate helper DSOs.

The demo here creates dumby libOpenGL.so.1 and libGLESv2.so.1 DSOs
with versioned symbols.  Then it shows how an application would link
against or the other or both and always get the intended symbol.

To see this in action, run:

    make symbol-version-tests && sh ./run-symbol-version-tests.sh

See Maintaining APIs and ABIs in Ulrich Drepper's DSO Howto: www.akkadia.org/drepper/dsohowto.pdf

Problem 2: one DSO as a "pass-thru" to another DSO
--------------

For backwards compatibility there will need to be a /usr/lib/libGL.so.1,
but it would be nice if that could just be an empty stub that routes to
the new OpenGL implementation in libOpenGL.so.1.

ELF filters can be used such that symbols advertised by libGL.so.1 are
actually satisfied by libOpenGL.so.1.

To see this in action, run:

    make filter-tests && sh ./run-filter-tests.sh

See:
* http://docs.oracle.com/cd/E23824_01/html/819-0690/chapter4-4.html
* GNU ld(1)'s '--filter' command line option


text:
        <title>hub</title>

        This package contains the core of the Hub implementation.

Getting Started

The Hub implementation


text:
@interface GPDaRenStepData : NSObject
@property (nonatomic,copy) NSString *pic; // 大图
@property (nonatomic,copy) NSString *pic_s; // 小图
@property (nonatomic,copy) NSString *content; // 内容
@end


text:
package com.springwebapp.authentication.impl;

import com.springwebapp.authentication.TokenManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

/**
 * Basic concrete implementation of a {@link com.springwebapp.authentication.TokenManager}
 *
 * It maps between Tokens and UserDetails
 */
@Component
public class SimpleTokenManager implements TokenManager {

    private Map<String, UserDetails> users = new HashMap<>();

    private SecureRandom secureRandom = new SecureRandom();

    @Override
    public String createNewToken(UserDetails userDetails) {
        String token;
        do {
            token = generateRandomToken();
        } while (users.containsKey(token));

        UserDetails previousUser = users.put(token, userDetails);
        if (previousUser != null)   {
            System.err.println(" The same token was generated again!!!");
            return null;
        }

        return token;
    }

    @Override
    public UserDetails getUserByToken(String token) {
        return users.get(token);
    }

    @Override
    public UserDetails removeUser(String token) {
        return users.remove(token);
    }

    private String generateRandomToken()    {
        byte [] bytes = new byte[64];
        secureRandom.nextBytes(bytes);
        return new String(Base64.encode(bytes), StandardCharsets.UTF_8);
    }
}


text:
from __future__ import division
from __future__ import print_function

import os
import subprocess
from .FileUtils import XMLUtil
from .git_core import Git
from pdb import set_trace
import shutil

root = os.getcwd()

class JavaUtil:
    def __init__(self, jar_path_json, fbp_path, save_path="metrics", file_name="metrics"):

        self.jar_path = jar_path_json
        self.fbp_path = fbp_path
        self.file_name = file_name if ".xml" in file_name else file_name + ".xml"

        self.save_path = os.path.abspath(save_path)

    @staticmethod
    def _run_ckjm(jar):
        cmd = ["java", "-jar", os.path.join(root, "tools/ckjm_ext.jar"),
               "-x",
               "-s",
               jar]

        return subprocess.Popen(cmd, stdout=subprocess.PIPE
                                , stderr=open(os.devnull, "w"))

    @staticmethod
    def _run_findbugs(fbp_file):
        cmd = [os.path.join(root, "tools/findbugs-3.0.1/bin/findbugs"),
               "-textui", "-project", fbp_file, "-xml"]

        return subprocess.Popen(cmd, stdout=subprocess.PIPE
                                , stderr=open(os.devnull, "w"))

    def save_metrics(self):

        for version, jarfiles in self.jar_path.iteritems():
            metrics = []
            fbp_file = os.path.join(self.fbp_path, version + ".fbp")
            print("\t+ Version: {}".format(version))
            print("\t+ -- Computing CK Metrics")
            for jar in jarfiles:
                metrics.append(self._run_ckjm(jar).communicate()[0])

            print("\t+ -- Running FindBugs")
            foundbugs = self._run_findbugs(fbp_file).communicate()[0]

            print(foundbugs,
                  file=open(os.path.join(self.save_path, "bug-" + version + ".xml"), "w+"))
            print("<metrics>", "\n".join(metrics), "</metrics>", sep="\n",
                  file=open(os.path.join(self.save_path, version + ".xml"), "w+"))

class JSUtil:
    def __init__(self, git_url, clone_path=None, project=None):
        self.project = project if project else git_url.split("/")[-1].split(".git")[0]
        self.clone_path = clone_path if clone_path is not None else os.path.abspath(os.path.join("/dev/shm/", self.project))
        self.git = Git(project=self.project, url=git_url, clone_path=self.clone_path)

    def fetch_project(self, hash=None):
        self.git.fetch_commit_hash(hash)

    def _run_escomplex(self):
        cmd = ["cr", "--ignoreerrors", "--format", "json", self.clone_path]
        return subprocess.Popen(cmd, stdout=subprocess.PIPE
                                , stderr=open(os.devnull, "w"))
    def isolate_changes(self, git_hash):
        self.git.isolate_changes(git_hash)

    def get_metrics(self):
        metrics = self._run_escomplex().communicate()[0]
        return metrics

    def clean_up(self):
        shutil.rmtree(self.clone_path)

def __test_util():
    """
    Commented this out to test JSUtil + Java isn't working at the moment.
    Run a test case
    :return:
    """
    m = JavaUtil(jar_file="data/ant-1.8.2/build/lib/ant.jar",
                 file_name="ant.xml")
    m.save_metrics()
    xml = XMLUtil(metrics_name="ant.xml")
    xml.save_as_csv()

def __test_JSUtil():
    m = JSUtil(git_url="https://github.com/facebook/react.git")
    m.fetch_project("30e6c6c9c9f8e52776981a0e91ccfbabb95f7974")
    metrics = m.get_metrics()
    return metrics

if __name__ == "__main__":
    metrics = __test_JSUtil()
    set_trace()


text:
import '../config';
import Application from './src/App';

class Server extends Application {
  constructor() {
    super();

    this.createServer();
    this.useHttpLogger();
    this.useBodyParser();
    this.useSession();
    this.useStaticResource();
    this.useViewEngine();
    this.initRouter();
    this.useWebSocketServer();
    this.useErrorHandler();
    this.run();
    this.connectDB().catch((e) => {
      console.log(e)
    });
    this.initAdmin();
  }
}

export default new Server();


text:
<?php

/**
 * class to store Sieve rule condition and to generate Sieve code for condition
 *
 * @package     Felamimail
 * @subpackage  Sieve
 */
class Felamimail_Sieve_Rule_Condition
{
    const COMPERATOR_CONTAINS   = 'contains';
    const COMPERATOR_OVER       = 'over';
    const COMPERATOR_UNDER      = 'under';
    const COMPERATOR_REGEX      = 'regex';

    const TEST_ADDRESS  = 'address';
    const TEST_HEADER   = 'header';
    const TEST_SIZE     = 'size';

    /**
     * what to test
     *
     * @var string
     */
    protected $_test;

    /**
     * how to compare
     *
     * @var string
     */
    protected $_comperator;

    /**
     * which header to check
     *
     * @var string
     */
    protected $_header;

    /**
     * key to match against
     *
     * @var string
     */
    protected $_key;

    /**
     * set test
     *
     * @param   string  $test   the test
     * @return  Felamimail_Sieve_Rule_Condition
     */
    public function setTest($test)
    {
        $this->_test = $test;

        return $this;
    }

    /**
     * set how to compare
     *
     * @param   string      $comperator     the comparator
     * @return  Felamimail_Sieve_Rule_Condition
     */
    public function setComperator($comperator)
    {
        if(!defined('self::COMPERATOR_' . strtoupper($comperator))) {
            throw new InvalidArgumentException('invalid comperator: ' . $comperator);
        }
        $this->_comperator = $comperator;

        return $this;
    }

    /**
     * the header to check
     *
     * @param   string  $header     the header
     * @return  Felamimail_Sieve_Rule_Condition
     */
    public function setHeader($header)
    {
        $this->_header = $header;

        return $this;
    }

    /**
     * set key to match against
     *
     * @param   string  $key    the key to match against
     * @return  Felamimail_Sieve_Rule_Condition
     */
    public function setKey($key)
    {
        $this->_key = $key;

        return $this;
    }

    /**
     * return the Sieve code for this condition
     *
     * @return string
     */
    public function __toString()
    {
        switch($this->_test) {
            case self::TEST_SIZE:
                return "$this->_test :$this->_comperator $this->_key";
                break;

            default:
                $header = $this->_quoteString($this->_header);
                $key = $this->_quoteString($this->_key);
                return "$this->_test :$this->_comperator $header $key";
                break;
        }
    }

    /**
     * quote string for usage in Sieve script
     *
     * @param   string  $string     the string to quote
     *
     * @todo generalize this
     */
    protected function _quoteString($string)
    {
        if(is_array($string)) {
            $string = array_map(array($this, '_quoteString'), $string);
            return '[' . implode(',', $string) . ']';
        } else {
            return '"' . str_replace('"', '\"', $string) . '"';
        }
    }

    /**
     * return values as array
     *
     * @return array
     */
    public function toArray()
    {
        return array(
            'test'            => $this->_test,
            'comperator'      => $this->_comperator,
            'header'          => $this->_header,
            'key'             => $this->_key,
        );
    }
}


text:
---
title: vars-on-top
rule_type: suggestion
further_reading:
- https://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
- https://danhough.com/blog/single-var-pattern-rant/
- https://benalman.com/news/2012/05/multiple-var-statements-javascript/
---

The `vars-on-top` rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.

## Rule Details

This rule aims to keep all variable declarations in the leading series of statements.
Allowing multiple declarations helps promote maintainability and is thus allowed.

Examples of **incorrect** code for this rule:

::: incorrect

```js
/*eslint vars-on-top: "error"*/

// Variable declaration in a nested block, and a variable declaration after other statements:
function doSomething() {
    if (true) {
        var first = true;
    }
    var second;
}

// Variable declaration in for initializer:
function doSomething() {
    for (var i=0; i<10; i++) {}
}
```

:::

::: incorrect

```js
/*eslint vars-on-top: "error"*/

// Variable declaration after other statements:
f();
var a;
```

:::

::: incorrect

```js
/*eslint vars-on-top: "error"*/

// Variables in class static blocks should be at the top of the static blocks.

class C {

    // Variable declaration in a nested block:
    static {
        if (something) {
            var a = true;
        }
    }

    // Variable declaration after other statements:
    static {
        f();
        var a;
    }

}
```

:::

Examples of **correct** code for this rule:

::: correct

```js
/*eslint vars-on-top: "error"*/

function doSomething() {
    var first;
    var second; //multiple declarations are allowed at the top
    if (true) {
        first = true;
    }
}

function doSomething() {
    var i;
    for (i=0; i<10; i++) {}
}
```

:::

::: correct

```js
/*eslint vars-on-top: "error"*/

var a;
f();
```

:::

::: correct

```js
/*eslint vars-on-top: "error"*/

class C {

    static {
        var a;
        if (something) {
            a = true;
        }
    }

    static {
        var a;
        f();
    }

}
```

:::

::: correct

```js
/*eslint vars-on-top: "error"*/

// Directives may precede variable declarations.
"use strict";
var a;
f();

// Comments can describe variables.
function doSomething() {
    // this is the first var.
    var first;
    // this is the second var.
    var second
}
```

:::


text:
package org.gunisalvo.automaton.controller;

import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.gunisalvo.automaton.controller.xml.AutomatonConfiguration;
import org.gunisalvo.automaton.exception.AutomatonException;
import org.gunisalvo.automaton.monitor.SimulationMonitor;

public abstract class SimulationController {

	protected SimulationMonitor monitor;

	protected AutomatonConfiguration configuration;

	public void configure(String configurationPath) {
		try{
			InputStream is = this.getClass().getResourceAsStream(configurationPath);
			JAXBContext jaxbContext = JAXBContext.newInstance(AutomatonConfiguration.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			this.configuration = (AutomatonConfiguration) jaxbUnmarshaller.unmarshal(is);
			if(this.monitor == null){
				this.monitor = new SimulationMonitor();
			}
			this.monitor.reset();
			if(this.configuration.getServiceLevelAgreement() == null){
				this.monitor.loadSla(this.configuration.getServiceLevelAgreementFile());
			}else{
				this.monitor.loadSla(this.configuration.getServiceLevelAgreement());
			}
		}catch(Exception ex){
			throw new AutomatonException(ex);
		}
	}

	public void configure(InputStream resourceAsStream) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(AutomatonConfiguration.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			this.configuration = (AutomatonConfiguration) jaxbUnmarshaller
					.unmarshal(resourceAsStream);
			if (this.monitor == null) {
				this.monitor = new SimulationMonitor();
			}
			this.monitor.reset();
			if (this.configuration.getServiceLevelAgreement() == null) {
				this.monitor.loadSla(this.configuration.getServiceLevelAgreementFile());
			} else {
				this.monitor.loadSla(this.configuration.getServiceLevelAgreement());
			}
		} catch (Exception ex) {
			throw new AutomatonException(ex);
		}
	}

}


text:
package com.vividsolutions.jts.index.quadtree;

import java.util.ArrayList;
import java.util.List;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.index.*;
/**
 * A Quadtree is a spatial index structure for efficient querying
 * of 2D rectangles.  If other kinds of spatial objects
 * need to be indexed they can be represented by their
 * envelopes
 *

 * The quadtree structure is used to provide a primary filter
 * for range rectangle queries.  The query() method returns a list of
 * all objects which may intersect the query rectangle.  Note that
 * it may return objects which do not in fact intersect.
 * A secondary filter is required to test for exact intersection.
 * Of course, this secondary filter may consist of other tests besides
 * intersection, such as testing other kinds of spatial relationships.
 *
 *

 * This implementation does not require specifying the extent of the inserted
 * items beforehand.  It will automatically expand to accomodate any extent
 * of dataset.
 *

 * This data structure is also known as an MX-CIF quadtree
 * following the usage of Samet and others.
 *
 * @version 1.7
 */
public class Quadtree
    implements SpatialIndex
{
  /**
   * Ensure that the envelope for the inserted item has non-zero extents.
   * Use the current minExtent to pad the envelope, if necessary
   */
  public static Envelope ensureExtent(Envelope itemEnv, double minExtent)
  {
    //The names "ensureExtent" and "minExtent" are misleading -- sounds like
    //this method ensures that the extents are greater than minExtent.
    //Perhaps we should rename them to "ensurePositiveExtent" and "defaultExtent".
    //[Jon Aquino]
    double minx = itemEnv.getMinX();
    double maxx = itemEnv.getMaxX();
    double miny = itemEnv.getMinY();
    double maxy = itemEnv.getMaxY();
    // has a non-zero extent
    if (minx != maxx && miny != maxy) return itemEnv;

    // pad one or both extents
    if (minx == maxx) {
      minx = minx - minExtent / 2.0;
      maxx = minx + minExtent / 2.0;
    }
    if (miny == maxy) {
      miny = miny - minExtent / 2.0;
      maxy = miny + minExtent / 2.0;
    }
    return new Envelope(minx, maxx, miny, maxy);
  }

  private Root root;
  /**

  * minExtent is the minimum envelope extent of all items
  * inserted into the tree so far. It is used as a heuristic value
  * to construct non-zero envelopes for features with zero X and/or Y extent.
  * Start with a non-zero extent, in case the first feature inserted has
  * a zero extent in both directions.  This value may be non-optimal, but
  * only one feature will be inserted with this value.
  **/
  private double minExtent = 1.0;

  /**
   * Constructs a Quadtree with zero items.
   */
  public Quadtree()
  {
    root = new Root();
  }

  /**
   * Returns the number of levels in the tree.
   */
  public int depth()
  {
    //I don't think it's possible for root to be null. Perhaps we should
    //remove the check. [Jon Aquino]
    //Or make an assertion [Jon Aquino 10/29/2003]
    if (root != null) return root.depth();
    return 0;
  }

  /**
   * Returns the number of items in the tree.
   *
   * @return the number of items in the tree
   */
  public int size()
  {
    if (root != null) return root.size();
    return 0;
  }

  public void insert(Envelope itemEnv, Object item)
  {
    collectStats(itemEnv);
    Envelope insertEnv = ensureExtent(itemEnv, minExtent);
    root.insert(insertEnv, item);
  }

  /**
   * Removes a single item from the tree.
   *
   * @param itemEnv the Envelope of the item to be removed
   * @param item the item to remove
   * @return true if the item was found (and thus removed)
   */
  public boolean remove(Envelope itemEnv, Object item)
  {
    Envelope posEnv = ensureExtent(itemEnv, minExtent);
    return root.remove(posEnv, item);
  }

/*
  public List OLDquery(Envelope searchEnv)
  {
    /**
     * the items that are matched are the items in quads which
     * overlap the search envelope
     */
    /*
    List foundItems = new ArrayList();
    root.addAllItemsFromOverlapping(searchEnv, foundItems);
    return foundItems;
  }
*/

  /**
   * Queries the tree and returns items which may lie in the given search envelope.
   * Precisely, the items that are returned are all items in the tree
   * whose envelope may intersect the search Envelope.
   * Note that some items with non-intersecting envelopes may be returned as well;
   * the client is responsible for filtering these out.
   * In most situations there will be many items in the tree which do not
   * intersect the search envelope and which are not returned - thus
   * providing improved performance over a simple linear scan.
   *
   * @param searchEnv the envelope of the desired query area.
   * @return a List of items which may intersect the search envelope
   */
  public List query(Envelope searchEnv)
  {
    /**
     * the items that are matched are the items in quads which
     * overlap the search envelope
     */
    ArrayListVisitor visitor = new ArrayListVisitor();
    query(searchEnv, visitor);
    return visitor.getItems();
  }

  /**
   * Queries the tree and visits items which may lie in the given search envelope.
   * Precisely, the items that are visited are all items in the tree
   * whose envelope may intersect the search Envelope.
   * Note that some items with non-intersecting envelopes may be visited as well;
   * the client is responsible for filtering these out.
   * In most situations there will be many items in the tree which do not
   * intersect the search envelope and which are not visited - thus
   * providing improved performance over a simple linear scan.
   *
   * @param searchEnv the envelope of the desired query area.
   * @param visitor a visitor object which is passed the visited items
   */
  public void query(Envelope searchEnv, ItemVisitor visitor)
  {
    /**
     * the items that are matched are the items in quads which
     * overlap the search envelope
     */
    root.visit(searchEnv, visitor);
  }

  /**
   * Return a list of all items in the Quadtree
   */
  public List queryAll()
  {
    List foundItems = new ArrayList();
    root.addAllItems(foundItems);
    return foundItems;
  }

  private void collectStats(Envelope itemEnv)
  {
    double delX = itemEnv.getWidth();
    if (delX < minExtent && delX > 0.0)
      minExtent = delX;

    double delY = itemEnv.getHeight();
    if (delY < minExtent && delY > 0.0)
      minExtent = delY;
  }

}


text:
static RelationshipConverter*        relationshipConverter;

@interface RelationshipConverter()
{
    sqlite3*        _database;
}
@end

@implementation RelationshipConverter

+ (instancetype)sharedManager
{
    static dispatch_once_t  once;
    dispatch_once(&once, ^{
        relationshipConverter = [[RelationshipConverter alloc] init];
    });
    [relationshipConverter openSQL];

    return relationshipConverter;
}

- (instancetype)init
{
    if (self = [super init]) {

    }
    return self;
}

#pragma mark -- private method
- (void)openSQL {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"RelationShipDate" ofType:@"sqlite"];

    if (sqlite3_open([path UTF8String], &_database) != SQLITE_OK) {
        sqlite3_close(_database);
        NSAssert(0, @"Failed to open database");
    }
}

- (void)closeSQL
{
    sqlite3_close(_database);
}

#pragma mark - Public Method
//根据描述返回称谓
- (NSString *)selectRelateWithRelateFrom:(NSString *)RelateFrom {
    NSString *SelectRelate = [NSString stringWithFormat:@"SELECT relate FROM Relation where relateFrom='%@'", RelateFrom];
    //返回的称谓
    NSString *relateStr;
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(_database, [SelectRelate UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *relateName = sqlite3_column_text(stmt, 0);
            relateStr = [NSString stringWithUTF8String:(const char*)relateName];
            break;
        }
        sqlite3_finalize(stmt);
    }
    [self closeSQL];

    return relateStr;
}

//判断自己的性别
- (NSString *)chooseRelateWithGender: (NSString *)Gender RelateFrom:(NSString *)RelateFrom{
    NSString *chooseStr;
    if ([Gender isEqualToString:@"male"]) {
        chooseStr = @"maleName";
    }else if ([Gender isEqualToString:@"female"]){
        chooseStr = @"femaleName";
    }

    NSString *SelectRelate = [NSString stringWithFormat:@"SELECT %@ FROM Relation where relateFrom='%@'", chooseStr, RelateFrom];
    //返回的称谓
    NSString *relateStr;
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(_database, [SelectRelate UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *relateName = sqlite3_column_text(stmt, 0);
            relateStr = [NSString stringWithUTF8String:(const char*)relateName];
            break;
        }
        sqlite3_finalize(stmt);
    }
    [self closeSQL];
    return relateStr;
}
//判断大小
- (NSString *)chooseRelateWithOldorYoung: (NSString *)OldorYoung RelateFrom:(NSString *)RelateFrom{

    NSString *chooseStr;
    if ([OldorYoung isEqualToString:@"old"]) {
        chooseStr = @"oldName";
    }else if ([OldorYoung isEqualToString:@"young"]){
        chooseStr = @"youngName";
    }

    NSString *SelectRelate = [NSString stringWithFormat:@"SELECT %@ FROM Relation where relateFrom='%@'", chooseStr, RelateFrom];
    //返回的称谓
    NSString *relateStr;
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(_database, [SelectRelate UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *relateName = sqlite3_column_text(stmt, 0);
            relateStr = [NSString stringWithUTF8String:(const char*)relateName];
            break;
        }
        sqlite3_finalize(stmt);
    }
    [self closeSQL];
    return relateStr;
}

//搜索
- (NSString *)searchRelateWithText:(NSString *)searchText{

    NSString *NSsql0 = [NSString stringWithFormat:@" SELECT relate FROM Call WHERE relate = '%@' ", searchText];
    NSString *NSsql1 = [NSString stringWithFormat:@" SELECT relate FROM Call WHERE otherCall like '%%%@%%' ", searchText];
    NSString *relateStr;
    const char *sql0=NSsql0.UTF8String;
    const char *sql1=NSsql1.UTF8String;
    sqlite3_stmt *stmt;

    if (sqlite3_prepare_v2(_database, sql0, -1, &stmt, nil) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *relateName = sqlite3_column_text(stmt, 0);
            relateStr = [NSString stringWithUTF8String:(const char*)relateName];
            break;
        }
        sqlite3_finalize(stmt);
    }

    if (!relateStr) {
        if (sqlite3_prepare_v2(_database, sql1, -1, &stmt, nil) == SQLITE_OK) {
            while (sqlite3_step(stmt) == SQLITE_ROW) {
                const unsigned char *relateName = sqlite3_column_text(stmt, 0);
                relateStr = [NSString stringWithUTF8String:(const char*)relateName];
                break;
            }
            sqlite3_finalize(stmt);
        }
    }

    [self closeSQL];
    return relateStr;
}

//根据称谓返回详细信息
- (RelatedHelper *)selectDetailsWithRelate:(NSString *)Relate {

    RelatedHelper *relateHelper = [RelatedHelper new];
    NSString *NSsql0 = [NSString stringWithFormat:@" SELECT idkey,relate,relateFrom,level,system,familyLevel,otherCall,based,englishCall,englishDetail FROM Call WHERE relate = '%@' ", Relate];
    const char *sql0=NSsql0.UTF8String;
    sqlite3_stmt *stmt0;

    if (sqlite3_prepare_v2(_database, sql0, -1, &stmt0, nil) == SQLITE_OK) {
        //数据库查询语句没有问题

        //每调用一次sqlite3_step函数,stmt就会指向下一条记录
        while (sqlite3_step(stmt0) == SQLITE_ROW) {//找到一条记录

            //取出数据
            const unsigned char *idkey = sqlite3_column_text(stmt0, 0);
            const unsigned char *relate = sqlite3_column_text(stmt0, 1);
            const unsigned char *relateFrom = sqlite3_column_text(stmt0, 2);
            const unsigned char *level = sqlite3_column_text(stmt0, 3);
            const unsigned char *system = sqlite3_column_text(stmt0, 4);
            const unsigned char *familyLevel = sqlite3_column_text(stmt0, 5);
            const unsigned char *otherCall = sqlite3_column_text(stmt0, 6);
            const unsigned char *based = sqlite3_column_text(stmt0, 7);
            const unsigned char *englishCall = sqlite3_column_text(stmt0, 8);
            const unsigned char *englishDetail = sqlite3_column_text(stmt0, 9);

            relateHelper.idkey = [NSString stringWithUTF8String:(const char*)idkey];
            relateHelper.relate = [NSString stringWithUTF8String:(const char*)relate];
            relateHelper.relateFrom = [NSString stringWithUTF8String:(const char*)relateFrom];
            relateHelper.level = [NSString stringWithUTF8String:(const char*)level];
            relateHelper.system = [NSString stringWithUTF8String:(const char*)system];
            relateHelper.familyLevel = [NSString stringWithUTF8String:(const char*)familyLevel];
            if (otherCall) {
                relateHelper.otherCall = [NSString stringWithUTF8String:(const char*)otherCall];
            }
            relateHelper.based = [NSString stringWithUTF8String:(const char*)based];
            if (englishCall) {
                relateHelper.englishCall = [NSString stringWithUTF8String:(const char*)englishCall];
            }
            if (englishDetail) {
                relateHelper.englishDetail = [NSString stringWithUTF8String:(const char*)englishDetail];
            }
        }
        sqlite3_finalize(stmt0);
    }

    [self closeSQL];
    return relateHelper;
}

@end


text:
static struct option longopts[] = {
	{ "papersize", required_argument, NULL, 's' },
    { "orientation", required_argument, NULL, 'o' }
};

void usage() {
	printf("Usage: html2pdf [options] file.html [file2.html ...]\n");
	printf("       --papersize=PAPERSIZE, -s PAPERSIZE: Specify a paper size\n");
    printf("       --orientation=ORIENTATION, -o ORIENTATION: landscape or portrait (default portrait)\n");
    printf("\n");
    printf("Valid paper sizes: ");

    NSArray *paperSizes = [[PaperSize validPresetNames] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    int i = 0;
    char cStringSize[81];
    for (NSString *paperSize in paperSizes) {
        [paperSize getCString:cStringSize maxLength:80 encoding:NSASCIIStringEncoding];
        printf("%s", cStringSize);
        i++;
        if (i < [paperSizes count]) {
            printf(", ");
        }
    }
    printf("\n");
}

int main(int argc, char *argv[]) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	PaperSize *paperSize = nil;
	NSString *presetName = @"letter";
    NSString *orientationString;
    NSPrintingOrientation orientation = NSPortraitOrientation;

	int ch;
	while ((ch = getopt_long(argc, argv, "s:o:", longopts, NULL)) != -1) {
		switch (ch) {
			case 's':
				presetName = [[NSString alloc] initWithCString:optarg encoding:NSUTF8StringEncoding];

				if (![PaperSize isValidPresetName:presetName]) {
					printf("%s is not a valid paper size preset (valid options: %s)\n", optarg, [[[PaperSize validPresetNames] componentsJoinedByString:@", "] cStringUsingEncoding:NSUTF8StringEncoding]);
					return 1;
				}

				break;
            case 'o':
                orientationString = [[NSString alloc] initWithCString:optarg encoding:NSUTF8StringEncoding];

                if ([orientationString isEqualToString:@"portrait"])
                    orientation = NSPortraitOrientation;
                else if ([orientationString isEqualToString:@"landscape"])
                    orientation = NSLandscapeOrientation;
                else {
                    printf("%s is not a valid orientation (must be either portrait or landscape)\n", optarg);
                    [orientationString release];
                    return 1;
                }

                [orientationString release];

                break;
			default:
				usage();
				return 1;
		}
	}

	paperSize = [PaperSize newWithPreset:presetName orientation:orientation];
	[paperSize autorelease];

	argc -= optind;
	argv += optind;

	if (argc == 0) {
		printf("Please specify at least one HTML file to convert to PDF.\n\n");
		usage();

		[pool release];
		return 1;
	}

	Html2PdfApplicationDelegate *delegate =
	[[Html2PdfApplicationDelegate alloc] initWithArgc:argc argv:argv paperSize:paperSize];

	NSApplication *app = [NSApplication sharedApplication];
	[app setDelegate:delegate];
	[app run];

	[pool release];

	return 0;
}


text:
typedef void irqreturn_t;
#define IRQ_NONE
#define IRQ_HANDLED
#endif

#ifndef MODULE_LICENSE
#define MODULE_LICENSE(x)
#endif

#ifndef __iomem
#define __iomem
#endif

#ifndef __attribute_used__
#define __attribute_used__	__devinitdata
#endif

#ifndef __user
#define __user
#endif

#ifndef SERVICE_ACTION_IN
#define SERVICE_ACTION_IN	0x9e
#endif
#ifndef READ_16
#define READ_16			0x88
#endif
#ifndef WRITE_16
#define WRITE_16		0x8a
#endif


text:
package com.thinkaurelius.titan.graphdb.database.idassigner;

public interface IDPool {

    public long nextID();

    public void close();

}


text:
package io.flic.lib;

/**
 * Represents possible values for the intent extra {@link FlicIntentExtras#TYPE}.
 */
class FlicIntentTypes {
	/**
	 * Indicates that the button was pressed or released.
	 * See {@link FlicIntentValues#UP} and {@link FlicIntentValues#DOWN}.
	 */
	public static final String UP_OR_DOWN = "UP_OR_DOWN";

	/**
	 * Indicates that the button was clicked or held.
	 * See {@link FlicIntentValues#CLICK} and {@link FlicIntentValues#HOLD}.
	 */
	public static final String CLICK_OR_HOLD = "CLICK_OR_HOLD";

	/**
	 * Indicates that the button was single- or double clicked.
	 * See {@link FlicIntentValues#SINGLE_CLICK} and {@link FlicIntentValues#DOUBLE_CLICK}.
	 */
	public static final String SINGLE_OR_DOUBLE_CLICK = "SINGLE_OR_DOUBLE_CLICK";

	/**
	 * Indicates that the button was single- or double clicked or held.
	 * See {@link FlicIntentValues#SINGLE_CLICK}, {@link FlicIntentValues#DOUBLE_CLICK} and {@link FlicIntentValues#HOLD}.
	 */
	public static final String SINGLE_OR_DOUBLE_CLICK_OR_HOLD = "SINGLE_OR_DOUBLE_CLICK_OR_HOLD";

	/**
	 * Indicates that this app for this button was released by the user in the Flic app.
	 *
	 * This broadcast receiver will no longer receive intents for this button, until {@link FlicButton#registerListenForBroadcast(int)} is called again.
	 */
	public static final String REMOVED = "REMOVED";
}


text:
package oauth1

import (
	"net/http"

	"golang.org/x/net/context"
)

type contextKey struct{}

// HTTPClient is the context key to associate an *http.Client value with
// a context.
var HTTPClient contextKey

// NoContext is the default context to use in most cases.
var NoContext = context.TODO()

// contextTransport gets the Transport from the context client or nil.
func contextTransport(ctx context.Context) http.RoundTripper {
	if client, ok := ctx.Value(HTTPClient).(*http.Client); ok {
		return client.Transport
	}
	return nil
}


text:
from django.db import models
from django.core.urlresolvers import reverse
from traceability.models.incident import Incident
from traceability.models.material import Material

class Batch(models.Model):
    batch_id = models.IntegerField(primary_key=True, )
    creation_date = models.DateField()
    incidents = models.ManyToManyField(
        Incident,
        blank=True,
        null=True, )

    class Meta:
        app_label = 'traceability'
        ordering = ('batch_id', )

    def __str__(self):
        return str(self.batch_id)

    def get_absolute_url(self):
        return reverse(
            'traceability:batch:batch_detail',
            args=[self.batch_id], )

class Input(models.Model):

    GRAMS = 0
    MILLILITER = 1

    AMOUNT_TYPE_CHOICES = (
        (GRAMS, 'Grams'),
        (MILLILITER, 'Milliliters'),
    )

    batch = models.ForeignKey(Batch)
    material = models.ForeignKey(Material)
    amount = models.DecimalField(max_digits=6, decimal_places=2)
    amount_type = models.IntegerField(
        max_length=1,
        choices=AMOUNT_TYPE_CHOICES,
        default=0)

    class Meta:
        app_label = 'traceability'
        unique_together = ['batch', 'material']

    def __str__(self):
        return str(self.material)


text:
package com.sonymobile.tools.gerrit.gerritevents.dto.attr;

import com.sonymobile.tools.gerrit.gerritevents.dto.GerritChangeKind;
import com.sonymobile.tools.gerrit.gerritevents.dto.GerritJsonDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

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

import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getDate;
import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getString;
import static com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory.getBoolean;

import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.NUMBER;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REVISION;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.REF;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.IS_DRAFT;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.KIND;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.UPLOADER;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.AUTHOR;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.APPROVALS;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.PARENTS;
import static com.sonymobile.tools.gerrit.gerritevents.dto.GerritEventKeys.CREATED_ON;

/**
 * Represents a Gerrit JSON Patchset DTO.
 * Refers to a specific patchset within a change.
 * @author Robert Sandell <robert.sandell@sonyericsson.com>
 */
public class PatchSet implements GerritJsonDTO {

    /**
     * The patchset number.
     */
    private String number;
    /**
     * Git commit-ish for this patchset.
     */
    private String revision;
    /**
     * The refspec
     */
    private String ref;
    /**
     * The flag for draft patch.
     */
    private boolean draft;
    /**
     * The kind of change uploaded.
     */
    private GerritChangeKind kind;
    /**
     * The one who uploaded the patch-set.
     */
    private Account uploader;
    /**
     * The patch author.
     */
    private Account author;
    /**
     * The list of approvals.
     */
    private List<Approval> approvals;
    /**
     * The list of parent ids.
     */
    private List<String> parents;
    /**
     * The Date when this change was created.
     */
    private Date createdOn;
    /**
     * Default constructor.
     */
    public PatchSet() {
    }

    /**
     * Constructor that fills with data directly.
     * @param json the JSON object with corresponding data.
     */
    public PatchSet(JSONObject json) {
        this.fromJson(json);
    }

    @Override
    public void fromJson(JSONObject json) {
        number = getString(json, NUMBER);
        revision = getString(json, REVISION);
        draft = getBoolean(json, IS_DRAFT);
        createdOn = getDate(json, CREATED_ON);
        if (json.containsKey(KIND)) {
            kind = GerritChangeKind.fromString(getString(json, KIND));
        }
        ref = getString(json, REF);
        if (json.containsKey(UPLOADER)) {
            uploader = new Account(json.getJSONObject(UPLOADER));
        }
        if (json.containsKey(AUTHOR)) {
            author = new Account(json.getJSONObject(AUTHOR));
        }
        if (json.containsKey(APPROVALS)) {
            approvals = new ArrayList<Approval>();
            JSONArray eventApprovals = json.getJSONArray(APPROVALS);
            for (int i = 0; i < eventApprovals.size(); i++) {
                approvals.add(new Approval(eventApprovals.getJSONObject(i)));
            }
        }
        if (json.containsKey(PARENTS)) {
            parents = new ArrayList<String>();
            JSONArray eventParents = json.getJSONArray(PARENTS);
            for (int i = 0; i < eventParents.size(); i++) {
                parents.add(eventParents.getString(i));
            }
        }
    }

    /**
     * @return the List of parent dependency hashes
     */
    public List<String> getParents() {
        return parents;
    }

    /**
     * The patchset number.
     * @return the number.
     */
    public String getNumber() {
        return number;
    }

    /**
     * The list of approvals for this patch set.
     *
     * @return the list of approvals
     */
    public List<Approval> getApprovals() {
        return approvals;
    }

    /**
     * The patchset number.
     * @param number the number.
     */
    public void setNumber(String number) {
        this.number = number;
    }

    /**
     * Git commit-ish for this patchset.
     * @return the revision commit-ish.
     */
    public String getRevision() {
        return revision;
    }

    /**
     * Git commit-ish for this patchset.
     * @param revision the revision commit-ish.
     */
    public void setRevision(String revision) {
        this.revision = revision;
    }

    /**
     * Gets the refspec, if it exists.
     * This value in the JSON stream-events data was introduced some version after the stream-events command was,
     * so it might not exist for all stream-events versions of Gerrit.
     * @return the refspec.
     */
    public String getRef() {
        return ref;
    }

    /**
     * Sets the refspec.
     * @param ref the refspec.
     */
    public void setRef(String ref) {
        this.ref = ref;
    }

    /**
     * Draft patchset or not.
     * @return true if draft patchset.
     */
    public boolean isDraft() {
        return draft;
    }

    /**
     * Sets the isDraft.
     * @param draft the isDraft.
     */
    public void setDraft(boolean draft) {
        this.draft = draft;
    }

    /**
     * Kind of change uploaded.
     * @return String of the change kind.
     */
    public GerritChangeKind getKind() {
        return kind;
    }

    /**
     * Sets the result of getKind().
     * @param kind the kind of the change.
     */
    public void setKind(GerritChangeKind kind) {
        this.kind = kind;
    }

    /**
     * The one who uploaded the patch-set.
     *
     * @return the account of the uploader.
     */
    public Account getUploader() {
        return uploader;
    }

    /**
     * The patch set author (may not be the owner).
     *
     * @return the author
     */
    public Account getAuthor() {
        return author;
    }

    /**
     * The one who uploaded the patch-set.
     * @param uploader the account of the uploader.
     */
    public void setUploader(Account uploader) {
        this.uploader = uploader;
    }

    /**
     * The Date this change was created on.
     * @return the Date.
     */
    public Date getCreatedOn() {
        return createdOn;
    }

    /**
     * The Date this change was created on.
     * @param date the Date.
     */
    public void setCreatedOn(Date date) {
        this.createdOn = date;
    }

    @Override
    public boolean equals(Object obj) {
        //CS IGNORE MagicNumber FOR NEXT 15 LINES. REASON: Autogenerated Code.
        //CS IGNORE AvoidInlineConditionals FOR NEXT 15 LINES. REASON: Autogenerated Code.
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PatchSet other = (PatchSet)obj;
        if ((this.number == null) ? (other.number != null) : !this.number.equals(other.number)) {
            return false;
        }
        if ((this.revision == null) ? (other.revision != null) : !this.revision.equals(other.revision)) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        //CS IGNORE MagicNumber FOR NEXT 5 LINES. REASON: Autogenerated Code.
        //CS IGNORE AvoidInlineConditionals FOR NEXT 5 LINES. REASON: Autogenerated Code.
        int hash = 7;
        hash = 79 * hash + (this.number != null ? this.number.hashCode() : 0);
        hash = 79 * hash + (this.revision != null ? this.revision.hashCode() : 0);
        return hash;
    }

    @Override
    public String toString() {
        return "PatchSet: " + getNumber();
    }

}


text:
var closest = require('closest')
var log = require('./client/log')('locations-view')
var textModal = require('text-modal')
var view = require('view')
var LocationSuggest = require('location-suggest')
var extend = require('extend')

/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function (view, plan) {
  plan.on('change', function () {
    view.resetIcons()
  })

  view.on('rendered', function () {
    // Reset the icons
    view.resetIcons()

    // On form submission
    closest(view.el, 'form').onsubmit = function (e) {
      e.preventDefault()

      plan.setAddresses(view.find('.from input').value, view.find('.to input').value, function (err) {
        if (err) {
          log.error('%e', err)
        } else {
          plan.updateRoutes()
        }
      })
    }
  })
})

extend(View.prototype, LocationSuggest.prototype)

/**
 * Show clear or current location, but not both
 */

View.prototype.resetIcons = function (e) {
  showClearOrCurrentLocation(this, 'from')
  showClearOrCurrentLocation(this, 'to')

  function showClearOrCurrentLocation (view, name) {
    var selector = '.' + name
    var value = view.find(selector + ' input').value
    var refresh = view.find(selector + ' .findingCurrentLocation')
    var clear = view.find(selector + ' .clear')
    var location = view.find(selector + ' .currentLocation')

    refresh.classList.add('hidden')

    if (!value || !value.trim || value.trim().length === 0) {
      clear.classList.add('hidden')
      location.classList.remove('hidden')
    } else {
      clear.classList.remove('hidden')
      location.classList.add('hidden')
    }
  }
}

/**
 * Use the current location if it's available
 */

View.prototype.currentLocation = function (e) {
  e.preventDefault()
  if ('geolocation' in navigator) {
    var name = e.target.parentNode.classList.contains('from') ? 'from' : 'to'
    var input = this.find('.' + name + ' input')
    var self = this

    e.target.classList.add('hidden')
    this.find('.' + name + ' .findingCurrentLocation').classList.remove('hidden')

    navigator.geolocation.getCurrentPosition(function (position) {
      var c = position.coords
      input.value = c.longitude + ', ' + c.latitude
      self.save(input)
    }, function (err) {
      console.error(err)
      self.resetIcons()
      window.alert('Whoops! We were unable to find your current location.')
    }, {
      enableHighAccuracy: true,  // use GPS if available
      maximumAge: 60000, // 60 seconds
      timeout: 30000  // 30 seconds
    })
  } else {
    window.alert('Whoops! Looks like GPS location not available on this device.')
  }
}

View.prototype.locationSelected = function (target) {
  this.save(target)
}

/**
 * Geocode && Save
 */

View.prototype.save = function (el) {
  var plan = this.model
  var name = el.name
  var val = el.value

  if (val && plan[name]() !== val) {
    this.model.setAddress(name, val, function (err, location) {
      if (err) {
        log.error('%e', err)
        textModal('Invalid address.')
      } else if (location) {
        plan.updateRoutes()
      }
    })
  }

  this.resetIcons()
}

/**
 * Highlight the selected input
 */

View.prototype.focusInput = function (e) {
  e.target.parentNode.classList.add('highlight')
}

/**
 * Clear
 */

View.prototype.clear = function (e) {
  e.preventDefault()
  var inputGroup = e.target.parentNode
  var input = inputGroup.getElementsByTagName('input')[0]
  input.value = ''
  input.focus()

  this.resetIcons()
}


text:
struct GLFWwindow;
class InputManager;

class Scene {
public:
    Scene();
    virtual ~Scene();
    void Run();

protected:
    struct Settings {
        string title = "Application";
        U32 width = 800;
        U32 height = 600;
        bool fullScreen = false;
        bool vsync = false;
    };

    virtual void Initialize();
    virtual void LoadContent() = 0;
    virtual void Update(const Timespan& elapsedTime) = 0;
    virtual void Draw(const Timespan& elapsedTime) = 0;
    const InputManager& GetInput() const;

    Settings settings;

private:
    void InitializeGLFW();
    void InitializeGLEW();
    Timespan CalcElapsedTime();

    GLFWwindow* window = nullptr;
    Timestamp time;
};


text:
'use strict';

//helper functions
window.helperUtils = {
    getDocDimen: function () {
        var winDimen = {};

        winDimen.height = window.innerHeight;
        winDimen.width = window.innerWidth;

        return winDimen;
    }
};

window.parseQueryString = function (str) {
    if (typeof str !== 'string') {
        return {};
    }
    str = str.trim().replace(/^\?/, '');
    if (!str) {
        return {};
    }
    return str.trim().split('&').reduce(function (ret, param) {
        var parts = param.replace(/\+/g, ' ').split('=');
        ret[parts[0]] = parts[1] === undefined ? null : decodeURIComponent(parts[1]);
        return ret;
    }, {});
};

/**
 * Get the value of a querystring
 * @param  {String} field The field to get the value of
 * @param  {String} url   The URL to get the value from (optional)
 * @return {String}       The field value
 */
window.getQueryString = function (field, url) {
    var href = url ? url : window.location.href;
    var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
    var string = reg.exec(href);
    return string ? string[1] : null;
};

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel

(function () {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function (callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function () { callback(currTime + timeToCall); },
	          timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function (id) {
            clearTimeout(id);
        };
}());


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

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

This test should not assert, and you should see a fully green square.


text:
using Cake.Common.Tools.XUnit;
using Xunit;

namespace Cake.Common.Tests.Unit.Tools.XUnit
{
    public sealed class XUnit2SettingsTests
    {
        public sealed class TheConstructor
        {
            [Fact]
            public void Should_Set_Output_Directory_To_Null_By_Default()
            {
                // Given, When
                var settings = new XUnit2Settings();

                // Then
                Assert.Null(settings.OutputDirectory);
            }

            [Fact]
            public void Should_Disable_XML_Report_By_Default()
            {
                // Given, When
                var settings = new XUnit2Settings();

                // Then
                Assert.False(settings.XmlReport);
            }

            [Fact]
            public void Should_Disable_HTML_Report_By_Default()
            {
                // Given, When
                var settings = new XUnit2Settings();

                // Then
                Assert.False(settings.HtmlReport);
            }

            [Fact]
            public void Should_Enable_Shadow_Copying_By_Default()
            {
                // Given, When
                var settings = new XUnit2Settings();

                // Then
                Assert.True(settings.ShadowCopy);
            }
        }
    }
}


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>

    <groupId>com.mongodb</groupId>
    <artifactId>M101J</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>MongoDB University - Homework 2.1</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.0.0-rc0</version>
        </dependency>

        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.19</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>1.7.9</version>
        </dependency>

    </dependencies>
</project>


text:
/**
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.cdlflex.ui.markup.html.repeater.data.table;

import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider;

/**
 * A service interface that helps to build DataTable instance.
 *
 * @param <T> The Model object type
 * @param <S> The type of the sorting parameter
 */
public interface ITableSkeleton<T, S> extends IColumnProvider<T, S> {

    /**
     * Returns the data provider used.
     *
     * @return a data provider
     */
    ISortableDataProvider<T, S> getDataProvider();

    /**
     * Returns the amount of rows per page to show.
     *
     * @return rows per page to show
     */
    Integer getRowsPerPage();
}


text:
package edu.uw.data.app;
import edu.uw.data.dao.UserDao;
import edu.uw.data.model.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * Hello spring application context with spring Jdbc template!
 *   we can run this from the command line
 *   1) start the standalone derby service
 *      cd DERBY_HOME\bin
 *      ./startNetworkServer
 *
 *   2) populate the database using sql squirrel and the attached all.sql script
 *
 *   3) Build this application as an exectuable jar
 *           mvn clean package -DskipTests spring-boot:repackage
 *
 *   4) run the application to connect to the remote server
 *      java -jar target/lecture1_jdbc-1.0-SNAPSHOT.jar
 *
 *   5) you should see user information printed out
 */
public class App7UsersSpring
{

  static final Logger log = LoggerFactory.getLogger(App7UsersSpring.class);

  public static void mainExample(String[] args) {
    log.info("Initializing Spring context.");

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContext.xml");

    log.info("Spring context initialized.");

    UserDao userDao = (UserDao) applicationContext.getBean("userDao");
    log.info("userDao."+userDao);

    List<User> users = userDao.findAll();
    for (User user : users) {
         System.out.println("User "+user);
      }
  }
}


text:
#include "config.h"
#include "vm.hpp"
#include "on_stack.hpp"
#include "object_memory.hpp"
#include "call_frame.hpp"
#include "metrics.hpp"
#include "exception_point.hpp"

#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/module.hpp"
#include "builtin/thread.hpp"
#include "builtin/native_method.hpp"

#include "capi/handle.hpp"

#include "gc/finalize.hpp"

#include "util/logger.hpp"

#include "dtrace/dtrace.h"

namespace rubinius {
  FinalizerThread::iterator::iterator(FinalizerThread* fh)
    : handler_(fh)
    , current_list_(NULL)
  {
    if(handler_->live_list_->empty()) {
      if(handler_->lists_->empty()) {
        current_ = handler_->live_list_->begin();
        end_ = handler_->live_list_->end();
        return;
      } else {
        current_list_ = handler_->lists_->front();
      }
    } else {
      current_list_ = handler_->live_list_;
    }

    current_ = current_list_->begin();

    if(handler_->lists_->empty()) {
      end_ = current_list_->end();
    } else {
      lists_iterator_ = handler_->lists_->begin();
      end_ = handler_->lists_->back()->end();
    }
  }

  void FinalizerThread::iterator::next(bool live) {
    if(current_list_ == handler_->live_list_) {
      if(!live) current_->queued();

      if(++current_ == current_list_->end()) {
        if(!handler_->lists_->empty()) {
          current_list_ = *lists_iterator_;
          current_ = current_list_->begin();
        }
      }
    } else {
      if(++current_ == end_) {
        return;
      } else if(current_ == current_list_->end()) {
        if(++lists_iterator_ != handler_->lists_->end()) {
          current_list_ = *lists_iterator_;
          current_ = current_list_->begin();
        }
      }
    }
  }

  bool FinalizerThread::iterator::end() {
    return current_ == end_;
  }

  FinalizerThread::FinalizerThread(STATE)
    : InternalThread(state, "rbx.finalizer")
    , lists_(NULL)
    , live_list_(NULL)
    , process_list_(NULL)
    , iterator_(NULL)
    , process_item_kind_(eRuby)
    , finishing_(false)
  {
    state->shared().set_finalizer_handler(this);

    lists_ = new FinalizeObjectsList();
    live_list_ = new FinalizeObjects();
  }

  FinalizerThread::~FinalizerThread() {
    if(iterator_) delete iterator_;
    if(live_list_) delete live_list_;

    if(lists_) {
      for(FinalizeObjectsList::iterator i = lists_->begin(); i != lists_->end(); ++i) {
        delete *i;
      }
      delete lists_;
    }
  }

  void FinalizerThread::initialize(STATE) {
    InternalThread::initialize(state);

    Thread::create(state, vm());

    live_guard_.init();
    worker_lock_.init();
    worker_cond_.init();
    supervisor_lock_.init();
    supervisor_cond_.init();
    finishing_ = false;
  }

  void FinalizerThread::wakeup(STATE) {
    utilities::thread::Mutex::LockGuard lg(worker_lock_);

    InternalThread::wakeup(state);

    worker_signal();
  }

  void FinalizerThread::stop(STATE) {
    state->shared().internal_threads()->unregister_thread(this);

    stop_thread(state);
  }

  void FinalizerThread::run(STATE) {
    GCTokenImpl gct;

    state->gc_dependent(gct, 0);

    while(!thread_exit_) {
      state->vm()->set_call_frame(0);

      if(!process_list_) first_process_item();

      if(!process_list_) {
        {
          utilities::thread::Mutex::LockGuard lg(worker_lock_);

          // exit_ might have been set after we grabbed the worker_lock
          if(thread_exit_) break;

          state->gc_independent(gct, 0);
          worker_wait();

          if(thread_exit_) break;
        }

        state->gc_dependent(gct, 0);

        {
          utilities::thread::Mutex::LockGuard lg(worker_lock_);
          if(thread_exit_) break;
        }

        continue;
      }

      finalize(state);
      next_process_item();
    }
  }

  void FinalizerThread::finalize(STATE) {
    switch(process_item_kind_) {
    case eRuby: {
      if(process_item_->ruby_finalizer) {
        CallFrame* call_frame = 0;
        // Rubinius specific code. If the finalizer is cTrue, then send the
        // object the __finalize__ message.
        if(process_item_->ruby_finalizer->true_p()) {
          process_item_->object->send(state, call_frame, state->symbol("__finalize__"));
        } else {
          Array* ary = Array::create(state, 1);
          ary->set(state, 0, process_item_->object->id(state));
          if(!process_item_->ruby_finalizer->send(state, call_frame, G(sym_call), ary)) {
            if(state->vm()->thread_state()->raise_reason() == cException) {
              utilities::logger::warn(
                  "finalizer: an exception occurred running a Ruby finalizer: %s",
                  state->vm()->thread_state()->current_exception()->message_c_str(state));
            }
          }
        }
      }

      process_item_->status = FinalizeObject::eRubyFinalized;
      break;
    }
    case eNative:
      if(process_item_->finalizer) {
        if(process_item_->kind == FinalizeObject::eUnmanaged) {
          (*process_item_->finalizer)(state, process_item_->object);
        } else {
          NativeMethodEnvironment* env = state->vm()->native_method_environment;
          NativeMethodFrame nmf(env, 0, 0);
          ExceptionPoint ep(env);
          CallFrame* call_frame = ALLOCA_CALLFRAME(0);

          call_frame->previous = 0;
          call_frame->constant_scope_ = 0;
          call_frame->dispatch_data = (void*)&nmf;
          call_frame->compiled_code = 0;
          call_frame->flags = CallFrame::cNativeMethod;
          call_frame->optional_jit_data = 0;
          call_frame->top_scope_ = 0;
          call_frame->scope = 0;
          call_frame->arguments = 0;

          env->set_current_call_frame(0);
          env->set_current_native_frame(&nmf);

          // Register the CallFrame, because we might GC below this.
          state->set_call_frame(call_frame);

          nmf.setup(Qnil, Qnil, Qnil, Qnil);

          PLACE_EXCEPTION_POINT(ep);

          if(unlikely(ep.jumped_to())) {
            // TODO: log this?
          } else {
            (*process_item_->finalizer)(state, process_item_->object);
          }

          state->set_call_frame(0);
          env->set_current_call_frame(0);
          env->set_current_native_frame(0);
        }
      }
      process_item_->status = FinalizeObject::eNativeFinalized;
      break;
    case eRelease:
      // Unhook any handle used by fi->object so that we don't accidentally
      // try and mark it later (after we've finalized it)
      if(capi::Handle* handle = process_item_->object->handle(state)) {
        handle->forget_object();
        process_item_->object->clear_handle(state);
      }

      process_item_->status = FinalizeObject::eReleased;

      break;
    }
  }

  void FinalizerThread::first_process_item() {
    if(!process_list_ && !lists_->empty()) {
      process_list_ = lists_->back();
      process_item_ = process_list_->begin();
    }
  }

  void FinalizerThread::next_process_item() {
    if(++process_item_ == process_list_->end()) {
      switch(process_item_kind_) {
      case eRuby:
        process_item_ = process_list_->begin();
        process_item_kind_ = eNative;
        break;
      case eNative:
        process_item_ = process_list_->begin();
        process_item_kind_ = eRelease;
        break;
      case eRelease:
        delete process_list_;
        process_list_ = NULL;
        process_item_kind_ = eRuby;
        lists_->pop_back();
        vm()->metrics().gc.objects_finalized++;
        break;
      }
    }
  }

  void FinalizerThread::finish(STATE, GCToken gct) {
    finishing_ = true;
    if(process_list_ || !lists_->empty() || !live_list_->empty()) {
      while(true) {
        if(!process_list_) {
          if(live_list_->empty() && lists_->empty()) break;

          // Everything is garbage when halting so keep adding live objects to
          // finalize queue until done.
          if(!live_list_->empty()) {
            for(FinalizeObjects::iterator i = live_list_->begin();
                i != live_list_->end();
                ++i)
            {
              i->queued();
            }

            queue_objects(state);
          }

          first_process_item();
          if(!process_list_) break;
        }

        while(process_list_) {
          finalize(state);
          next_process_item();
        }
      }
    }

    if(!lists_->empty() || !live_list_->empty() || process_list_ != NULL) {
      utilities::logger::warn("FinalizerThread exiting with pending finalizers");
    }

    VM::discard(state, vm());
  }

  void FinalizerThread::record(Object* obj, FinalizerFunction func,
      FinalizeObject::FinalizeKind kind)
  {
    utilities::thread::Mutex::LockGuard lg(live_guard_);

    if(finishing_) return;

    FinalizeObject fi;
    fi.object = obj;
    fi.kind = kind;
    fi.status = FinalizeObject::eLive;
    fi.finalizer = func;

    // Makes a copy of fi.
    live_list_->push_front(fi);

    vm()->metrics().gc.objects_queued++;
  }

  void FinalizerThread::set_ruby_finalizer(Object* obj, Object* finalizer) {
    utilities::thread::Mutex::LockGuard lg(live_guard_);

    // Ignore Ruby finalizers created when finishing running finalizers.
    if(finishing_) return;

    // Check if the object is already in the finalizer list.
    for(FinalizeObjects::iterator i = live_list_->begin();
        i != live_list_->end();
        ++i)
    {
      if(i->object == obj) {
        if(finalizer->nil_p()) {
          live_list_->erase(i);
        } else {
          i->ruby_finalizer = finalizer;
        }
        return;
      }
    }

    // Adding a nil finalizer is only used to delete an existing finalizer,
    // which we apparently don't have if we get here.
    if(finalizer->nil_p()) {
      return;
    }

    // Ok, create it.

    FinalizeObject fi;
    fi.object = obj;
    fi.status = FinalizeObject::eLive;

    // Rubinius specific API. If the finalizer is the object, we're going to send
    // the object __finalize__. We mark that the user wants this by putting cTrue
    // as the ruby_finalizer.
    if(obj == finalizer) {
      fi.ruby_finalizer = cTrue;
    } else {
      fi.ruby_finalizer = finalizer;
    }

    // Makes a copy of fi.
    live_list_->push_front(fi);
  }

  void FinalizerThread::queue_objects(STATE) {
    if(live_list_->empty()) return;

    FinalizeObjects* dead_list = new FinalizeObjects();

    for(FinalizeObjects::iterator i = live_list_->begin();
        i != live_list_->end();
        /* advance is handled in the loop */)
    {
      if(i->queued_p()) {
        if(i->kind == FinalizeObject::eUnmanaged && !i->ruby_finalizer) {
          i->finalizer(state, i->object);
        } else {
          dead_list->push_front(*i);
        }

        i = live_list_->erase(i);
      } else {
        ++i;
      }
    }

    if(!dead_list->empty()) {
      lists_->push_front(dead_list);
    } else {
      delete dead_list;
    }
  }

  void FinalizerThread::start_collection(STATE) {
    if(process_item_kind_ == eRelease) {
      while(process_list_) {
        finalize(state);
        next_process_item();
      }
    }
  }

  void FinalizerThread::finish_collection(STATE) {
    queue_objects(state);

    if(iterator_) {
      delete iterator_;
      iterator_ = NULL;
    }

    worker_signal();
  }

  void FinalizerThread::supervisor_signal() {
    supervisor_cond_.signal();
  }

  void FinalizerThread::supervisor_wait() {
    supervisor_cond_.wait(supervisor_lock_);
  }

  void FinalizerThread::worker_signal() {
    worker_cond_.signal();
  }

  void FinalizerThread::worker_wait() {
    worker_cond_.wait(worker_lock_);
  }

  FinalizerThread::iterator& FinalizerThread::begin() {
    if(iterator_) delete iterator_;
    iterator_ = new iterator(this);
    return *iterator_;
  }
}