text:
/*
 * Bed6Interval.h
 *
 *  Created on: Nov 13, 2012
 *      Author: nek3d
 */

#ifndef BEDGRAPHINTERVAL_H_
#define BEDGRAPHINTERVAL_H_

#include "Bed3Interval.h"

class SingleLineDelimTextFileReader;

class BedGraphInterval : public Bed3Interval {
public:
	friend class FreeList<BedGraphInterval>;

	BedGraphInterval();
	virtual bool initFromFile(SingleLineDelimTextFileReader *);
	virtual void print(string &outBuf) const;
	virtual void print(string &outBuf, CHRPOS start, CHRPOS end) const;
	virtual void print(string &outBuf, const string & start, const string & end) const;
	virtual void printNull(string &outBuf) const;
	virtual FileRecordTypeChecker::RECORD_TYPE getType() const { return FileRecordTypeChecker::BEDGRAPH_RECORD_TYPE; }

	virtual const string &getField(int fieldNum) const;
	virtual int getNumFields() const  { return 4; }

	static bool isNumericField(int fieldNum);

protected:
	virtual ~BedGraphInterval();
};

#endif /* BEDGRAPHINTERVAL_H_ */


text:
package com.palantir.atlasdb.persister;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.palantir.atlasdb.annotation.Reusable;
import com.palantir.atlasdb.persist.api.Persister;
import com.palantir.common.base.Throwables;
import java.io.IOException;

@Reusable
public class JsonNodePersister implements Persister<JsonNode> {
    static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public byte[] persistToBytes(JsonNode jsonNode) {
        try {
            return mapper.writeValueAsBytes(jsonNode);
        } catch (JsonProcessingException e) {
            throw Throwables.throwUncheckedException(e);
        }
    }

    @Override
    public JsonNode hydrateFromBytes(byte[] input) {
        try {
            return mapper.readTree(input);
        } catch (IOException e) {
            throw Throwables.throwUncheckedException(e);
        }
    }

    @Override
    public Class<JsonNode> getPersistingClassType() {
        return JsonNode.class;
    }
}

redpajama_set_name: RedPajamaGithub


text:
    <form>
        <md-card>
            <md-card-title>Code Info</md-card-title>
            <md-card-content>
                <md-input [(ngModel)]="code.url" placeholder="Code Url"></md-input>
            </md-card-content>
        </md-card>
        <md-card>
            <md-card-title>Code Tags</md-card-title>
            <tags [tagList]="tagList"></tags>

                <button md-raised-button type="submit" color="primary" (click)="addCode()">Submit</button>

        </md-card>
    </form>


text:
set -o nounset -o pipefail -o errexit -x

#source code/config_genes.sh
#gene=${GENES[$(($LSB_JOBINDEX - 1))]}
genome=~astlingd/genomes/bowtie-1.1.2/hg38/hg38
folder=template
result_folder=alignments/spikein/total-strata

source code/config_domains.sh
domain=${DOMAINS[$(($LSB_JOBINDEX - 1))]}

for sample in fastq/$folder/*/${domain}_*_1.fastq.gz
#for sample in fastq/$folder/${gene}_*_1.fa.gz
do
        sample=`echo $sample | perl -pe 's/^.+?\/([^\/]+?)_[12].fastq.gz/$1/'`
	gene=`echo $sample | perl -pe 's/^(NBPF[^_]+).+?$/$1/'`
        if [[ ! -d $result_folder/$gene ]]; then
                mkdir -p $result_folder/$gene
        fi

        first_pair=fastq/$folder/$gene/${sample}_1.fastq
        second_pair=fastq/$folder/$gene/${sample}_2.fastq

	gunzip -c $first_pair.gz > $first_pair
	gunzip -c $second_pair.gz > $second_pair

	code/bowtie_multiread.sh -g $genome -b $result_folder/$gene/${sample}_paired.bam $first_pair $second_pair

	code/bowtie_multiread.sh -g $genome -b $result_folder/$gene/${sample}_single.bam $first_pair

	#bowtie -p 12 -X 2000 --best --strata --all -v 2 -S --un $result_folder/${sample}_paired_unaligned $genome -1 $first_pair -2 $second_pair | samtools view -Sb - > $result_folder/${sample}_paired.bam
	#bowtie -p 12 -X 2000 --best --strata --all -v 2 -S --un $result_folder/${sample}_single_unaligned $genome $first_pair | samtools view -Sb - > $result_folder/${sample}_single.bam

	rm $first_pair
	rm $second_pair
done


text:
'use strict'
var path = require('path')
var assert = require('yeoman-assert')
var helpers = require('yeoman-test')

describe('generator-evergrow:model', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/model'))
      .withArguments(['Message'])
      .toPromise()
  })

  it('creates files', function () {
    assert.file([
      'module/message'
    ])
  })
})


text:
{% extends 'directorio/base.html' %}

{% block content %}

	{% if not asignatura.archivada %}
		 Volver a Lista de Asignaturas
	{% else %}
		 Volver a Lista de Asignaturas Archivadas
	{% endif %}

		{{ asignatura.nombre }}
		{% if perms.auth.es_gestor %}

		{% endif %}

			{% if asignatura.n_alternativo1 %}

{{ asignatura.n_alternativo1 }}

			{% endif %}
			{% if asignatura.n_alternativo2 %}

{{ asignatura.n_alternativo2 }}

			{% endif %}

 {{ asignatura.organizacion.nombre }}

Código: {{ asignatura.cod_asig }}

			{% if asignatura.id_srm %}

ID SRM: {{ asignatura.id_srm }}

			{% endif %}
			{% if asignatura.archivada %}

Esta asignatura está archivada.

			{% endif %}
			{% if perms.aut.es_gestor %}

 Ver valoraciones

			{% endif %}

		Vídeos
		{% if perms.auth.es_gestor %}

		{% endif %}

	{% if asignatura.video_set.all %}

				Título	Enlace

				{% for vid in asignatura.video_set.all %}

					{{ vid.titulo|default:'(Vacío)' }}

						{{ vid.enlace }}

					  {% if perms.auth.es_gestor %}

					  {% endif %}

				{% endfor %}

	{% else %}

 No se han encontrado vídeos asociados a esta asignatura.

	{% endif %}

Convocatorias y Profesores de esta Asignatura:

	{% if pacs_convs %}

			{% for pac_conv in pacs_convs %}

					 {{ pac_conv.convocatorias.get_mes_display }} {{ pac_conv.convocatorias.anio }}

				{% for pac_prof in pacs_profs %}
					{% if pac_prof.convocatorias == pac_conv.convocatorias %}

							 {{ pac_prof.profesores.apellidos }}, {{ pac_prof.profesores.nombre }}
							({{ pac_prof.programas.nombre }})

					{% endif %}
				{% endfor %}

			{% endfor %}

	{% else %}

 No se han encontrado convocatorias para esta asignatura.

	{% endif %}

{% endblock %}


text:
package io.subutai.core.localpeer.impl.binding;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Commands batch output
 */
public class BatchOutput
{
    @JsonProperty( "output" )
    private QuotaOutput output;
    @JsonProperty( "exitcode" )
    private Integer exitcode;

    public BatchOutput( @JsonProperty( "output" ) final QuotaOutput output,
                        @JsonProperty( "exitcode" ) Integer exitcode )
    {
        this.output = output;
        this.exitcode = exitcode;
    }

    public QuotaOutput getOutput()
    {
        return output;
    }

    public Integer getExitcode()
    {
        return exitcode;
    }
}


text:
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "list/list.h"

typedef uint16_t symbol_id_t;

#define PARSER_RETCODE_WARN 2
#define PARSER_RETCODE_ERR  1
#define PARSER_RETCODE_SUCC 0

#define MAX_PARSER_ERR_STR  1024

/* assigned pathID is in [1, 64] */
#define MAX_SUBPATH_ID      64

enum subpath_type {
	SUBPATH_TYPE_GENERNODE,
	SUBPATH_TYPE_WILDCARD,
	SUBPATH_TYPE_NORMAL
};

struct subpath_node {
	uint32_t         token_id;
	uint32_t         sons;
	struct list_node ln;
};

struct subpath {
	uint32_t              path_id;
	list                  path_nodes;
	enum subpath_type     type;
	union {
		symbol_id_t       lf_symbol_id;
		symbol_id_t       ge_hash;
	};
	symbol_id_t           fr_hash;
	struct list_node      ln;
};

struct subpaths {
	list      li;
	uint32_t  n_lr_paths;
	uint32_t  n_subpaths;
};

struct tex_parse_ret {
	uint32_t         code;
	char             msg[MAX_PARSER_ERR_STR];
	struct subpaths  subpaths;
	void            *operator_tree;
};

struct tex_parse_ret tex_parse(const char *, size_t,
                               bool /* keep operator tree */);

void subpaths_print(struct subpaths*, FILE*);

void subpath_free(struct subpath*);
void subpaths_release(struct subpaths*);


text:
package ariba.appcore;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Column;

import java.util.Date;
import ariba.ui.meta.persistence.ObjectContext;

import java.util.Collections;

@Entity
public class Global
{
    @Id @GeneratedValue
    private Long id;

    @Column(name="thekey")
    String key;

    Date lastModified;

    long longValue;

    String stringValue;

    public Date getLastModified ()
    {
        return lastModified;
    }

    protected void modified ()
    {
        // bogus: should update with pre-commit observer
        lastModified = new Date();
    }

    public long getLongValue ()
    {
        return longValue;
    }

    public void setLongValue (long longValue)
    {
        modified();
        this.longValue = longValue;
    }

    public String getStringValue ()
    {
        return stringValue;
    }

    public void setStringValue (String stringValue)
    {
        modified();
        this.stringValue = stringValue;
    }

    public static Global find (String key)
    {
        ObjectContext context = ObjectContext.get();
        return context.findOne(Global.class, Collections.singletonMap("key", (Object)key));
    }

    public static Global create (String key)
    {
        ObjectContext context = ObjectContext.get();
        Global global = context.create(Global.class);
        global.key = key;
        global.modified();
        return global;
    }

