text:
#ifndef RASTER_SELECTION_H
#define RASTER_SELECTION_H

// TnzCore includes
#include "tcommon.h"
#include "tpalette.h"
#include "ttoonzimage.h"
#include "trasterimage.h"
#include "tstroke.h"
#include "tdata.h"

// TnzLib includes
#include "toonz/ttileset.h"
#include "toonz/txshcell.h"

// TnzQt includes
#include "toonzqt/selection.h"

#undef DVAPI
#undef DVVAR
#ifdef TNZTOOLS_EXPORTS
#define DVAPI DV_EXPORT_API
#define DVVAR DV_EXPORT_VAR
#else
#define DVAPI DV_IMPORT_API
#define DVVAR DV_IMPORT_VAR
#endif

// forward declaration
class TTileSetCM32;
class StrokesData;
class RasterImageData;

//=============================================================================
// RasterSelection
//! Selection of TToonzImage and TRasterImage.
//-----------------------------------------------------------------------------

class DVAPI RasterSelection : public TSelection
{
	TImageP m_currentImage;
	TXshCell m_currentImageCell;

	TPaletteP m_oldPalette;
	TRectD m_selectionBbox;
	std::vector<TStroke> m_strokes;
	std::vector<TStroke> m_originalStrokes;
	TAffine m_affine;
	TPoint m_startPosition;
	TRasterP m_floatingSelection;
	TRasterP m_originalfloatingSelection;
	TFrameId m_fid;
	int m_transformationCount;
	bool m_isPastedSelection;
	bool m_noAntialiasing;

private:
	void pasteSelection(const RasterImageData *data);

public:
	RasterSelection();
	RasterSelection(const RasterSelection &src);

	TSelection *clone() const;
	void notify();

	const TImageP &getCurrentImage() const { return m_currentImage; }
	const TXshCell &getCurrentImageCell() const { return m_currentImageCell; }
	void setCurrentImage(const TImageP &img, const TXshCell &imageCell)
	{
		m_currentImage = img, m_currentImageCell = imageCell;
	}

	void setStrokes(const std::vector<TStroke> &strokes) { m_strokes = strokes; }
	std::vector<TStroke> getStrokes() const { return m_strokes; }
	std::vector<TStroke> getOriginalStrokes() const { return m_originalStrokes; }

	void setTransformation(const TAffine &affine) { m_affine = affine; }
	TAffine getTransformation() const { return m_affine; }

	void setStartPosition(const TPoint &position) { m_startPosition = position; }
	TPoint getStartPosition() const { return m_startPosition; }

	void setFloatingSeletion(const TRasterP &floatingSelection) { m_floatingSelection = floatingSelection; }
	TRasterP getFloatingSelection() const { return m_floatingSelection; }
	TRasterP getOriginalFloatingSelection() const { return m_originalfloatingSelection; }

	void setFrameId(const TFrameId &fid) { m_fid = fid; }
	TFrameId getFrameId() const { return m_fid; }

	int getTransformationCount() const { return m_transformationCount; }
	void setTransformationCount(int transformationCount) { m_transformationCount = transformationCount; }

	void setNoAntialiasing(bool value) { m_noAntialiasing = value; }

	bool isPastedSelection() const { return m_isPastedSelection; }

	/*! Returns strokes bounding box.*/
	TRectD getStrokesBound(std::vector<TStroke> strokes) const;
	/*! Returns m_strokes bounding box in world coordinates.
      The bounding box results transformed if the selection is transformed.*/
	TRectD getSelectionBound() const;
	/*! Returns m_originlStrokes bounding box in world coordinates.*/
	TRectD getOriginalSelectionBound() const;

	/*! Return \b m_selectionBbox.
      Can be different from getSelectionBound() after a free deform transformation. */
	TRectD getSelectionBbox() const;
	void setSelectionBbox(const TRectD &rect);

	void selectNone();

	//!Take a rect in world coordinates and put it in the selection.
	void select(const TRectD &rect);
	void select(TStroke &stroke);
	void selectAll();
	bool isEmpty() const;

	void enableCommands();

	bool isFloating() const;
	void transform(const TAffine &affine);

	//commands

	//!Build the floating image using m_strokes.
	void makeFloating();
	//!Paste the floating image over the current image and empty the selection.
	void pasteFloatingSelection();
	//!Delete the floating image.
	void deleteSelection();
	//!Copy the floating image  in the clipboard.
	void copySelection();
	//!Cut the floating image.
	void cutSelection();
	//!Create the floating image using clipboard Data.
	void pasteSelection();

	bool isTransformed();
};

#endif //RASTER_SELECTION_H


text:
module Geonames
  module API
    class Dummy
      extend API::Endpoint

      endpoint :children

      resource :placename

      param :geoname_id
      param :max_rows, as: :limit, optional: true

      def geoname_id
        placename.geoname_id
      end

      def limit
        option(:limit) || placename.number_of_children
      end
    end

    RSpec.describe Dummy do
      let(:endpoint) { Dummy.new(placename, limit: 5) }
      let(:placename) {
        double('Placename', geoname_id: 1827)
      }

      describe '#name' do
        subject { endpoint.name }

        it { is_expected.to eql(:children) }
      end

      describe '#limit' do
        subject { endpoint.limit }

        it { is_expected.to eql(5) }
      end

      describe '#params' do
        subject { endpoint.params }

        it {
          is_expected.to eql(
            geoname_id: 1827,
            max_rows: 5,
          )
        }
      end

      describe '#placename' do
        subject { endpoint.placename }

        it { is_expected.to eql(placename) }
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.jukusoft.libgdx.rpg.engine.hud;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.jukusoft.libgdx.rpg.engine.game.BaseGame;
import com.jukusoft.libgdx.rpg.engine.time.GameTime;

/**
 * Created by Justin on 08.02.2017.
 */
public interface HUDWidget {

    public void update (BaseGame game, GameTime time);

    public void drawLayer0 (GameTime time, SpriteBatch batch);

    public void drawLayer1 (GameTime time, ShapeRenderer shapeRenderer);

    public void drawLayer2 (GameTime time, SpriteBatch batch);

    public float getX ();

    public float getY ();

    public void setPosition (float x, float y);

    public void onMoveGroup (float groupX, float groupY);

    public void dispose ();

}


text:
package org.wso2.carbon.device.mgt.core.dto.operation.mgt;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.Properties;

public class Operation implements Serializable {

	public enum Type {
		CONFIG, MESSAGE, INFO, COMMAND, PROFILE , POLICY
	}

    public enum Status {
        IN_PROGRESS, PENDING, COMPLETED, ERROR
    }

    private String code;
    private Properties properties;
    private Type type;
    private int id;
    private Status status;
    private String receivedTimeStamp;
    private String createdTimeStamp;
    private boolean isEnabled;
    private Object payLoad;
    private Object operationResponse;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public int getId() {
        return id;
    }

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

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public String getReceivedTimeStamp() {
        return receivedTimeStamp;
    }

    public void setReceivedTimeStamp(String receivedTimeStamp) {
        this.receivedTimeStamp = receivedTimeStamp;
    }

    public String getCreatedTimeStamp() {
        return createdTimeStamp;
    }

    public void setCreatedTimeStamp(String createdTimeStamp) {
        this.createdTimeStamp = createdTimeStamp;
    }

    public boolean isEnabled() {
        return isEnabled;
    }

    public void setEnabled(boolean isEnabled) {
        this.isEnabled = isEnabled;
    }

    public Object getPayLoad() {
        return payLoad;
    }

    public void setPayLoad(Object payLoad) {
        this.payLoad = payLoad;
    }

    public Object getOperationResponse() {
        return operationResponse;
    }

    public void setOperationResponse(Object operationResponse) {
        this.operationResponse = operationResponse;
    }

}


text:
<!doctype html>

		<meta charset="UTF-8" />
		<title>Kenny Social Network - Home</title>

Kenny Social Network

						Home

						Profile

						Friends

Welcome to the Kenny Social Network

Here you can find friends or stalk strangers.

The Kenny Social Network does not take any responsibility for the information found.


text:
import sys,string,os
sys.path.insert(1, os.path.join(sys.path[0], '..')) ### import parent dir dependencies

import scipy, numpy
import statistics
from visualization_scripts import clustering

def evaluateMultiLinRegulatoryStructure(all_genes_TPM,MarkerFinder,SignatureGenes,state=None,query=None):
    all_indexes, group_index, expressionData = loopThroughEachState(all_genes_TPM)

    if state!=None:
        states = [state] ### For example, we only want to look in annotated Multi-Lin's
    else:
        states = group_index
    state_scores=[]

    for state in states:
        print '\n',state, 'running now.'
        score = evaluateStateRegulatoryStructure(expressionData,all_indexes,group_index,MarkerFinder,SignatureGenes,state,query=query)
        state_scores.append([score,state])
        print state, score
    state_scores.sort()
    state_scores.reverse()
    print state_scores

def loopThroughEachState(all_genes_TPM):
    ### Import all genes with TPM values for all cells
    matrix, column_header, row_header, dataset_name, group_db = clustering.importData(all_genes_TPM)
    group_index={}
    all_indexes=[]
    for sampleName in group_db:
        ICGS_state = group_db[sampleName][0]
        try: group_index[ICGS_state].append(column_header.index(sampleName))
        except Exception: group_index[ICGS_state] = [column_header.index(sampleName)]
        all_indexes.append(column_header.index(sampleName))
    for ICGS_state in group_index:
        group_index[ICGS_state].sort()
    all_indexes.sort()
    expressionData = matrix, column_header, row_header, dataset_name, group_db
    return all_indexes, group_index, expressionData

