text:
<?xml version="1.0" encoding="utf-8"?>
<regress-exe>
  <test>
    <default>
      <files>array_fastinit.js</files>
      <baseline>array_fastinit.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_at.js</files>
      <compile-flags>-args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_flat.js</files>
      <compile-flags>-args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_findlast.js</files>
      <compile-flags>-ESArrayFindFromLast -args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_findlastindex.js</files>
      <compile-flags>-ESArrayFindFromLast -args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_qsortr.js</files>
      <tags>exclude_windows</tags>
      <compile-flags>-JsBuiltIn-</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_init.js</files>
      <baseline>array_init.baseline</baseline>
      <tags>Slow</tags>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-Serialized</compile-flags>
      <files>array_init2.js</files>
      <baseline>array_init2.baseline</baseline>
      <tags>exclude_forceserialized</tags>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-args summary -endargs -ForceArrayBTree -recyclerStress</compile-flags>
      <files>SpliceBtreeMemoryCorruption.js</files>
      <tags>exclude_test,Slow</tags>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-forcearraybtree -off:nativearray -args summary -endargs</compile-flags>
      <files>sliceArrayForceBtreeBug616623.js</files>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-ForceArrayBTree</compile-flags>
      <files>bug945376SegLeftPlusSizeGreaterThanMaxArrayLen.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug1062870.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug1065362.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug11370283.js</files>
      <compile-flags>-bgjit- -lic:1</compile-flags>
      <tags>exclude_dynapogo</tags>
    </default>
  </test>
  <test>
    <default>
      <files>bug4916987.js</files>
      <compile-flags>-mic:1 -off:simplejit</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>bug6268659.js</files>
      <compile-flags>-mic:1 -off:simplejit</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-ForceArrayBTree</compile-flags>
      <files>ArrayBtreeBadCodeGen.js</files>
      <baseline>ArrayBtreeBadCodeGen.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>SliceandConcatAlterOriginalArrayBug.js</files>
      <compile-flags>-args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-ForceArrayBTree -maxinterpretcount:1 -maxsimplejitruncount:2</compile-flags>
      <files>rawLastUsedSegmentBugInFloatArray.js</files>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-maxinterpretcount:1 -maxsimplejitruncount:1 -force:rejit -ForceArrayBTree</compile-flags>
      <files>ArrayElementMissingValueSetToZero.js</files>
    </default>
  </test>
  <test>
    <default>
      <compile-flags> -forcejitloopbody -ForceArrayBTree -off:ArrayCheckHoist</compile-flags>
      <files>TryGrowHeadSegmentBug.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>array_init2.js</files>
      <baseline>array_init2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_ctr.js</files>
      <baseline>array_ctr.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-arrayValidate</compile-flags>
      <files>array_ctr.js</files>
      <baseline>array_ctr.baseline</baseline>
      <tags>exclude_test</tags>
    </default>
  </test>
  <test>
    <default>
      <files>arr_bailout.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>concat1.js</files>
      <baseline>concat1.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>concat2.js</files>
      <baseline>concat2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>delete.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>es5array_push.js</files>
      <baseline>es5array_push.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>ldindex.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug612012.js</files>
      <compile-flags>-maxinterpretcount:1 -loopinterpretcount:1 -ForceArrayBTree -oopjit-</compile-flags>
      <tags>exclude_serialized</tags>
    </default>
  </test>
  <test>
    <default>
      <files>SegmentMapFlagResetInJSArrayConstructor.js</files>
      <compile-flags> -maxinterpretcount:1 -maxsimplejitruncount:2  -ForceArrayBTree</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>LastUsedSegmentHasNULLElement.js</files>
      <compile-flags> -maxinterpretcount:1 -maxsimplejitruncount:2  -ForceArrayBTree</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_length.js</files>
      <baseline>array_length.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>join2.js</files>
      <baseline>join2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>missing.js</files>
      <baseline>missing.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>pop1.js</files>
      <baseline>pop1.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>pop2.js</files>
      <baseline>pop2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>pop3.js</files>
      <baseline>pop3.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>push1.js</files>
      <baseline>push1_2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>push2.js</files>
      <compile-flags>-es6toLength</compile-flags>
      <baseline>push2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>push3.js</files>
      <compile-flags>-off:nativearray -ForceES5Array</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>push4_traps.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>reverse1.js</files>
      <baseline>reverse1.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>reverse2.js</files>
      <baseline>reverse2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>shift_unshift.js</files>
      <baseline>shift_unshift.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>toString.js</files>
      <baseline>toString.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>toString.js</files>
      <compile-flags>-ForceES5Array</compile-flags>
      <tags>exclude_test</tags>
      <baseline>toString.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>toLocaleString.js</files>
      <baseline>toLocaleString.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>toLocaleString.js</files>
      <compile-flags>-ForceES5Array</compile-flags>
      <tags>exclude_test</tags>
      <baseline>toLocaleString.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_slice.js</files>
      <baseline>array_slice.baseline</baseline>
      <timeout>300</timeout>
    </default>
  </test>
  <test>
    <default>
      <files>array_slice2.js</files>
      <baseline>array_slice2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_sort.js</files>
      <compile-flags>-args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_includes.js</files>
      <compile-flags>-args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_splice.js</files>
      <baseline>array_splice.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_splice_double.js</files>
      <baseline>array_splice_double.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-arrayValidate</compile-flags>
      <files>array_splice.js</files>
      <baseline>array_splice.baseline</baseline>
      <tags>exclude_test</tags>
    </default>
  </test>
  <test>
    <default>
      <files>array_splice1.js</files>
      <baseline>array_splice1.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_splice2.js</files>
      <baseline>array_splice2.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_splice3.js</files>
      <baseline>array_splice3_3.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_splice4.js</files>
      <baseline>array_splice4.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>sparsearray.js</files>
      <baseline>sparsearray.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_lastindexof.js</files>
      <baseline>array_lastindexof.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_indexOf.js</files>
      <baseline>array_indexOf.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_indexOf.js</files>
      <compile-flags>-ForceArrayBTree</compile-flags>
      <baseline>array_indexOf.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_indexOf.js</files>
      <compile-flags>-JsBuiltIn-</compile-flags>
      <baseline>array_indexOf.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_indexOfSparse.js</files>
      <baseline>array_indexOfSparse.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>negindex.js</files>
      <baseline>negindex.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_forin.js</files>
      <baseline>array_forin.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_literal.js</files>
      <baseline>array_literal.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-recyclerStress</compile-flags>
      <files>array_literal.js</files>
      <baseline>array_literal.baseline</baseline>
      <tags>exclude_test,Slow</tags>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen1.js</files>
      <baseline>nativearray_gen1.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen1.js</files>
      <compile-flags>-sse:0 -forceserialized</compile-flags>
      <baseline>nativearray_gen1.baseline</baseline>
      <!-- Exclude the serialized variants because we're using -forceserialized here. -->
      <tags>exclude_serialized</tags>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen2.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen3.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen4.js</files>
      <baseline>nativearray_gen4.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen5.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen6.js</files>
      <compile-flags>-loopinterpretcount:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen7.js</files>
      <baseline>nativearray_gen7.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>nativearray_gen8.js</files>
      <compile-flags>-force:jitloopbody</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>arrlit.js</files>
      <baseline>arrlit.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>protoLookup.js</files>
      <baseline>protoLookup.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>protoLookup_native.js</files>
      <baseline>protoLookup_native.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>protoLookupWithGetters.js</files>
      <baseline>protoLookupWithGetters.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>array_apply.js</files>
      <baseline>array_apply.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>nativeArrayPushInlining.js</files>
      <baseline>nativeArrayPushInlining.baseline</baseline>
      <compile-flags>-maxinterpretcount:1 -off:arraycheckhoist -off:fixedmethods</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>reverse_native.js</files>
      <baseline>reverse_native.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>nativeFloatArray_shift_unshift.js</files>
      <baseline>nativeFloatArray_shift_unshift.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>nativeFloatArray_sort.js</files>
      <baseline>nativeFloatArray_sort.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>missingItemFastPathCheck.js</files>
      <baseline>missingItemFastPathCheck.baseline</baseline>
      <compile-flags>-maxinterpretcount:1</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_opts.js</files>
      <compile-flags>-maxinterpretcount:1</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>nativeIntPop.js</files>
      <baseline>nativeIntPop.baseline</baseline>
      <compile-flags>-maxinterpretcount:1 -off:fixedmethods -off:Arraycheckhoist</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>nativeFloatPop.js</files>
      <baseline>nativeFloatPop.baseline</baseline>
      <compile-flags>-maxinterpretcount:1 -off:fixedmethods -off:Arraycheckhoist</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>popImplicitCall.js</files>
      <baseline>popImplicitCall.baseline</baseline>
      <compile-flags>-maxinterpretcount:1 -off:fixedmethods -off:Arraycheckhoist</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_splice_515632.js</files>
      <baseline>array_splice_515632.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>InlineArrayPopWithIntConstSrc.js</files>
      <baseline>InlineArrayPopWithIntConstSrc.baseline</baseline>
      <compile-flags>-maxinterpretcount:1 -off:simplejit</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>FailToSetLength.js</files>
      <compile-flags>-args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>foreach_nativearray_change.js</files>
      <baseline>foreach_nativearray_change.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>newfromargs.js</files>
      <baseline>newfromargs.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <compile-flags>-ForceArrayBTree</compile-flags>
      <files>bug945376SizeBoundStartSeg.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>CopyOnAccessArray_bugs.js</files>
      <tags>require_backend</tags>
      <compile-flags>-force:copyonaccessarray</compile-flags>
      <baseline>CopyOnAccessArray_bugs.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>CopyOnAccessArray_cache_index_overflow.js</files>
      <tags>exclude_nonative,exclude_forceserialized,require_backend</tags>
      <compile-flags>-force:copyonaccessarray -testtrace:CopyOnAccessArray</compile-flags>
      <baseline>CopyOnAccessArray_cache_index_overflow.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>memop_lifetime_bug.js</files>
      <compile-flags>-mic:1 -off:simplejit -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memset.js</files>
      <compile-flags>-mic:1 -off:simplejit -off:JITLoopBody -off:inline -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memset_invariant.js</files>
      <tags>Slow</tags>
      <compile-flags>-mic:1 -off:simplejit -mmoc:0 -off:JITLoopBody</compile-flags>
      <timeout>300</timeout>
    </default>
  </test>
  <!--
  TODO fix and re-enable, or remove this test (disabled in 91e0e9128)
  Microsoft/ChakraCore#2977
  <test>
    <default>
      <files>memset_simd.js</files>
      <compile-flags>-mic:1 -off:simplejit -mmoc:0 -off:JITLoopBody -simdjs -simd128typespec</compile-flags>
    </default>
  </test>
  -->
  <test>
    <default>
      <files>memset2.js</files>
      <compile-flags>-mic:1 -off:simplejit -off:JITLoopBody -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memcopy.js</files>
      <compile-flags>-mic:1 -off:simplejit -off:JITLoopBody -off:inline -off:globopt:1.18-1.30 -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memcopy.js</files>
      <compile-flags>-mic:1 -off:simplejit -off:JITLoopBody -off:inline -off:globopt:1.18-1.30 -mmoc:0 -args float -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memcopy_length_bug.js</files>
      <compile-flags>-bgjit- -lic:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memcopy_missing_values.js</files>
      <compile-flags>-mic:1 -off:simplejit -bgjit- -lic:1</compile-flags>
      <baseline>memcopy_missing_values.baseline</baseline>
    </default>
  </test>
  <test>
    <default>
      <files>memop_alias.js</files>
      <compile-flags>-mic:1 -off:simplejit -off:jitloopbody -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memop_field.js</files>
      <compile-flags>-mic:1 -off:simplejit -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memop_slot.js</files>
      <compile-flags>-mic:1 -off:simplejit -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memop_bounds_check.js</files>
      <compile-flags>-mic:1 -off:simplejit -mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>memop_missingValues.js</files>
      <compile-flags>-mmoc:0</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>bug4587739.js</files>
      <compile-flags>-mic:1 -off:simplejit</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>bug8159763.js</files>
      <compile-flags>-mic:1 -off:simplejit -mmoc:0 -off:bailonnoprofile</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>Array_TypeConfusion_bugs.js</files>
      <compile-flags>-args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>Array_TypeConfusion_bugs.js</files>
      <compile-flags>-ForceArrayBTree -args summary -endargs</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>bug_9575461.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug_12044876.js</files>
      <compile-flags>-forcearraybtree</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>array_conv_src.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug12340575.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>constructor_fastpath.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug16717501.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>FilterWithTypedArray.js</files>
    </default>
  </test>
  <test>
    <default>
      <files>bug_gh5667.js</files>
      <tags>exclude_windows</tags>
      <compile-flags>-JsBuiltIn-</compile-flags>
    </default>
  </test>
  <test>
    <default>
      <files>bug_gh6320.js</files>
      <tags>exclude_nonative</tags>
    </default>
  </test>
  <!-- TODO improve performance of sort for no-jit builds then re-enable this case for them-->
  <test>
    <default>
      <files>array_sort_random.js</files>
      <tags>exclude_disable_jit,exclude_lite</tags>
    </default>
  </test>