    public static Global findOrCreate (String key)
    {
        Global global = find(key);
        return  (global != null) ? global : create(key);
    }
}


text:
* Proposal: [SDL-0072](0072-New-vehicle-data-FuelRange.md)
* Author: [Robin Kurian](https://github.com/robinmk)
* Status: **Accepted with Revisions**
* Impacted Platforms: [Core/Android/iOS/RPC]

## Introduction

This proposal is about adding a new vehicle data to get the distance a vehicle can travel with the current level of fuel.

## Motivation

The Ford Owner application requires the fuel range data to provide related information to the user.
Other applications could also benefit from such a data. As an example, a Navigation application may use it to provide a more fuel-efficient route or to locate the nearest fuel station before the end of the fuel range.

## Proposed solution

The solution proposes adding the possibility to get and subscribe to the fuel range by making the following additions to the Mobile API and HMI API.

### Additions to Mobile_API

```xml
<enum name="FuelType">
    <element name="GASOLINE" />
    <element name="DIESEL" />
    <element name="CNG">
        <description>
            For vehicles using compressed natural gas.
        </description>
    </element>
    <element name="LPG">
        <description>
            For vehicles using liquefied petroleum gas.
        </description>
    </element>
    <element name="HYDROGEN">
        <description>For FCEV (fuel cell electric vehicle).</description>
    </element>
    <element name="BATTERY">
        <description>For BEV (Battery Electric Vehicle), PHEV (Plug-in Hybrid Electric Vehicle), solar vehicles and other vehicles which run on a battery.</description>
    </element>
</enum>

<struct name="FuelRange">
    <param name="type" type="FuelType" mandatory="false"/>
    <param name="range" type="Float" minvalue="0" maxvalue="10000" mandatory="false">
        <description>
            The estimate range in KM the vehicle can travel based on fuel level and consumption.
        </description>
    </param>
</struct>

<enum name="VehicleDataType">
            :
    <element name="VEHICLEDATA_FUELRANGE" />
</enum>

<function name="SubscribeVehicleData" functionID="SubscribeVehicleDataID" messagetype="request">
            :
    <param name="fuelRange" type="Boolean" mandatory="false">
        <description>The estimate range in KM the vehicle can travel based on fuel level and consumption</description>
    </param>
</function>
<function name="SubscribeVehicleData" functionID="SubscribeVehicleDataID" messagetype="response">
            :
    <param name="fuelRange" type="VehicleDataResult" mandatory="false">
        <description>The estimate range in KM the vehicle can travel based on fuel level and consumption</description>
    </param>
</function>

<function name="UnsubscribeVehicleData" functionID="UnsubscribeVehicleDataID" messagetype="request">
            :
    <param name="fuelRange" type="Boolean" mandatory="false">
        <description>The estimate range in KM the vehicle can travel based on fuel level and consumption</description>
    </param>
</function>
<function name="UnsubscribeVehicleData" functionID="UnsubscribeVehicleDataID" messagetype="response">
            :
    <param name="fuelRange" type="VehicleDataResult" mandatory="false">
        <description>The estimate range in KM the vehicle can travel based on fuel level and consumption</description>
    </param>
</function>
<param name="fuelRange" type="FuelRange" minsize="0" maxsize="100" array="true" mandatory="false">
<function name="GetVehicleData" functionID="GetVehicleDataID" messagetype="request">
            :
    <param name="fuelRange" type="Boolean" mandatory="false">
        <description>The estimate range in KM the vehicle can travel based on fuel level and consumption</description>
    </param>
</function>
<function name="GetVehicleData" functionID="GetVehicleDataID" messagetype="response">
            :
    <param name="fuelRange" type="FuelRange" minsize="0" maxsize="100" array="true" mandatory="false">
        <description>The estimate range in KM the vehicle can travel based on fuel level and consumption</description>
    </param>
</function>

<function name="OnVehicleData" functionID="OnVehicleDataID" messagetype="notification">
            :
    <param name="fuelRange" type="FuelRange" minsize="0" maxsize="100" array="true" mandatory="false">
        <description>The estimate range in KM the vehicle can travel based on fuel level and consumption</description>
    </param>
</function>
```

### Additions to HMI_API

Changes to enums and functions in the mobile API should also be applied to the HMI API.

### HMI

If the HMI can provide the fuel range it should read the CAN signals related to the fuel range and map it to the `fuelRange` parameter. Otherwise the HMI should reply with `VEHICLE_DATA_NOT_AVAILABLE` if the head unit cannot provide the fuel range.

## Potential downsides

NA

## Impact on existing code

- requires changes on SDL core, both SDKs (Android, iOS) and APIs (mobile, HMI).
- would require a minor version change.

Existing head units of an older version replies with INVALID_DATA as expected if an app tries to subscribe to fuelRange.

## Alternatives considered

NA


text:
/**
 * This program tests string search performance.
 * APIs tested:
 * ICU4C
 */

#include "strsrchperf.h"

StringSearchPerformanceTest::StringSearchPerformanceTest(int32_t argc, const char *argv[], UErrorCode &status)
:UPerfTest(argc,argv,status){
    int32_t start, end;
    srch = NULL;
    pttrn = NULL;
    if(status== U_ILLEGAL_ARGUMENT_ERROR || line_mode){
       fprintf(stderr,gUsageString, "strsrchperf");
       return;
    }
    /* Get the Text */
    src = getBuffer(srcLen, status);

#if 0
    /* Get a word to find. Do this by selecting a random word with a word breakiterator. */
    UBreakIterator* brk = ubrk_open(UBRK_WORD, locale, src, srcLen, &status);
    if(U_FAILURE(status)){
        fprintf(stderr, "FAILED to create pattern for searching. Error: %s\n", u_errorName(status));
        return;
    }
    start = ubrk_preceding(brk, 1000);
    end = ubrk_following(brk, start);
    pttrnLen = end - start;
    UChar* temp = (UChar*)malloc(sizeof(UChar)*(pttrnLen));
    for (int i = 0; i < pttrnLen; i++) {
        temp[i] = src[start++];
    }
    pttrn = temp; /* store word in pttrn */
    ubrk_close(brk);
#else
    /* The first line of the file contains the pattern */
    start = 0;

    for(end = start; ; end += 1) {
        UChar ch = src[end];

        if (ch == 0x000A || ch == 0x000D || ch == 0x2028) {
            break;
        }
    }

    pttrnLen = end - start;
    UChar* temp = (UChar*)malloc(sizeof(UChar)*(pttrnLen));
    for (int i = 0; i < pttrnLen; i++) {
        temp[i] = src[start++];
    }
    pttrn = temp; /* store word in pttrn */
#endif

    /* Create the StringSearch object to be use in performance test. */
    srch = usearch_open(pttrn, pttrnLen, src, srcLen, locale, NULL, &status);

    if(U_FAILURE(status)){
        fprintf(stderr, "FAILED to create UPerfTest object. Error: %s\n", u_errorName(status));
        return;
    }

}

StringSearchPerformanceTest::~StringSearchPerformanceTest() {
    if (pttrn != NULL) {
        free(pttrn);
    }
    if (srch != NULL) {
        usearch_close(srch);
    }
}

UPerfFunction* StringSearchPerformanceTest::runIndexedTest(int32_t index, UBool exec, const char *&name, char *par) {
    switch (index) {
        TESTCASE(0,Test_ICU_Forward_Search);
        TESTCASE(1,Test_ICU_Backward_Search);

        default:
            name = "";
            return NULL;
    }
    return NULL;
}

UPerfFunction* StringSearchPerformanceTest::Test_ICU_Forward_Search(){
    StringSearchPerfFunction* func = new StringSearchPerfFunction(ICUForwardSearch, srch, src, srcLen, pttrn, pttrnLen);
    return func;
}

UPerfFunction* StringSearchPerformanceTest::Test_ICU_Backward_Search(){
    StringSearchPerfFunction* func = new StringSearchPerfFunction(ICUBackwardSearch, srch, src, srcLen, pttrn, pttrnLen);
    return func;
}

int main (int argc, const char* argv[]) {
    UErrorCode status = U_ZERO_ERROR;
    StringSearchPerformanceTest test(argc, argv, status);
    if(U_FAILURE(status)){
        return status;
    }
    if(test.run()==FALSE){
        fprintf(stderr,"FAILED: Tests could not be run please check the arguments.\n");
        return -1;
    }
    return 0;
}


text:
using System;
using System.Diagnostics.Contracts;
using System.Text;

namespace System.IO
{

    public class StreamWriter : TextWriter
    {
        public virtual extern bool AutoFlush { get; set; }

        public virtual Stream BaseStream
        {
            get
            {
                Contract.Ensures(Contract.Result<Stream>() != null);
                return default(Stream);
            }
        }

#if false
        public System.Text.Encoding Encoding
        {
          get;
        }
    public void Write(string value)
    {

    }
#endif
#if false

    public void Write(char[] buffer, int index, int count)
    {
      Contract.Requires(buffer != null);
      Contract.Requires(index >= 0);
      Contract.Requires(count >= 0);
      Contract.Requires(index + count <= buffer.Length);

    }
    public void Write(char[] buffer)
    {

    }
    public void Write(char value)
    {

    }
    public void Flush()
    {

    }
    public void Close()
    {

    }
    public StreamWriter(string path, bool append, System.Text.Encoding encoding, int bufferSize)
    {
      Contract.Requires(path != null);
      Contract.Requires(encoding != null);
      Contract.Requires(bufferSize > 0);

      return default(StreamWriter);
    }
    public StreamWriter(string path, bool append, System.Text.Encoding encoding)
    {
      Contract.Requires(path != null);
      Contract.Requires(encoding != null);

      return default(StreamWriter);
    }
    public StreamWriter(string path, bool append)
    {
      Contract.Requires(path != null);

      return default(StreamWriter);
    }
    public StreamWriter(string path)
    {
      Contract.Requires(path != null);

      return default(StreamWriter);
    }
    public StreamWriter(Stream stream, System.Text.Encoding encoding, int bufferSize)
    {
      Contract.Requires(stream != null);
      Contract.Requires(encoding != null);
      Contract.Requires(bufferSize > 0);

      return default(StreamWriter);
    }
    public StreamWriter(Stream stream, System.Text.Encoding encoding)
    {
      Contract.Requires(stream != null);
      Contract.Requires(encoding != null);
    }
#endif

        public StreamWriter(Stream stream)
        {
            Contract.Requires(stream != null);
        }

        public StreamWriter(string path)
        {
            Contract.Requires(!String.IsNullOrEmpty(path));
            Contract.EnsuresOnThrow<System.IO.IOException>(true,@"path includes an incorrect or invalid syntax for file name, directory name, or volume label.");
            Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true,@"The specified path is invalid (for example, it is on an unmapped drive.");
            Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file cannot be found.");
        }

        public StreamWriter(Stream stream, Encoding encoding)
        {
            Contract.Requires(stream != null);
            Contract.Requires(encoding != null);
        }

        public StreamWriter(string path, bool append)
        {
            Contract.Requires(!String.IsNullOrEmpty(path));
            Contract.EnsuresOnThrow<System.IO.IOException>(true,
                                                           @"path includes an incorrect or invalid syntax for file name, directory name, or volume label.");
            Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true,@"The specified path is invalid (for example, it is on an unmapped drive.");
            Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true,@"The specified path, file name, or both exceed the system-defined maximum length.");
        }

        public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
        {
            Contract.Requires(stream != null);
            Contract.Requires(encoding != null);
            Contract.Requires(bufferSize >= 0);
        }

        public StreamWriter(string path, bool append, Encoding encoding)
        {
            Contract.Requires(!String.IsNullOrEmpty(path));
            Contract.EnsuresOnThrow<System.IO.IOException>(true,@"path includes an incorrect or invalid syntax for file name, directory name, or volume label.");
            Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true,@"The specified path is invalid (for example, it is on an unmapped drive.");
            Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true,@"The specified path, file name, or both exceed the system-defined maximum length.");
        }

        public StreamWriter(string path, bool append, Encoding encoding, int bufferSize)
        {
            Contract.Requires(!String.IsNullOrEmpty(path));
            Contract.Requires(encoding != null);
            Contract.Requires(bufferSize >= 0);
            Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path includes an incorrect or invalid syntax for file name, directory name, or volume label.");
            Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
            Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
        }

        public override void Write(char value)
        {
            Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs.");
        }

        public override void Write(char[] buffer)
        {
            Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs.");
        }

        public override void Write(string value)
        {
            Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs.");
        }

        public override void Write(char[] buffer, int index, int count)
        {
            Contract.Requires(buffer != null);
            Contract.Requires(index >= 0);
            Contract.Requires(count >= 0);
            Contract.Requires((buffer.Length - index) >= count);
            Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs.");
        }