def evaluateStateRegulatoryStructure(expressionData, all_indexes,group_index,MarkerFinder,SignatureGenes,state,query=None):
    """Predict multi-lineage cells and their associated coincident lineage-defining TFs"""

    useProbablityOfExpression=False
    ICGS_State_as_Row = False

    matrix, column_header, row_header, dataset_name, group_db = expressionData

    def importGeneLists(fn):
        genes={}
        for line in open(fn,'rU').xreadlines():
            data = clustering.cleanUpLine(line)
            gene,cluster = string.split(data,'\t')[0:2]
            genes[gene]=cluster
        return genes

    def importMarkerFinderHits(fn):
        genes={}
        ICGS_State_ranked={}
        skip=True
        for line in open(fn,'rU').xreadlines():
            data = clustering.cleanUpLine(line)
            if skip: skip=False
            else:
                try:
                    gene,symbol,rho,ICGS_State = string.split(data,'\t')
                except Exception:
                    gene,symbol,rho,rho_p,ICGS_State = string.split(data,'\t')
                #if ICGS_State!=state and float(rho)>0.0:
                if float(rho)>0.15:
                    try: ICGS_State_ranked[ICGS_State].append([float(rho),gene,symbol])
                    except Exception: ICGS_State_ranked[ICGS_State] = [[float(rho),gene,symbol]]

        for ICGS_State in ICGS_State_ranked:
            ICGS_State_ranked[ICGS_State].sort()
            ICGS_State_ranked[ICGS_State].reverse()
            #print ICGS_State, ICGS_State_ranked[ICGS_State][:50]
            for (rho,gene,symbol) in ICGS_State_ranked[ICGS_State][:50]:
                genes[gene]=rho,ICGS_State ### Retain all population specific genes (lax)
                genes[symbol]=rho,ICGS_State
        return genes

    def importQueryDataset(fn):
        matrix, column_header, row_header, dataset_name, group_db = clustering.importData(fn)
        return matrix, column_header, row_header, dataset_name, group_db

    signatureGenes = importGeneLists(SignatureGenes)
    markerFinderGenes = importMarkerFinderHits(MarkerFinder)
    #print len(signatureGenes),len(markerFinderGenes)

    ### Determine for each gene, its population frequency per cell state
    index=0
    expressedGenesPerState={}
    stateAssociatedMarkers={}

    def freqCutoff(x,cutoff):
        if x>cutoff: return 1 ### minimum expression cutoff
        else: return 0

    for row in matrix:
        ICGS_state_gene_frq={}
        gene = row_header[index]
        for ICGS_state in group_index:
            state_values = map(lambda i: row[i],group_index[ICGS_state])
            def freqCheck(x):
                if x>1: return 1 ### minimum expression cutoff
                else: return 0

            expStateCells = sum(map(lambda x: freqCheck(x),state_values))
            statePercentage = (float(expStateCells)/len(group_index[ICGS_state]))
            ICGS_state_gene_frq[ICGS_state] = statePercentage

        datasets_values = map(lambda i: row[i],all_indexes)
        all_cells_frq = sum(map(lambda x: freqCheck(x),datasets_values))/(len(datasets_values)*1.0)
        all_states_frq = map(lambda x: ICGS_state_gene_frq[x],ICGS_state_gene_frq)
        all_states_frq.sort() ### frequencies of all non-multilin states
        states_expressed = sum(map(lambda x: freqCutoff(x,0.5),all_states_frq))/(len(all_states_frq)*1.0)

        for State in ICGS_state_gene_frq:
            state_frq = ICGS_state_gene_frq[State]
            rank = all_states_frq.index(state_frq)
            if state_frq > 0.25 and rank>0: #and states_expressed<0.75 #and all_cells_frq>0.75
                if 'Rik' not in gene and 'Gm' not in gene and '-' not in gene:
                    if gene in markerFinderGenes:# and gene in markerFinderGenes:
                        if ICGS_State_as_Row:
                            ICGS_State = signatureGenes[gene]
                        if gene in markerFinderGenes:
                            if ICGS_State_as_Row == False:
                                rho, ICGS_State = markerFinderGenes[gene]
                            else:
                                rho, ICGS_Cell_State = markerFinderGenes[gene] #ICGS_Cell_State
                            score = int(rho*100*state_frq)*(float(rank)/len(all_states_frq))
                            try: expressedGenesPerState[ICGS_State].append((score,gene))
                            except Exception: expressedGenesPerState[ICGS_State]=[(score,gene)] #(rank*multilin_frq)
                            try: stateAssociatedMarkers[gene,ICGS_State].append(State)
                            except Exception: stateAssociatedMarkers[gene,ICGS_State] = [State]
        index+=1

    if query!=None:
        matrix, column_header, row_header, dataset_name, group_db = importQueryDataset(query)

    markers_to_exclude=[]
    expressedGenesPerState2={}
    for (gene,ICGS_State) in stateAssociatedMarkers:
        if len(stateAssociatedMarkers[(gene,ICGS_State)])<2: # or len(stateAssociatedMarkers[(gene,ICGS_State)])>len(ICGS_state_gene_frq)/2.0:
            markers_to_exclude.append(gene)
        else:
            print ICGS_State, gene, stateAssociatedMarkers[(gene,ICGS_State)]
    for ICGS_State in expressedGenesPerState:
        for (score,gene) in expressedGenesPerState[ICGS_State]:
            if gene not in markers_to_exclude:
                try: expressedGenesPerState2[ICGS_State].append((score,gene))
                except Exception: expressedGenesPerState2[ICGS_State] = [(score,gene)]
    expressedGenesPerState = expressedGenesPerState2

    createPseudoCell=True
    ### The expressedGenesPerState defines genes and modules co-expressed in the multi-Lin
    ### Next, find the cells that are most frequent in mulitple states
    representativeMarkers={}
    for ICGS_State in expressedGenesPerState:
        expressedGenesPerState[ICGS_State].sort()
        expressedGenesPerState[ICGS_State].reverse()
        if '1Multi' not in ICGS_State:
            markers = expressedGenesPerState[ICGS_State]#[:5]
            markers_unique = list(set(map(lambda x: x[1],list(markers))))
            print ICGS_State,":",string.join(markers_unique,', ')
            if createPseudoCell:
                for gene in markers:
                    def getBinary(x):
                        if x>1: return 1
                        else: return 0
                    if gene[1] in row_header: ### Only for query datasets
                        row_index = row_header.index(gene[1])
                        if useProbablityOfExpression:
                            pvalues = calculateGeneExpressProbilities(matrix[row_index]) ### probability of expression
                            values = pvalues
                        else:
                            binaryValues = map(lambda x: getBinary(x), matrix[row_index])
                            values = binaryValues
                        #if gene[1]=='S100a8': print binaryValues;sys.exit()
                        try: representativeMarkers[ICGS_State].append(values)
                        except Exception: representativeMarkers[ICGS_State] = [values]
            else:
                representativeMarkers[ICGS_State]=markers[0][-1]
        #int(len(markers)*.25)>5:
        #print ICGS_State, markers
    #sys.exit()

    for ICGS_State in representativeMarkers:
        if createPseudoCell:
            signature_values = representativeMarkers[ICGS_State]
            if useProbablityOfExpression:
                signature_values = [numpy.median(value) for value in zip(*signature_values)]
            else:
                signature_values = [int(numpy.median(value)) for value in zip(*signature_values)]
            representativeMarkers[ICGS_State] = signature_values
        else:
            gene = representativeMarkers[ICGS_State]
            row_index = row_header.index(gene)
            gene_values = matrix[row_index]
            representativeMarkers[ICGS_State] = gene_values

    ### Determine for each gene, its population frequency per cell state
    expressedStatesPerCell={}
    multilin_probability={}
    import export
    print 'Writing results matrix to:',MarkerFinder[:-4]+'-cellStateScores.txt'
    eo = export.ExportFile(MarkerFinder[:-4]+'-cellStateScores.txt')
    eo.write(string.join(['UID']+column_header,'\t')+'\n')
    for ICGS_State in representativeMarkers:
        gene_values = representativeMarkers[ICGS_State]
        index=0
        scoreMatrix=[]
        HitsCount=0
        for cell in column_header:
            value = gene_values[index]
            expressedLiklihood = '0'
            if (value<0.05 and useProbablityOfExpression==True) or (value==1 and useProbablityOfExpression==False):
                try: expressedStatesPerCell[cell].append(ICGS_State)
                except Exception: expressedStatesPerCell[cell] = [ICGS_State]
                expressedLiklihood = '1'
                HitsCount+=1
            if useProbablityOfExpression:
                try: multilin_probability[cell].append(value)
                except Exception: multilin_probability[cell] = [value]
            index+=1
            scoreMatrix.append(expressedLiklihood)
        if HitsCount>1:
            #print ICGS_State,HitsCount
            eo.write(string.join([ICGS_State]+scoreMatrix,'\t')+'\n')
    eo.close()

    def multiply(values):
        p = 1
        for i in values:
            if i>0:
                p = p*i
            else:
                p = p*1.e-16
        return p

    ### Compute a matrix of Cell-State to LineagePotential
    eo = export.ExportFile(MarkerFinder[:-4]+'-primingMatrix.txt')
    cell_state_matrix = {}
    lineages = []
    cell_population_count = {}
    for cell in expressedStatesPerCell:
        cell_state = string.split(cell,':')[0]
        #print cell, cell_state; sys.exit()
        try: cell_population_count[cell_state]+=1
        except: cell_population_count[cell_state]=1
        if cell_state not in lineages:
            lineages.append(cell_state)
        primed_lineages = expressedStatesPerCell[cell]
        for primed_lineage in primed_lineages:
            if cell_state not in cell_state_matrix:
                priming_count={}
                priming_count[primed_lineage]=1
                cell_state_matrix[cell_state] = priming_count
            else:
                priming_count = cell_state_matrix[cell_state]
                try: priming_count[primed_lineage]+=1
                except: priming_count[primed_lineage]=1
    eo.write(string.join(['Cell Populations']+lineages,'\t')+'\n')
    for cell_state in lineages:
        priming_count_db = cell_state_matrix[cell_state]
        sum_scores = []
        for cell_state2 in lineages:
            if cell_state2 in priming_count_db:
                sum_score = priming_count_db[cell_state2]
                sum_scores.append((sum_score*1.000/cell_population_count[cell_state2]))
            else:
                sum_scores.append(0)
        eo.write(string.join([cell_state]+map(str,sum_scores),'\t')+'\n')
    eo.close()

    cell_mutlilin_ranking=[]
    for cell in expressedStatesPerCell:
        #if 'Multi-Lin:Gmp.R3.10' in cell: sys.exit()
        if useProbablityOfExpression:
            p = numpy.mean(multilin_probability[cell]) ### mean state probability
        lineageCount = expressedStatesPerCell[cell]
        if useProbablityOfExpression:
            cell_mutlilin_ranking.append((p,len(lineageCount),cell))
        else:
            cell_mutlilin_ranking.append((len(lineageCount),cell))
    cell_mutlilin_ranking.sort()
    if useProbablityOfExpression == False:
        cell_mutlilin_ranking.reverse()

    scores = []
    state_scores={}
    cellsPerState={} ### Denominator for z-score analysis
    for cell in cell_mutlilin_ranking:
        score = cell[0]
        scores.append(score)
        cell_state = string.split(cell[-1],':')[0]
        try: cellsPerState[cell_state]+=1
        except Exception: cellsPerState[cell_state]=1
        try: state_scores[cell_state].append(float(score))
        except Exception: state_scores[cell_state] = [float(score)]

    scoreMean = numpy.mean(scores)
    scoreSD = numpy.std(scores)
    oneSD = scoreMean+scoreSD
    twoSD = scoreMean+scoreSD+scoreSD
    oneStandDeviationAway={}
    twoStandDeviationsAway={}
    oneStandDeviationAwayTotal=0
    twoStandDeviationsAwayTotal=0

    print 'Mean:',scoreMean
    print 'STDev:',scoreSD
    state_scores2=[]
    for cell_state in state_scores:
        state_scores2.append((numpy.mean(state_scores[cell_state]),cell_state))
    i=0

    print 'Writing results matrix to:',MarkerFinder[:-4]+'-cell-combined-scores.txt'
    eo = export.ExportFile(MarkerFinder[:-4]+'-cell-combined-score.txt')

    for cell in cell_mutlilin_ranking:
        score,cellName = cell
        CellState,CellName = string.split(cellName,':')
        if score>=oneSD:
            try: oneStandDeviationAway[CellState]+=1
            except Exception: oneStandDeviationAway[CellState]=1
            oneStandDeviationAwayTotal+=1
            if score>=twoSD:
                try: twoStandDeviationsAway[CellState]+=1
                except Exception: twoStandDeviationsAway[CellState]=1
                twoStandDeviationsAwayTotal+=1
            #print cell, string.join(expressedStatesPerCell[cell[-1]],'|')
            a = expressedStatesPerCell[cell[-1]]
            eo.write(str(cell[1])+'\t'+str(cell[0])+'\t'+'\n')
        i+=1
    state_scores2
    state_scores2.sort()
    state_scores2.reverse()
    eo.close()

    twoStandDeviationsAway = oneStandDeviationAway
    twoStandDeviationsAwayTotal = oneStandDeviationAwayTotal

    print '\n\n'
    import statistics
    zscores = []
    for CellState in twoStandDeviationsAway:
        #print CellState
        highMetaScoreCells = twoStandDeviationsAway[CellState]
        totalCellsPerState = cellsPerState[CellState]
        r = highMetaScoreCells
        n = twoStandDeviationsAwayTotal
        R = totalCellsPerState
        N = len(column_header)
        z = statistics.zscore(r,n,N,R)
        scores = [z, CellState,statistics.p_value(z)]
        zscores.append(scores)

    zscores.sort()
    zscores.reverse()
    for scores in zscores:
        scores = string.join(map(str,scores),'\t')
        print scores

    """
    for i in state_scores2:
        print str(i[0])+'\t'+str(i[1])"""
    sys.exit()
    return numpy.mean(state_scores)