</regress-exe>


text:
const onLongPress = (element: JQuery<HTMLElement>, handler: () => void): void => {
   const duration = 1000;

   let durationTimeout: number;
   let isLongPress: boolean;

   element.on('mousedown', ev => {
      isLongPress = false;

      durationTimeout = window.setTimeout(() => {
         ev.stopPropagation();
         ev.preventDefault();

         isLongPress = true;

         handler();
      }, duration);
   });

   element.on('mouseup', () => {
      window.clearTimeout(durationTimeout);
   });

   element.on('click', ev => {
      if (isLongPress) {
         ev.stopPropagation();
         ev.preventDefault();
      }
   });
};

export default onLongPress;

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<DARoots Version="1" Minor="26">
  <FileSet Name="sources_1" Type="DesignSrcs" RelSrcDir="$PSRCDIR/sources_1">
    <Filter Type="Srcs"/>
    <File Path="$PPRDIR/../S_Reg.vhd">
      <FileInfo>
        <Attr Name="UsedInSynthesis" Val="1"/>
        <Attr Name="UsedInSimulation" Val="1"/>
      </FileInfo>
    </File>
    <File Path="$PDATADIR/sources_1/ports.xml">
      <FileInfo SFType="PortsDb"/>
    </File>
    <Config>
      <Option Name="DesignMode" Val="RTL"/>
      <Option Name="TopModule" Val="S_Reg"/>
    </Config>
  </FileSet>
</DARoots>


text:
import numpy as np
import pytest

from pandas import DataFrame, Series
import pandas._testing as tm

class TestLookup:
    def test_lookup_float(self, float_frame):
        df = float_frame
        rows = list(df.index) * len(df.columns)
        cols = list(df.columns) * len(df.index)
        with tm.assert_produces_warning(FutureWarning):
            result = df.lookup(rows, cols)

        expected = np.array([df.loc[r, c] for r, c in zip(rows, cols)])
        tm.assert_numpy_array_equal(result, expected)

    def test_lookup_mixed(self, float_string_frame):
        df = float_string_frame
        rows = list(df.index) * len(df.columns)
        cols = list(df.columns) * len(df.index)
        with tm.assert_produces_warning(FutureWarning):
            result = df.lookup(rows, cols)

        expected = np.array(
            [df.loc[r, c] for r, c in zip(rows, cols)], dtype=np.object_
        )
        tm.assert_almost_equal(result, expected)

    def test_lookup_bool(self):
        df = DataFrame(
            {
                "label": ["a", "b", "a", "c"],
                "mask_a": [True, True, False, True],
                "mask_b": [True, False, False, False],
                "mask_c": [False, True, False, True],
            }
        )
        with tm.assert_produces_warning(FutureWarning):
            df["mask"] = df.lookup(df.index, "mask_" + df["label"])

        exp_mask = np.array(
            [df.loc[r, c] for r, c in zip(df.index, "mask_" + df["label"])]
        )

        tm.assert_series_equal(df["mask"], Series(exp_mask, name="mask"))
        assert df["mask"].dtype == np.bool_

    def test_lookup_raises(self, float_frame):
        with pytest.raises(KeyError, match="'One or more row labels was not found'"):
            with tm.assert_produces_warning(FutureWarning):
                float_frame.lookup(["xyz"], ["A"])

        with pytest.raises(KeyError, match="'One or more column labels was not found'"):
            with tm.assert_produces_warning(FutureWarning):
                float_frame.lookup([float_frame.index[0]], ["xyz"])

        with pytest.raises(ValueError, match="same size"):
            with tm.assert_produces_warning(FutureWarning):
                float_frame.lookup(["a", "b", "c"], ["a"])

    def test_lookup_requires_unique_axes(self):
        # GH#33041 raise with a helpful error message
        df = DataFrame(np.random.randn(6).reshape(3, 2), columns=["A", "A"])

        rows = [0, 1]
        cols = ["A", "A"]

        # homogeneous-dtype case
        with pytest.raises(ValueError, match="requires unique index and columns"):
            with tm.assert_produces_warning(FutureWarning):
                df.lookup(rows, cols)
        with pytest.raises(ValueError, match="requires unique index and columns"):
            with tm.assert_produces_warning(FutureWarning):
                df.T.lookup(cols, rows)

        # heterogeneous dtype
        df["B"] = 0
        with pytest.raises(ValueError, match="requires unique index and columns"):
            with tm.assert_produces_warning(FutureWarning):
                df.lookup(rows, cols)

def test_lookup_deprecated():
    # GH#18262
    df = DataFrame(
        {"col": ["A", "A", "B", "B"], "A": [80, 23, np.nan, 22], "B": [80, 55, 76, 67]}
    )
    with tm.assert_produces_warning(FutureWarning):
        df.lookup(df.index, df["col"])


text:
package com.google.cloud.dialogflow.v2.samples;

// [START dialogflow_v2_generated_conversationsclient_createconversation_projectnameconversation_sync]
import com.google.cloud.dialogflow.v2.Conversation;
import com.google.cloud.dialogflow.v2.ConversationsClient;
import com.google.cloud.dialogflow.v2.ProjectName;

public class SyncCreateConversationProjectnameConversation {

  public static void main(String[] args) throws Exception {
    syncCreateConversationProjectnameConversation();
  }

  public static void syncCreateConversationProjectnameConversation() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (ConversationsClient conversationsClient = ConversationsClient.create()) {
      ProjectName parent = ProjectName.of("[PROJECT]");
      Conversation conversation = Conversation.newBuilder().build();
      Conversation response = conversationsClient.createConversation(parent, conversation);
    }
  }
}
// [END dialogflow_v2_generated_conversationsclient_createconversation_projectnameconversation_sync]


text:
<?php

namespace Grav\Plugin;

require_once __DIR__.'/../vendor/autoload.php';

use Grav\Common\Grav;
use Grav\Common\GravTrait;
use \Carbon\Carbon;

class DateTools
{
	use GravTrait;

	/**
	 * @var object Config
	 */
	protected $config;

	/**
	 * @var string Date format
	 */
	protected $dateFormat;

	/**
	 * @var object Current Carbon datetime
	 */
	protected $now;

	/**
	 * Various on the fly dates
	 */
	public $today;
	public $tomorrow;
	public $yesterday;
	public $startOfWeek;
	public $endOfWeek;
	public $startOfMonth;
	public $endOfMonth;
	public $startOfYear;
	public $endOfYear;

	/**
	 * Date variables for processing from today
	 */
	protected $year;
	protected $month;
	protected $day;
	protected $hour;
	protected $min;
	protected $dayOfWeek;
	protected $dayOfYear;
	protected $weekOfMonth;
	protected $weekOfYear;
	protected $daysInMonth;

	/**
	 * Construct
	 */
	public function __construct()
	{
		// get the config
		$this->config = self::$grav['config'];
		// date format
		$this->dateFormat = $this->config->get('plugins.datetools.dateFormat.default');
		// get today
		$this->now = $this->now();

		// initialize processing vars
		$this->initProcessingVars();

		// initialize common dates
		$this->initCommonDates();
	}

	/**
	 * Initialize processing vars
	 *
	 * @internal
	 */
	private function initProcessingVars()
	{
		$this->year = $this->now->year;
		$this->month = $this->now->month;
		$this->day = $this->now->day;
		$this->hour = $this->now->hour;
		$this->minute = $this->now->minute;
		$this->dayOfWeek = $this->now->dayOfWeek;
		$this->dayOfYear = $this->now->dayOfYear;
		$this->weekOfMonth = $this->now->weekOfMonth;
		$this->weekOfYear = $this->now->weekOfYear;
		$this->daysInMonth = $this->now->daysInMonth;
	}

	/**
	 * Initialize common dates
	 *
	 * @internal
	 */
	private function initCommonDates()
	{
		$this->today	 	= $this->now()->format($this->dateFormat);
		$this->tomorrow 	= $this->tomorrow()->format($this->dateFormat);
		$this->yesterday 	= $this->yesterday()->format($this->dateFormat);
		$this->startOfWeek 	= $this->startOfWeek()->format($this->dateFormat);
		$this->endOfWeek 	= $this->endOfWeek()->format($this->dateFormat);
		$this->startOfMonth = $this->startOfMonth()->format($this->dateFormat);
		$this->endOfMonth 	= $this->endOfMonth()->format($this->dateFormat);
		$this->startOfYear 	= $this->startOfYear()->format($this->dateFormat);
		$this->endOfYear 	= $this->endOfYear()->format($this->dateFormat);
	}

	/**
	 * Parse a relative date
	 *
	 * @param string $string Relative Date string
	 * @return string DateTime
	 */
	public function parseDate($string = null)
	{
		if ($string == null) {
			return null;
		}

		return Carbon::parse($string);
	}

	/**
	 * Get today's date
	 *
	 * @return string DateTime
	 */
	public function now()
	{
		return Carbon::now();
	}

	/**
	 * Get tomorrow's date
	 *
	 * @return string DateTime
	 */
	public function tomorrow()
	{
		return Carbon::tomorrow();
	}

	/**
	 * Get yesterday's date
	 *
	 * @return string DateTime
	 */
	public function yesterday()
	{
		return Carbon::yesterday();
	}

	/**
	 * Get start of week
	 *
	 * @return string DateTime
	 */
	public function startOfWeek()
	{
		return Carbon::parse('last monday');
	}

	/**
	 * Get end of week
	 *
	 * @return string DateTime
	 */
	public function endOfWeek()
	{
		return Carbon::parse('next monday');
	}

	/**
	 * Get start of month
	 *
	 * @return string DateTime
	 */
	public function startOfMonth()
	{
		return Carbon::create($this->year, $this->month, 1, 0, 0, 0);
	}

	/**
	 * Get end of month
	 *
	 * @return string DateTime
	 */
	public function endOfMonth()
	{
		return Carbon::create($this->year, $this->month, $this->daysInMonth, 0, 0, 0);
	}

	/**
	 * Get start of year
	 *
	 * @return string DateTime
	 */
	public function startOfYear()
	{
		return Carbon::create($this->year, 1, 1, 0, 0, 0);
	}