#if false
        public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
        {
            Contract.Requires(stream != null);
            Contract.Requires(encoding != null);
            Contract.Requires(bufferSize >= 0);
        }

#endif
    }
}


text:
package org.apache.xbean.propertyeditor;

/**
 * @version $Rev: 6680 $ $Date: 2005-12-24T04:38:27.427468Z $
 */
public class StringEditor extends AbstractConverter {
    public StringEditor() {
        super(String.class);
    }

    protected Object toObjectImpl(String text) {
        return text;
    }
}


text:
package com.bafomdad.realfilingcabinet.init;

import com.bafomdad.realfilingcabinet.RealFilingCabinet;
import com.bafomdad.realfilingcabinet.entity.EntityCabinet;
import com.bafomdad.realfilingcabinet.entity.ModelEntityCabinet;
import com.bafomdad.realfilingcabinet.entity.RenderEntityCabinet;
import com.bafomdad.realfilingcabinet.helpers.ResourceUpgradeHelper;

import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class RFCEntities {

	public static void init() {

		EntityRegistry.registerModEntity(new ResourceLocation(RealFilingCabinet.MOD_ID, "entitycabinet"), EntityCabinet.class, "cabinet", 0, RealFilingCabinet.instance, 64, 3, true, 0xFFFFFF, 0xEBE1DF);
	}

	@SideOnly(Side.CLIENT)
	public static void initModels() {

		RenderingRegistry.registerEntityRenderingHandler(EntityCabinet.class, RenderEntityCabinet.FACTORY);
	}
}


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 com.facebook.presto.memory;

import com.facebook.presto.Session;
import com.facebook.presto.execution.buffer.TestingPagesSerdeFactory;
import com.facebook.presto.operator.Driver;
import com.facebook.presto.operator.DriverContext;
import com.facebook.presto.operator.Operator;
import com.facebook.presto.operator.OperatorContext;
import com.facebook.presto.operator.OutputFactory;
import com.facebook.presto.operator.TableScanOperator;
import com.facebook.presto.operator.TaskContext;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.QueryId;
import com.facebook.presto.spi.memory.MemoryPoolId;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spiller.SpillSpaceTracker;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.facebook.presto.testing.LocalQueryRunner;
import com.facebook.presto.testing.PageConsumerOperator.PageConsumerOutputFactory;
import com.facebook.presto.tpch.TpchConnectorFactory;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.units.DataSize;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

import static com.facebook.presto.testing.LocalQueryRunner.queryRunnerWithInitialTransaction;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static com.facebook.presto.testing.TestingTaskContext.createTaskContext;
import static io.airlift.units.DataSize.Unit.BYTE;
import static io.airlift.units.DataSize.Unit.GIGABYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

@Test(singleThreaded = true)
public class TestMemoryPools
{
    private static final DataSize TEN_MEGABYTES = new DataSize(10, MEGABYTE);
    private static final DataSize TEN_MEGABYTES_WITHOUT_TWO_BYTES = new DataSize(TEN_MEGABYTES.toBytes() - 2, BYTE);
    private static final DataSize ONE_BYTE = new DataSize(1, BYTE);

    private QueryId fakeQueryId;
    private LocalQueryRunner localQueryRunner;
    private MemoryPool userPool;
    private MemoryPool systemPool;
    private List<Driver> drivers;
    private TaskContext taskContext;

    private void setUp(Supplier<List<Driver>> driversSupplier)
    {
        Session session = testSessionBuilder()
                .setCatalog("tpch")
                .setSchema("tiny")
                .setSystemProperty("task_default_concurrency", "1")
                .build();

        localQueryRunner = queryRunnerWithInitialTransaction(session);

        // add tpch
        localQueryRunner.createCatalog("tpch", new TpchConnectorFactory(1), ImmutableMap.of());

        userPool = new MemoryPool(new MemoryPoolId("test"), TEN_MEGABYTES);
        systemPool = new MemoryPool(new MemoryPoolId("testSystem"), TEN_MEGABYTES);
        fakeQueryId = new QueryId("fake");
        SpillSpaceTracker spillSpaceTracker = new SpillSpaceTracker(new DataSize(1, GIGABYTE));
        QueryContext queryContext = new QueryContext(new QueryId("query"), TEN_MEGABYTES, userPool, systemPool, localQueryRunner.getExecutor(), TEN_MEGABYTES, spillSpaceTracker);
        taskContext = createTaskContext(queryContext, localQueryRunner.getExecutor(), session);
        drivers = driversSupplier.get();
    }