def calculateGeneExpressProbilities(values, useZ=False):
    ### First calculate z-scores - scipy.stats.mstats.zscore for the entire matrix
    avg = numpy.mean(values)
    std = numpy.std(values)
    if std ==0:
        std = 0.1
    if useZ:
        values = map(lambda x: (x-avg)/std,values)
    else:
        values = map(lambda x: x*2,values)
    p_values = 1 - scipy.special.ndtr(values)
    return p_values

if __name__ == '__main__':
    #query_dataset = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/Mm_Gottgens_3k-scRNASeq/ExpressionInput/exp.GSE81682_HTSeq-cellHarmony-filtered.txt'
    all_tpm = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/BoneMarrow/ExpressionInput/exp.BoneMarrow-scRNASeq.txt'
    markerfinder = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/BoneMarrow/ExpressionOutput/MarkerFinder/AllGenes_correlations-ReplicateBased.txt'
    signature_genes = '/Users/saljh8/Desktop/Old Mac/Desktop/Grimes/KashishNormalization/test/Panorama.txt'
    state = 'DC'

    all_tpm = '/Users/saljh8/Desktop/dataAnalysis/Collaborative/Grimes/All-Fluidigm/updated.8.29.17/ExpressionInput/exp.Guide3-cellHarmony-revised.txt'
    #markerfinder = '/Users/saljh8/Desktop/dataAnalysis/Collaborative/Grimes/All-Fluidigm/updated.8.29.17/ExpressionOutput/MarkerFinder/AllGenes_correlations-ReplicateBased.txt'
    signature_genes = '/Users/saljh8/Desktop/Old Mac/Desktop/Grimes/KashishNormalization/test/Panorama.txt'

    query_dataset = None
    query_dataset = '/Users/saljh8/Desktop/dataAnalysis/Collaborative/Grimes/All-Fluidigm/exp.NaturePan-PreGM-CD150-.txt'
    query_dataset = None
    """
    #all_tpm = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/Mm_Gottgens_3k-scRNASeq/ExpressionInput/MultiLin/exp.Gottgens_HarmonizeReference.txt'
    all_tpm = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/Mm_Gottgens_3k-scRNASeq/MultiLin/ExpressionInput/exp.Gottgens_HarmonizeReference.txt'
    #signature_genes = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/Mm_Gottgens_3k-scRNASeq/MultiLin/ExpressionInput/Gottgens_HarmonizeReference.txt'
    signature_genes = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/Mm_Gottgens_3k-scRNASeq/MultiLin/Gottgens_HarmonizeReference.txt'
    #markerfinder = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/Mm_Gottgens_3k-scRNASeq/ExpressionOutput/MarkerFinder/AllGenes_correlations-ReplicateBased.txt'
    markerfinder = '/Users/saljh8/Desktop/Old Mac/Desktop/demo/Mm_Gottgens_3k-scRNASeq/MultiLin/ExpressionInput/MarkerFinder/AllGenes_correlations-ReplicateBased.txt'
    state = 'Eryth_Multi-Lin'
    """
    state = None
    import getopt
    options, remainder = getopt.getopt(sys.argv[1:],'', ['q=','expdir=','m=','ICGS=','state='])
    #print sys.argv[1:]
    for opt, arg in options:
        if opt == '--q': query_dataset=arg
        elif opt == '--expdir': all_tpm=arg
        elif opt == '--m': markerfinder=arg
        elif opt == '--ICGS': signature_genes=arg
        elif opt == '--state': state=arg

    #state = None
    #evaluateMultiLinRegulatoryStructure(all_tpm,markerfinder,signature_genes,state);sys.exit()

    evaluateMultiLinRegulatoryStructure(all_tpm,markerfinder,signature_genes,state,query = query_dataset);sys.exit()


text:
/**
 * @author dgeorge
 *
 * $Id: NutritionalFactorData.java,v 1.1 2005-09-28 21:20:25 georgeda Exp $
 *
 * $Log: not supported by cvs2svn $
 *
 */
package gov.nih.nci.camod.webapp.form;

import gov.nih.nci.camod.webapp.form.cibase.*;

/**
 * Nutritional factor interface for CI screen
 */
public interface NutritionalFactorData  extends NameData, DoseData, AgeGenderData, TreatmentData {

}


text:
using System.Text.Json;
using Azure.Core;
using Azure.Search.Documents.Models;

namespace Azure.Search.Documents.Indexes.Models
{
    public partial class LexicalAnalyzer : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("@odata.type");
            writer.WriteStringValue(ODataType);
            writer.WritePropertyName("name");
            writer.WriteStringValue(Name);
            writer.WriteEndObject();
        }

        internal static LexicalAnalyzer DeserializeLexicalAnalyzer(JsonElement element)
        {
            if (element.TryGetProperty("@odata.type", out JsonElement discriminator))
            {
                switch (discriminator.GetString())
                {
                    case "#Microsoft.Azure.Search.CustomAnalyzer": return CustomAnalyzer.DeserializeCustomAnalyzer(element);
                    case "#Microsoft.Azure.Search.PatternAnalyzer": return PatternAnalyzer.DeserializePatternAnalyzer(element);
                    case "#Microsoft.Azure.Search.StandardAnalyzer": return LuceneStandardAnalyzer.DeserializeLuceneStandardAnalyzer(element);
                    case "#Microsoft.Azure.Search.StopAnalyzer": return StopAnalyzer.DeserializeStopAnalyzer(element);
                }
            }
            return UnknownLexicalAnalyzer.DeserializeUnknownLexicalAnalyzer(element);
        }
    }
}


text:
package Paws::IoT::GetPolicyResponse;
  use Moose;
  has DefaultVersionId => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'defaultVersionId');
  has PolicyArn => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'policyArn');
  has PolicyDocument => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'policyDocument');
  has PolicyName => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'policyName');

  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::IoT::GetPolicyResponse

=head1 ATTRIBUTES

=head2 DefaultVersionId => Str

The default policy version ID.

=head2 PolicyArn => Str

The policy ARN.

=head2 PolicyDocument => Str

The JSON document that describes the policy.

=head2 PolicyName => Str

The policy name.

=head2 _request_id => Str

=cut


text:
@implementation STSwipeInteraction

- (instancetype)init{
    if (self = [super init]){
        _direction = STDirectionHorizontal;
        _reverse = NO;
    }
    return self;
}

- (Class)gestureRecognizerClass{
    return [UIPanGestureRecognizer class];
}