	/**
	 * Get end of year
	 *
	 * @return string DateTime
	 */
	public function endOfYear()
	{
		return Carbon::create($this->year, 12, 31, 0, 0, 0);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   	<bool name="has_one_pane">true</bool>

   	<item name="lyt_activity_main" type="layout">@layout/lyt_activity_main_one_pane_land</item>
</resources>


text:
'use strict';
var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');

chai.use(sinonChai);

var expect = chai.expect;

describe('arg-parser', function () {
  var parser, options;
  before(function () {
    parser = require('../src/arg-parser');
  });

  beforeEach(function () {
    options = { '_': [] };
  });

  describe('defaults',function(){
    it('should remove iojs',function(){
      var args = ['/some/path/to/iojs', 'some/long/path'];
      var arr = parser.parse(args, options);
      expect(arr).to.not.include('/some/path/to/iojs');
    });

    it('should remove node', function(){
      var args = ['node', 'some/long/path'];
      var arr = parser.parse(args, options);
      expect(arr).to.not.include('node');
    });

    it('should remove esw',function(){
      var args = ['bla','/bin/esw', '/something/else'];
      var arr = parser.parse(args, options);
      expect(arr).not.include('/bin/esw');
    });
  });

  describe('watch', function(){
    it('parses for -w', function(){
      var args = ['node', 'some/long/path/to/prog', '-w'];
      var arr = parser.parse(args, options);
      expect(arr).to.not.contain('-w');
    });

    it('parses for --watch', function () {
      var watch = '--watch';
      var args = ['node', 'some/long/path/to/prog', watch];
      var arr = parser.parse(args, options);
      expect(arr).to.not.contain(watch);
    });
  });

  describe('path', function () {
    it('sets a default path if one isn\'t provided', function () {
      var arr = parser.parse([], options);
      expect(arr).to.contain('./');
    });

    it('doesn\'t set the default if a path is provided', function () {
      var path = 'something/short/';
      options._.push(path);
      var arr = parser.parse([], options);
      expect(arr).to.not.contain('./');
    });
  });

  describe('formatters', function () {
    var find = function (arr, what) {
      var result = false;
      for (var i = 0; i < arr.length; i++) {
        result = result || arr[i].indexOf(what) > -1;
      }
      return result;
    };
    var occurance = function (arr, what) {
      var result = 0;
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].indexOf(what) > -1) {
          result += 1;
        }
      }
      return result;
    };
    var pathStub;
    beforeEach(function () {
      var path = require('path');
      pathStub = sinon.stub(path, 'join', function () {
        return 'src\\' + arguments[1] + '\\' + arguments[2];
      });
    });

    afterEach(function () {
      pathStub.restore();
    });

    it('sets the full path to the formatters folder', function () {
      options.format = 'simple';
      var arr = parser.parse(['-f', 'simple'], options);
      var result = find(arr, 'src\\formatters\\simple');
      expect(result).to.be.true;
    });

    it('sets the default formatter to simple-detail using args', function () {
      options.format = 'simple-detail';
      var arr = parser.parse(['-f', 'simple-detail'], options);
      var result = find(arr, 'formatters\\simple-detail');
      expect(result).to.be.true;
    });

    it('handles passing in default', function () {
      options.format = 'simple-detail';
      var arr = parser.parse(['-f', 'simple-detail'], options);
      var result = occurance(arr, 'formatters\\simple-detail');
      expect(result).to.equal(1);
    });
  });
});


text:
title: "Ticketmaster at HackPoly"
category: event

date_title: "Sat-Sun, February 6-7, 2016"
date_start: "2016-02-03 9:30:00"
date_end: "2016-02-04 12:24:00"

img: "/assets/img/events/hackpoly.jpg"

place:
  - "Bronco Student Center
"
  - "https://www.google.com/maps/place/Bronco+Student+Center/@34.0563994,-117.8235895,17z/data=!3m1!4b1!4m2!3m1!1s0x80c32eafe97cfa0f:0x4b135e36979ae41"
city: "Pomona, CA"
rsvp: "http://hackpoly.com/"
link: "http://hackpoly.com/"
tags:
  - hackathon

---

Ticketmaster is a proud sponsor of HackPoly this year! From February 6-7 at the Bronco Student Center, we invite YOU to come out to this annual 24-hour hackathon and create whatever you can imagine with our API!


text:
package compiler

import (
	"fmt"
	"go/ast"
	html "html/template"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"strings"
	text "text/template"
	"text/template/parse"

	"github.com/mh-cbon/template-compiler/compiled"
	"github.com/mh-cbon/template-tree-simplifier/simplifier"
	"github.com/serenize/snaker"
)

// CompiledTemplatesProgram ...
type CompiledTemplatesProgram struct {
	varName      string
	imports      []*ast.ImportSpec
	funcs        []*ast.FuncDecl
	idents       []string
	builtinTexts map[string]string
}

// NewCompiledTemplatesProgram prepare a new instance.
// it automatically adds io and template/parse packages,
// and declares static idents.
func NewCompiledTemplatesProgram(varName string) *CompiledTemplatesProgram {
	ret := &CompiledTemplatesProgram{
		varName: varName,
		idents: []string{
			"t", "b", "w", "werr", "data", "indata", varName,
		},
		builtinTexts: map[string]string{},
	}
	ret.addImport("io")
	ret.addImport("github.com/mh-cbon/template-compiler/std/text/template/parse")
	return ret
}

// CompileAndWrite the configuration and write the resulting program to config.OutPath.
func (c *CompiledTemplatesProgram) CompileAndWrite(config *compiled.Configuration) error {
	program, err := c.Compile(config)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(config.OutPath, []byte(program), os.ModePerm); err != nil {
		return fmt.Errorf("Failed to write the compiled templates: %v", err)
	}
	return nil
}

//Compile the configuration, it returns a string of the output program.
func (c *CompiledTemplatesProgram) Compile(config *compiled.Configuration) (string, error) {
	if err := updateOutPkg(config); err != nil {
		return "", err
	}

	templatesToCompile, err := c.getTemplatesToCompile(config)
	if err != nil {
		return "", err
	}

	return c.compileTemplates(config.OutPkg, templatesToCompile)
}

//compileTemplates generates the output program for the given templates to compile.
func (c *CompiledTemplatesProgram) compileTemplates(outpkg string, templatesToCompile []*TemplateToCompile) (string, error) {
	if err := c.convertTemplates(templatesToCompile); err != nil {
		return "", err
	}
	return c.generateProgram(outpkg, templatesToCompile), nil
}

// convertTemplates convert each TemplateToCompile into functions.
func (c *CompiledTemplatesProgram) convertTemplates(templatesToCompile []*TemplateToCompile) error {
	for _, t := range templatesToCompile {
		for _, f := range t.files {
			for _, name := range f.names() {
				f.tplsFunc[name] = c.makeFuncName(f.tplsFunc[name])
				f.tplsFunc[name] = snakeToCamel(f.tplsFunc[name])

				dataConfig, err := t.getDataConfiguration(name)
				if err != nil {
					return err
				}

				err = convertTplTree(
					f.tplsFunc[name],
					f.tplsTree[name],
					t.FuncsExport,
					t.PublicIdents,
					dataConfig,
					f.tplsTypeCheck[name],
					c,
				)
				if err != nil {
					return err
				}
			}
		}
	}
	return nil
}

// getTemplatesToCompile prepares the templates for the given configuration.
func (c *CompiledTemplatesProgram) getTemplatesToCompile(conf *compiled.Configuration) ([]*TemplateToCompile, error) {
	templatesToCompile := convertConfigToTemplatesToCompile(conf)
	for _, t := range templatesToCompile {
		if err := t.prepare(); err != nil {
			return templatesToCompile, err
		}
	}
	return templatesToCompile, nil
}

// updatedOutPkg ensure the configuration OutPkg is set.
// if OutPkg is empty, it tries to detect the package automatically
// by reading the files existing in the OutPath directory and extracting the package declaration.
func updateOutPkg(conf *compiled.Configuration) error {
	if conf.OutPkg == "" {
		pkgName, err := LookupPackageName(conf.OutPath)
		if err != nil {
			return fmt.Errorf("Failed to lookup for the package name: %v", err)
		}
		conf.OutPkg = pkgName
	}
	return nil
}

// getDataQualifier returns the contextualized data qualifer for the program imports.
func (c *CompiledTemplatesProgram) getDataQualifier(dataConf compiled.DataConfiguration) string {
	dataAlias := c.addImport(dataConf.PkgPath)
	dataQualifier := fmt.Sprintf("%v.%v", dataAlias, dataConf.DataTypeName)
	if dataConf.IsPtr {
		dataQualifier = fmt.Sprintf("*%v.%v", dataAlias, dataConf.DataTypeName)
	}
	return dataQualifier
}

// addImport adds a new import spec to the output program.
// if the pkgpath is already imported, it is imported once only.
// if the pkgpath collides with another exisiting ident, it is renamed appropriately.
// it returns the alias of the pkgpath.
func (c *CompiledTemplatesProgram) addImport(pkgpath string) string {
	qpath := fmt.Sprintf("%q", pkgpath)
	bpath := filepath.Base(pkgpath)
	// if already imported, return the current alias
	for _, i := range c.imports {
		if i.Path.Value == qpath {
			if i.Name == nil {
				return bpath
			}
			return i.Name.Name
		}
	}
	newImport := &ast.ImportSpec{
		Path: &ast.BasicLit{Value: qpath},
	}
	c.imports = append(c.imports, newImport)
	duplicated := false
	i := 0
	okAlias := bpath
	for c.isCollidingIdent(okAlias) {
		if i == 0 {
			okAlias = "alias" + bpath
		} else {
			okAlias = fmt.Sprintf("alias%v%v", bpath, i)
		}
		i++
		duplicated = true
	}
	if duplicated {
		newImport.Name = &ast.Ident{Name: okAlias}
	}
	c.idents = append(c.idents, okAlias)
	return okAlias
}

// hasImport tells if pkgPath is imported.
func (c *CompiledTemplatesProgram) hasImport(pkgpath string) bool {
	qpath := fmt.Sprintf("%q", pkgpath)
	for _, i := range c.imports {
		if i.Path.Value == qpath {
			return true
		}
	}
	return false
}

// isCollidingIdent tells if given ident will collide exisiting idents.
func (c *CompiledTemplatesProgram) isCollidingIdent(ident string) bool {
	// check for imports
	for _, i := range c.imports {
		if i.Name != nil && i.Name.Name == ident {
			return true
		}
	}
	// check for static idents
	for _, i := range c.idents {
		if i == ident {
			return true
		}
	}
	return false
}

// makeFuncName produces a new unique func name.
func (c *CompiledTemplatesProgram) makeFuncName(baseName string) string {
	x := baseName
	i := 0
	for c.isCollidingIdent(x) {
		x = fmt.Sprintf("%v%v%v", "fn", i, baseName)
		i++
	}
	c.idents = append(c.idents, x)
	return x
}

// createFunc creates the ast code of a compiled template function with given name.
func (c *CompiledTemplatesProgram) createFunc(name string) *ast.FuncDecl {
	gocode := fmt.Sprintf(
		`package aa
func %v(t parse.Templater, w io.Writer, indata interface{}) error {}`,
		name,
	)
	f := stringToAst(gocode)
	fn := f.Decls[0].(*ast.FuncDecl)
	c.funcs = append(c.funcs, fn)
	return fn
}

// addBuiltintText registers a static builtin text to the program.
func (c *CompiledTemplatesProgram) addBuiltintText(text string) string {
	if x, ok := c.builtinTexts[text]; ok {
		return x
	}
	c.builtinTexts[text] = fmt.Sprintf("%v%v", "builtin", len(c.builtinTexts))
	return c.builtinTexts[text]
}