    private void setUpCountStarFromOrdersWithJoin()
    {
        // query will reserve all memory in the user pool and discard the output
        setUp(() -> {
            OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> { }));
            return localQueryRunner.createDrivers("SELECT COUNT(*) FROM orders JOIN lineitem USING (orderkey)", outputFactory, taskContext);
        });
    }

    private RevocableMemoryOperator setupConsumeRevocableMemory(DataSize reservedPerPage, long numberOfPages)
    {
        AtomicReference<RevocableMemoryOperator> createOperator = new AtomicReference<>();
        setUp(() -> {
            DriverContext driverContext = taskContext.addPipelineContext(0, false, false).addDriverContext();
            OperatorContext revokableOperatorContext = driverContext.addOperatorContext(
                    Integer.MAX_VALUE,
                    new PlanNodeId("revokable_operator"),
                    TableScanOperator.class.getSimpleName());

            OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> { }));
            Operator outputOperator = outputFactory.createOutputOperator(2, new PlanNodeId("output"), ImmutableList.of(), Function.identity(), new TestingPagesSerdeFactory()).createOperator(driverContext);
            RevocableMemoryOperator revocableMemoryOperator = new RevocableMemoryOperator(revokableOperatorContext, reservedPerPage, numberOfPages);
            createOperator.set(revocableMemoryOperator);

            return ImmutableList.of(new Driver(driverContext, revocableMemoryOperator, outputOperator));
        });
        return createOperator.get();
    }

    @AfterTest
    public void tearDown()
            throws Exception
    {
        localQueryRunner.close();
    }

    @Test
    public void testBlockingOnUserMemory()
            throws Exception
    {
        setUpCountStarFromOrdersWithJoin();
        assertTrue(userPool.tryReserve(fakeQueryId, TEN_MEGABYTES.toBytes()));
        runDriversUntilBlocked(waitingForUserMemory());
        assertTrue(userPool.getFreeBytes() <= 0, String.format("Expected empty pool but got [%d]", userPool.getFreeBytes()));
        userPool.free(fakeQueryId, TEN_MEGABYTES.toBytes());
        assertDriversProgress(waitingForUserMemory());
    }

    @Test
    public void testBlockingOnRevocableMemoryFreeUser()
            throws Exception
    {
        setupConsumeRevocableMemory(ONE_BYTE, 10);
        assertTrue(userPool.tryReserve(fakeQueryId, TEN_MEGABYTES_WITHOUT_TWO_BYTES.toBytes()));

        // we expect 2 iterations as we have 2 bytes remaining in system pool and we allocate 1 byte per page
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2);
        assertTrue(userPool.getFreeBytes() <= 0, String.format("Expected empty pool but got [%d]", userPool.getFreeBytes()));

        // lets free 5 bytes
        userPool.free(fakeQueryId, 5);
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 5);
        assertTrue(userPool.getFreeBytes() <= 0, String.format("Expected empty pool but got [%d]", userPool.getFreeBytes()));

        // 3 more bytes is enough for driver to finish
        userPool.free(fakeQueryId, 3);
        assertDriversProgress(waitingForRevocableSystemMemory());
        assertEquals(userPool.getFreeBytes(), 10);
    }

    @Test
    public void testBlockingOnRevocableMemoryFreeViaRevoke()
            throws Exception
    {
        RevocableMemoryOperator revocableMemoryOperator = setupConsumeRevocableMemory(ONE_BYTE, 5);
        assertTrue(userPool.tryReserve(fakeQueryId, TEN_MEGABYTES_WITHOUT_TWO_BYTES.toBytes()));

        // we expect 2 iterations as we have 2 bytes remaining in system pool and we allocate 1 byte per page
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2);
        revocableMemoryOperator.getOperatorContext().requestMemoryRevoking();

        // 2 more iterations
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2);
        revocableMemoryOperator.getOperatorContext().requestMemoryRevoking();

        // 3 more bytes is enough for driver to finish
        assertDriversProgress(waitingForRevocableSystemMemory());
        assertEquals(userPool.getFreeBytes(), 2);
    }

    private long runDriversUntilBlocked(Predicate<OperatorContext> reason)
    {
        long iterationsCount = 0;

        // run driver, until it blocks
        while (!isOperatorBlocked(drivers, reason)) {
            for (Driver driver : drivers) {
                driver.process();
            }
            iterationsCount++;
        }

        // driver should be blocked waiting for memory
        for (Driver driver : drivers) {
            assertFalse(driver.isFinished());
        }
        return iterationsCount;
    }

    private void assertDriversProgress(Predicate<OperatorContext> reason)
    {
        do {
            assertFalse(isOperatorBlocked(drivers, reason));
            boolean progress = false;
            for (Driver driver : drivers) {
                ListenableFuture<?> blocked = driver.process();
                progress = progress | blocked.isDone();
            }
            // query should not block
            assertTrue(progress);
        } while (!drivers.stream().allMatch(Driver::isFinished));
    }

    private Predicate<OperatorContext> waitingForUserMemory()
    {
        return (OperatorContext operatorContext) -> !operatorContext.isWaitingForMemory().isDone();
    }

    private Predicate<OperatorContext> waitingForRevocableSystemMemory()
    {
        return (OperatorContext operatorContext) ->
                !operatorContext.isWaitingForRevocableMemory().isDone() &&
                        !operatorContext.isMemoryRevokingRequested();
    }

    private static boolean isOperatorBlocked(List<Driver> drivers, Predicate<OperatorContext> reason)
    {
        for (Driver driver : drivers) {
            for (OperatorContext operatorContext : driver.getDriverContext().getOperatorContexts()) {
                if (reason.apply(operatorContext)) {
                    return true;
                }
            }
        }
        return false;
    }

    private class RevocableMemoryOperator
            implements Operator
    {
        private final DataSize reservedPerPage;
        private final long numberOfPages;
        private final OperatorContext operatorContext;
        private long producedPagesCount = 0;

        public RevocableMemoryOperator(OperatorContext operatorContext, DataSize reservedPerPage, long numberOfPages)
        {
            this.operatorContext = operatorContext;
            this.reservedPerPage = reservedPerPage;
            this.numberOfPages = numberOfPages;
        }

        @Override
        public ListenableFuture<?> startMemoryRevoke()
        {
            return Futures.immediateFuture(null);
        }

        @Override
        public void finishMemoryRevoke()
        {
            operatorContext.setRevocableMemoryReservation(0);
        }

        @Override
        public OperatorContext getOperatorContext()
        {
            return operatorContext;
        }

        @Override
        public List<Type> getTypes()
        {
            return ImmutableList.of();
        }

        @Override
        public void finish()
        {
            operatorContext.setRevocableMemoryReservation(0);
        }

        @Override
        public boolean isFinished()
        {
            return producedPagesCount >= numberOfPages;
        }

        @Override
        public boolean needsInput()
        {
            return false;
        }

        @Override
        public void addInput(Page page)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public Page getOutput()
        {
            operatorContext.reserveRevocableMemory(reservedPerPage.toBytes());
            producedPagesCount++;
            if (producedPagesCount == numberOfPages) {
                finish();
            }
            return new Page(10);
        }
    }
}


text:
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace LinqToDB.DataProvider
{
	public class DataTools
	{
		/// <summary>
		/// Improved version of <c>Replace("[", "[[]")</c> code, used before.
		/// </summary>
		[return: NotNullIfNotNull("str")]
		public static string? EscapeUnterminatedBracket(string? str)
		{
			if (str == null)
				return str;

			var nextIndex = str.IndexOf('[');
			if (nextIndex < 0)
				return str;

			var lastIndex = 0;
			var newStr = new StringBuilder(str.Length + 10);

			while (nextIndex >= 0)
			{
				if (nextIndex != 0)
					newStr.Append(str.Substring(lastIndex, nextIndex - lastIndex));

				lastIndex = nextIndex;

				var closeBracket = str.IndexOf(']', nextIndex + 1);
				nextIndex        = str.IndexOf('[', nextIndex + 1);

				if ((closeBracket > 0 && (closeBracket < nextIndex || nextIndex < 0))
				    ||
				    (closeBracket - lastIndex == 2 && closeBracket - nextIndex == 1))
				{
					if (nextIndex < 0)
						newStr.Append('[');
				}
				else
					newStr.Append("[[]");

			}

			newStr.Append(str.Substring(lastIndex + 1));
			return newStr.ToString();
		}

		static readonly char[] _escapes = { '\x0', '\'' };

		public static void ConvertStringToSql(
			StringBuilder stringBuilder,
			string plusOperator,
			string? startPrefix,
			Action<StringBuilder,int> appendConversion,
			string value,
			char[]? extraEscapes)
		{
			if (value.Length > 0
				&& (value.IndexOfAny(_escapes) >= 0 || (extraEscapes != null && value.IndexOfAny(extraEscapes) >= 0)))
			{
				var isInString = false;

				for (var i = 0; i < value.Length; i++)
				{
					var c = value[i];

					switch (c)
					{
						case '\x0' :
							if (isInString)
							{
								isInString = false;
								stringBuilder
									.Append('\'');
							}

							if (i != 0)
								stringBuilder
									.Append(' ')
									.Append(plusOperator)
									.Append(' ')
									;

							appendConversion(stringBuilder, c);

							break;

						case '\''  :
							if (!isInString)
							{
								isInString = true;

								if (i != 0)
									stringBuilder
										.Append(' ')
										.Append(plusOperator)
										.Append(' ')
										;

								stringBuilder.Append(startPrefix).Append('\'');
							}

							stringBuilder.Append("''");

							break;

						default   :
							if (extraEscapes != null && extraEscapes.Any(e => e == c))
							{
								if (isInString)
								{
									isInString = false;
									stringBuilder
										.Append('\'');
								}

								if (i != 0)
									stringBuilder
										.Append(' ')
										.Append(plusOperator)
										.Append(' ')
										;

								appendConversion(stringBuilder, c);
								break;
							}

							if (!isInString)
							{
								isInString = true;

								if (i != 0)
									stringBuilder
										.Append(' ')
										.Append(plusOperator)
										.Append(' ')
										;

								stringBuilder.Append(startPrefix).Append('\'');
							}

							stringBuilder.Append(c);

							break;
					}
				}

				if (isInString)
					stringBuilder.Append('\'');
			}
			else
			{
				stringBuilder
					.Append(startPrefix)
					.Append('\'')
					.Append(value)
					.Append('\'')
					;
			}
		}

		public static void ConvertCharToSql(StringBuilder stringBuilder, string startString, Action<StringBuilder,int> appendConversion, char value)
		{
			switch (value)
			{
				case '\x0' :
					appendConversion(stringBuilder,value);
					break;

				case '\''  :
					stringBuilder
						.Append(startString)
						.Append("''")
						.Append('\'')
						;
					break;

				default    :
					stringBuilder
						.Append(startString)
						.Append(value)
						.Append('\'')
						;
					break;
			}
		}

		public static Expression<Func<DbDataReader, int, string>> GetCharExpression = (dr, i) => GetCharFromString(dr.GetString(i));

		private static string GetCharFromString(string str)
		{
			if (str.Length > 0)
				return str[0].ToString();

			return string.Empty;
		}

		#region Create/Drop Database

		internal static void CreateFileDatabase(
			string databaseName,
			bool deleteIfExists,
			string extension,
			Action<string> createDatabase)
		{
			databaseName = databaseName.Trim();

			if (!databaseName.ToLower().EndsWith(extension))
				databaseName += extension;

			if (File.Exists(databaseName))
			{
				if (!deleteIfExists)
					return;
				File.Delete(databaseName);
			}

			createDatabase(databaseName);
		}

		internal static void DropFileDatabase(string databaseName, string extension)
		{
			databaseName = databaseName.Trim();

			if (File.Exists(databaseName))
			{
				File.Delete(databaseName);
			}
			else
			{
				if (!databaseName.ToLower().EndsWith(extension))
				{
					databaseName += extension;

					if (File.Exists(databaseName))
						File.Delete(databaseName);
				}
			}
		}
		#endregion
	}
}


text:
from scipy import stats

def loadData():
	x = []
	y = []
	mmm = open('data/mmm.csv')
	spy = open('data/spy.csv')

	for line in mmm.readlines():
		lineArr1 = line.strip().split('\r')
		for element in lineArr1:
			ele = element.split(',')
			temp = float(ele[5])
			x.append(temp)
#		lineX = map(float, line.strip().split('\n'))

#		mmm_open, mmm_high, mmm_low, mmm_close, mmm_volume, mmm_adjusted = line.split(",")
#		x.extend(mmm_adjusted)
	for line in spy.readlines():
		lineArr2 = line.strip().split('\r')

		y.extend(float(lineArr2[5]))
#		spy_open, spy_high, spy_low, spy_close, spy_volume, spy_adjusted = line.split(",")
#		y.extend(spy_adjusted)
	return (mat(x).transpose(), mat(y).transpose())

y, x = loadData()
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
print "Gradient and intercept", gradient, intercept
#print "R-squared", r_value**2
#print "p-value", p_value