- (void)handlerGesture:(UIPanGestureRecognizer *)gesture{
    CGFloat progress;
    if (_direction == STDirectionHorizontal){
        progress = [gesture translationInView:self.viewController.view.superview].x / (self.viewController.view.superview.bounds.size.width * 1);
    }
    else{
        progress = [gesture translationInView:self.viewController.view.superview].y / (self.viewController.view.superview.bounds.size.height * 1);
    }
    progress = MIN(1.0, MAX(0.0, progress*(_reverse?-1:1)));

    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:{
            CGFloat shouldBeginOffset = (_direction == STDirectionHorizontal)?[gesture translationInView:self.viewController.view].x:[gesture translationInView:self.viewController.view].y;
            if (_reverse?(shouldBeginOffset<0):(shouldBeginOffset>0)){
                if (STTransitionPop == self.type){
                    self.onInteractiving = YES;
                    [self.viewController.navigationController popViewControllerAnimated:YES];
                }
                else if (STTransitionDismiss == self.type){
                    self.onInteractiving = YES;
                    [self.viewController dismissViewControllerAnimated:YES completion:nil];
                }
            }
            break;
        }
        case UIGestureRecognizerStateChanged:{
            [self updateInteractiveTransition:progress];
            break;
        }
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:{
            if (self.onInteractiving){
                CGPoint v = [gesture velocityInView:self.viewController.view.superview];
                BOOL shouldFinished = NO;
                CGFloat maxV = 500;
                if (_reverse){
                    if (_direction == STDirectionHorizontal){
                        shouldFinished = v.x<-maxV;
                    }
                    else{
                        shouldFinished = v.y<-maxV;
                    }
                }
                else{
                    if (_direction == STDirectionHorizontal){
                        shouldFinished = v.x>maxV;
                    }
                    else{
                        shouldFinished = v.y>maxV;
                    }
                }

                if (progress > 0.43 || shouldFinished) {
                    [self finishInteractiveTransition];
                }
                else {
                    [self cancelInteractiveTransition];
                }
                self.onInteractiving = NO;
            }
            break;
        }
        default:
            break;
    }
}

@end


text:
package com.lightcrafts.ui.browser.ctrls;

import com.lightcrafts.platform.Platform;
import static com.lightcrafts.ui.browser.ctrls.Locale.LOCALE;
import com.lightcrafts.ui.browser.view.AbstractImageBrowser;
import com.lightcrafts.ui.browser.view.ImageBrowserActions;
import com.lightcrafts.ui.toolkit.CoolButton;
import com.lightcrafts.prefs.ApplicationMode;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

/**
 * A button that triggers a popup menu of rating actions for a browser.
 */
public class RatingButton extends CoolButton {

    private final static String ToolTip = LOCALE.get("RateButtonToolTip");
    // private final static String Star = "\u2605";

    private final static Icon starIcon =
        ButtonFactory.getIconByName("star");

    private JPopupMenu popup;

    public RatingButton(AbstractImageBrowser browser) {
        // setText(Star);
        setIcon(starIcon);
        setToolTipText(ToolTip);

        ApplicationMode.maybeSetToolTip(this);

        popup = new JPopupMenu();

        ImageBrowserActions actions = browser.getActions();
        List<Action> rateActions = actions.getRatingActions();
        for (Action rateAction : rateActions) {
            JMenuItem item = new JMenuItem(rateAction);
            // On Windogs only the core fonts seem to see stars
            if (Platform.getType() == Platform.Windows)
                item.setFont(new Font("Serif", Font.PLAIN, 14));
            item.setAccelerator(null);
            popup.add(item);
        }
        popup.addSeparator();

        Action clearAction = actions.getClearRatingAction();
        JMenuItem item = new JMenuItem(clearAction);
        item.setAccelerator(null);
        popup.add(item);

        // Show the popup on mouse-pressed, not on action-performed.
        // (But not in Basic mode.)
        if (! ApplicationMode.isBasicMode()) {
            addMouseListener(
                new MouseAdapter() {
                    public void mousePressed(MouseEvent event) {
                        Dimension size = RatingButton.this.getSize();
                        popup.show(RatingButton.this, 0, size.height);
                    }
                }
            );
        }
        // Enable and disable this button with one of the actions, which
        // follow the browser selection.
        clearAction.addPropertyChangeListener(
            new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent event) {
                    String propName = event.getPropertyName();
                    if (propName.equals("enabled")) {
                        boolean enabled = (Boolean) event.getNewValue();
                        setEnabled(enabled);
                        repaint();
                    }
                }
            }
        );
        setEnabled(clearAction.isEnabled());
    }
}


text:
 0">

			сохранено: {{count()}}

			{{li != '' ? li : 'Все'}}


text:
<?php
  // start session
  session_start ();

  // set actual page session variable
  $_SESSION["act_page"] = "priv_del_obj_search";

  // start session, check if the user is already logged in and if he is a superuser or not
  include ("../check_user.inc");
  include ("../library_functions.inc");

  // check if the logged-in is a superuser
  if (!$user_superuser && isset($_SESSION["user_id"])){
    header("Location: ../User/sti_library.php?error=1");
    exit;
  } // end if
?>

<!doctype html public "-//W3C//DTD HTML 4.01//EN">

    <title>STI-Innsbruck Library</title>

    <meta http-equiv="keywords" content="STI-Innsbruck - Library" />
	<meta http-equiv="generator" content="PHP Designer 2005" />
	<meta http-equiv="author" content="Nathalie Steinmetz" />
    <meta http-equiv="Content-Style-Type" content="text/css">

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

  <?php
    // including vertical menue
    include("menue1.inc");
  ?>

      STI-Innsbruck Library > Privileged functions > Delete object - Search & list

  <?php
    // including vertical menue
    include("menue2.inc");
  ?>

Delete object - Object search

                  <form action = "del_obj_list.php" method = "post">

signature

                       <input type="text" name="signature" value="" size="30" maxlength="15">

title

                       <input type="text" name="title" value="" size="30" maxlength="250">

status

                        <select name ="status" size="1">
                          <option selected></option>
                          <option> new </option>
                          <option> available </option>
                          <option> not available </option>
                          <option> checked out </option>
                          <option> missing </option>
                        </select>

                       <input type="submit" value="  Search  ">
                       <input type="reset" value="  Reset form  ">

                  </form>