// generateInitFunc generates the init func body.
// the init func contains the code to declare the compiled templates
// and associate their defined templates.
func (c *CompiledTemplatesProgram) generateInitFunc(tpls []*TemplateToCompile) string {
	initfunc := ""
	initfunc += fmt.Sprintf("func init () {\n")
	for _, t := range tpls {
		for _, f := range t.files {
			for _, name := range f.names() {
				funcname := f.tplsFunc[name]
				initfunc += fmt.Sprintf("  %v.Add(%#v, %v)\n", c.varName, name, funcname)
			}
		}
	}

	for _, t := range tpls {
		for i, f := range t.files {
			for e, name := range f.definedTemplates {
				varX := fmt.Sprintf("tpl%vX%v", i, e)
				varY := fmt.Sprintf("tpl%vY%v", i, e)
				initfunc += fmt.Sprintf("  %v := %v.MustGet(%#v)\n", varX, c.varName, f.name)
				initfunc += fmt.Sprintf("  %v := %v.MustGet(%#v)\n", varY, c.varName, name)
				initfunc += fmt.Sprintf("  %v, _ = %v.Compiled(%v)\n", varX, varX, varY)
				initfunc += fmt.Sprintf("  %v.Set(%#v, %v)\n", c.varName, f.name, varX)
			}
		}
	}

	initfunc += fmt.Sprintf("}")
	return initfunc
}

// generateProgram generates the output program.
func (c *CompiledTemplatesProgram) generateProgram(outpkg string, tpls []*TemplateToCompile) string {
	program := fmt.Sprintf("package %v\n\n", outpkg)
	program += fmt.Sprintf("//golint:ignore\n\n")
	program += fmt.Sprintf("%v\n\n", c.generateImportStmt())
	program += fmt.Sprintf("%v\n\n", c.generateBuiltins())
	program += fmt.Sprintf("%v\n\n", c.generateInitFunc(tpls))
	for _, f := range c.funcs {
		program += fmt.Sprintf("%v\n\n", astNodeToString(f))
	}
	return program
}

// generateImportStmt generates all import statements.
func (c *CompiledTemplatesProgram) generateImportStmt() string {
	importStmt := ""
	importStmt += fmt.Sprintf("import (\n")
	for _, i := range c.imports {
		importStmt += fmt.Sprintf("\t")
		if i.Name != nil {
			importStmt += fmt.Sprintf("%v ", i.Name.Name)
		}
		importStmt += fmt.Sprintf("%v\n", i.Path.Value)
	}
	importStmt += fmt.Sprintf(")")
	return importStmt
}

// generateBuiltins generates the builtins text variable declarations.
func (c *CompiledTemplatesProgram) generateBuiltins() string {
	builtins := ""
	for text, name := range c.builtinTexts {
		builtins += fmt.Sprintf("var %v = []byte(%q)\n", name, text)
	}
	return builtins
}

// convertConfigToTemplatesToCompile convert the confguration into instances of TemplateToCompile
func convertConfigToTemplatesToCompile(conf *compiled.Configuration) []*TemplateToCompile {
	ret := []*TemplateToCompile{}
	for _, t := range conf.Templates {
		ret = append(ret, makeTemplateToCompile(t))
	}
	return ret
}

// TemplateToCompile links a configuration and all the template files it matches.
type TemplateToCompile struct {
	*compiled.TemplateConfiguration
	files []TemplateFileToCompile
}

// TemplateFileToCompile links a template file with all the templates defined in it.
type TemplateFileToCompile struct {
	name             string
	tplsTree         map[string]*parse.Tree
	tplsFunc         map[string]string
	tplsTypeCheck    map[string]*simplifier.State
	definedTemplates []string
}

// names returns all template names sorted asc.
func (t TemplateFileToCompile) names() []string {
	strs := []string{}
	for name := range t.tplsTree {
		strs = append(strs, name)
	}
	sort.Strings(strs)
	return strs
}

// getDataConfiguration returns the data configuration for the given template name.
func (t TemplateToCompile) getDataConfiguration(name string) (compiled.DataConfiguration, error) {
	if ret, ok := t.TemplatesDataConfiguration[name]; ok {
		return ret, nil
	}
	if ret, ok := t.TemplatesDataConfiguration["*"]; ok {
		return ret, nil
	}
	return compiled.DataConfiguration{}, fmt.Errorf("Template data configuration not found for %v", name)
}

// getData returns the data value for the given template name.
func (t TemplateToCompile) getData(name string) (interface{}, error) {
	if ret, ok := t.TemplatesData[name]; ok {
		return ret, nil
	}
	if ret, ok := t.TemplatesData["*"]; ok {
		return ret, nil
	}
	return nil, fmt.Errorf("Template data configuration not found for %v", name)
}

// makeTemplateToCompile creates a new instance of TemplateToCompile for the given TemplateConfiguration.
func makeTemplateToCompile(templateConf compiled.TemplateConfiguration) *TemplateToCompile {
	ret := &TemplateToCompile{
		TemplateConfiguration: &templateConf,
		files: []TemplateFileToCompile{},
	}
	return ret
}

// prepare evalutes the files of the TemplateConfiguration and prepares the resulting templates.
func (t *TemplateToCompile) prepare() error {
	if t.TemplatesPath != "" {
		tplsPath, err := filepath.Glob(t.TemplatesPath)
		if err != nil {
			return fmt.Errorf("Failed to glob the templates: %v %v", t.TemplatesPath, err)
		}
		for _, tplPath := range tplsPath {
			fileTpl, err := makeTemplateFileToCompileFromFile(tplPath, t)
			if err != nil {
				return err
			}
			t.files = append(t.files, fileTpl)
		}
	} else {
		fileTpl, err := makeTemplateFileToCompileFromStr(t.TemplateName, t.TemplateContent, t)
		if err != nil {
			return err
		}
		t.files = append(t.files, fileTpl)
	}
	return nil
}

//makeTemplateFileToCompileFromFile creates a new TemplateFileToCompile instance for the given template file.
func makeTemplateFileToCompileFromFile(tplPath string, tplToCompile *TemplateToCompile) (TemplateFileToCompile, error) {

	fileTpl := TemplateFileToCompile{
		name:             filepath.Base(tplPath),
		tplsTree:         map[string]*parse.Tree{},
		tplsFunc:         map[string]string{},
		tplsTypeCheck:    map[string]*simplifier.State{},
		definedTemplates: []string{},
	}

	content, err := ioutil.ReadFile(tplPath)
	if err != nil {
		return fileTpl, err
	}
	mainName := fileTpl.name
	funcs := tplToCompile.FuncsExport

	var treeNames map[string]*parse.Tree
	if tplToCompile.HTML {
		treeNames, err = compileHTMLTemplate(mainName, string(content), funcs)
	} else {
		treeNames, err = compileTextTemplate(mainName, string(content), funcs)
	}
	if err != nil {
		return fileTpl, err
	}
	fileTpl.tplsTree = treeNames
	for treeName, tree := range fileTpl.tplsTree {
		data, err := tplToCompile.getData(treeName)
		if err != nil {
			return fileTpl, err
		}
		fileTpl.tplsTypeCheck[treeName] = simplifier.TransformTree(tree, data, funcs)
		if treeName != mainName {
			fileTpl.tplsFunc[treeName] = cleanTplName("fn" + mainName + "_" + treeName)
			fileTpl.definedTemplates = append(fileTpl.definedTemplates, treeName)
		} else {
			fileTpl.tplsFunc[treeName] = cleanTplName("fn" + mainName)
		}
	}
	return fileTpl, nil
}

//makeTemplateFileToCompileFromStr creates a new TemplateFileToCompile instance for the given template content.
func makeTemplateFileToCompileFromStr(name, tplContent string, tplToCompile *TemplateToCompile) (TemplateFileToCompile, error) {

	fileTpl := TemplateFileToCompile{
		name:             name,
		tplsTree:         map[string]*parse.Tree{},
		tplsFunc:         map[string]string{},
		tplsTypeCheck:    map[string]*simplifier.State{},
		definedTemplates: []string{},
	}
	funcs := tplToCompile.FuncsExport

	var err error
	var treeNames map[string]*parse.Tree
	if tplToCompile.HTML {
		treeNames, err = compileHTMLTemplate(name, tplContent, funcs)
	} else {
		treeNames, err = compileTextTemplate(name, tplContent, funcs)
	}
	if err != nil {
		return fileTpl, err
	}
	fileTpl.tplsTree = treeNames
	mainName := fileTpl.name
	for treeName, tree := range fileTpl.tplsTree {
		data, err := tplToCompile.getData(treeName)
		if err != nil {
			return fileTpl, err
		}
		fileTpl.tplsTypeCheck[treeName] = simplifier.TransformTree(tree, data, funcs)
		if treeName != mainName {
			fileTpl.tplsFunc[treeName] = cleanTplName("fn" + mainName + "_" + treeName)
			fileTpl.definedTemplates = append(fileTpl.definedTemplates, treeName)
		} else {
			fileTpl.tplsFunc[treeName] = cleanTplName("fn" + mainName)
		}
	}
	return fileTpl, nil
}

// compileTextTemplate compiles a file template as a text/template, it returns a map of trees by their name.
func compileTextTemplate(name string, content string, funcsMap map[string]interface{}) (map[string]*parse.Tree, error) {
	ret := map[string]*parse.Tree{}

	t, err := text.New(name).Funcs(funcsMap).Parse(content)
	if err != nil {
		return ret, err
	}

	for _, tpl := range t.Templates() {
		tpl.Execute(ioutil.Discard, nil) // ignore err, it is just to force parse.
		if tpl.Tree != nil {
			ret[tpl.Name()] = tpl.Tree
		}
	}

	return ret, nil
}

// compileHTMLTemplate compiles a file template as an html/template, it returns a map of trees by their name.
func compileHTMLTemplate(name string, content string, funcsMap map[string]interface{}) (map[string]*parse.Tree, error) {
	ret := map[string]*parse.Tree{}

	t, err := html.New(name).Funcs(funcsMap).Parse(content)
	if err != nil {
		return ret, err
	}

	for _, tpl := range t.Templates() {
		tpl.Execute(ioutil.Discard, nil) // ignore err, it is just to force parse.
		if tpl.Tree != nil {
			ret[tpl.Name()] = tpl.Tree
		}
	}

	return ret, nil
}

// LookupPackageName search a directory for its declaring package.
func LookupPackageName(someDir string) (string, error) {
	dir := filepath.Dir(someDir)
	// the dir must exists
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		return "", err
	}
	files, err := filepath.Glob(filepath.Dir(someDir) + "/*.go")
	if err != nil {
		return "", err
	}
	if len(files) == 0 {
		// maybe it is pointing to an empty dir
		dir := filepath.Dir(someDir)
		// the package name will be basename of dir
		return filepath.Base(dir), nil
	}
	f := files[0]
	b, err := ioutil.ReadFile(f)
	if err != nil {
		return "", err
	}
	return LookupPackageNameFromStr(string(b)), nil
}

// LookupPackageNameFromStr extract the declaring package from given go source string.
func LookupPackageNameFromStr(gocode string) string {
	// improve this. really q&d.
	gocode = gocode[strings.Index(gocode, "package"):]
	gocode = gocode[0:strings.Index(gocode, "\n")]
	return strings.Split(gocode, "package ")[1]
}

func snakeToCamel(s string) string {
	s = snaker.SnakeToCamel(s)
	if len(s) > 0 {
		s = strings.ToLower(s[:1]) + s[1:]
	}
	return s
}

func cleanTplName(name string) string {
	return replaceAll(name, []string{"."}, "_")
}

func replaceAll(old string, removals []string, replacement string) string {
	for _, r := range removals {
		old = strings.Replace(old, r, replacement, -1)
	}
	return old
}


text:
//
//  MenuElement.h
//  pxlframework
//
//  Created by Gaëtan de Villèle on 8/26/13.
//
//

#ifndef __pxlframework__MenuElement__
#define __pxlframework__MenuElement__

// C++
#include <cassert>
#include <vector>
// pxlframework
#include "Sprite.h"
#include "../types/Point.h"
// px::tools
#include "Device.h"
#include "TouchEvent.h"