text:
package com.bddinaction.flyinghigh.model;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public enum Status {

    Bronze(0), Silver(300), Gold(700), Platinum(1500);

    private final int minimumPoints;

    Status(int minimumPoints) {
        this.minimumPoints = minimumPoints;
    }

    public static Status statusLevelFor(int points) {
        List<Status> statusesInDescendingOrder = Arrays.asList(Status.values());
        Collections.reverse(statusesInDescendingOrder);
        for(Status status : statusesInDescendingOrder) {
            if (points >= status.getMinimumPoints()) {
                return status;
            }
        }
        return Bronze;
    }

    public int getMinimumPoints() {
        return minimumPoints;
    }

}


text:
package org.drools.template.objects;

import org.drools.template.DataProvider;
import org.drools.template.parser.Column;
import org.drools.template.parser.TemplateContainer;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * An object of this class acts as a DataProvider for rule templates.
 * It may be created with a collection of maps or objects. The template's
 * column names are used as keys or Bean-stype accessors to obtain the
 * actual parameters for the substitution.
 */
public class ObjectDataProvider implements DataProvider {

    private Column[]    columns;
    private Iterator<?> iter;

    /**
     * Constructor from a template container
     *
     * @param tcont a template container
     * @param objs  a collection of maps or objects
     */
    public ObjectDataProvider(TemplateContainer tcont, Collection<?> objs) {
        columns = tcont.getColumns();
        iter = objs.iterator();
    }

    public boolean hasNext() {
        return iter.hasNext();
    }

    private Method getMethod(Class<?> clazz, String field) {
        String Field = Character.toUpperCase(field.charAt(0)) + field.substring(1);
        String getter = "get" + Field;
        try {
            return clazz.getMethod(getter);
        } catch (SecurityException e) {
            return null;
        } catch (NoSuchMethodException e) {
        }
        getter = "is" + Field;
        try {
            return clazz.getMethod(getter);
        } catch (SecurityException e) {
            return null;
        } catch (NoSuchMethodException e) {
        }
        getter = field;
        try {
            return clazz.getMethod(getter);
        } catch (Exception e) {
            return null;
        }
    }

    private Field getField(Class<?> clazz, String field) {
        try {
            return clazz.getField(field);
        } catch (Exception e) {
            return null;
        }
    }

    private String[] nextFromMap(Object obj) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map) obj;
        String[] values = new String[columns.length];
        for (int iCol = 0; iCol < columns.length; iCol++) {
            Object target = map.get(columns[iCol].getName());
            values[iCol] = target == null ? null : target.toString();
        }
        return values;
    }

    private String[] nextFromObject(Object obj) {
        Class<?> clazz = obj.getClass();
        String[] values = new String[columns.length];
        for (int iCol = 0; iCol < columns.length; iCol++) {
            String fieldName = columns[iCol].getName();
            Object val = null;
            try {
                Method method = getMethod(clazz, fieldName);
                if (method != null) {
                    val = method.invoke(obj);
                } else {
                    Field field = getField(clazz, fieldName);
                    if (field != null) {
                        val = field.get(obj);
                    }
                }
            } catch (Exception e) {
                // leave it null
            }
            values[iCol] = val == null ? null : val.toString();
        }
        return values;
    }

    public String[] next() {
        Object obj = iter.next();
        if (obj instanceof Map) {
            return nextFromMap(obj);
        } else {
            return nextFromObject(obj);
        }
    }
}


text:
package hu.experiment_team;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.util.Random;

/**
 * Created by Jakab on 2016.04.03..
 */
public enum PokemonUtils {
    INSTANCE;

    public ImageView getPokemonImageView(int id){

        ImageView pokemonImage;

        /*
        if(id < 10)
            pokemonImage = new ImageView("/images/battlers/00" + String.valueOf(id) + ".gif");
        else if (id < 100)
            pokemonImage = new ImageView("/images/battlers/0" + String.valueOf(id) + ".gif");
        else
            pokemonImage = new ImageView("/images/battlers/" + String.valueOf(id) + ".gif");
        */

        pokemonImage = new ImageView("/images/battlers/pokiAdiss.gif");

        pokemonImage.setPreserveRatio(true);
        pokemonImage.setFitHeight(80);

        return pokemonImage;
    }

    public Image getPokemonImage(int id){

        Image pokemonImage;

        /*
        if(id < 10)
            pokemonImage = new Image("/images/battlers/00" + String.valueOf(id) + ".gif");
        else if (id < 100)
            pokemonImage = new Image("/images/battlers/0" + String.valueOf(id) + ".gif");
        else
            pokemonImage = new Image("/images/battlers/" + String.valueOf(id) + ".gif");
        */

        pokemonImage = new Image("/images/battlers/pokiAdiss.gif");

        return pokemonImage;
    }

    public Image getPokemonBackImage(int id){

        Image pokemonImage;

        /*
        if(id < 10)
            pokemonImage = new Image("/images/battlers/00" + String.valueOf(id) + "b.gif");
        else if (id < 100)
            pokemonImage = new Image("/images/battlers/0" + String.valueOf(id) + "b.gif");
        else
            pokemonImage = new Image("/images/battlers/" + String.valueOf(id) + "b.gif");
        */
        pokemonImage = new Image("/images/battlers/pokiAdiss_b.gif");

        return pokemonImage;
    }

    public Image getRandomTrainerImage(){
        Random r = new Random();
        return new Image("/images/trainers/" + r.nextInt(8) + ".png");
    }

}


text:
package com.orientechnologies.orient.enterprise.channel.binary;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import com.orientechnologies.common.thread.OSoftThread;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;

/**
 * Service thread that catches internal messages sent by the server
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 */
public class OAsynchChannelServiceThread extends OSoftThread {
	private OChannelBinaryClient				network;
	private int													sessionId;
	private ORemoteServerEventListener	remoteServerEventListener;
	private static AtomicInteger				sessionIdSerial	= new AtomicInteger(Integer.MIN_VALUE);

	public OAsynchChannelServiceThread(final ORemoteServerEventListener iRemoteServerEventListener,
			final OChannelBinaryClient iFirstChannel, final String iThreadName) {
		super(Orient.getThreadGroup(), iThreadName);
		sessionId = sessionIdSerial.getAndIncrement();
		remoteServerEventListener = iRemoteServerEventListener;
		network = iFirstChannel;
		start();
	}

	@Override
	protected void execute() throws Exception {
		try {
			try {
				network.beginResponse(sessionId);
				final byte request = network.readByte();

				Object obj = null;

				switch (request) {
				case OChannelBinaryProtocol.REQUEST_PUSH_RECORD:
					obj = (ORecordInternal<?>) OChannelBinaryProtocol.readIdentifiable(network);
					break;

				case OChannelBinaryProtocol.PUSH_NODE2CLIENT_DB_CONFIG:
					obj = new ODocument().fromStream(network.readBytes());
					break;
				}

				if (remoteServerEventListener != null)
					remoteServerEventListener.onRequest(request, obj);

			} catch (IOException ioe) {
				// EXCEPTION RECEIVED (THE SOCKET HAS BEEN CLOSED?) ASSURE TO UNLOCK THE READ AND EXIT THIS THREAD
				sendShutdown();
				network.close();

			} finally {
				network.endResponse();
			}

		} catch (Exception e) {
			// OLogManager.instance().error(this, "Error in service thread", e);
			sendShutdown();
		}
	}
}


text:
"use strict";

var mowa = module.exports = require('./lib/mowa.js');


text:
<?php
if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"]))
	exit ("Do not access this file directly.");
?>


text:
using System;
using System.Windows.Input;

namespace WickedSick.MVVM
{
    public class RelayCommand : ICommand
    {
        private Action _Execute;
        private Func<bool> _CanExecute;

        public RelayCommand(Action execute)
            : this(execute, () => true)
        {
        }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            _Execute = execute;
            _CanExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _CanExecute();
        }

        public event EventHandler CanExecuteChanged;

        public void ForceCanExecuteChanged()
        {
            var obj = CanExecuteChanged;
            if (obj != null)
                obj(this, new EventArgs());
        }

        public void Execute(object parameter = null)
        {
            _Execute();
        }
    }

    public class RelayCommand<T> : ICommand
    {
        private Action<T> _Execute;
        private Func<T, bool> _CanExecute;

        public RelayCommand(Action<T> execute)
            : this(execute, t => true)
        {
        }

        public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentException("Invalid execute action.");
            if (canExecute == null)
                throw new ArgumentException("Invalid can execute func.");
            _Execute = execute;
            _CanExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _CanExecute((T)parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void ForceCanExecuteChanged()
        {
            var obj = CanExecuteChanged;
            if (obj != null)
                obj(this, new EventArgs());
        }

        public void Execute(object parameter)
        {
            _Execute((T)parameter);
        }
    }
}


text:
layout:     post
title:      "LeetCode: Symmetric Tree"
subtitle:   " \"对称树的判定\""
date:       2015-11-20 23:30:00
author:     "Beld"
header-img: "img/post-bg-tree.png"
tags:
    - LeetCode
---