Delete object - Object list

                <?php

                  // start database connection for the superuser, with error handling
                  $db = mysql_connect("localhost", "librarySuperuser", "superuser");
                  if (!mysql_select_db ("stilibrary", $db)){
                    die ("Connection to database failed - superuser");
                  } // end if

                  // write values to session variables
                  $_SESSION["act_del_obj_page"] = "search";

                  // send select publication query to database
                  $res = mysql_db_query("stilibrary", "SELECT pid, author, title, year, signature, status FROM publication ORDER BY title;");
                  if (mysql_errno() != 0) {
                    // logging function call
                    $string = "Error: sqlSelectObj: " . mysql_errno() . ": " . mysql_error(). "\n";
                    library_log($string);
                    echo ("Database error! - Please see log file for detailed information.

");
                  } // end if

                  // get number of results
                  $num = mysql_num_rows($res);
                  if ($num > 0) {
                    echo "
";
                    echo "
";
                    echo "
title
 	";
                    echo "
author
 	";
                    echo "
year
 	";
                    echo "
signature
 	";
                    echo "
status
 	";
                    echo "
";
                    $color=1;     // variable to indicate how to style a row
                    for ($i=0; $i<$num; $i++)
                    {
                      // extract publication results
                      $pid = mysql_result($res, $i, "pid");
                      $author = mysql_result($res, $i, "author");
                      if ($author == "NULL")
                        $author="";
                      $title = mysql_result($res, $i, "title");
                      $year = mysql_result($res, $i, "year");
                      if (($year == "NULL") || ($year == "0000"))
                        $year="";
                      $signature = mysql_result($res, $i, "signature");
                      $status = mysql_result($res, $i, "status");
                      // begin row and indicate color (class row)
                        if ($color) {
                          echo "
";
                          $color=0;
                        } // end if
                        else {
                          echo "
";
                          $color=1;
                        } // end else
                      echo "  $title  	";
                      echo " $author 	";
                      echo " $year 	";
                      echo "  $signature 	";
                      echo " $status 	";
                      echo "
";
                    } // end for
                    echo "
";
                  } // end if
                  else
                    echo "

 No objects found!

";

                  // close database connection
                  mysql_close($db);
                ?>

    <?php
      // including links
      include("menue3.inc");
    ?>


text:
"""
Traditional Django model fields, except their type is
explicitly `text` as opposed to `varchar`. All other
validations and behaviors are identical.

The reason this exists is because in Postgres, `text`
and `varchar` are nearly identical. The issue is when
picking a CharField and needing to size up the length
needing a database migration. Typically the database
validation isn't strictly required, so we can use
`text` type instead to only enforce the length in
python to allow us to size up the lengths without any
migrations.
"""

from __future__ import absolute_import

from django.db import models

__all__ = ("CharField", "EmailField")

class TextType(object):
    def db_type(self, connection):
        return "text"

class CharField(TextType, models.CharField):
    pass

class EmailField(TextType, models.EmailField):
    pass


text:
cd source
make

mkdir -p $PREFIX/bin

cp readal $PREFIX/bin
cp statal $PREFIX/bin
cp trimal $PREFIX/bin


text:
<!doctype html>

    <title></title>
    <link rel="stylesheet" href="assets/bootstrap/dist/css/bootstrap.css" />

Clint Walker's Site test

                <button type="button" class="btn btn-default">Login</button>
                <button type="button" class="btn btn-default">Register</button>

                        {{item.title}}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="Markup Rocks is an open source browser based document editor and converter.">
    <meta name="keywords" content="Markdown, Org-mode, LaTeX, Markup Rocks, Editor, CodeMirror, Github, Open Source, Haskell, GHCJS, Pandoc">
    <meta name="author" content="Ozan Sener">

    <title>markup.rocks</title>

    <link rel="apple-touch-icon" sizes="57x57" href="/static/icon/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/static/icon/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/static/icon/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/static/icon/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/static/icon/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/static/icon/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/static/icon/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/static/icon/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/static/icon/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="/static/icon/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/static/icon/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/static/icon/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/static/icon/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/static/icon/manifest.json">
    <link rel="shortcut icon" href="/static/icon/favicon.ico">
    <meta name="apple-mobile-web-app-title" content="markup.rocks">
    <meta name="application-name" content="markup.rocks">
    <meta name="msapplication-TileColor" content="#2d89ef">
    <meta name="msapplication-TileImage" content="/static/icon/mstile-144x144.png">
    <meta name="msapplication-config" content="/static/icon/browserconfig.xml">
    <meta name="theme-color" content="#ffffff">

    <link href='http://fonts.googleapis.com/css?family=Droid+Sans+Mono|Source+Sans+Pro:400,400italic,600,600italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="/static/style.css">

              Markdown

# Loading

*(2.2 MB total)*

              Preview

              Loading

(2.2 MB total)


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Just the Form</title>

    <form>
    <fieldset class="no-legend">
        <legend>Contact</legend>

                Your Name
                <input type="text" class="field" id="orderName" required
                    autofocus placeholder="ex. Hugo Reyes" />

    </fieldset>
    </form>


text:
package edu.uci.ics.hyracks.data.std.primitive;

import edu.uci.ics.hyracks.api.dataflow.value.ITypeTraits;
import edu.uci.ics.hyracks.data.std.api.AbstractPointable;
import edu.uci.ics.hyracks.data.std.api.IComparable;
import edu.uci.ics.hyracks.data.std.api.IHashable;
import edu.uci.ics.hyracks.data.std.api.INumeric;
import edu.uci.ics.hyracks.data.std.api.IPointable;
import edu.uci.ics.hyracks.data.std.api.IPointableFactory;

public final class BytePointable extends AbstractPointable implements IHashable, IComparable, INumeric {
    public static final ITypeTraits TYPE_TRAITS = new ITypeTraits() {
        private static final long serialVersionUID = 1L;

        @Override
        public boolean isFixedLength() {
            return true;
        }

        @Override
        public int getFixedLength() {
            return 1;
        }
    };

    public static final IPointableFactory FACTORY = new IPointableFactory() {
        private static final long serialVersionUID = 1L;

        @Override
        public IPointable createPointable() {
            return new BytePointable();
        }

        @Override
        public ITypeTraits getTypeTraits() {
            return TYPE_TRAITS;
        }
    };

    public static byte getByte(byte[] bytes, int start) {
        return bytes[start];
    }

    public static void setByte(byte[] bytes, int start, byte value) {
        bytes[start] = value;
    }

    public byte getByte() {
        return getByte(bytes, start);
    }

    public void setByte(byte value) {
        setByte(bytes, start, value);
    }

    public byte preIncrement() {
        byte v = getByte();
        ++v;
        setByte(v);
        return v;
    }

    public byte postIncrement() {
        byte v = getByte();
        byte ov = v++;
        setByte(v);
        return ov;
    }

    @Override
    public int compareTo(IPointable pointer) {
        return compareTo(pointer.getByteArray(), pointer.getStartOffset(), pointer.getLength());
    }

    @Override
    public int compareTo(byte[] bytes, int start, int length) {
        byte b = getByte();
        byte ob = getByte(bytes, start);
        return b < ob ? -1 : (b > ob ? 1 : 0);
    }

    @Override
    public int hash() {
        return getByte();
    }

    @Override
    public byte byteValue() {
        return getByte();
    }

    @Override
    public short shortValue() {
        return getByte();
    }

    @Override
    public int intValue() {
        return getByte();
    }

    @Override
    public long longValue() {
        return getByte();
    }

    @Override
    public float floatValue() {
        return getByte();
    }

    @Override
    public double doubleValue() {
        return getByte();
    }
}


text:
<!DOCTYPE html>

    <meta charset=utf-8 />
    <title>OSRM Frontend</title>
    <meta name='viewport' content='initial-scale=1.0 maximum-scale=1.0'>
    <link rel="shortcut icon" href="favicon.ico" />
    <link rel="stylesheet" href="../bin/map.css" />


text:
#ifndef NEBULA_BASE_FUNC_FACTORY_MANAGER_H_
#define NEBULA_BASE_FUNC_FACTORY_MANAGER_H_

#include <string>
#include <unordered_map>

#include "nebula/base/logger/glog_util.h"

namespace nebula {

//////////////////////////////////////////////////////////////////////////
template<typename F, typename K=std::string>
class FuncFactoryManager {
public:
  ~FuncFactoryManager() {}

  struct RegisterTemplate {
    RegisterTemplate(const K& k, F f) {
      auto& factories = FuncFactoryManager<F, K>::GetInstance().factories_;
      auto it = factories.find(k);
      if (it != factories.end()) {
        LOG(ERROR) << "RegisterTemplate - duplicate entry for key: " << k;
      } else {
        // lambda表达式
        factories.emplace(k, f);
      }
    }

    explicit RegisterTemplate(F f) {
      auto& default_func = FuncFactoryManager<F, K>::GetInstance().default_func_;
      default_func = f;
    }
  };

  template<typename... Args>
  static bool Execute(const K& k, Args... args) {
    auto& factories = GetInstance().factories_;
    auto it = factories.find(k);
    if (it == factories.end()) {
      auto& default_f = GetInstance().default_func_;
      if (default_f) {
        default_f(args...);
        return true;
      } else {
        // TODO(@benqi): 是否需要抛出异常?
        LOG(ERROR) << "Execute - not exist func key: " << k;
        return false;
      }
    } else {
      it->second(args...);
      return true;
    }
  }

  // 执行类成员函数
  template<typename C, typename... Args>
  static bool Execute2(C* c, const K& k, Args... args) {
    auto& factories = GetInstance().factories_;
    auto it = factories.find(k);
    if (it == factories.end()) {
      auto& default_f = GetInstance().default_func_;
      if (default_f) {
        (c->*default_f)(args...);
        return true;
      } else {
        // TODO(@benqi): 是否需要抛出异常?
        LOG(ERROR) << "Execute2 - not exist func key: " << k;
        return false;
      }
    } else {
      // TODO(@benqi): 是否需要抛出异常?
      (c->*it->second)(args...);
      return true;
    }
  }

  // 有返回值
  template<typename... Args>
  static typename std::result_of<F(Args... args)>::type Execute3(const K& k, Args... args) {
    auto& factories = GetInstance().factories_;
    auto it = factories.find(k);
    if (it == factories.end()) {
      LOG(ERROR) << "Execute3 - not exist func key: " << k;
    } else {
    }

    return it->second(args...);
  }

  // 检查是K否存在
  static bool Check(const K& k) {
    auto& factories = GetInstance().factories_;
    return factories.find(k) != factories.end();
  }

private:
  FuncFactoryManager() = default;
  FuncFactoryManager(const FuncFactoryManager&) = delete;
  FuncFactoryManager(FuncFactoryManager&&) = delete;

  static FuncFactoryManager& GetInstance() {
    static FuncFactoryManager g_func_factorys;
    return g_func_factorys;
  }

  std::unordered_map<K, F> factories_;
  F default_func_;      // 默认
};

// template<class F, class K>
// using FuncRegister = FuncFactoryManager<F, K>::RegisterTemplate;

}

#endif // NEBULA_BASE_FUNC_FACTORY_MANAGER_H_


text:
/**
 * Created by greg.kedge on 2/11/16.
 */

/*jshint nonew:true, jquery:true, curly:true, noarg:true, indent:2,
 trailing:true, white:true, forin:true, noempty:true, smarttabs:true,
 eqeqeq:true, strict:true, undef:true, debug:true, bitwise:true,
 browser:true, gcl:true, devel:true */

/* eslint no-multi-spaces: [2, { exceptions: { "VariableDeclarator": true } }]  */
/* eslint key-spacing: [2, { align: "colon" }] */
/* eslint no-underscore-dangle: 0 */

/* global CRISP, jQuery, console */

((function ($) {
    'use strict';

    var NIBRS = window.NIBRS || {};

    NIBRS.namespace = function (name, immediateDefinition) {
        NIBRS.module = NIBRS.module || {};

        var parts = name.split('.'),
            container = NIBRS.module;

        for (var i = 0; i < parts.length; i++) {
            if (i < parts.length - 1 && !container[parts[i]]) {
                container[parts[i]] = {};
            }
            else {
                if (container[parts[i]]) {
                    log.warn('Double module import: ' + name);
                    return;
                }
                container[parts[i]] = immediateDefinition(container, $);
            }
            container = container[parts[i]];
        }
    };

    window.NIBRS = NIBRS;

}))(jQuery);


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Cache;

use PhpCsFixer\Cache\CacheInterface;
use PhpCsFixer\Cache\CacheManagerInterface;
use PhpCsFixer\Cache\FileCacheManager;
use PhpCsFixer\Cache\FileHandlerInterface;
use PhpCsFixer\Cache\SignatureInterface;
use PhpCsFixer\Tests\TestCase;
use Prophecy\Argument;

/**
 * @author Andreas Möller <am@localheinz.com>
 *
 * @internal
 *
 * @covers \PhpCsFixer\Cache\FileCacheManager
 */
final class FileCacheManagerTest extends TestCase
{
    public function testIsFinal(): void
    {
        $reflection = new \ReflectionClass(FileCacheManager::class);

        static::assertTrue($reflection->isFinal());
    }

    public function testImplementsCacheManagerInterface(): void
    {
        $reflection = new \ReflectionClass(FileCacheManager::class);

        static::assertTrue($reflection->implementsInterface(CacheManagerInterface::class));
    }

    public function testCreatesCacheIfHandlerReturnedNoCache(): void
    {
        $signature = $this->prophesize(SignatureInterface::class)->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->shouldBeCalled()->willReturn(null);
        $handlerProphecy->write(Argument::that(static function (CacheInterface $cache) use ($signature): bool {
            return $cache->getSignature() === $signature;
        }))->shouldBeCalled();
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature
        );

        unset($manager);
    }

    public function testCreatesCacheIfCachedSignatureIsDifferent(): void
    {
        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->shouldBeCalled()->willReturn(false);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->shouldBeCalled()->willReturn($cachedSignature);
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->shouldBeCalled()->willReturn($cache);
        $handlerProphecy->write(Argument::that(static function (CacheInterface $cache) use ($signature): bool {
            return $cache->getSignature() === $signature;
        }))->shouldBeCalled();
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature
        );

        unset($manager);
    }

    public function testUsesCacheIfCachedSignatureIsEqual(): void
    {
        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->shouldBeCalled()->willReturn($cachedSignature);
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->shouldBeCalled()->willReturn($cache);
        $handlerProphecy->write(Argument::is($cache))->shouldBeCalled();
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature
        );

        unset($manager);
    }

    public function testNeedFixingReturnsTrueIfCacheHasNoHash(): void
    {
        $file = 'hello.php';
        $fileContent = '<?php echo "Hello!"';

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->has(Argument::is($file))->willReturn(false);
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($this->getFile());
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature
        );

        static::assertTrue($manager->needFixing($file, $fileContent));
    }

    public function testNeedFixingReturnsTrueIfCachedHashIsDifferent(): void
    {
        $file = 'hello.php';
        $fileContent = '<?php echo "Hello!"';
        $previousFileContent = '<?php echo "Hello, world!"';

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->has(Argument::is($file))->willReturn(true);
        $cacheProphecy->get(Argument::is($file))->willReturn(md5($previousFileContent));
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($this->getFile());
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature
        );

        static::assertTrue($manager->needFixing($file, $fileContent));
    }

    public function testNeedFixingReturnsFalseIfCachedHashIsIdentical(): void
    {
        $file = 'hello.php';
        $fileContent = '<?php echo "Hello!"';

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->has(Argument::is($file))->willReturn(true);
        $cacheProphecy->get(Argument::is($file))->willReturn(md5($fileContent));
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($this->getFile());
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature
        );

        static::assertFalse($manager->needFixing($file, $fileContent));
    }

    public function testNeedFixingUsesRelativePathToFile(): void
    {
        $cacheFile = $this->getFile();
        $file = '/foo/bar/baz/src/hello.php';
        $relativePathToFile = 'src/hello.php';
        $fileContent = '<?php echo "Hello!"';

        $directoryProphecy = $this->prophesize(\PhpCsFixer\Cache\DirectoryInterface::class);
        $directoryProphecy->getRelativePathTo(Argument::is($file))->willReturn($relativePathToFile);

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->has(Argument::is($relativePathToFile))->willReturn(true);
        $cacheProphecy->has(Argument::is($relativePathToFile))->willReturn(0);
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($cacheFile);
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature,
            false,
            $directoryProphecy->reveal()
        );

        static::assertTrue($manager->needFixing($file, $fileContent));
    }

    public function testSetFileSetsHashOfFileContent(): void
    {
        $cacheFile = $this->getFile();
        $file = 'hello.php';
        $fileContent = '<?php echo "Hello!"';

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->set(Argument::is($file), Argument::is(md5($fileContent)))->shouldBeCalled();
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($cacheFile);
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature
        );

        $manager->setFile($file, $fileContent);
    }

    public function testSetFileSetsHashOfFileContentDuringDryRunIfCacheHasNoHash(): void
    {
        $isDryRun = true;
        $cacheFile = $this->getFile();
        $file = 'hello.php';
        $fileContent = '<?php echo "Hello!"';

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->has(Argument::is($file))->willReturn(false);
        $cacheProphecy->set(Argument::is($file), Argument::is(md5($fileContent)))->shouldBeCalled();
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($cacheFile);
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature,
            $isDryRun
        );

        $manager->setFile($file, $fileContent);
    }

    public function testSetFileClearsHashDuringDryRunIfCachedHashIsDifferent(): void
    {
        $isDryRun = true;
        $cacheFile = $this->getFile();
        $file = 'hello.php';
        $fileContent = '<?php echo "Hello!"';
        $previousFileContent = '<?php echo "Hello, world!"';

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->has(Argument::is($file))->willReturn(true);
        $cacheProphecy->get(Argument::is($file))->willReturn(md5($previousFileContent));
        $cacheProphecy->clear(Argument::is($file))->shouldBeCalled();
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($cacheFile);
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature,
            $isDryRun
        );

        $manager->setFile($file, $fileContent);
    }

    public function testSetFileUsesRelativePathToFile(): void
    {
        $cacheFile = $this->getFile();
        $file = '/foo/bar/baz/src/hello.php';
        $relativePathToFile = 'src/hello.php';
        $fileContent = '<?php echo "Hello!"';

        $directoryProphecy = $this->prophesize(\PhpCsFixer\Cache\DirectoryInterface::class);
        $directoryProphecy->getRelativePathTo(Argument::is($file))->willReturn($relativePathToFile);

        $cachedSignature = $this->prophesize(SignatureInterface::class)->reveal();

        $signatureProphecy = $this->prophesize(SignatureInterface::class);
        $signatureProphecy->equals(Argument::is($cachedSignature))->willReturn(true);
        $signature = $signatureProphecy->reveal();

        $cacheProphecy = $this->prophesize(CacheInterface::class);
        $cacheProphecy->getSignature()->willReturn($cachedSignature);
        $cacheProphecy->set(Argument::is($relativePathToFile), Argument::is(md5($fileContent)))->shouldBeCalled();
        $cache = $cacheProphecy->reveal();

        $handlerProphecy = $this->prophesize(FileHandlerInterface::class);
        $handlerProphecy->read()->willReturn($cache);
        $handlerProphecy->getFile()->willReturn($cacheFile);
        $handlerProphecy->write(Argument::is($cache));
        $handler = $handlerProphecy->reveal();

        $manager = new FileCacheManager(
            $handler,
            $signature,
            false,
            $directoryProphecy->reveal()
        );

        $manager->setFile($file, $fileContent);
    }

    private function getFile(): string
    {
        return __DIR__.'/../Fixtures/.php_cs.empty-cache';
    }
}