namespace px
{
	namespace engine
	{
		/**
		 * It represents an displayable element
		 * that can be contained in a Menu object
		 *
		 * It can only be place with a relative position
		 * based on screen or another MenuSprite
		 *
		 * a MenuSprite object always have an anchor point of (0.5,0.5)
		 *
		 * A Sprite can normaly contains other sprites, but MenuSprite
		 * can only contain MenuSprite objects
		 *
		 *
		 *
		 * - a MenuSprite object can only have relative positionning
		 * - in this class we use Sprite::_position as margin from the relative position
		 */
		class MenuSprite : public Sprite
		{

		public:

			typedef std::vector<MenuSprite*> MenuSpriteChildrenVector;

			enum class RelativePosition : uint8_t
			{
				UNDEFINED = 0,
				CENTER = 1,
				TOP = 2,
				RIGHT = 3,
				BOTTOM = 4,
				LEFT = 5,
				TOP_LEFT = 6,
				TOP_RIGHT = 7,
				BOTTOM_LEFT = 8,
				BOTTOM_RIGHT = 9
			};

			/**
			 * different status of a slider
			 * @brief this enum will be more global later (GUI)
			 */
			enum class State : uint8_t
			{
				NORMAL = 0,
				PRESSED = 1,
				FOCUSED = 2,
				DISABLED = 3,
			};

			/**
			 * convert values from the "MenuSpriteRelativePosition" enumeration into anchor point
			 */
			static Point convertRelativePositionIntoAnchorPoint(RelativePosition relativePosition);

			/**
			 * factory method
			 */
			static MenuSprite* newMenuSprite(const Size contentSize,
											 const RelativePosition relativePosition,
											 const RelativePosition anchor,
											 const Point& position);

			/**
			 * factory method
			 */
			static MenuSprite* newMenuSpriteWithTexture(const std::string& textureName,
														const RelativePosition relativePosition,
														const RelativePosition anchor,
														const Point& position);

			/**
			 * factory method without positionning infos for ScrollView widgets
			 */
			static MenuSprite* newMenuSprite(const std::string& textureName);

			/**
			 * Destructor
			 */
			virtual ~MenuSprite();

#pragma mark - Methods -

			/**
			 * GUI touch pipeline
			 * @return true if the touch is consumed
			 */
			virtual bool onTouch( TouchEvent event );

			/**
			 * convert touch event from [this->parent] coordinates
			 * into [this] coordinates (bottom left corner)
			 */
			TouchEvent convertTouchEventCoordinates( TouchEvent event );

#pragma mark - Accessors -

			/**
			 * returns the positionning mode
			 */
			const RelativePosition getRelativePosition() const {return _relativePosition;}
			const State getState() const {return _state;}
			const float getParallaxFactor() const {return _parallaxFactor;}
			const RelativePosition getAnchorToBeForcedTo() const {return _anchorToBeForcedTo;}
			/**
			 * compute on-screen bounding box
			 * the bounding box is relative to parent
			 * it contains position and the content size of the MenuSprite
			 *
			 * could be relative to parent (like CCNode in Cocos2D) .... not absolute
			 * and the click position could be transform in the parent landmark progressivelly
			 *
			 * (used to detect click)
			 */
			px::tools::Rect getBoundingBox();

#pragma mark - Modifiers -

			void setState(const State state) {_state = state;setChanged(true);}
			void setRelativePosition(RelativePosition relativePosition) {_relativePosition = relativePosition;}
			void setParallaxFactor(const float factor) {_parallaxFactor = factor;}
			void setAnchorToBeForcedTo(const RelativePosition anchor) {_anchorToBeForcedTo = anchor;}

            inline bool isScaledToFitDeviceResolution(){ return _scaledToFitDeviceResolution; }
            inline void setScaledToFitDeviceResolution(){ _scaledToFitDeviceResolution = true; }

		protected:

			bool init(const Size contentSize,
					  const RelativePosition relativePosition,
					  const RelativePosition anchor,
					  const Point& position);

			/**
			 * Default Constructor
			 * only this class and its sub classes can use it
			 */
			MenuSprite();

			/**
			 * current state of the widget
			 */
			State _state;

		private:

			/**
			 * relative positionning mode
			 * it defines the relative positionning in its parent
			 * it defines wich parent's point will be used as parent's
			 * anchor for this particular child
			 */
			RelativePosition _relativePosition;

			/**
			 * factor applied to the menusprite movements
			 * @brief use to do parallax in ScrollView. Value is 1.0f by default.
			 */
			float _parallaxFactor;

			/**
			 * anchor to be forced to on setContentSize(...)
			 */
			RelativePosition _anchorToBeForcedTo;

            /**
             * Has to be set to trus if device is already scaled to fit device's resolution
             * to avoid children from scaling, again (already scaled in cascade)
             * if parent is already scaled, child should set _scaledToFitDeviceResolution = true;
             */
            bool _scaledToFitDeviceResolution;

			/** Disable copying */
			DISALLOW_COPY_AND_ASSIGN(MenuSprite);

		};
	}
}

#endif


text:
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from dataset import CUB_200_2011
from storage import datastore
from deep_extractor import CNN_Features_CAFFE_REFERENCE
from datetime import datetime as dt
import numpy
import settings
import utils

cub_full = CUB_200_2011(settings.CUB_ROOT, full=True)
cub = CUB_200_2011(settings.CUB_ROOT, full=False)
features_storage = datastore(settings.storage('ccc'))
feature_extractor_full = CNN_Features_CAFFE_REFERENCE(features_storage, full=True)
feature_extractor = CNN_Features_CAFFE_REFERENCE(features_storage, full=False)

features_storage_f = datastore(settings.storage('ccfc'))
feature_extractor_full_f = CNN_Features_CAFFE_REFERENCE(features_storage_f, full=True)
feature_extractor_f = CNN_Features_CAFFE_REFERENCE(features_storage_f, full=False)

Xtrain, ytrain, Xtest, ytest = cub_full.get_train_test(feature_extractor_full.extract_one, feature_extractor.extract_one)
Xtrain_f, ytrain_f, Xtest_f, ytest_f = cub_full.get_train_test(feature_extractor_full_f.extract_one, feature_extractor_f.extract_one)

print Xtrain.shape, ytrain.shape
print Xtest.shape, ytest.shape

from sklearn import svm
from sklearn.metrics import accuracy_score

a = dt.now()
model = svm.LinearSVC(C=0.0001)
model.fit(numpy.concatenate((Xtrain, Xtrain_f)), numpy.concatenate((ytrain, ytrain_f)))
b = dt.now()
print 'fitted in: %s' % (b - a)

a = dt.now()
predictions = model.predict(Xtest)
b = dt.now()
print 'predicted in: %s' % (b - a)

print 'accuracy', accuracy_score(ytest, predictions)
print 'mean accuracy', utils.mean_accuracy(ytest, predictions)


text:
package server

import (
	"fmt"
	"github.com/leoferlopes/secret/crypto"
	"github.com/leoferlopes/secret/types"
	"github.com/leoferlopes/secret/util"
	"net"
	"os"
)

type Server struct {
	File string
	Bind string
}

func NewServer(params types.ServerParams) *Server {
	return &Server{
		File: params.File,
		Bind: fmt.Sprintf(":%d", params.Port),
	}
}

func check(e error) {
	if e != nil {
		panic(e)
	}
}

func (server *Server) Run() {
	ln, err := net.Listen("tcp", server.Bind)
	check(err)

	conn, err := ln.Accept()
	check(err)

	defer conn.Close()
	server.handleConnection(conn)
}

func (server *Server) handleConnection(conn net.Conn) {
	file, err := os.Create(server.File)
	check(err)
	cypher := crypto.NewStandartCypher()
	util.TransferDecryptBuffer(conn, file, cypher)
	file.Close()
	conn.Close()
}


text:
from math import sin, cos, radians
from collections import namedtuple
import logging

__version__ = "1.1.1"

# Point type
Point = namedtuple("Point", ('x', 'y'))

# Tile size
TS = 16
# Smart selection
SMART_SEL = False