[题目链接](https://leetcode.com/problems/symmetric-tree/)

题目很简单,基本与same tree一样,稍加改动即可。

#### 递归 Recursion

忘记了对空树的判断。

```java
public boolean isSymmetric(TreeNode root) {
    if (root == null) {
        return true;
    } else {
        return isSymmetricTree(root.left, root.right);
    }
}

public boolean isSymmetricTree(TreeNode left, TreeNode right) {
    if (left == null && right == null) {
        return true;
    } else if (left == null || right ==null ) {
        return false;
    } else {
       return (left.val == right.val) && isSymmetricTree(left.left, right.right)
                                      && isSymmetricTree(left.right, right.left);
    }
}
```

#### 非递归,迭代,Iteration

```java
public boolean isSymmetric(TreeNode root) {
    if (root == null) {
        return true;
    } else {
        return isSymmetricTree(root.left, root.right);
    }
}

public boolean isSymmetricTree(TreeNode left, TreeNode right) {
    LinkedList<TreeNode> stackL = new LinkedList<TreeNode>();
    LinkedList<TreeNode> stackR = new LinkedList<TreeNode>();
    stackL.push(left);
    stackR.push(right);
    while(!stackL.isEmpty() && !stackR.isEmpty()) {
        left = stackL.pop();
        right = stackR.pop();
        if (left == null) {
            if (right != null) {
                return false;
            } else continue;
        } else if (right == null) {
            return false;
        } else {
            if (left.val != right.val) {
                return false;
            } else {
                stackL.push(left.left);
                stackR.push(right.right);
                stackL.push(left.right);
                stackR.push(right.left);
            }
        }
    }
    return true;
}
```


text:
import createSchema from 'part:@sanity/base/schema-creator'

// Then import schema types from any plugins that might expose them
import schemaTypes from 'all:part:@sanity/base/schema-type'

// We import object and document schemas
import blockContent from './blockContent'
import category from './category'
import post from './post'
import author from './author'

// Then we give our schema to the builder and provide the result to Sanity
export default createSchema({
  // We name our schema
  name: 'default',
  // Then proceed to concatenate our document type
  // to the ones provided by any plugins that are installed
  types: schemaTypes.concat([
    // The following are document types which will appear
    // in the studio.
    post,
    author,
    category,
    // When added to this list, object types can be used as
    // { type: 'typename' } in other document schemas
    blockContent,
  ]),
})


text:
// Copyright 2018 Google LLC
//
// 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 com.google.firebase.components;

import java.util.concurrent.atomic.AtomicBoolean;

/** Records a side-effect by a depended upon component. */
public class InitTracker {
  private final AtomicBoolean initialized = new AtomicBoolean(false);

  public void initialize() {
    initialized.set(true);
  }

  public boolean isInitialized() {
    return initialized.get();
  }
}


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

-- | Tests for 'Streams'.
--
-- The tests here use QuickCheck's monadic testing framework, defined
-- in the module 'Test.QuickCheck.Monadic', and try to follow some of
-- the ideas in the paper "Testing Monadic Code with QuickCheck" by
-- Koen Classen and John Hughes. In particular, I've created an
-- 'Action' type and tried exercising properties after achieving
-- reachable states by executing constrained sequences of actions.

module StreamTests (test) where

import Control.Applicative ((<$>), (<*>))
import Control.Exception (SomeException, try)
import Control.Monad (void, unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.IORef (IORef, newIORef, atomicModifyIORef, readIORef)
import Data.List (foldl')
import Data.Maybe (isNothing, catMaybes)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck (Gen, arbitrary, choose, oneof, sized, vectorOf, forAll, Property)
import Test.QuickCheck.Monadic (PropertyM, run, pick, monadicIO, assert, forAllM, pre, stop)
import Test.QuickCheck.Property (failed, reason)

import Network.SPDY.Frames (StreamID(..), DeltaWindowSize)
import Network.SPDY.Internal.BoundedBuffer (Sized(..))
import Network.SPDY.Stream hiding (updateOutgoingWindowSize)
import qualified Network.SPDY.Stream as S

import Instances ()

test :: Test
test = testGroup "All stream model and stream tests" [
  testGroup "Stream model tests" [
     testProperty "Model adds content when there is room, updates local window size"
     prop_specAddIncoming,
     testProperty "Model refuses to add oversized content"
     prop_specRefuseAddIncoming
     ],
  testGroup "Stream tests" [
     testProperty "Pusher if and only if local half-open" $
     monadicIO $ propM_pusherIffLocalHalfOpen,
     testProperty "Reject incoming data chunks that are bigger than the remaining free space" $
     monadicIO $ propM_rejectIncomingDataBiggerThanFreeSpace,
     testProperty "Updating outgoing window size follows spec" $
     monadicIO $ propM_updateOutgoingWindowSize,
     testProperty "Pushing content follows spec" $
     monadicIO $ propM_push,
     testProperty "Buffering incoming content follows spec if there's room" $
     monadicIO $ propM_addIncoming,
     testProperty "Pulling buffered content follows spec" $
     monadicIO $ propM_pull
     ]
  ]

-- model tests, ordinary QuickCheck tests that confirm that the model
-- has the properties we desire

prop_specAddIncoming :: Property
prop_specAddIncoming =
  forAll genReachableModel $ \sm ->
  forAll (genIncomingContent sm) $ \c ->
  let (added, sm') = specAddIncoming c sm
  in added &&
     smBuffered sm' == smBuffered sm ++ [c] &&
     smLocalDWS sm' == smLocalDWS sm - size c

prop_specRefuseAddIncoming :: Property
prop_specRefuseAddIncoming =
  forAll genReachableModel $ \sm ->
  forAll (genOversizedIncomingContent sm) $ \c ->
  let (added, sm') = specAddIncoming c sm
  in not added && sm' == sm

-- Tests of the real stream implementation. Most of these are tests
-- for correspondence between the model and the real implementation.

propM_pusherIffLocalHalfOpen :: PropertyM IO ()
propM_pusherIffLocalHalfOpen = forAllM arbitrary $ \halfClosed -> do
  (_, maybePusher, _) <- doNothingStream halfClosed
  assert $ halfClosed == isNothing maybePusher

propM_rejectIncomingDataBiggerThanFreeSpace :: PropertyM IO ()
propM_rejectIncomingDataBiggerThanFreeSpace =
  forAllReachable $ \ts -> do
    freeSpace <- run $ smLocalDWS <$> abstract ts
    c    <- pick $ bytesBetween (freeSpace + 1) (2 * freeSpace + 2)
    last <- pick arbitrary
    queued <- run $ addIncomingData (tsStream ts) c last
    assert $ not queued

propM_updateOutgoingWindowSize :: PropertyM IO ()
propM_updateOutgoingWindowSize =
  implements' (fromTestStream genDeltaWindowSize)
  (flip updateOutgoingWindowSize) specUpdateOutgoingWindowSize

propM_push :: PropertyM IO ()
propM_push =
  implements' (fromTestStream genOutgoingContent) (flip push) specPush

propM_addIncoming :: PropertyM IO ()
propM_addIncoming =
  implements (fromTestStream $ \sm ->
               oneof [genIncomingContent sm
                     ,genOversizedIncomingContent sm])
  (flip addIncoming) specAddIncoming

propM_pull :: PropertyM IO ()
propM_pull =
  implementsIf
  (run . (not . null . smBuffered <$>) . abstract)
  (const $ return ())
  (const pull) (const specPull)

-- We approach testing a stream in one of the ways described by
-- Klassen and Hughes: assert that the stream implements a pure model,
-- under randomly reachable states. In order to generate randomly
-- reachable states, we defines a small language of stream actions,
-- and generate legal sequences of actions. Both the stream and the
-- abstract model of the stream can interpret these actions.

-- There is one wrinkle though: since a stream has callback actions
-- for sending content and window updates, we need to do a little work
-- to make use of the callbacks observable. Here, we embed a Stream in
-- a TestStream and supply it with callbacks that update parts of the
-- TestStream.

data TestStream =
  TestStream { tsStream :: Stream
             , tsPush :: StreamContent -> IO ()
             , tsPull :: IO StreamContent
             , tsRemoteBufSize :: Int
             , tsPushed :: IORef [StreamContent]
             , tsSentWUs :: IORef [DeltaWindowSize] }

newTestStream :: StreamID -> Int -> Int -> IO TestStream
newTestStream sid remoteBufSize localBufSize = do
  pushed <- newIORef []
  sentWUs <- newIORef []
  let opts = NewStreamOpts remoteBufSize localBufSize False recordOutgoing recordWindowUpdate doNothing
      recordOutgoing = doAppend pushed
      recordWindowUpdate = doAppend sentWUs
      doAppend xsRef x = atomicModifyIORef xsRef (\xs -> (xs ++ [x], ()))
  (s, Just push, pull) <- newStream sid opts
  return TestStream { tsStream = s
                    , tsPush = push
                    , tsPull = pull
                    , tsRemoteBufSize = remoteBufSize
                    , tsPushed = pushed
                    , tsSentWUs = sentWUs}

push :: TestStream -> StreamContent -> IO ()
push ts  = tsPush ts

addIncoming :: TestStream -> StreamContent -> IO Bool
addIncoming ts = forContent forHeaders forData
  where forHeaders hs last = addIncomingHeaders (tsStream ts) hs last >> return True
        forData bs last = addIncomingData (tsStream ts) bs last

addIncomingOrDie :: TestStream -> StreamContent -> IO ()
addIncomingOrDie ts sc = do
  added <- addIncoming ts sc
  unless added $ failedToAdd "test stream" sc =<< abstract ts

pull :: TestStream -> IO StreamContent
pull ts = tsPull ts

updateOutgoingWindowSize :: TestStream -> DeltaWindowSize -> IO ()
updateOutgoingWindowSize ts = S.updateOutgoingWindowSize (tsStream ts)

abstract :: TestStream -> IO StreamModel
abstract ts = do
  (remoteWindowSize, localWindowSize, buffered) <- snapshot $ tsStream ts
  pushed <- readIORef $ tsPushed ts
  sentWUs <- readIORef $ tsSentWUs ts
  return StreamModel { smRemoteBufSize = tsRemoteBufSize ts
                     , smRemoteDWS = remoteWindowSize
                     , smPushed = pushed
                     , smSentWUs = sentWUs
                     , smLocalDWS = localWindowSize
                     , smBuffered = buffered }

data StreamModel =
  StreamModel { smRemoteBufSize :: Int
                -- ^ Total remote buffering capacity, or the initial
                -- remote window size
              , smRemoteDWS :: Int
                -- ^ Remote data window size
              , smPushed :: [StreamContent]
                -- ^ Content sent on the stream
              , smSentWUs :: [DeltaWindowSize]
                -- ^ Window updates sent to the remote end
              , smLocalDWS :: Int
                -- ^ Local data window size
              , smBuffered :: [StreamContent]
                -- ^ Content in the local buffer
              }
  deriving (Eq, Show)

specPush :: StreamContent -> StreamModel -> StreamModel
specPush sc sm =
  forContent forHeaders forData sc
  where forHeaders _ _ = sm'
        forData c _ = sm' { smRemoteDWS = smRemoteDWS sm' - size c }
        sm' = sm { smPushed = smPushed sm ++ [sc] }

specAddIncoming :: StreamContent -> StreamModel -> (Bool, StreamModel)
specAddIncoming sc sm =
  forContent forHeaders forData sc
  where forHeaders _ _ = (True, sm')
        forData c _ = if size c <= smLocalDWS sm'
                      then (True, sm' { smLocalDWS = smLocalDWS sm' - size c })
                      else (False, sm)
        sm' = sm { smBuffered = smBuffered sm ++ [sc] }

specAddIncomingOrDie :: StreamContent -> StreamModel -> StreamModel
specAddIncomingOrDie sc sm =
  let (added, sm') = specAddIncoming sc sm
  in if added then sm' else failedToAdd "stream model" sc sm

specPull :: StreamModel -> (StreamContent, StreamModel)
specPull sm =
  (sc, forContent forHeaders forData sc)
  where sc = head $ smBuffered sm
        forHeaders _ _ = sm'
        forData c _ = sm' { smLocalDWS = smLocalDWS sm' + size c
                          , smSentWUs = smSentWUs sm ++ [ fromIntegral $ size c ] }
        sm' = sm { smBuffered = tail $ smBuffered sm }

specUpdateOutgoingWindowSize :: DeltaWindowSize -> StreamModel -> StreamModel
specUpdateOutgoingWindowSize wu sm =
  sm { smRemoteDWS = smRemoteDWS sm + fromIntegral wu }

failedToAdd :: String -> StreamContent -> StreamModel -> a
failedToAdd toWhat sc sm =
  error $
  "Failed to add incoming content of size " ++ show (size sc) ++
  " to " ++ toWhat ++
  " when there are " ++ show (smLocalDWS sm) ++
  " bytes free in the buffer."

data Action =
  Push StreamContent |
  AddIncoming StreamContent |
  Pull |
  UpdateOutgoingWindowSize DeltaWindowSize
  deriving (Eq, Show)

performAll :: TestStream -> [Action] -> IO ()
performAll s = mapM_ (performOne s)

performOne :: TestStream -> Action -> IO ()
performOne ts (Push sc) = push ts sc
performOne ts (AddIncoming sc) = addIncomingOrDie ts sc
performOne ts Pull = void (pull ts)
performOne ts (UpdateOutgoingWindowSize wu) = updateOutgoingWindowSize ts wu

specPerform :: StreamModel -> Action -> StreamModel
specPerform sm a = case a of
  Push sc -> specPush sc sm
  AddIncoming sc -> specAddIncomingOrDie sc sm
  Pull -> snd $ specPull sm
  UpdateOutgoingWindowSize wu -> specUpdateOutgoingWindowSize wu sm

-- | Generates a single non-blocking action and its effect on a stream
-- model.
step :: StreamModel -> Gen (StreamModel, Action)
step sm = do
  a <- oneof legalSteps
  return (specPerform sm a, a)
  where legalSteps =
          (if null (smBuffered sm) then [] else [return Pull]) ++
          [ Push <$> genOutgoingContent sm,
            AddIncoming <$> genIncomingContent sm,
            UpdateOutgoingWindowSize <$> genDeltaWindowSize sm ]

genOutgoingContent :: StreamModel -> Gen StreamContent
genOutgoingContent sm =
  oneof $ catMaybes [ Just genHeaders,
                      maybeGenData $ smRemoteDWS sm ]

genIncomingContent :: StreamModel -> Gen StreamContent
genIncomingContent sm =
  oneof $ catMaybes [ Just genHeaders,
                      maybeGenData $ smLocalDWS sm ]

genOversizedIncomingContent :: StreamModel -> Gen StreamContent
genOversizedIncomingContent sm =
  moreData <$> bytesBetween (localDWS + 1) (localDWS + 10) <*> arbitrary
    where localDWS = smLocalDWS sm

genHeaders :: Gen StreamContent
genHeaders = flip moreHeaders False <$> arbitrary

maybeGenData :: Int -> Maybe (Gen StreamContent)
maybeGenData max =
  if max > 0 then Just (flip moreData False <$> bytesBetween 1 max) else Nothing

genDeltaWindowSize :: StreamModel -> Gen DeltaWindowSize
genDeltaWindowSize sm = fromIntegral <$> choose (0, smRemoteBufSize sm - smRemoteDWS sm)

genReachableModel :: Gen StreamModel
genReachableModel = do
  rws <- windowSize
  lws <- windowSize
  let sm = StreamModel { smRemoteBufSize = rws
                       , smRemoteDWS = rws
                       , smPushed = []
                       , smSentWUs = []
                       , smLocalDWS = lws
                       , smBuffered = [] }
  foldl' specPerform sm <$> sized (actions sm)

-- | Generates a sequence of non-blocking actions.
actions :: StreamModel
           -- ^ An initial stream model, used to ensure that the
           -- actions will be non-blocking.
           -> Int
           -- ^ The length of the generated program.
           -> Gen [Action]
           -- ^ A sequence of actions that can be legally applied to
           -- the stream model in the order given.
actions sm n = snd <$> steps n sm
  where steps 0 sm = return (sm, [])
        steps n sm = do (sm', s) <- step sm
                        (sm'', ss) <- steps (n-1) sm'
                        return (sm'', s:ss)

commutes :: Eq a =>
            TestStream
            -> (TestStream -> IO a)
            -> (StreamModel -> (a, StreamModel))
            -> IO Bool
commutes ts tsOp modelOp = do
  initial <- abstract ts
  x <- tsOp ts
  final <- abstract ts
  return ((x, final) == modelOp initial)

forAllReachable :: (TestStream -> PropertyM IO ()) -> PropertyM IO ()
forAllReachable aPropM = do
  sid <- pick streamID
  rws <- pick windowSize
  lws <- pick windowSize
  ts  <- run $ newTestStream sid rws lws
  model <- run $ abstract ts
  as <- pick (sized $ actions model)
  failOnException $ performAll ts as
  aPropM ts

implementsIf :: Eq b =>
                (TestStream -> PropertyM IO Bool)
                -> (TestStream -> PropertyM IO a)
                -> (a -> TestStream -> IO b)
                -> (a -> StreamModel -> (b, StreamModel))
                -> PropertyM IO ()
implementsIf condition legalOperand tsOp modelOp =
  forAllReachable $ \ts -> do
    pre =<< condition ts
    x <- legalOperand ts
    assert =<< (failOnException $ commutes ts (tsOp x) (modelOp x))

implements :: Eq b =>
              (TestStream -> PropertyM IO a)
              -> (a -> TestStream -> IO b)
              -> (a -> StreamModel -> (b, StreamModel))
              -> PropertyM IO ()
implements = implementsIf (const $ return True)

implements' :: (TestStream -> PropertyM IO a)
               -> (a -> TestStream -> IO ())
               -> (a -> StreamModel -> StreamModel)
               -> PropertyM IO ()
implements' legalOperand tsOp modelOp =
  implements legalOperand tsOp (\x sm -> ((), modelOp x sm))

failOnException :: IO a -> PropertyM IO a
failOnException op =
  either stopExn return =<< (run $ try op)
  where stopExn e = stop $ failed { reason = "Exception: " ++ show (e :: SomeException) }

fromTestStream :: Show a => (StreamModel -> Gen a) -> TestStream -> PropertyM IO a
fromTestStream fromModel ts = run (abstract ts) >>= (pick . fromModel)

doNothingStream :: Bool
                   -> PropertyM IO (Stream, Maybe (StreamContent -> IO ()), IO StreamContent)
doNothingStream halfClosed = do
  sid <- pick streamID
  ws <- pick windowSize
  bs <- pick windowSize
  let opts = NewStreamOpts ws bs halfClosed doNothing doNothing doNothing
  run $ newStream sid opts

streamID :: Gen StreamID
streamID = StreamID <$> arbitrary

windowSize :: Gen Int
windowSize = choose (1, 64)

bytesBetween :: Int -> Int -> Gen ByteString
bytesBetween low hi = B.pack <$> vectorBetween low hi arbitrary

vectorBetween :: Int -> Int -> Gen a -> Gen [a]
vectorBetween low hi g = choose (low, hi) >>= flip vectorOf g

doNothing = const $ return ()


text:
from datetime import datetime, timezone
import argparse
import logging
import csv
import os
import json

"""
Purpose
Amazon Rekognition Custom Labels model example used in the service documentation.
Shows how to create an image-level (classification) manifest file from a CSV file.
You can specify multiple image level labels per image.
CSV file format is
image,label,label,..
If necessary, use the bucket argument to specify the S3 bucket folder for the images.
https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/md-gt-cl-transform.html
"""

logger = logging.getLogger(__name__)

def check_duplicates(csv_file, deduplicated_file, duplicates_file):
    """
    Checks for duplicate images in a CSV file. If duplicate images
    are found, deduplicated_file is the deduplicated CSV file - only the first
    occurence of a duplicate is recorded. Other duplicates are recorded in duplicates_file.
    :param csv_file: The source CSV file.
    :param deduplicated_file: The deduplicated CSV file to create. If no duplicates are found
    this file is removed.
    :param duplicates_file: The duplicate images CSV file to create. If no duplicates are found
    this file is removed.
    :return: True if duplicates are found, otherwise false.
    """

    logger.info("Deduplicating %s", csv_file)

    duplicates_found = False

    # Find duplicates.
    with open(csv_file, 'r', newline='', encoding="UTF-8") as f,\
            open(deduplicated_file, 'w', encoding="UTF-8") as dedup,\
            open(duplicates_file, 'w', encoding="UTF-8") as duplicates:

        reader = csv.reader(f, delimiter=',')
        dedup_writer = csv.writer(dedup)
        duplicates_writer = csv.writer(duplicates)

        entries = set()
        for row in reader:
            # Skip empty lines.
            if not ''.join(row).strip():
                continue

            key = row[0]
            if key not in entries:
                dedup_writer.writerow(row)
                entries.add(key)
            else:
                duplicates_writer.writerow(row)
                duplicates_found = True

    if duplicates_found:
        logger.info("Duplicates found check %s", duplicates_file)

    else:
        os.remove(duplicates_file)
        os.remove(deduplicated_file)

    return duplicates_found

def create_manifest_file(csv_file, manifest_file, s3_path):
    """
    Reads a CSV file and creates a Custom Labels classification manifest file.
    :param csv_file: The source CSV file.
    :param manifest_file: The name of the manifest file to create.
    :param s3_path: The S3 path to the folder that contains the images.
    """
    logger.info("Processing CSV file %s", csv_file)

    image_count = 0
    label_count = 0

    with open(csv_file, newline='', encoding="UTF-8") as csvfile,\
            open(manifest_file, "w", encoding="UTF-8") as output_file:

        image_classifications = csv.reader(
            csvfile, delimiter=',', quotechar='|')

        # Process each row (image) in CSV file.
        for row in image_classifications:
            source_ref = str(s3_path)+row[0]

            image_count += 1

            # Create JSON for image source ref.
            json_line = {}
            json_line['source-ref'] = source_ref

            # Process each image level label.
            for index in range(1, len(row)):
                image_level_label = row[index]

                # Skip empty columns.
                if image_level_label == '':
                    continue
                label_count += 1

               # Create the JSON line metadata.
                json_line[image_level_label] = 1
                metadata = {}
                metadata['confidence'] = 1
                metadata['job-name'] = 'labeling-job/' + image_level_label
                metadata['class-name'] = image_level_label
                metadata['human-annotated'] = "yes"
                metadata['creation-date'] = \
                    datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')
                metadata['type'] = "groundtruth/image-classification"

                json_line[f'{image_level_label}-metadata'] = metadata

                # Write the image JSON Line.
            output_file.write(json.dumps(json_line))
            output_file.write('\n')

    output_file.close()
    logger.info("Finished creating manifest file %s\nImages: %s\nLabels: %s",
                manifest_file, image_count, label_count)

    return image_count, label_count

def add_arguments(parser):
    """
    Adds command line arguments to the parser.
    :param parser: The command line parser.
    """

    parser.add_argument(
        "csv_file", help="The CSV file that you want to process."
    )

    parser.add_argument(
        "--s3_path", help="The S3 bucket and folder path for the images."
        " If not supplied, column 1 is assumed to include the S3 path.", required=False
    )

def main():

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    try:

        # Get command line arguments
        parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
        add_arguments(parser)
        args = parser.parse_args()

        s3_path = args.s3_path
        if s3_path is None:
            s3_path = ''

        # Create file names.
        csv_file = args.csv_file
        file_name = os.path.splitext(csv_file)[0]
        manifest_file = f'{file_name}.manifest'
        duplicates_file = f'{file_name}-duplicates.csv'
        deduplicated_file = f'{file_name}-deduplicated.csv'

        # Create manifest file, if there are no duplicate images.
        if check_duplicates(csv_file, deduplicated_file, duplicates_file):
            print(f"Duplicates found. Use {duplicates_file} to view duplicates "
                  f"and then update {deduplicated_file}. ")
            print(f"{deduplicated_file} contains the first occurence of a duplicate. "
                  "Update as necessary with the correct label information.")
            print(f"Re-run the script with {deduplicated_file}")
        else:
            print("No duplicates found. Creating manifest file.")

            image_count, label_count = create_manifest_file(csv_file,
                                                            manifest_file,
                                                            s3_path)

            print(f"Finished creating manifest file: {manifest_file} \n"
                  f"Images: {image_count}\nLabels: {label_count}")

    except FileNotFoundError as err:
        logger.exception("File not found: %s", err)
        print(f"File not found: {err}. Check your input CSV file.")

if __name__ == "__main__":
    main()

# snippet-end:[rekognition.python.custom_labels_csv_manifest.complete]


text:
      {{dateService.getDate | amDateFormat:'hh'}}{{dateService.getDate | amDateFormat:':mm'}}
      {{dateService.getDate | amDateFormat:'A'}}


text:
var crypto = require('crypto');
var xml2js = require('node-xml');
var moment = require('moment');

var data_obj = require('./redis.js');
var socket_obj = require('./socket.js');

function sha1(str) {
    var md5sum = crypto.createHash('sha1');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
}

exports.validateToken = function(req, res) {
    var query = req.query;
    var signature = query.signature;
    var echostr = query.echostr;
    var timestamp = query['timestamp'];
    var nonce = query.nonce;
    var oriArray = new Array(0);
    oriArray[0] = nonce;
    oriArray[1] = timestamp;
    oriArray[2] = "414cf5d02e";// your token
    oriArray.sort();
    var original = oriArray[0]+oriArray[1]+oriArray[2];
    console.log("Original Str:"+original);
    console.log("signature:"+signature);
    var scyptoString = sha1(original);
    if (signature == scyptoString) {
        res.send(echostr);
    }
    else {
        res.send("Bad Token!");
    }
};

function processMessage(data, res){
	//var tempid="";
	var xmldata="";
	var ToUserName="";
	var FromUserName="";
	var CreateTime="";
	var MsgType="";
	var Content="";
	var EventKey="";
	var Location_X="";
	var Location_Y="";
	var Scale=1;
	//var Label="";
	//var tempstate = "";
	var PicUrl="";
	var FuncFlag="";
	var tempName="";
		var json_out = {
		"DeviceId"  : "00000000",
		"IsSuccess" : "Success",
		"NSlots"    : "5",
		"State"     : "00000",
		"ServerTime": "2014-5-19 14:47:56"
	};

	json_out.ServerTime = moment().format('YYYY-MM-DD, HH:mm:ss');

	var parse=new xml2js.SaxParser(function(cb){
		cb.onStartElementNS(function(elem,attra,prefix,uri,namespaces){
			tempName=elem;
		});
		cb.onCharacters(function(chars){
			chars=chars.replace(/(^\s*)|(\s*$)/g, "");
			if(tempName=="CreateTime"){
				CreateTime=chars;
			}else if(tempName=="Location_X"){
				Location_X=chars;
			}else if(tempName=="Location_Y"){
				Location_Y=chars;
			}else if(tempName=="Scale"){
				Scale=chars;
			}
		});
		cb.onCdata(function(cdata){
			if(tempName=="ToUserName"){
				ToUserName=cdata;
			}else if(tempName=="FromUserName"){
				FromUserName=cdata;
			}else if(tempName=="MsgType"){
				MsgType=cdata;
			}else if(tempName=="Content"){
				Content=cdata;
			}else if(tempName=="PicUrl"){
				PicUrl=cdata;
			}else if(tempName=="EventKey"){
				EventKey=cdata;
			}
			//console.log("cdata:"+cdata);
		});
		cb.onEndElementNS(function(elem,prefix,uri){
			tempName="";
		});
		cb.onEndDocument(function(){
			tempName="";
			var msg="";
			if(MsgType=="text"){
				msg="你说的是:"+Content;
			}else if (MsgType=="event"){
				msg="Your command:"+EventKey;
				Content = EventKey;
			}else if (MsgType=="image"){
				msg="你发的图片是:"+PicUrl;
			}else {
				//console.log(MsgType);
			}
			//xmldata = ToXML(FromUserName,ToUserName,'text',msg,FuncFlag);
			//broadcast('SYSTEM',"Command long:" + Content.length + '\n');
			if(Content.indexOf("bind") != -1) {
				if(Content.length == 13) {
					data_obj.bindRedis(FromUserName, Content.substr(5,8) , function(temp){
						socket_obj.broadcast('SYSTEM',JSON.stringify(temp) + '\n');
					});
				}
			} else if(Content.indexOf("打开台灯") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 5, 1, function(temp){
					json_out.State = temp;
					//console.log("temp.length " + temp.length );
					if(temp.length == 5) {
						data_obj.getRedis(FromUserName , function(temp1){
							json_out.DeviceId = temp1;
							socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
						});
					} else {
						msg = "您的账号未绑定任何设备!";
						console.log("NOTBINDYET!");
					}
				});
			} else if(Content.indexOf("关闭台灯") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 5, 0, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("打开音箱") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 4, 1, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("关闭音箱") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 4, 0, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("打开苹果充电器") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 3, 1, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("关闭苹果充电器") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 3, 0, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("打开安卓充电器") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 2, 1, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("关闭安卓充电器") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 2, 0, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("打开树莓派") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 1, 1, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else if(Content.indexOf("关闭树莓派") != -1) {
				data_obj.WechatSetRedis(null, FromUserName, 1, 0, function(temp){
					json_out.State = temp;
					data_obj.getRedis(FromUserName , function(temp1){
						json_out.DeviceId = temp1;
						socket_obj.broadcast('SYSTEM',JSON.stringify(json_out) + '\n');
					});
				});
			} else {
				socket_obj.broadcast('SYSTEM',"Command long:" + Content.length + '\n');
			}
			xmldata = ToXML(FromUserName,ToUserName,'text',msg,FuncFlag);
			res.send(xmldata);
		});
	});
	parse.parseString(data);
	return xmldata;
}

function ToXML(FromUserName,ToUserName,MsgType,Msg,FuncFlag) {
    var msgxml = "" +
    "<xml>" +
    "<ToUserName>" + FromUserName + "</ToUserName>" +
    "<FromUserName>" + ToUserName + "</FromUserName>" +
    "<CreateTime>" + Date.now()/1000 + "</CreateTime>" +
    "<FuncFlag>0</FuncFlag>" +
    "<MsgType>" + MsgType + "</MsgType>";

    // switch(MsgType) {
    //   case 'text' :
    msgxml += "" +
    "<Content>" + Msg + "</Content>" +
    "</xml>";
    return msgxml;
    // }
}

exports.handler = function(req, res) {
  //RES = res;
  var xml = '';
  var xmldata = '';
  //var self = this;

  req.setEncoding('utf8');
  req.on('data', function (chunk) {
    xml += chunk;
  });

  req.on('end', function() {
    xmldata = processMessage(xml, res);
  });

  return xmldata;
};