text:
"""Train a part-of-speech tagger from provided training and props files."""

import os
import subprocess32

from .config import DATA_DIR_NAME, PATH_TO_DATA_DIR, PATH_TO_JAR

def train_tagger(props_file, heap_size='-mx1g', jar_path=PATH_TO_JAR):
    """Train a part-of-speech tagger from a provided properties file."""
    # we assume that the props file is in the 'datafiles' directory
    path_to_props = os.path.join(PATH_TO_DATA_DIR, props_file)
    subprocess32.call(['java', heap_size, '-classpath', jar_path,
                       'edu.stanford.nlp.tagger.maxent.MaxentTagger',
                       '-props', path_to_props])


text:
package au.com.gridstone.grex.converters;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;

import au.com.gridstone.grex.converter.Converter;
import au.com.gridstone.grex.converter.ConverterException;

public class JacksonConverter implements Converter {
    private ObjectMapper objectMapper;

    public JacksonConverter() {
        this(new ObjectMapper());
    }

    public JacksonConverter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public <T> void write(T data, Writer writer) throws ConverterException {
        try {
            objectMapper.writeValue(writer, data);
        } catch (IOException e) {
            throw new ConverterException(e);
        }
    }

    @Override
    public <T> T read(Reader reader, Type type) throws ConverterException {
        JavaType javaType = objectMapper.getTypeFactory().constructType(type);
        try {
            return objectMapper.readValue(reader, javaType);
        } catch (Exception e) {
            throw new ConverterException(e);
        }
    }
}


text:
import { expect } from 'chai'
import * as Up from '../../../Main'
import { insideDocumentAndParagraph } from '../Helpers'

describe('A paragraph directly followed by a video on its own line', () => {
  it('produces a pagraph node followed by a video node, not a line block', () => {
    const markup = `
Do not pour the spiders into your sister's cereal.
[video: spiders crawling out of mouth][http://example.com/spiders.webm]`
    expect(Up.parse(markup)).to.deep.equal(
      new Up.Document([
        new Up.Paragraph([
          new Up.Text("Do not pour the spiders into your sister's cereal.")
        ]),
        new Up.Video('spiders crawling out of mouth', 'http://example.com/spiders.webm')
      ]))
  })
})

describe('An otherwise-valid video convention with mismatched brackets surrounding its description', () => {
  it('does not produce a video node', () => {
    expect(Up.parse('I like [video: ghosts}(http://example.com/ghosts.webm).')).to.deep.equal(
      insideDocumentAndParagraph([
        new Up.Text('I like [video: ghosts}'),
        new Up.NormalParenthetical([
          new Up.Text('('),
          new Up.Link([
            new Up.Text('example.com/ghosts.webm')
          ], 'http://example.com/ghosts.webm'),
          new Up.Text(')')
        ]),
        new Up.Text('.')
      ]))
  })
})

describe('An otherwise-valid video convention with mismatched brackets surrounding its URL', () => {
  it('does not produce a video node', () => {
    expect(Up.parse('I like [video: ghosts][http://example.com/ghosts.webm).')).to.deep.equal(
      insideDocumentAndParagraph([
        new Up.Text('I like '),
        new Up.SquareParenthetical([
          new Up.Text('[video: ghosts]')
        ]),
        new Up.Text('['),
        new Up.Link([
          new Up.Text('example.com/ghosts.webm).')
        ], 'http://example.com/ghosts.webm).')
      ]))
  })
})

context('Unmatched opening parentheses in a video description have no affect on', () => {
  specify('parentheses surounding the URL', () => {
    expect(Up.parse('[video: sad :( sad :( sounds](http://example.com/sad.ogg)')).to.deep.equal(
      new Up.Document([
        new Up.Video('sad :( sad :( sounds', 'http://example.com/sad.ogg')
      ]))
  })

  specify('parentheses that follow the convention', () => {
    expect(Up.parse('([video: sad :( sad :( sounds][http://example.com/sad.ogg])')).to.deep.equal(
      new Up.Document([
        new Up.Paragraph([
          new Up.NormalParenthetical([
            new Up.Text('('),
            new Up.Video('sad :( sad :( sounds', 'http://example.com/sad.ogg'),
            new Up.Text(')')
          ])
        ])
      ]))
  })
})

describe('Unmatched opening parentheses in a video URL', () => {
  it('do not affect any markup that follows the link', () => {
    const markup = '(^[video: West Virginia exit polling][https://example.com/a(normal(url])'

    const footnote = new Up.Footnote([
      new Up.Video('West Virginia exit polling', 'https://example.com/a(normal(url')
    ], { referenceNumber: 1 })

    expect(Up.parse(markup)).to.deep.equal(
      new Up.Document([
        new Up.Paragraph([
          footnote
        ]),
        new Up.FootnoteBlock([
          footnote
        ])
      ]))
  })
})


text:
""" Classes for building the graphs
"""
import operator

__all__ = ['NodeBlueprint', 'TangledSelf', 'TangledSource', 'MethodCallBlueprint']