class Singleton(type):

    """Class for the singleton pattern
    """
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(
                Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

def debug(message, *args):
    """Print a debug message if debugging is active
    """
    logger = logging.getLogger()
    if logger.isEnabledFor(logging.DEBUG):
        if len(args) == 0:
            logger.debug(message)
        else:
            logger.debug("[-- %s --", message)
            for item in args:
                name, value = item
                logger.debug(" -- %s -> %s", name, value)
            logger.debug(" --]")

def rotate_point(point, pivot, degrees):
    """Rotate the point for tot degrees respect the pivot
    """
    rad = radians(degrees)
    sin_ = round(sin(rad))
    cos_ = round(cos(rad))
    new_pos = Point(
        point.x - pivot.x,
        point.y - pivot.y
    )
    new_pos = Point(
        new_pos.x * cos_ - new_pos.y * sin_,
        new_pos.x * sin_ + new_pos.y * cos_
    )
    new_pos = Point(
        int(round(new_pos.x + pivot.x)),
        int(round(new_pos.y + pivot.y))
    )
    return new_pos


text:
mat3
=======

mat3 for the browser and node.js


text:
package edu.duke.cabig.c3pr.web.ajax;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Required;

import edu.duke.cabig.c3pr.dao.DiseaseTermDao;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.ICD9DiseaseSiteDao;
import edu.duke.cabig.c3pr.dao.InvestigatorDao;
import edu.duke.cabig.c3pr.dao.StudyDao;
import edu.duke.cabig.c3pr.dao.StudyPersonnelDao;
import edu.duke.cabig.c3pr.domain.DiseaseTerm;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.ICD9DiseaseSite;
import edu.duke.cabig.c3pr.domain.Investigator;
import edu.duke.cabig.c3pr.domain.RemoteHealthcareSite;
import edu.duke.cabig.c3pr.domain.StudyPersonnel;

/**
 * @author Himanshu Gupta
 */
public class CommonAjaxFacade {
    private StudyDao studyDao;

    private DiseaseTermDao diseaseTermDao;
    private HealthcareSiteDao healthcareSiteDao;
    private InvestigatorDao investigatorDao;
    private ICD9DiseaseSiteDao icd9DiseaseSiteDao ;
    private StudyPersonnelDao studyPersonnelDao;

    public void setStudyPersonnelDao(StudyPersonnelDao studyPersonnelDao) {
		this.studyPersonnelDao = studyPersonnelDao;
	}

	private static Log log = LogFactory.getLog(CommonAjaxFacade.class);

    @SuppressWarnings("unchecked")
    private <T> T buildReduced(T src, List<String> properties) {
        T dst = null;
        try {
            dst = (T) src.getClass().newInstance();
        }
        catch (InstantiationException e) {
            throw new RuntimeException("Failed to instantiate " + src.getClass().getName(), e);
        }
        catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to instantiate " + src.getClass().getName(), e);
        }

        BeanWrapper source = new BeanWrapperImpl(src);
        BeanWrapper destination = new BeanWrapperImpl(dst);
        for (String property : properties) {
            // only for nested props
            String[] individualProps = property.split("\\.");
            String temp = "";
            for (int i = 0; i < individualProps.length - 1; i++) {
                temp += (i != 0 ? "." : "") + individualProps[i];
                Object o = source.getPropertyValue(temp);
                if (destination.getPropertyValue(temp) == null) {
                    try {
                        destination.setPropertyValue(temp, o.getClass().newInstance());
                    }
                    catch (BeansException e) {
                        log.error(e.getMessage());
                    }
                    catch (InstantiationException e) {
                        log.error(e.getMessage());
                    }
                    catch (IllegalAccessException e) {
                        log.error(e.getMessage());
                    }
                }
            }
            destination.setPropertyValue(property, source.getPropertyValue(property));
        }
        return dst;
    }

    public List<HealthcareSite> matchHealthcareSites(String text) throws Exception {
        List<HealthcareSite> healthcareSites = healthcareSiteDao.getBySubnames(extractSubnames(text));
        List<HealthcareSite> reducedHealthcareSites = new ArrayList<HealthcareSite>(healthcareSites.size());
        for (HealthcareSite healthcareSite : healthcareSites) {
        	if(healthcareSite instanceof RemoteHealthcareSite){
        		reducedHealthcareSites.add(buildReduced(healthcareSite, Arrays.asList("id", "name", "externalId", "identifiersAssignedToOrganization", "ctepCode")));
        	}
        	else {
        		reducedHealthcareSites.add(buildReduced(healthcareSite, Arrays.asList("id", "name", "identifiersAssignedToOrganization",  "ctepCode")));
        	}
        }
        return reducedHealthcareSites;
    }

    public List<DiseaseTerm> matchDiseaseTerms(String text) {
        List<DiseaseTerm> diseaseTerms = diseaseTermDao.getBySubnames(extractSubnames(text));
        List<DiseaseTerm> reducedList = new ArrayList<DiseaseTerm>(diseaseTerms.size());
        for (DiseaseTerm diseaseTerm: diseaseTerms) {
        	reducedList .add(buildReduced(diseaseTerm, Arrays.asList("id", "ctepTerm")));
        }
        return reducedList;
    }

	public List<Investigator> matchInvestigators(String text) throws Exception {
		List<Investigator> investigators = investigatorDao.getBySubnames(extractSubnames(text));
		List<Investigator> reducedInvestigators = new ArrayList<Investigator>(investigators.size());
		for (Investigator investigator: investigators) {
			reducedInvestigators .add(buildReduced(investigator, Arrays.asList("id", "firstName", "lastName", "assignedIdentifier")));
        }
        return reducedInvestigators;
	}

	public List<StudyPersonnel> matchStudyPersonnel(String text) throws Exception {
		List<StudyPersonnel> personnel = studyPersonnelDao.getBySubnames(extractSubnames(text));
		List<StudyPersonnel> reducedPersonnel = new ArrayList<StudyPersonnel>(personnel.size());
		for (StudyPersonnel studyPerson: personnel) {
			reducedPersonnel .add(buildReduced(studyPerson, Arrays.asList("personUser.id", "personUser.firstName", "personUser.lastName", "personUser.assignedIdentifier")));
        }
        return reducedPersonnel;
	}

	public List<ICD9DiseaseSite> matchDiseaseSites(String text) {
	  List<ICD9DiseaseSite> anatomicSites = icd9DiseaseSiteDao.getBySubnames(extractSubnames(text));
	  List<ICD9DiseaseSite> reducedAnatomicSites = new ArrayList<ICD9DiseaseSite>();
	  for (ICD9DiseaseSite anatomicSite : anatomicSites) {
	  	if(anatomicSite.getSelectable()){
	  		reducedAnatomicSites.add(buildReduced(anatomicSite, Arrays.asList("id", "name","code")));
	  	}
	  }
	  return reducedAnatomicSites;
	}

    private String[] extractSubnames(String text) {
        return text.split("\\s+");
    }

    @Required
    public void setStudyDao(StudyDao studyDao) {
        this.studyDao = studyDao;
    }

    public StudyDao getStudyDao() {
        return studyDao;
    }

    public DiseaseTermDao getDiseaseTermDao() {
        return diseaseTermDao;
    }

    public void setDiseaseTermDao(DiseaseTermDao diseaseTermDao) {
        this.diseaseTermDao = diseaseTermDao;
    }

    public HealthcareSiteDao getHealthcareSiteDao() {
        return healthcareSiteDao;
    }

    public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) {
        this.healthcareSiteDao = healthcareSiteDao;
    }

    public InvestigatorDao getInvestigatorDao() {
        return investigatorDao;
    }

    public void setInvestigatorDao(InvestigatorDao investigatorDao) {
        this.investigatorDao = investigatorDao;
    }

	public ICD9DiseaseSiteDao getICD9DiseaseSiteDao() {
		return icd9DiseaseSiteDao;
	}

	public void setIcd9DiseaseSiteDao(ICD9DiseaseSiteDao icd9DiseaseSiteDao) {
		this.icd9DiseaseSiteDao = icd9DiseaseSiteDao;
	}
}


text:
%
% Copyright (c) 2015, Yarpiz (www.yarpiz.com)
% All rights reserved. Please read the "license.txt" for license terms.
%
% Project Code: YPEA124
% Project Title: Implementation of MOEA/D
% Muti-Objective Evolutionary Algorithm based on Decomposition
% Publisher: Yarpiz (www.yarpiz.com)
%
% Developer: S. Mostapha Kalami Heris (Member of Yarpiz Team)
%
% Contact Info: sm.kalami@gmail.com, info@yarpiz.com
%

function y=Crossover(x1,x2,params)

    gamma=params.gamma;
    VarMin=params.VarMin;
    VarMax=params.VarMax;

    alpha=unifrnd(-gamma,1+gamma,size(x1));

    y=alpha.*x1+(1-alpha).*x2;

    y=min(max(y,VarMin),VarMax);

end


text:
(function(window) {
    'use strict';

    var noResultsMesssage = 'No results returned from search, please try again.';
    var responseErrorMessage = 'Error returned from search, please try again.';

    function getSearchOptions(origin, destination, date) {
        return {
            method: 'POST',
            body: JSON.stringify({
                date: date,
                origin: origin,
                destination: destination
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        };
    }

    function fetchSearchForDate(origin, destination, date) {
        var options = getSearchOptions(origin, destination, date);

        return fetch('api/search', options).then(handleResponse);
    }

    function fetchSearchForDates(origin, destination, searchDates) {
        return Promise.all(searchDates.map(fetchSearchForDate.bind(null, origin, destination)));
    }

    function handleNoResults(results) {
        if (!results.length) {
            throw Error(noResultsMesssage);
        }

        return results;
    }

    function handleResponse(response) {
        if (!response.ok) {
            return response.text().then(function(text) {
                throw Error(text || responseErrorMessage);
            });
        }

        return response.json();
    }

    var requestHelper = {};

    requestHelper.fetchSearch = function(data, searchDates) {
        return fetchSearchForDates(data.origin, data.destination, searchDates)
            .then(handleNoResults);
    }

    window.requestHelper = requestHelper;

})(window);


text:
package de.iss.mv2.server.data;

import de.iss.mv2.io.CommunicationPartner;
import de.iss.mv2.server.io.ClientThread;

/**
 * Default implementation of {@link SessionManager}.
 * @author Marcel Singer
 *
 */
public class SessionManagerImpl implements SessionManager {

	/**
	 * Creates a new instance of {@link SessionManager}.
	 */
	public SessionManagerImpl() {

	}

	@Override
	public boolean hasActiveLoginProcedure(CommunicationPartner client) {
		return ((ClientThread) client).hasActiveLoginProcedure();
	}

	@Override
	public String getLoginIdentifier(CommunicationPartner client) {
		return ((ClientThread) client).getIdentifier();
	}

	@Override
	public boolean isAuthenticated(CommunicationPartner client) {
		return ((ClientThread) client).isAuthenticated();
	}

	@Override
	public void startLoginProcedure(CommunicationPartner client,
			String identifier, byte[] testPhrase) {
		ClientThread cT = (ClientThread) client;
		cT.setHasActiveLoginProcedure(true);
		cT.setIdentifier(identifier);
		cT.setLoginTestPhrase(testPhrase);
	}

	@Override
	public void cancelLoginProcedure(CommunicationPartner client) {
		ClientThread cT = (ClientThread) client;
		cT.setHasActiveLoginProcedure(false);
		cT.setAuthenticated(false);
		cT.setHasActiveLoginProcedure(false);
		cT.setLoginTestPhrase(null);
	}

	@Override
	public void completeLoginProcedure(CommunicationPartner client) {
		ClientThread cT = (ClientThread) client;
		cT.setHasActiveLoginProcedure(false);
		cT.setAuthenticated(true);
	}

	@Override
	public String getIdentifier(CommunicationPartner client) {
		return ((ClientThread) client).getIdentifier();
	}

	@Override
	public byte[] getLoginTestPhrase(CommunicationPartner client) {
		return ((ClientThread) client).getLoginTestPhrase();
	}

}


text:
#include "config.h"

#if ENABLE(SVG)
#include "SVGTextChunkBuilder.h"

#include "RenderSVGInlineText.h"
#include "SVGElement.h"
#include "SVGInlineTextBox.h"
#include "SVGLengthContext.h"

namespace WebCore {

SVGTextChunkBuilder::SVGTextChunkBuilder()
{
}

void SVGTextChunkBuilder::transformationForTextBox(SVGInlineTextBox* textBox, AffineTransform& transform) const
{
    DEFINE_STATIC_LOCAL(const AffineTransform, s_identityTransform, ());
    if (!m_textBoxTransformations.contains(textBox)) {
        transform = s_identityTransform;
        return;
    }

    transform = m_textBoxTransformations.get(textBox);
}

void SVGTextChunkBuilder::buildTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes)
{
    if (lineLayoutBoxes.isEmpty())
        return;

    bool foundStart = false;
    unsigned lastChunkStartPosition = 0;
    unsigned boxPosition = 0;
    unsigned boxCount = lineLayoutBoxes.size();
    for (; boxPosition < boxCount; ++boxPosition) {
        SVGInlineTextBox* textBox = lineLayoutBoxes[boxPosition];
        if (!textBox->startsNewTextChunk())
            continue;

        if (!foundStart) {
            lastChunkStartPosition = boxPosition;
            foundStart = true;
        } else {
            ASSERT(boxPosition > lastChunkStartPosition);
            addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition);
            lastChunkStartPosition = boxPosition;
        }
    }

    if (!foundStart)
        return;

    if (boxPosition - lastChunkStartPosition > 0)
        addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition);
}

void SVGTextChunkBuilder::layoutTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes)
{
    buildTextChunks(lineLayoutBoxes);
    if (m_textChunks.isEmpty())
        return;

    unsigned chunkCount = m_textChunks.size();
    for (unsigned i = 0; i < chunkCount; ++i)
        processTextChunk(m_textChunks[i]);

    m_textChunks.clear();
}

void SVGTextChunkBuilder::addTextChunk(Vector<SVGInlineTextBox*>& lineLayoutBoxes, unsigned boxStart, unsigned boxCount)
{
    SVGInlineTextBox* textBox = lineLayoutBoxes[boxStart];
    ASSERT(textBox);

    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(textBox->textRenderer());
    ASSERT(textRenderer);

    const RenderStyle* style = textRenderer->style();
    ASSERT(style);

    const SVGRenderStyle* svgStyle = style->svgStyle();
    ASSERT(svgStyle);

    // Build chunk style flags.
    unsigned chunkStyle = SVGTextChunk::DefaultStyle;

    // Handle 'direction' property.
    if (!style->isLeftToRightDirection())
        chunkStyle |= SVGTextChunk::RightToLeftText;

    // Handle 'writing-mode' property.
    if (svgStyle->isVerticalWritingMode())
        chunkStyle |= SVGTextChunk::VerticalText;

    // Handle 'text-anchor' property.
    switch (svgStyle->textAnchor()) {
    case TA_START:
        break;
    case TA_MIDDLE:
        chunkStyle |= SVGTextChunk::MiddleAnchor;
        break;
    case TA_END:
        chunkStyle |= SVGTextChunk::EndAnchor;
        break;
    };

    // Handle 'lengthAdjust' property.
    float desiredTextLength = 0;
    if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(textRenderer->parent())) {
        SVGLengthContext lengthContext(textContentElement);
        desiredTextLength = textContentElement->specifiedTextLength().value(lengthContext);

        switch (textContentElement->lengthAdjust()) {
        case SVGLengthAdjustUnknown:
            break;
        case SVGLengthAdjustSpacing:
            chunkStyle |= SVGTextChunk::LengthAdjustSpacing;
            break;
        case SVGLengthAdjustSpacingAndGlyphs:
            chunkStyle |= SVGTextChunk::LengthAdjustSpacingAndGlyphs;
            break;
        };
    }

    SVGTextChunk chunk(chunkStyle, desiredTextLength);

    Vector<SVGInlineTextBox*>& boxes = chunk.boxes();
    for (unsigned i = boxStart; i < boxStart + boxCount; ++i)
        boxes.append(lineLayoutBoxes[i]);

    m_textChunks.append(chunk);
}