class NodeBlueprint(object):
    """ Descriptor used as part of the blueprint for building the instance graph.
    """

    def __init__(self, func, *blueprint_args):
        """
        func - callable that will be applied to the results of the input nodes
        args - input Element descriptors, these will provide the input to func in
                the realised node.
        """
        self.func = func
        self.blueprint_args = blueprint_args
        self.name = id(self)
        self.owner_class = None

    def __str__(self):
        class_name  = self.__class__.__name__
        return f'<{class_name} "{self.name}">'

    def __repr__(self):
        return self.__str__()

    def __set_name__(self, owner_class, name):
        self.owner_class = owner_class
        self.name = name

    @property
    def arg_count(self):
        return len(self.blueprint_args)

    @property
    def is_value_node(self):
        return False

    def is_anonymous(self):
        """ Anonymous elements do not have an owner, in that case
        this returns None
        """
        return self.owner_class is None

    def node_for_other_class(self, instance):
        return not self.is_anonymous() and not isinstance(instance, self.owner_class)

    def get_or_build_node(self, instance):
        tree_node = instance.builder.build(instance, self)
        return tree_node

    def __get__(self, instance, cls):
        """ descriptor protocol implementation
        """
        if instance is not None:
            # If accessed from an instance, build or return cached tree
            node = self.get_or_build_node(instance)
            instance.evaluator.evaluate(node)
            result = node.value()
            return result
        elif cls:
            # If we access from a class then return self so it can be used to
            # build the blueprint graph
            return self

    # Magic methods create new NodeMakers objects for all standard operations
    # These elements won't have a name and is thus anonymous
    def __add__(self, other):
        return NodeBlueprint(operator.add, self, other)

    def __matmul__(self, other):
        return NodeBlueprint(operator.matmul, self, other)

    def __mul__(self, other):
        return NodeBlueprint(operator.mul, self, other)

    def __sub__(self, other):
        return NodeBlueprint(operator.sub, self, other)

    def __truediv__(self, other):
        return NodeBlueprint(operator.truediv, self, other)

class TangledSource(NodeBlueprint):

    def __init__(self):
        self.name = None
        self.owner_class = None
        self.args = ()

    @property
    def arg_count(self):
        return 0

    @property
    def is_value_node(self):
        return True

    def __set__(self, instance, value):
        node = self.get_or_build_node(instance)
        node.set_value(value)

class MethodCallBlueprint(NodeBlueprint):
    """ Element to allow graph building in an element type way
    """
    def __init__(self, method_name):
        self.method_name = method_name
        super().__init__(None)

    def build_node(self, obj, args):
        method = getattr(obj, element.method_name)
        node = treeprimitives.FunctionNode(method, obj, args)
        return node

class TangledSelf(NodeBlueprint):
    """ object that is a proxy for the class itself. To be able
    to build the graph from a method call.
    """

    def __init__(self):
        super().__init__(None)

    def __getattr__(self, method_name):
        return MethodCallBlueprint(method_name)


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class WeaponHolder : MonoBehaviour {

    //Ten skrypt obsługuje wszystkie bronie jakie posiada player
    //Woła by strzelały / machały mieczem

    //TODO: Powinien być tu jakiś array z broniami jakie gracz posiada, dodatkowo coś
    //co pozwala na scrollowanie między nimi

    private List<Transform> weapons = new List<Transform>();
    private int weaponsCount;
    //activeWeaponIndex zaczyna się od 0 a kończy na weaponsCount-1

    private int activeWeaponIndex = 0;

    public Image reloadAnimation;
    public Text AmmoText;

    void Awake()
    {
        //Dodaj wszystkie bronie:

        //Ile player ma w posiadaniu broni
        weaponsCount = transform.childCount;

        for (int i = 0; i < weaponsCount; i++)
        {
            //Debug.Log(transform.GetChild(i));
            //Debug.Log(i);
            //Debug.Log(weaponsCount);
            weapons.Add(transform.GetChild(i));
        }
    }

    public void ReloadAnimationUpdate(float proc) // proc to wartość 0-1
    {
        reloadAnimation.gameObject.SetActive(true);
        reloadAnimation.fillAmount = 1-proc; // odwracam ta by 0.3 dawało 0.7,  DLA ŁADNEGO WYGLĄDU TYLKO
    }
    public void ReloadAnimationHide()
    {
        reloadAnimation.gameObject.SetActive(false);
        reloadAnimation.fillAmount = 0;
    }
    //funkcje zmieniające aktywną broń
    //Jedna bierze index za argument i zmienia na broń, bo klikneliśmy np. klawisz "1"
    //Druga bierze stringa scroll = "next" albo "previous", by kółkiem myszy też dało się zmieniać bronie.
    public void ChangeWeapon(int index)
    {
        for (int i = 0; i < weaponsCount; ++i)
        {
            if (index == i)
            {
                transform.GetChild(i).gameObject.SetActive(true);
                activeWeaponIndex = i;
            }
            else
                transform.GetChild(i).gameObject.SetActive(false);
        }
    }
    public void ChangeWeapon(string scroll)
    {
        if (scroll=="next") {
            //jeśli ostatnia broń jest aktywna
            if (activeWeaponIndex+1 == weaponsCount)
            {
                activeWeaponIndex = 0;
                ChangeWeapon(activeWeaponIndex);
            }
            else
            {
                activeWeaponIndex ++;
                ChangeWeapon(activeWeaponIndex);
            }
        }
        else // scroll==previous
        {
            //jeśli pierwsza broń jest aktywna
            if (activeWeaponIndex == 0)
            {
                activeWeaponIndex = weaponsCount-1;
                ChangeWeapon(activeWeaponIndex);
            }
            else
            {
                activeWeaponIndex--;
                ChangeWeapon(activeWeaponIndex);
            }
        }

    }

    //funkcja wołana z player_actions
    public void leftClick()
    {
        //useMain, bo może w przyszłości bronie będą miały więcej niż 1 atak
        BroadcastMessage("useMain", null, SendMessageOptions.DontRequireReceiver); //działa na "enabled" bronie w weaponHolderze
    }

    public void r()
    {
        //useMain, bo może w przyszłości bronie będą miały więcej niż 1 atak
        BroadcastMessage("R", null, SendMessageOptions.DontRequireReceiver); //działa na "enabled" bronie w weaponHolderze
        //Debug.Log("rr");
    }

    public void pickUpAmmo(ammoDrop AmmoDrop)
    {
        // do dokończenia
        //bronie nie mogą mieć ammo w sobie, musi być to przechowywane w weaponholderze, ZRÓB JAKĄŚ KLASĘ NA BRONIE I ICH TYPY
        //Protip: każda broń implementuje interfejs weaponInterface -> posiada guziki R lmb rmb ...
        //https://forum.unity3d.com/threads/adding-scripts-to-a-list-an-attempt-at-a-modular-spell-system.138945/

        //2nd try:
        /*WHen pickup, enable all weapons, send adding ammo and disable all unused*/
        foreach (Transform child in transform)
        {
            child.gameObject.SetActive(true);
            Debug.Log(child.gameObject);
        }

        BroadcastMessage("AddAmmo", AmmoDrop, SendMessageOptions.DontRequireReceiver);

        foreach (Transform child in transform)
        {
            child.gameObject.SetActive(false);
        }
        transform.GetChild(activeWeaponIndex).gameObject.SetActive(true);
    }

    public void UpdateAmmoUI(int inMag, int inReserve)
    {
        AmmoText.text = string.Format("Ammo: {0}/{1}", inMag, inReserve);
    }
}


text:
<!doctype html>

    <title>Code coverage report for cjs/operators/switchMapTo.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../prettify.css">
    <link rel="stylesheet" href="../../base.css">

Code coverage report for cjs/operators/switchMapTo.js

        Statements: 65.52% (19 / 29)
        Branches: 50% (6 / 12)
        Functions: 37.5% (3 / 8)
        Lines: 68.18% (15 / 22)
        Ignored: none

All files » cjs/operators/ » switchMapTo.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

1
1

1

1

1

1

1
1

1

1

1
1

1

1

1

'use strict';

exports.__esModule = true;
exports['default'] = switchMapTo;