void SVGTextChunkBuilder::processTextChunk(const SVGTextChunk& chunk)
{
    bool processTextLength = chunk.hasDesiredTextLength();
    bool processTextAnchor = chunk.hasTextAnchor();
    if (!processTextAnchor && !processTextLength)
        return;

    const Vector<SVGInlineTextBox*>& boxes = chunk.boxes();
    unsigned boxCount = boxes.size();
    if (!boxCount)
        return;

    // Calculate absolute length of whole text chunk (starting from text box 'start', spanning 'length' text boxes).
    float chunkLength = 0;
    unsigned chunkCharacters = 0;
    chunk.calculateLength(chunkLength, chunkCharacters);

    bool isVerticalText = chunk.isVerticalText();
    if (processTextLength) {
        if (chunk.hasLengthAdjustSpacing()) {
            float textLengthShift = (chunk.desiredTextLength() - chunkLength) / chunkCharacters;
            unsigned atCharacter = 0;
            for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
                Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments();
                if (fragments.isEmpty())
                    continue;
                processTextLengthSpacingCorrection(isVerticalText, textLengthShift, fragments, atCharacter);
            }
        } else {
            ASSERT(chunk.hasLengthAdjustSpacingAndGlyphs());
            float textLengthScale = chunk.desiredTextLength() / chunkLength;
            AffineTransform spacingAndGlyphsTransform;

            bool foundFirstFragment = false;
            for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
                SVGInlineTextBox* textBox = boxes[boxPosition];
                Vector<SVGTextFragment>& fragments = textBox->textFragments();
                if (fragments.isEmpty())
                    continue;

                if (!foundFirstFragment) {
                    foundFirstFragment = true;
                    buildSpacingAndGlyphsTransform(isVerticalText, textLengthScale, fragments.first(), spacingAndGlyphsTransform);
                }

                m_textBoxTransformations.set(textBox, spacingAndGlyphsTransform);
            }
        }
    }

    if (!processTextAnchor)
        return;

    // If we previously applied a lengthAdjust="spacing" correction, we have to recalculate the chunk length, to be able to apply the text-anchor shift.
    if (processTextLength && chunk.hasLengthAdjustSpacing()) {
        chunkLength = 0;
        chunkCharacters = 0;
        chunk.calculateLength(chunkLength, chunkCharacters);
    }

    float textAnchorShift = chunk.calculateTextAnchorShift(chunkLength);
    for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) {
        Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments();
        if (fragments.isEmpty())
            continue;
        processTextAnchorCorrection(isVerticalText, textAnchorShift, fragments);
    }
}

void SVGTextChunkBuilder::processTextLengthSpacingCorrection(bool isVerticalText, float textLengthShift, Vector<SVGTextFragment>& fragments, unsigned& atCharacter)
{
    unsigned fragmentCount = fragments.size();
    for (unsigned i = 0; i < fragmentCount; ++i) {
        SVGTextFragment& fragment = fragments[i];

        if (isVerticalText)
            fragment.y += textLengthShift * atCharacter;
        else
            fragment.x += textLengthShift * atCharacter;

        atCharacter += fragment.length;
    }
}

void SVGTextChunkBuilder::processTextAnchorCorrection(bool isVerticalText, float textAnchorShift, Vector<SVGTextFragment>& fragments)
{
    unsigned fragmentCount = fragments.size();
    for (unsigned i = 0; i < fragmentCount; ++i) {
        SVGTextFragment& fragment = fragments[i];

        if (isVerticalText)
            fragment.y += textAnchorShift;
        else
            fragment.x += textAnchorShift;
    }
}

void SVGTextChunkBuilder::buildSpacingAndGlyphsTransform(bool isVerticalText, float scale, const SVGTextFragment& fragment, AffineTransform& spacingAndGlyphsTransform)
{
    spacingAndGlyphsTransform.translate(fragment.x, fragment.y);

    if (isVerticalText)
        spacingAndGlyphsTransform.scaleNonUniform(1, scale);
    else
        spacingAndGlyphsTransform.scaleNonUniform(scale, 1);

    spacingAndGlyphsTransform.translate(-fragment.x, -fragment.y);
}

}

#endif // ENABLE(SVG)


text:
define(["jquery", "can/util/can", "can/util/attr", "can/event", "can/util/array/each", "can/util/inserted"], function ($, can, attr, event) {
	var isBindableElement = function (node) {
		// In IE8 window.window !== window.window, so we allow == here.
		/*jshint eqeqeq:false*/
		return ( node.nodeName && (node.nodeType === 1 || node.nodeType === 9) )|| node == window;
	};
	// _jQuery node list._
	$.extend(can, $, {
		trigger: function (obj, event, args, bubbles) {
			if (isBindableElement( obj ) ) {
				$.event.trigger(event, args, obj, !bubbles);
			} else if (obj.trigger) {
				obj.trigger(event, args);
			} else {
				if (typeof event === 'string') {
					event = {
						type: event
					};
				}
				event.target = event.target || obj;
				if(args){
					if( args.length && typeof args === "string") {
						args = [args];
					} else if(! args.length ) {
						args = [args];
					}
				}
				if(!args){
					args = [];
				}
				can.dispatch.call(obj, event, args);
			}
		},
		event: can.event,
		addEvent: can.addEvent,
		removeEvent: can.removeEvent,
		buildFragment: function (elems, context) {
			// Check if this has any html nodes on our own.
			var ret;
			elems = [elems];
			// Set context per 1.8 logic
			context = context || document;
			context = !context.nodeType && context[0] || context;
			context = context.ownerDocument || context;
			ret = $.buildFragment(elems, context);
			return ret.cacheable ? $.clone(ret.fragment) : ret.fragment || ret;
		},
		$: $,
		each: can.each,
		bind: function (ev, cb) {
			// If we can bind to it...
			if (this.bind && this.bind !== can.bind) {
				this.bind(ev, cb);
			} else if (isBindableElement(this)) {
				$.event.add(this, ev, cb);
			} else {
				// Make it bind-able...
				can.addEvent.call(this, ev, cb);
			}
			return this;
		},
		unbind: function (ev, cb) {
			// If we can bind to it...
			if (this.unbind && this.unbind !== can.unbind) {
				this.unbind(ev, cb);
			} else if (isBindableElement(this)) {
				$.event.remove(this, ev, cb);
			} else {
				// Make it bind-able...
				can.removeEvent.call(this, ev, cb);
			}
			return this;
		},
		delegate: function (selector, ev, cb) {
			if (this.delegate) {
				this.delegate(selector, ev, cb);
			} else if (isBindableElement(this)) {
				$(this)
					.delegate(selector, ev, cb);
			} else {
				// make it bind-able ...
				can.bind.call(this, ev, cb);
			}
			return this;
		},
		undelegate: function (selector, ev, cb) {
			if (this.undelegate) {
				this.undelegate(selector, ev, cb);
			} else if (isBindableElement(this)) {
				$(this)
					.undelegate(selector, ev, cb);
			} else {
				can.unbind.call(this, ev, cb);
			}
			return this;
		},
		proxy: function (fn, context) {
			return function () {
				return fn.apply(context, arguments);
			};
		},
		attr: attr
	});
	// Wrap binding functions.
	/*$.each(['bind','unbind','undelegate','delegate'],function(i,func){
		can[func] = function(){
			var t = this[func] ? this : $([this]);
			t[func].apply(t, arguments);
			return this;
		};
	});*/
	// Aliases
	can.on = can.bind;
	can.off = can.unbind;
	// Wrap modifier functions.
	$.each([
		'append',
		'filter',
		'addClass',
		'remove',
		'data',
		'get',
		'has'
	], function (i, name) {
		can[name] = function (wrapped) {
			return wrapped[name].apply(wrapped, can.makeArray(arguments)
				.slice(1));
		};
	});
	// Memory safe destruction.
	var oldClean = $.cleanData;
	$.cleanData = function (elems) {
		$.each(elems, function (i, elem) {
			if (elem) {
				can.trigger(elem, 'removed', [], false);
			}
		});
		oldClean(elems);
	};
	var oldDomManip = $.fn.domManip,
		cbIndex;
	// feature detect which domManip we are using
	$.fn.domManip = function (args, cb1, cb2) {
		for (var i = 1; i < arguments.length; i++) {
			if (typeof arguments[i] === 'function') {
				cbIndex = i;
				break;
			}
		}
		return oldDomManip.apply(this, arguments);
	};
	$(document.createElement("div"))
		.append(document.createElement("div"));

	$.fn.domManip = (cbIndex === 2 ?
		function (args, table, callback) {
			return oldDomManip.call(this, args, table, function (elem) {
				var elems;
				if (elem.nodeType === 11) {
					elems = can.makeArray(elem.childNodes);
				}
				var ret = callback.apply(this, arguments);
				can.inserted(elems ? elems : [elem]);
				return ret;
			});
		} :
		function (args, callback) {
			return oldDomManip.call(this, args, function (elem) {
				var elems;
				if (elem.nodeType === 11) {
					elems = can.makeArray(elem.childNodes);
				}
				var ret = callback.apply(this, arguments);
				can.inserted(elems ? elems : [elem]);
				return ret;
			});
		});

	if (!can.attr.MutationObserver) {
		// handle via calls to attr
		var oldAttr = $.attr;
		$.attr = function (el, attrName) {
			var oldValue, newValue;
			if (arguments.length >= 3) {
				oldValue = oldAttr.call(this, el, attrName);
			}
			var res = oldAttr.apply(this, arguments);
			if (arguments.length >= 3) {
				newValue = oldAttr.call(this, el, attrName);
			}
			if (newValue !== oldValue) {
				can.attr.trigger(el, attrName, oldValue);
			}
			return res;
		};
		var oldRemove = $.removeAttr;
		$.removeAttr = function (el, attrName) {
			var oldValue = oldAttr.call(this, el, attrName),
				res = oldRemove.apply(this, arguments);

			if (oldValue != null) {
				can.attr.trigger(el, attrName, oldValue);
			}
			return res;
		};
		$.event.special.attributes = {
			setup: function () {
				can.data(can.$(this), "canHasAttributesBindings", true);
			},
			teardown: function () {
				$.removeData(this, "canHasAttributesBindings");
			}
		};
	} else {
		// setup a special events
		$.event.special.attributes = {
			setup: function () {
				var self = this;
				var observer = new can.attr.MutationObserver(function (mutations) {
					mutations.forEach(function (mutation) {
						var copy = can.simpleExtend({}, mutation);
						can.trigger(self, copy, []);
					});

				});
				observer.observe(this, {
					attributes: true,
					attributeOldValue: true
				});
				can.data(can.$(this), "canAttributesObserver", observer);
			},
			teardown: function () {
				can.data(can.$(this), "canAttributesObserver")
					.disconnect();
				$.removeData(this, "canAttributesObserver");

			}
		};
	}

	// ## Fix build fragment.
	// In IE8, we can pass jQuery a fragment and it removes newlines.
	// This checks for that and replaces can.buildFragment with something
	// that if only a single text node is returned, returns a fragment with
	// a text node that is set to the content.
	(function(){

		var text = "<-\n>",
			frag = can.buildFragment(text, document);
		if(text !== frag.childNodes[0].nodeValue) {

			var oldBuildFragment  = can.buildFragment;
			can.buildFragment = function(content, context){
				var res = oldBuildFragment(content, context);
				if(res.childNodes.length === 1 && res.childNodes[0].nodeType === 3) {
					res.childNodes[0].nodeValue = content;
				}
				return res;
			};

		}

	})();

	$.event.special.inserted = {};
	$.event.special.removed = {};
	return can;
});


text:
<?php
/**
 * BaseConfiguration.php
 *
 * @since 17/10/16
 * @author gseidel
 */

namespace Enhavo\Bundle\GridBundle\Item\Configuration;

use Enhavo\Bundle\GridBundle\Item\AbstractConfiguration;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BaseConfiguration extends AbstractConfiguration
{
    public function configureOptions(OptionsResolver $optionsResolver)
    {
        parent::configureOptions($optionsResolver);
    }

    public function getType()
    {
        return 'base';
    }
}


text:
@interface PodsDummy_Pods_RecExample_OSX_Rec : NSObject
@end
@implementation PodsDummy_Pods_RecExample_OSX_Rec
@end


text:
package graph

import (
	"container/ring"
	"crypto/md5"
	"encoding/hex"
	"io"
	"sync"

	"github.com/Sirupsen/logrus"
)

type NetworkGraph struct {
	// nodeName -> Node
	NodesMap  map[string]*NetworkNode `json:"nodes"`
	NodesLock *sync.RWMutex           `json:"-"`

	// nodeName,nodeName -> NetworkLink
	LinksMap  map[string]*NetworkLink `json:"edges"`
	LinksLock *sync.RWMutex           `json:"-"`

	RoutesMap  map[string]*NetworkRoute `json:"routes"`
	RoutesLock *sync.RWMutex            `json:"-"`

	// event stuff
	eventChannels     map[chan *Event]bool
	eventRegistration chan chan *Event
	internalEvents    chan *Event
}

func Create() *NetworkGraph {
	g := &NetworkGraph{
		NodesMap:   make(map[string]*NetworkNode),
		NodesLock:  &sync.RWMutex{},
		LinksMap:   make(map[string]*NetworkLink),
		LinksLock:  &sync.RWMutex{},
		RoutesMap:  make(map[string]*NetworkRoute),
		RoutesLock: &sync.RWMutex{},

		eventChannels:     make(map[chan *Event]bool),
		eventRegistration: make(chan chan *Event),
		internalEvents:    make(chan *Event),
	}

	go g.publisher()

	return g
}

// TODO: buffer messages?
// goroutine target to do all the publishing of events
func (g *NetworkGraph) publisher() {
	for {
		select {
		case newChannel := <-g.eventRegistration:
			g.eventChannels[newChannel] = true
		case newEvent := <-g.internalEvents:
			//logrus.Infof("got a new event! %v", newEvent)
			for subscriberChannel := range g.eventChannels {
				select {
				case subscriberChannel <- newEvent:
					//logrus.Infof("sent that event to a channel")
				default:
					//logrus.Infof("Unable to send event to that subscriber, killing")
					delete(g.eventChannels, subscriberChannel)
					close(subscriberChannel)
				}
			}
		}
	}
}

// TODO: locking here
// Dump everything in the NetworkGraph into a channel
func (g *NetworkGraph) EventDumpChannel() chan *Event {
	// TODO: buffer?
	c := make(chan *Event)
	go func(c chan *Event) {
		// dump nodes
		for _, n := range g.NodesMap {
			c <- &Event{
				E:    addEvent,
				Item: n,
			}
		}
		// dump links
		for _, l := range g.LinksMap {
			c <- &Event{
				E:    addEvent,
				Item: l,
			}
		}
		// dump routes
		for _, route := range g.RoutesMap {
			c <- &Event{
				E:    addEvent,
				Item: route,
			}
		}

		close(c)
	}(c)
	return c
}

// add subscriber to our events
func (g *NetworkGraph) Subscribe(c chan *Event) {
	g.eventRegistration <- c
}

func (g *NetworkGraph) IncrNode(name string, newNode *NetworkNode) (*NetworkNode, bool) {
	g.NodesLock.Lock()
	defer g.NodesLock.Unlock()
	n, ok := g.NodesMap[name]
	// if this one doesn't exist, lets add it
	if !ok {
		if newNode == nil {
			n = NewNetworkNode(name, g.internalEvents)
		} else {
			n = newNode
			n.updateChan = g.internalEvents
		}
		g.NodesMap[name] = n

		// Now that there is a new thing we fire an addEvent.
		// Note: if the background DNS lookup was initiated an updateEvent
		// will fire as soon as the lookup completes
		g.internalEvents <- &Event{
			E:    addEvent,
			Item: n,
		}
	}
	n.refCount++
	return n, !ok
}

func (g *NetworkGraph) GetNode(name string) *NetworkNode {
	g.NodesLock.RLock()
	defer g.NodesLock.RUnlock()
	n, _ := g.NodesMap[name]
	return n
}

func (g *NetworkGraph) GetNodeCount() int {
	g.NodesLock.RLock()
	defer g.NodesLock.RUnlock()
	return len(g.NodesMap)
}

func (g *NetworkGraph) DecrNode(name string) (*NetworkNode, bool) {
	g.NodesLock.Lock()
	defer g.NodesLock.Unlock()
	n, ok := g.NodesMap[name]

	if !ok {
		logrus.Warningf("Attempted to remove node with ip %v which wasn't in the graph", name)
		return nil, false
	}

	n.refCount--
	if n.refCount == 0 {
		delete(g.NodesMap, name)
		g.internalEvents <- &Event{
			E:    removeEvent,
			Item: n,
		}
		return n, true
	}
	return n, false
}

func (g *NetworkGraph) IncrLink(src, dst string, newLink *NetworkLink) (*NetworkLink, bool) {
	key := src + ";" + dst
	g.LinksLock.Lock()
	defer g.LinksLock.Unlock()
	l, ok := g.LinksMap[key]
	if !ok {
		if newLink == nil {
			srcNode, _ := g.IncrNode(src, nil)
			dstNode, _ := g.IncrNode(dst, nil)
			l = &NetworkLink{
				SrcName: srcNode.Name,
				srcNode: srcNode,
				DstName: dstNode.Name,
				dstNode: dstNode,
			}
		} else {
			srcNode, _ := g.IncrNode(src, newLink.srcNode)
			dstNode, _ := g.IncrNode(dst, newLink.dstNode)
			// update child pointers
			newLink.srcNode = srcNode
			newLink.dstNode = dstNode
			l = newLink
		}
		g.LinksMap[key] = l
		g.internalEvents <- &Event{
			E:    addEvent,
			Item: l,
		}
	}
	l.refCount++
	return l, !ok
}

func (g *NetworkGraph) GetLink(key string) *NetworkLink {
	g.LinksLock.RLock()
	defer g.LinksLock.RUnlock()
	l, _ := g.LinksMap[key]
	return l
}

func (g *NetworkGraph) GetLinkCount() int {
	g.LinksLock.RLock()
	defer g.LinksLock.RUnlock()
	return len(g.LinksMap)
}

func (g *NetworkGraph) DecrLink(src, dst string) (*NetworkLink, bool) {
	key := src + ";" + dst
	g.LinksLock.Lock()
	defer g.LinksLock.Unlock()
	l, ok := g.LinksMap[key]
	if !ok {
		logrus.Warningf("Attempted to remove link %v which wasn't in the graph", key)
		return nil, false
	}
	// decrement ourselves
	l.refCount--
	if l.refCount == 0 {
		// Decrement our children
		g.DecrNode(src)
		g.DecrNode(dst)
		delete(g.LinksMap, key)
		g.internalEvents <- &Event{
			E:    removeEvent,
			Item: l,
		}
		return l, true
	}
	return l, false
}

func (g *NetworkGraph) pathKey(hops []string) string {
	h := md5.New()
	for _, hop := range hops {
		io.WriteString(h, hop)
	}
	return hex.EncodeToString(h.Sum(nil))
}

func (g *NetworkGraph) IncrRoute(hops []string, newRoute *NetworkRoute) (*NetworkRoute, bool) {
	key := g.pathKey(hops)

	g.RoutesLock.Lock()
	defer g.RoutesLock.Unlock()

	// check if we have a route for this already
	route, ok := g.RoutesMap[key]
	// if we don't have it, lets make it
	if !ok {
		logrus.Debugf("New Route: key=%s %v", key, hops)
		if newRoute == nil {
			path := make([]*NetworkNode, 0, len(hops))
			for i, hop := range hops {
				hopNode, _ := g.IncrNode(hop, nil)
				path = append(path, hopNode)
				// If there was something prior-- lets add the link as well
				if i-1 >= 0 {
					g.IncrLink(hops[i-1], hop, nil)
				}
			}
			route = &NetworkRoute{
				Path:       hops,
				path:       path,
				State:      Up,
				metricRing: ring.New(100), // TODO: config
				mLock:      &sync.RWMutex{},
				updateChan: g.internalEvents,
			}
		} else {
			newRoute.path = make([]*NetworkNode, len(newRoute.Path))
			for i, nodeName := range newRoute.Path {
				// Increment the node (this will convert the name to a pointer)
				node, _ := g.IncrNode(nodeName, nil)
				// set the pointer in our `path`
				newRoute.path[i] = node

				// If there was something prior-- lets add the link as well
				if i-1 >= 0 {
					g.IncrLink(newRoute.path[i-1].Name, nodeName, nil)
				}
			}
			route = newRoute
			route.updateChan = g.internalEvents
		}

		g.RoutesMap[key] = route

		g.internalEvents <- &Event{
			E:    addEvent,
			Item: route,
		}
	}

	// increment route's refcount
	route.refCount++

	return route, !ok
}

func (g *NetworkGraph) GetRoute(hops []string) *NetworkRoute {
	g.RoutesLock.RLock()
	defer g.RoutesLock.RUnlock()
	r, _ := g.RoutesMap[g.pathKey(hops)]
	return r
}

func (g *NetworkGraph) GetRouteCount() int {
	g.RoutesLock.RLock()
	defer g.RoutesLock.RUnlock()
	return len(g.RoutesMap)
}

func (g *NetworkGraph) DecrRoute(hops []string) (*NetworkRoute, bool) {
	key := g.pathKey(hops)

	g.RoutesLock.Lock()
	defer g.RoutesLock.Unlock()
	r, ok := g.RoutesMap[key]
	if !ok {
		logrus.Warningf("Attempted to remove route %v which wasn't in the graph", key)
		return nil, false
	}

	r.refCount--
	if r.refCount == 0 {
		// decrement all the links/nodes as well
		for i, nodeName := range r.Path {
			g.DecrNode(nodeName)
			if i-1 >= 0 {
				g.DecrLink(r.Path[i-1], nodeName)
			}
		}

		delete(g.RoutesMap, key)
		g.internalEvents <- &Event{
			E:    removeEvent,
			Item: r,
		}
		return r, true
	}
	return r, false
}


text:
<resources>
    <string name="app_name">KonamiCode</string>
    <string name="default_callback_msg">Konami Code!</string>
</resources>


text:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Windows.Foundation.Collections;
using Windows.Storage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Videorb.Common;

namespace Videorb
{
    public class VideoList : ObservableCollection<VideoItem>
    {
        public VideoList() :base()
        {

        }

        public string Title { get; set; }
        public string Description { get; set; }
        public string Subtitle { get; set; }
        public string Image { get; set; }
        public string Path { get; set; }
        public StorageFile File { get; set; }
        public VideoInfoHelper Meta { get; set; }

        private List<VideoItem> _Items = new List<VideoItem>();
        public List<VideoItem> Items
        {
            get
            {
                return this._Items;
            }
        }
    }

    public class VideoItem : BindableStorageFile
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Subtitle { get; set; }
        public string Image { get; set; }
        public string Path { get; set; }
        public StorageFile File { get; set; }
        public VideoInfoHelper Meta { get; set; }

    }
}