function _inherits(subClass, superClass) { Iif (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); Eif (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _mergeMapToSupport = require('./mergeMapTo-support');

function switchMapTo(observable, projectResult) {
    return this.lift(new SwitchMapToOperator(observable, projectResult));
}

var SwitchMapToOperator = (function () {
    function SwitchMapToOperator(observable, resultSelector) {
        _classCallCheck(this, SwitchMapToOperator);

        this.observable = observable;
        this.resultSelector = resultSelector;
    }

    SwitchMapToOperator.prototype.call = function call(subscriber) {
        return new SwitchMapToSubscriber(subscriber, this.observable, this.resultSelector);
    };

    return SwitchMapToOperator;
})();

var SwitchMapToSubscriber = (function (_MergeMapToSubscriber) {
    _inherits(SwitchMapToSubscriber, _MergeMapToSubscriber);

    function SwitchMapToSubscriber(destination, observable, resultSelector) {
        _classCallCheck(this, SwitchMapToSubscriber);

        _MergeMapToSubscriber.call(this, destination, observable, resultSelector, 1);
    }

    //# sourceMappingURL=switchMapTo.js.map
    return SwitchMapToSubscriber;
})(_mergeMapToSupport.MergeMapToSubscriber);

module.exports = exports['default'];
//# sourceMappingURL=switchMapTo.js.map

Generated by istanbul at Mon Oct 26 2015 13:47:29 GMT-0700 (PDT)


text:
package com.learn.db;

import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;

import java.net.MalformedURLException;

public class CouchDB {

    public static CouchDbConnector getConnection() throws MalformedURLException {
        HttpClient httpClient = new StdHttpClient.Builder()
                .password("a8adf07a5531730e03b803534378b27c3154ec06ad1dc4ba7365d2b5b863d008")
                .username("346d3c4d-7eb8-49e3-bb6a-138e9af5d276-bluemix")
                .url("https://346d3c4d-7eb8-49e3-bb6a-138e9af5d276-bluemix:a8adf07a5531730e03b803534378b27c3154ec06ad1dc4ba7365d2b5b863d008@346d3c4d-7eb8-49e3-bb6a-138e9af5d276-bluemix.cloudant.com")
                .build();

        CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);

        return new StdCouchDbConnector("blog", dbInstance);
    }
}


text:
import { gridBorderColor, gridBackgroundColor, gridBorderWidth, gridSize, gridX, gridY } from '../configs.js';

export default class Grid {
  constructor({ ctx }) {
    this.ctx = ctx;
    this.x = gridX;
    this.y = gridY;
    this.width = this.height = gridSize;
    this.borderWidth = gridBorderWidth;
    this.strokeStyle = gridBorderColor;
    this.fillStyle = gridBackgroundColor;
  }

  render() {
    const { ctx, strokeStyle, fillStyle, borderWidth, x, y, width, height } = this;
    if (borderWidth) {
      ctx.strokeStyle = strokeStyle;
      ctx.lineWidth = borderWidth;
      ctx.strokeRect(x, y, width, height);
    }
    ctx.fillStyle = fillStyle;
    ctx.fillRect(x, y, width, height);
  }
}


text:
# Replication Policies

## iOS replication policies

Replication policies on iOS run in a background task to allow them to run independently of the rest of your application
and to enable them to continue even when the app is suspended or terminated.

It is also possible to configure periodic replication of data whilst the app is in the background. It is important
to realise that iOS imposes restrictions on background data transfer and these apply to replication policies. In
particular, iOS limits the time during which data transfers can occur while the app is in the background to 30
seconds. Also, although a minimum background fetch interval can be specified, this is the absolute minimum period
between performing background data transfers and the actual interval may be significantly different to the minimum
interval specified.

### Configuring background execution

To configure background execution, it is necessary to:
* enable the Background fetch option for the Background modes section of the Capabilites tab in your Xcode project (you
  can also enable this support by including the `UIBackgroundModes` key with the `fetch` value in your app's `Info.plist`
  file).
* implement an app delegate method `application:performFetchWithCompletionHandler:` to initiate the replications. Once
  replications are complete, this method must execute the provided completion handler block, passing a result that
  indicates whether content was available.
* set the minimum background fetch interval by calling `setMinimumBackgroundFetchInterval:` on the application's
  `UIApplication` object. The value given to `setMinimumBackgroundFetchInterval:` is advisory only and the actual
  time between background replications may vary considerably from the value set.

You should note that enabling background fetch does not guarantee that iOS will give your app any time to perform
background fetches as iOS will attempt to balance your app's need to fetch content with the needs of the system and
of other apps.

### Example

Let's assume we wish to configure a replication policy as follows:

* We only ever want replications to occur when the device is connected to a WiFi network.
* We want to do sync replications (pull and push).
* When the app is not displaying data to the user we want replications to occur once every 24 hours to keep the data on the device fairly fresh.
* When the app is displaying data to the user we want replications to occur every 5 minutes so the data displayed to the user is only ever a few minutes out of date if we're on Wifi.
* When the app is displaying data to the user we want to refresh the UI to display the new data when the pull replication has completed.
* After the device has rebooted, we want replications to continue in the same way as prior to the reboot.

#### Configuring app capabilities

On the `Capabilities` tab of your Xcode project turn on `Background Modes` and select `Background fetch`.

#### Configure your replications

Configure your replications following the guidance in the [Replication guide](replication.md).

Note however, that in the following example we'll use the `startWithTaskGroup:error:` method of
`CDTReplicator` instead of `startWithError:` so that we can batch the replication tasks and wait
for the completion of all of them.

For example:
```objc
/** Start both a push and pull replication.
 *
 *  @param taskGroup A dispatch_group_t to allow us to wait for replications to complete.
 */
- (void)startReplications:(dispatch_group_t)taskGroup
{
    // Create the replicator factory
    CDTReplicatorFactory *replicatorFactory =
       [[CDTReplicatorFactory alloc] initWithDatastoreManager:manager];

    // username/password can be Cloudant API keys
    NSString *s = @"https://username:password@username.cloudant.com/my_database";
    NSURL *remoteDatabaseURL = [NSURL URLWithString:s];
    CDTDatastore *datastore = [manager datastoreNamed:@"my_datastore"];

    // Create a replicator that replicates changes from the local
    // datastore to the remote database.
    CDTPushReplication *pushReplication = [CDTPushReplication replicationWithSource:datastore
                                                                             target:remoteDatabaseURL];

    // Create a replicator that replicates changes from a remote
    // database to the local one.
    CDTPullReplication *pullReplication = [CDTPullReplication replicationWithSource:remoteDatabaseURL
                                                                             target:datastore];

    NSError *pushError;
    CDTReplicator *pushReplicator = [replicatorFactory oneWay:pushReplication
                                        sessionConfigDelegate:self
                                                        error:&error];

    NSError *pullError;
    CDTReplicator *pullReplicator = [replicatorFactory oneWay:pullReplication
                                        sessionConfigDelegate:self
                                                        error:&error];

    // Start the push replication
    if (![pushReplicator startWithTaskGroup:taskGroup error:&error]){
        //handle error
    }

    // Start the pull replication
    if (![pullReplicator startWithTaskGroup:taskGroup error:&error]){
        //handle error
    }
}
```

Create a method to start replications and wait for their completion (on a background thread).

```objc
-(void)syncInBackgroundWithCompletionHandler:(void (^)())completionHandler
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        dispatch_group_t backgroundTasks = dispatch_group_create();

        UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

        [self startReplications:backgroundTasks];

        dispatch_group_wait(backgroundTasks, dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC));

        if (completionHandler) {
            completionHandler();
        }

        [[UIApplication sharedApplication] endBackgroundTask:taskId];
    });
}
```

Setup an NSURLSessionConfigurationDelegate to customise the NSURLSession as you require:

```objc
- (void)customiseNSURLSessionConfiguration:(nonnull NSURLSessionConfiguration *)config {
    config.allowsCellularAccess = NO; // Wifi only.
    config.sessionSendsLaunchEvents = YES;
}
```

#### Setting up the App Delegate

In your `UIApplicationDelegate` add the following to your `application:didFinishLaunchingWithOptions:` method:

```objc
int backgroundInterval24hrs = 24*60*60;
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:backgroundInterval24hrs];
```

Implement the `application:performFetchWithCompletionHandler:` method - e.g.:
```objc
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [self.myReplicator syncInBackgroundWithCompletionHandler:^{
        // Do whatever you want when replication is complete (e.g. refresh the UI)

        // Call the completion handler once the sync has finished.
        completionHandler(UIBackgroundFetchResultNewData);
    }];
}
```

#### Configure replication when a particular screen is visible

In your screen's view controller, add methods to start and stop the timer performing replications:

```objc
@property (nonatomic, strong) NSTimer *timer;

- (void)startTimer:(id)sender {
    _timer = [NSTimer scheduledTimerWithTimeInterval:30
                                              target:self
                                            selector:@selector(periodicReplication:)
                                            userInfo:nil
                                             repeats:YES];
}

- (void)stopTimer:(id)sender {
    [_timer invalidate];
    _timer = nil;
}

- (void)periodicReplication:(NSTimer *)timer
{
    [self.todoReplicator syncInBackgroundWithCompletionHandler:^{
        // Do whatever you want when replication is complete (e.g. refresh the UI)
    }];
}
```

Add the following to the View Controller's `viewWillAppear:animated` method:

```objc
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopTimer:) name:UIApplicationWillResignActiveNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startTimer:) name:UIApplicationWillEnterForegroundNotification object:nil];
```


text:
namespace laminaFS {
namespace util {

//! Simple ring buffer of a fixed capacity.
template <typename T>
class RingBuffer {
public:
	RingBuffer() {
		_capacity = 0;
		_full = true;
	}

	RingBuffer(lfs_allocator_t &alloc, uint64_t capacity, Semaphore *sem = nullptr) {
		_alloc = alloc;
		_capacity = capacity;
		_buffer = reinterpret_cast<T*>(_alloc.alloc(_alloc.allocator, sizeof(T) * capacity, alignof(T)));
		_full = false;
		_semaphore = sem;
	}

	~RingBuffer() {
		_alloc.free(_alloc.allocator, _buffer);
	}

	//! Push an item into the buffer. Blocks if buffer is full.
	//! @param v the item to push.
	void push(T v) {
		bool done = false;

		while (!done) {
			while (_full)
				std::this_thread::yield();

			bool notify = false;
			{
				std::lock_guard<std::mutex> lock(_lock);
				if (!_full) {
					notify = _writePos == _readPos;
					_buffer[_writePos++] = v;

					if (_writePos == _capacity)
						_writePos = 0;

					if (_writePos == _readPos)
						_full = true;
					done = true;
				}
			}
			if (_semaphore && notify)
				_semaphore->notify();
		}
	}

	//! Attemps to pop an item. Nonblocking.
	//! @param defaultValue the value to return if the buffer is empty
	//! @return an item or the default value
	T pop(T defaultValue) {
		std::lock_guard<std::mutex> lock(_lock);
		if (_full || _readPos != _writePos) {
			uint64_t oldReadPos = _readPos++;

			_full = false;
			if (_readPos == _capacity)
				_readPos = 0;

			return _buffer[oldReadPos];
		} else {
			return defaultValue;
		}
	}

	//! Gets the capacity of the buffer.
	//! @return the capacity
	uint64_t getCapacity() const { return _capacity; }

	//! Gets the current number of items in the buffer.
	//! @return the current number of items
	uint64_t getCount() {
		std::lock_guard<std::mutex> lock(_lock);
		uint64_t result = 0;

		if (_full) {
			result = _capacity;
		} else if (_readPos <= _writePos) {
			result = _writePos - _readPos;
		} else {
			result = _capacity - _readPos + _writePos;
		}

		return result;
	}

private:
	T *_buffer;
	lfs_allocator_t _alloc;
	uint64_t _capacity;
	uint64_t _readPos = 0;
	uint64_t _writePos = 0;
	Semaphore *_semaphore;
	std::mutex _lock;
	std::atomic<bool> _full;
};
}
}


text:
@interface StaticListViewController : UITableViewController

@property (readwrite, nonatomic) StaticListViewModel *viewModel;

@end


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 io.prestosql.plugin.session.file;

import com.google.inject.Injector;
import io.airlift.bootstrap.Bootstrap;
import io.airlift.json.JsonModule;
import io.prestosql.spi.resourcegroups.SessionPropertyConfigurationManagerContext;
import io.prestosql.spi.session.SessionPropertyConfigurationManager;
import io.prestosql.spi.session.SessionPropertyConfigurationManagerFactory;

import java.util.Map;

public class FileSessionPropertyManagerFactory
        implements SessionPropertyConfigurationManagerFactory
{
    @Override
    public String getName()
    {
        return "file";
    }

    @Override
    public SessionPropertyConfigurationManager create(Map<String, String> config, SessionPropertyConfigurationManagerContext context)
    {
        Bootstrap app = new Bootstrap(
                new JsonModule(),
                new FileSessionPropertyManagerModule());

        Injector injector = app
                .strictConfig()
                .doNotInitializeLogging()
                .setRequiredConfigurationProperties(config)
                .initialize();

        return injector.getInstance(FileSessionPropertyManager.class);
    }
}