text:
package org.simpleframework.xml.core;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Text;

/**
 * The ConstructorScanner object is used to scan all
 * all constructors that have XML annotations for their parameters.
 * parameters. Each constructor scanned is converted in to a
 * Initializer object. In order to ensure consistency
 * amongst the annotated parameters each named parameter must have
 * the exact same type and annotation attributes across the
 * constructors. This ensures a consistent XML representation.
 *
 * @author Niall Gallagher
 *
 * @see org.simpleframework.xml.core.Scanner
 */
class ConstructorScanner {

   /**
    * This contains a list of all the initializers for the class.
    */
   private List<Initializer> list;

   /**
    * This represents the default no argument constructor used.
    */
   private Initializer primary;

   /**
    * This is used to acquire a parameter by the parameter name.
    */
   private Signature signature;

   /**
    * This is the type that is scanner for annotated constructors.
    */
   private Class type;

   /**
    * Constructor for the ConstructorScanner object.
    * This is used to scan the specified class for constructors that
    * can be used to instantiate the class. Only constructors that
    * have all parameters annotated will be considered.
    *
    * @param type this is the type that is to be scanned
    */
   public ConstructorScanner(Class type) throws Exception {
      this.list = new ArrayList<Initializer>();
      this.signature = new Signature(type);
      this.type = type;
      this.scan(type);
   }

   /**
    * This is used to create the object instance. It does this by
    * either delegating to the default no argument constructor or by
    * using one of the annotated constructors for the object. This
    * allows deserialized values to be injected in to the created
    * object if that is required by the class schema.
    *
    * @return this returns the creator for the class object
    */
   public Creator getCreator() {
      return new ClassCreator(list, signature, primary);
   }

   /**
    * This is used to scan the specified class for constructors that
    * can be used to instantiate the class. Only constructors that
    * have all parameters annotated will be considered.
    *
    * @param type this is the type that is to be scanned
    */
   private void scan(Class type) throws Exception {
      Constructor[] array = type.getDeclaredConstructors();

      if(!isInstantiable(type)) {
         throw new ConstructorException("Can not construct inner %s", type);
      }
      for(Constructor factory: array){
         Signature index = new Signature(type);

         if(!type.isPrimitive()) {
            scan(factory, index);
         }
      }
   }

   /**
    * This is used to scan the specified constructor for annotations
    * that it contains. Each parameter annotation is evaluated and
    * if it is an XML annotation it is considered to be a valid
    * parameter and is added to the parameter map.
    *
    * @param factory this is the constructor that is to be scanned
    * @param map this is the parameter map that contains parameters
    */
   private void scan(Constructor factory, Signature map) throws Exception {
      Annotation[][] labels = factory.getParameterAnnotations();
      Class[] types = factory.getParameterTypes();

      for(int i = 0; i < types.length; i++) {
         for(int j = 0; j < labels[i].length; j++) {
            Parameter value = process(factory, labels[i][j], i);

            if(value != null) {
               String name = value.getName();

               if(map.containsKey(name)) {
                  throw new PersistenceException("Parameter '%s' is a duplicate in %s", name, factory);
               }
               signature.put(name, value);
               map.put(name, value);
            }
         }
      }
      if(types.length == map.size()) {
         build(factory, map);
      }
   }

   /**
    * This is used to build the Initializer object that is
    * to be used to instantiate the object. The initializer contains
    * the constructor at the parameters in the declaration order.
    *
    * @param factory this is the constructor that is to be scanned
    * @param signature the parameter map that contains parameters
    */
   private void build(Constructor factory, Signature signature) throws Exception {
      Initializer initializer = new Initializer(factory, signature);

      if(initializer.isDefault()) {
         primary = initializer;
      }
      list.add(initializer);
   }

   /**
    * This is used to create a Parameter object which is
    * used to represent a parameter to a constructor. Each parameter
    * contains an annotation an the index it appears in.
    *
    * @param factory this is the constructor the parameter is in
    * @param label this is the annotation used for the parameter
    * @param ordinal this is the position the parameter appears at
    *
    * @return this returns the parameter for the constructor
    */
   private Parameter process(Constructor factory, Annotation label, int ordinal) throws Exception{
      if(label instanceof Attribute) {
         return create(factory, label, ordinal);
      }
      if(label instanceof ElementList) {
         return create(factory, label, ordinal);
      }
      if(label instanceof ElementArray) {
         return create(factory, label, ordinal);
      }
      if(label instanceof ElementMap) {
         return create(factory, label, ordinal);
      }
      if(label instanceof Element) {
         return create(factory, label, ordinal);
      }
      if(label instanceof Text) {
         return create(factory, label, ordinal);
      }
      return null;
   }

   /**
    * This is used to create a Parameter object which is
    * used to represent a parameter to a constructor. Each parameter
    * contains an annotation an the index it appears in.
    *
    * @param factory this is the constructor the parameter is in
    * @param label this is the annotation used for the parameter
    * @param ordinal this is the position the parameter appears at
    *
    * @return this returns the parameter for the constructor
    */
   private Parameter create(Constructor factory, Annotation label, int ordinal) throws Exception {
      Parameter value = ParameterFactory.getInstance(factory, label, ordinal);
      String name = value.getName();

      if(signature.containsKey(name)) {
         validate(value, name);
      }
      return value;
   }

   /**
    * This is used to validate the parameter against all the other
    * parameters for the class. Validating each of the parameters
    * ensures that the annotations for the parameters remain
    * consistent throughout the class.
    *
    * @param parameter this is the parameter to be validated
    * @param name this is the name of the parameter to validate
    */
   private void validate(Parameter parameter, String name) throws Exception {
      Parameter other = signature.get(name);
      Annotation label = other.getAnnotation();

      if(!parameter.getAnnotation().equals(label)) {
         throw new MethodException("Annotations do not match for '%s' in %s", name, type);
      }
      Class expect = other.getType();

      if(expect != parameter.getType()) {
         throw new MethodException("Method types do not match for '%s' in %s", name, type);
      }
   }

   /**
    * This is used to determine if the class is an inner class. If
    * the class is a inner class and not static then this returns
    * false. Only static inner classes can be instantiated using
    * reflection as they do not require a "this" argument.
    *
    * @param type this is the class that is to be evaluated
    *
    * @return this returns true if the class is a static inner
    */
   private boolean isInstantiable(Class type) {
      int modifiers = type.getModifiers();

      if(Modifier.isStatic(modifiers)) {
         return true;
      }
      return !type.isMemberClass();
   }
}


text:
tags:  code ruby
title: Ruby (Deep) Copy Object
---

I wanted to make an object. Then copy it. Then change that copy and leave original object intact. But I did not know how to do it. When I do not know how to do something, I always ask wtr-general mailing list. I posted my question. Then I though it would be nice if I explained why I want to copy an object. But it got pretty long, so I put it at my blog.

I got a reply.

Try Object#clone.

Could it be that easy?! It could be. After all, this is Ruby. But no, it is not that easy. It did not work. Original object was changing with it's duplicate.

{% highlight ruby %}
class Page
  attr_accessor :texts
  def initialize(url, texts)
    @url, @texts = url, texts
  end
end

page_view = Page.new("app.com/view.aspx", ["File > View"])
page_view_after_add = page_view.clone
page_view_after_add.texts << "File added."

puts page_view.inspect
puts page_view_after_add.inspect
{% endhighlight %}

Output:

{% highlight shell %}
#<Page:0x2820ae0 @url="app.com/view.aspx", @texts=["File > View", "File added."]>
#<Page:0x2820a98 @url="app.com/view.aspx", @texts=["File > View", "File added."]>
{% endhighlight %}

But now I new where to look. So I typed ri Object#clone and ri Object#dup at Command Prompt (and even looked at ruby-doc.org/core). It said (at both places, for both Object#clone and Object#dup):

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference.

So, it creates a "shallow" copy. I do not need this. I need a "real" copy.

Google helped me. I searched for "ruby copy object" and found the solution. Secret word is "deep" copy.

I added this to class Page (and replaced page_view.clone with page_view.deep_clone) and got what I needed!

{% highlight ruby %}
def deep_clone
  Marshal::load(Marshal.dump(self))
end
{% endhighlight %}

Output:

{% highlight shell %}
#<Page:0x4c1dd10 @url="app.com/view.aspx", @texts=["File > View"]>
#<Page:0x4c1dc50 @url="app.com/view.aspx", @texts=["File > View", "File added."]>
{% endhighlight %}

I do not understand how it works, and I do not care, as long as it works.

redpajama_set_name: RedPajamaGithub


text:
var path = require('path')
var fs = require('fs')
var md5 = require('md5')
var existsSync = fs.existsSync || path.existsSync

var nodePaths = process.env.NODE_PATH ? process.env.NODE_PATH.split(':') : []
var cwd = process.cwd()
nodePaths.push(cwd)

function resolvePath(searchPath, pathBase) {
  if (searchPath[0] === '.') {
    // relative path, e.g. require("./foo")
    return findModuleMain(path.resolve(pathBase, searchPath))
  }

  // npm-style path, e.g. require("npm").
  // Climb parent directories in search for "node_modules"
  var modulePath = findModuleMain(path.resolve(pathBase, 'node_modules', searchPath))
  if (modulePath) {
    return modulePath
  }

  return ''
}

function resolveRequire(rawPath, currentPath) {
  var resolvedPath = resolvePath(rawPath, path.dirname(currentPath))

  if (!resolvedPath && rawPath[0] !== '.' && rawPath[0] !== '/') {
    for (var i = 0; i < nodePaths.length; i++) {
      resolvedPath = findModuleMain(path.resolve(nodePaths[i], rawPath))
      /* istanbul ignore if */
      if (resolvedPath) {
        break
      }
    }
  }

  return resolvedPath
}

function findModuleMain(absModulePath) {
  var foundPath = ''
  function attempt(aPath) {
    if (foundPath) {
      return
    }
    if (existsSync(aPath)) {
      foundPath = aPath
    }
  }
  if (path.extname(absModulePath) === '.js') {
    absModulePath = absModulePath.replace(/\..+/, '')
  }

  attempt(absModulePath + '.js')
  try {
    var pkg = JSON.parse(fs.readFileSync(absModulePath + '/package.json').toString())
    attempt(path.resolve(absModulePath, pkg.main + '.js'))
    attempt(path.resolve(absModulePath, pkg.main))
  } catch (e) {}
  attempt(absModulePath + '/index.js')

  return foundPath
}

var REQUIRE_REGEXP = /require\s*\(['"]([\w\/\.-]*)['"]\)/g // do not contain `@weex-module` and `@weex-component`

function parseAndReplaceRequire(code, curPath) {
  curPath = curPath || '.'
  var requires = {}
  var log = []
  code = code.replace(REQUIRE_REGEXP, function ($0, $1) {
    var subModulePath

    subModulePath = resolveRequire(path.resolve(cwd, curPath, $1), '.')
    if (!subModulePath) {
      subModulePath = resolveRequire($1, '.')
    }

    if (!subModulePath) {
      log.push({reason: 'ERROR: Cannot find required module "' + $1 + '"'})
      return $0
    }
    else {
      var md5Path = md5(subModulePath)
      requires[md5Path] = subModulePath
      return 'browserifyRequire("' + md5Path +  '")'
    }
  })
  return {
    code: code,
    requires: requires,
    log: log
  }
}

exports.parseAndReplaceRequire = parseAndReplaceRequire


text:
import Vue from 'vue'
import Vuex from 'vuex'

import * as actions from './actions'
import categories from './modules/categories'
import detail from './modules/detail'
import list from './modules/list'

Vue.use(Vuex)

const options = {
    actions,
    modules: {
        categories,
        detail,
        list
    },
    strict: process.env.NODE_ENV !== 'production'
}

export default new Vuex.Store(options)
export { options }


text:
namespace GeoHash.Net.GeoCoords
{
    internal struct GeoCoordinateWithError
    {
        public double Latitude { get; }

        public double Longitude { get; }

        public double LatitudeError { get; }

        public double LongitudeError { get; }

        public GeoCoordinateWithError(double latitude, double longitude, double latitudeError, double longitudeError)
        {
            Latitude = latitude;
            Longitude = longitude;
            LongitudeError = latitudeError;
            LatitudeError = longitudeError;
        }

        public override string ToString()
        {
            return $"{Latitude},{Longitude}";
        }

        public override bool Equals(object other)
        {
            return other is GeoCoordinateWithError && Equals((GeoCoordinateWithError)other);
        }

        public override int GetHashCode()
        {
            return Latitude.GetHashCode() ^ Longitude.GetHashCode() ^ LatitudeError.GetHashCode() ^ LongitudeError.GetHashCode();
        }

        private bool Equals(GeoCoordinateWithError other)
        {
            return Latitude.Equals(other.Latitude)
                && Longitude.Equals(other.Longitude)
                && LatitudeError.Equals(other.LatitudeError)
                && LongitudeError.Equals(other.LongitudeError);
        }
    }
}


text:
// +build !linux

package mount

type NsenterMounter struct{}

var _ = Interface(&NsenterMounter{})

func (*NsenterMounter) Mount(source string, target string, fstype string, options []string) error {
	return nil
}

func (*NsenterMounter) Unmount(target string) error {
	return nil
}

func (*NsenterMounter) List() ([]MountPoint, error) {
	return []MountPoint{}, nil
}

func (*NsenterMounter) IsMountPoint(file string) (bool, error) {
	return false, nil
}


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.cordovavuemap" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>CordovaVueMap</name>
    <description>
        A cordova app to display map with vue js 2
    </description>
    <author email="davidverriere+cheesecode@gmail.com" href="http://cheesecode.fr">
        Cheesecode Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <hook src="scripts/vueify-build.js" type="before_compile" />
    <engine name="android" spec="~5.2.2" />
</widget>


text:
<?php

namespace Eloquent\Lockbox;

use Eloquent\Endec\DecoderInterface;
use Eloquent\Lockbox\Cipher\Result\Factory\CipherResultFactoryInterface;

/**
 * Decrypts encoded data using keys.
 */
class Decrypter extends AbstractDecrypter
{
    /**
     * Get the static instance of this decrypter.
     *
     * @return DecrypterInterface The static decrypter.
     */
    public static function instance()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    /**
     * Construct a new decrypter.
     *
     * @param DecrypterInterface|null           $rawDecrypter  The raw decrypter to use.
     * @param DecoderInterface|null             $decoder       The decoder to use.
     * @param CipherResultFactoryInterface|null $resultFactory The result factory to use.
     */
    public function __construct(
        DecrypterInterface $rawDecrypter = null,
        DecoderInterface $decoder = null,
        CipherResultFactoryInterface $resultFactory = null
    ) {
        if (null === $rawDecrypter) {
            $rawDecrypter = RawDecrypter::instance();
        }

        parent::__construct($rawDecrypter, $decoder, $resultFactory);
    }

    private static $instance;
}


text:
#ifndef _A_OUT_H
#define _A_OUT_H
/** lux 定义了a.out类型的可执行脚本
 */

#define __GNU_EXEC_MACROS__
//lux a.out可执行文件头部
struct exec {
  unsigned long a_magic;	/* Use macros N_MAGIC, etc for access */
  unsigned a_text;		/* length of text, in bytes */
  unsigned a_data;		/* length of data, in bytes */
  unsigned a_bss;		/* length of uninitialized data area for file, in bytes */
  unsigned a_syms;		/* length of symbol table data in file, in bytes */
  unsigned a_entry;		/* start address */
  unsigned a_trsize;		/* length of relocation info for text, in bytes */
  unsigned a_drsize;		/* length of relocation info for data, in bytes */
};

#ifndef N_MAGIC
#define N_MAGIC(exec) ((exec).a_magic)
#endif

#ifndef OMAGIC
/* Code indicating object file or impure executable.  */
#define OMAGIC 0407
/* Code indicating pure executable.  */
#define NMAGIC 0410
/* Code indicating demand-paged executable.  */
#define ZMAGIC 0413
#endif /* not OMAGIC */

#ifndef N_BADMAG
#define N_BADMAG(x)					\
 (N_MAGIC(x) != OMAGIC && N_MAGIC(x) != NMAGIC		\
  && N_MAGIC(x) != ZMAGIC)
#endif

#define _N_BADMAG(x)					\
 (N_MAGIC(x) != OMAGIC && N_MAGIC(x) != NMAGIC		\
  && N_MAGIC(x) != ZMAGIC)

#define _N_HDROFF(x) (SEGMENT_SIZE - sizeof (struct exec))

#ifndef N_TXTOFF
#define N_TXTOFF(x) \
 (N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) : sizeof (struct exec))
#endif

#ifndef N_DATOFF
#define N_DATOFF(x) (N_TXTOFF(x) + (x).a_text)
#endif

#ifndef N_TRELOFF
#define N_TRELOFF(x) (N_DATOFF(x) + (x).a_data)
#endif

#ifndef N_DRELOFF
#define N_DRELOFF(x) (N_TRELOFF(x) + (x).a_trsize)
#endif

#ifndef N_SYMOFF
#define N_SYMOFF(x) (N_DRELOFF(x) + (x).a_drsize)
#endif

#ifndef N_STROFF
#define N_STROFF(x) (N_SYMOFF(x) + (x).a_syms)
#endif

/* Address of text segment in memory after it is loaded.  */
#ifndef N_TXTADDR
#define N_TXTADDR(x) 0
#endif

/* Address of data segment in memory after it is loaded.
   Note that it is up to you to define SEGMENT_SIZE
   on machines not listed here.  */
#if defined(vax) || defined(hp300) || defined(pyr)
#define SEGMENT_SIZE PAGE_SIZE
#endif
#ifdef	hp300
#define	PAGE_SIZE	4096
#endif
#ifdef	sony
#define	SEGMENT_SIZE	0x2000
#endif	/* Sony.  */
#ifdef is68k
#define SEGMENT_SIZE 0x20000
#endif
#if defined(m68k) && defined(PORTAR)
#define PAGE_SIZE 0x400
#define SEGMENT_SIZE PAGE_SIZE
#endif

#define PAGE_SIZE 4096
#define SEGMENT_SIZE 1024

#define _N_SEGMENT_ROUND(x) (((x) + SEGMENT_SIZE - 1) & ~(SEGMENT_SIZE - 1))

#define _N_TXTENDADDR(x) (N_TXTADDR(x)+(x).a_text)

#ifndef N_DATADDR
#define N_DATADDR(x) \
    (N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x)) \
     : (_N_SEGMENT_ROUND (_N_TXTENDADDR(x))))
#endif

/* Address of bss segment in memory after it is loaded.  */
#ifndef N_BSSADDR
#define N_BSSADDR(x) (N_DATADDR(x) + (x).a_data)
#endif

#ifndef N_NLIST_DECLARED
struct nlist {
  union {
    char *n_name;
    struct nlist *n_next;
    long n_strx;
  } n_un;
  unsigned char n_type;
  char n_other;
  short n_desc;
  unsigned long n_value;
};
#endif

#ifndef N_UNDF
#define N_UNDF 0
#endif
#ifndef N_ABS
#define N_ABS 2
#endif
#ifndef N_TEXT
#define N_TEXT 4
#endif
#ifndef N_DATA
#define N_DATA 6
#endif
#ifndef N_BSS
#define N_BSS 8
#endif
#ifndef N_COMM
#define N_COMM 18
#endif
#ifndef N_FN
#define N_FN 15
#endif

#ifndef N_EXT
#define N_EXT 1
#endif
#ifndef N_TYPE
#define N_TYPE 036
#endif
#ifndef N_STAB
#define N_STAB 0340
#endif

/* The following type indicates the definition of a symbol as being
   an indirect reference to another symbol.  The other symbol
   appears as an undefined reference, immediately following this symbol.

   Indirection is asymmetrical.  The other symbol's value will be used
   to satisfy requests for the indirect symbol, but not vice versa.
   If the other symbol does not have a definition, libraries will
   be searched to find a definition.  */
#define N_INDR 0xa

/* The following symbols refer to set elements.
   All the N_SET[ATDB] symbols with the same name form one set.
   Space is allocated for the set in the text section, and each set
   element's value is stored into one word of the space.
   The first word of the space is the length of the set (number of elements).

   The address of the set is made into an N_SETV symbol
   whose name is the same as the name of the set.
   This symbol acts like a N_DATA global symbol
   in that it can satisfy undefined external references.  */

/* These appear as input to LD, in a .o file.  */
#define	N_SETA	0x14		/* Absolute set element symbol */
#define	N_SETT	0x16		/* Text set element symbol */
#define	N_SETD	0x18		/* Data set element symbol */
#define	N_SETB	0x1A		/* Bss set element symbol */

/* This is output from LD.  */
#define N_SETV	0x1C		/* Pointer to set vector in data area.  */

#ifndef N_RELOCATION_INFO_DECLARED

/* This structure describes a single relocation to be performed.
   The text-relocation section of the file is a vector of these structures,
   all of which apply to the text section.
   Likewise, the data-relocation section applies to the data section.  */

struct relocation_info
{
  /* Address (within segment) to be relocated.  */
  int r_address;
  /* The meaning of r_symbolnum depends on r_extern.  */
  unsigned int r_symbolnum:24;
  /* Nonzero means value is a pc-relative offset
     and it should be relocated for changes in its own address
     as well as for changes in the symbol or section specified.  */
  unsigned int r_pcrel:1;
  /* Length (as exponent of 2) of the field to be relocated.
     Thus, a value of 2 indicates 1<<2 bytes.  */
  unsigned int r_length:2;
  /* 1 => relocate with value of symbol.
          r_symbolnum is the index of the symbol
	  in file's the symbol table.
     0 => relocate with the address of a segment.
          r_symbolnum is N_TEXT, N_DATA, N_BSS or N_ABS
	  (the N_EXT bit may be set also, but signifies nothing).  */
  unsigned int r_extern:1;
  /* Four bits that aren't used, but when writing an object file
     it is desirable to clear them.  */
  unsigned int r_pad:4;
};
#endif /* no N_RELOCATION_INFO_DECLARED.  */

#endif /* __A_OUT_GNU_H__ */


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

package com.google.archivepatcher.sample;

import com.google.archivepatcher.generator.FileByFileV1DeltaGenerator;
import com.google.archivepatcher.shared.DefaultDeflateCompatibilityWindow;
import java.io.File;
import java.io.FileOutputStream;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;

/** Generate a patch; args are old file path, new file path, and patch file path. */
public class SamplePatchGenerator {
  public static void main(String... args) throws Exception {
    if (!new DefaultDeflateCompatibilityWindow().isCompatible()) {
      System.err.println("zlib not compatible on this system");
      System.exit(-1);
    }
    File oldFile = new File(args[0]); // must be a zip archive
    File newFile = new File(args[1]); // must be a zip archive
    Deflater compressor = new Deflater(9, true); // to compress the patch
    try (FileOutputStream patchOut = new FileOutputStream(args[2]);
        DeflaterOutputStream compressedPatchOut =
            new DeflaterOutputStream(patchOut, compressor, 32768)) {
      new FileByFileV1DeltaGenerator().generateDelta(oldFile, newFile, compressedPatchOut);
      compressedPatchOut.finish();
      compressedPatchOut.flush();
    } finally {
      compressor.end();
    }
  }
}


text: My solutions for Harvard's/Edx's CS50 course.


text:
package kafka.producer.async

import kafka.utils.{SystemTime, Logging}
import java.util.concurrent.{TimeUnit, CountDownLatch, BlockingQueue}
import collection.mutable.ArrayBuffer
import kafka.producer.KeyedMessage
import kafka.metrics.KafkaMetricsGroup
import com.yammer.metrics.core.Gauge

class ProducerSendThread[K,V](val threadName: String,
                              val queue: BlockingQueue[KeyedMessage[K,V]],
                              val handler: EventHandler[K,V],
                              val queueTime: Long,
                              val batchSize: Int,
                              val clientId: String) extends Thread(threadName) with Logging with KafkaMetricsGroup {

  private val shutdownLatch = new CountDownLatch(1)
  private val shutdownCommand = new KeyedMessage[K,V]("shutdown", null.asInstanceOf[K], null.asInstanceOf[V])

  newGauge(clientId + "-ProducerQueueSize",
          new Gauge[Int] {
            def value = queue.size
          })

  override def run {
    try {
      processEvents
    }catch {
      case e: Throwable => error("Error in sending events: ", e)
    }finally {
      shutdownLatch.countDown
    }
  }

  def shutdown = {
    info("Begin shutting down ProducerSendThread")
    queue.put(shutdownCommand)
    shutdownLatch.await
    info("Shutdown ProducerSendThread complete")
  }

  private def processEvents() {
    var lastSend = SystemTime.milliseconds
    var events = new ArrayBuffer[KeyedMessage[K,V]]
    var full: Boolean = false

    // drain the queue until you get a shutdown command
    Stream.continually(queue.poll(scala.math.max(0, (lastSend + queueTime) - SystemTime.milliseconds), TimeUnit.MILLISECONDS))
                      .takeWhile(item => if(item != null) item ne shutdownCommand else true).foreach {
      currentQueueItem =>
        val elapsed = (SystemTime.milliseconds - lastSend)
        // check if the queue time is reached. This happens when the poll method above returns after a timeout and
        // returns a null object
        val expired = currentQueueItem == null
        if(currentQueueItem != null) {
          trace("Dequeued item for topic %s, partition key: %s, data: %s"
              .format(currentQueueItem.topic, currentQueueItem.key, currentQueueItem.message))
          events += currentQueueItem
        }

        // check if the batch size is reached
        full = events.size >= batchSize

        if(full || expired) {
          if(expired)
            debug(elapsed + " ms elapsed. Queue time reached. Sending..")
          if(full)
            debug("Batch full. Sending..")
          // if either queue time has reached or batch size has reached, dispatch to event handler
          tryToHandle(events)
          lastSend = SystemTime.milliseconds
          events = new ArrayBuffer[KeyedMessage[K,V]]
        }
    }
    // send the last batch of events
    tryToHandle(events)
    if(queue.size > 0)
      throw new IllegalQueueStateException("Invalid queue state! After queue shutdown, %d remaining items in the queue"
        .format(queue.size))
  }

  def tryToHandle(events: Seq[KeyedMessage[K,V]]) {
    val size = events.size
    try {
      debug("Handling " + size + " events")
      if(size > 0)
        handler.handle(events)
    }catch {
      case e: Throwable => error("Error in handling batch of " + size + " events", e)
    }
  }

}


text:
module.exports = function(grunt, config) {

	var push = {};

	// set target configurations for the libraries
	config.libraries.forEach(function(library) {

		if (library.bower !== false && grunt.option('publish')) {
			var repoName = 'packaged-' + library.name;
			push[repoName] = {
				options: {
					verbose: true,
					cwd: 'tmp/' + repoName,
					branch: grunt.option('publish-branch'),
					tags: true
				}
			};
		}

	});

	return push;

};


text:
- [Fix for overwriting old backup files](https://github.com/log4js-node/streamroller/pull/43)
- Updated lodash to 4.17.14

## 1.0.5

- [Updated dependencies](https://github.com/log4js-node/streamroller/pull/38)
- [Fix for initial file date when appending to existing file](https://github.com/log4js-node/streamroller/pull/40)

## 1.0.4

- [Fix for initial size when appending to existing file](https://github.com/log4js-node/streamroller/pull/35)

## 1.0.3

- [Fix for crash when pattern is all digits](https://github.com/log4js-node/streamroller/pull/33)

## 1.0.2

- is exactly the same as 1.0.1, due to me being an idiot and not pulling before I pushed

## Previous versions

Previous release details are available by browsing the milestones in github.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Kiss.Data;

namespace Kiss.DataTest
{
    [TestFixture]
    public class TestTemplate
    {

        public void TestCompile()
        {
            string sql = @"test {{p1}} and2 {{p2 out string}} and3 {{p3 inout date}} and4 {{p4 refcursor}}";
            TextTemplate text = TextTemplate.Compile(sql);
            Assert.AreEqual("test {{p1}} and2 {{p2}} and3 {{p3}} and4 {{p4}}", text.Text);
            Assert.AreEqual("Name:p1", text.Parameters[0].ToString());
            Assert.AreEqual("Name:p2;DbType:String;Direction:Output", text.Parameters[1].ToString());
            Assert.AreEqual("Name:p3;DbType:Date;Direction:InputOutput", text.Parameters[2].ToString());
            Assert.AreEqual("Name:p4;ProviderDbType:refcursor", text.Parameters[3].ToString());

            sql = @"test p1 p2";
            text = TextTemplate.Compile(sql);
            Assert.AreEqual("test p1 p2", text.Text);
            Assert.AreEqual(0, text.Parameters.Count);

            sql = @"test {{p1}} test";
            text = TextTemplate.Compile(sql);
            Assert.AreEqual("test {{p1}} test", text.Text);
            Assert.AreEqual("Name:p1", text.Parameters[0].ToString());

        }
    }
}


text:
package be.seriousbusiness.brusselnieuws.rss.datastore.mongodb.repository;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:config/test-brusselnieuws-rss-datastore-mongodb-config.xml")
public class MongoArticleRepositoryTest {
	@Autowired
	private MongoArticleRepository mongoArticleRepository;

	@Before
	public void before(){
		Assert.assertNotNull("The MongoArticleRepository cannot be null",mongoArticleRepository);
	}

	@After
	public void after(){
		mongoArticleRepository.deleteAll();
	}

	@Test
	public void test(){
		Assert.assertEquals("The MongoArticleRepository should be empty",0,mongoArticleRepository.count());
	}

}


text:
<?php

namespace Hatimeria\ExtJSBundle\Response;

/**
 * Records response, for extjs store with paging implemented
 *
 * @author Michal Wujas
 */
class Records implements Response
{
    private $limit = 0, $total, $records, $start = 0;

    public function result(array $records)
    {
        $this->total   = count($records);
        $this->records = $records;
        $this->limit   = 0;

        return $this;
    }

    public function limit($limit)
    {
        $this->limit = $limit;

        return $this;
    }

    public function start($start)
    {
        $this->start = $start;

        return $this;
    }

    public function total($total)
    {
        $this->total = $total;

        return $this;
    }

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

    public function toArray()
    {
        $r = new Success();
        $r->set("limit", $this->limit);
        $r->set("records", $this->records);
        $r->set("total", $this->total);
        $r->set("start", $this->start);

        return $r->toArray();
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

use yii\helpers\ArrayHelper;
use app\models\Edificio;
use app\models\Coodinador;
use app\models\TipoLaboratorio;

use app\components\widgets\DropDownWidget;
/* @var $this yii\web\View */
/* @var $model app\models\Laboratorio */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'LABO_NOMBRE')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'LABO_NIVEL')->textInput() ?>

        <?= $form->field($model, 'EDIF_ID')->dropDownList(ArrayHelper::map(Edificio::find()->asArray()->all(), 'EDIF_ID', 'EDIF_NOMBRE'), ['prompt'=>'-Seleccione una opcion-'])?>

     <?= $form->field($model, 'COOR_ID')->dropDownList(ArrayHelper::map(Edificio::findBySql("
        select
        TBL_PERSONAS.PERS_NOMBRE,
        TBL_COORDINADORES.COOR_ID
        FROM
        TBL_COORDINADORES
        INNER JOIN TBL_PERSONAS ON (TBL_COORDINADORES.PERS_ID = TBL_PERSONAS.PERS_ID)
         ")->asArray()->all(), 'COOR_ID', 'PERS_NOMBRE'), ['prompt'=>'-Seleccione una opcion-'])?>

    <?= $form->field($model, 'TILA_ID')->dropDownList(ArrayHelper::map(TipoLaboratorio::find()->asArray()->all(), 'TILA_ID', 'TILA_NOMBRE'), ['prompt'=>'-Seleccione una opcion-'])?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php
/**
 * Used to set up and fix common variables and include
 * the Multisite procedural and class library.
 *
 * Allows for some configuration in wp-config.php (see ms-default-constants.php)
 *
 * @package WordPress
 * @subpackage Multisite
 * @since 3.0.0
 */

/** Include Multisite initialization functions */
require( ABSPATH . WPINC . '/ms-load.php' );
require( ABSPATH . WPINC . '/ms-default-constants.php' );

if ( defined( 'SUNRISE' ) )
	include_once( WP_CONTENT_DIR . '/sunrise.php' );

/** Check for and define SUBDOMAIN_INSTALL and the deprecated VHOST constant. */
ms_subdomain_constants();

if ( !isset( $current_site ) || !isset( $current_blog ) ) {

	$domain = addslashes( $_SERVER['HTTP_HOST'] );
	if ( false !== strpos( $domain, ':' ) ) {
		if ( substr( $domain, -3 ) == ':80' ) {
			$domain = substr( $domain, 0, -3 );
			$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -3 );
		} elseif ( substr( $domain, -4 ) == ':443' ) {
			$domain = substr( $domain, 0, -4 );
			$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -4 );
		} else {
			wp_die( /*WP_I18N_NO_PORT_NUMBER*/'Multisite only works without the port number in the URL.'/*/WP_I18N_NO_PORT_NUMBER*/ );
		}
	}

	$domain = rtrim( $domain, '.' );
	$cookie_domain = $domain;
	if ( substr( $cookie_domain, 0, 4 ) == 'www.' )
		$cookie_domain = substr( $cookie_domain, 4 );

	$path = preg_replace( '|([a-z0-9-]+.php.*)|', '', $_SERVER['REQUEST_URI'] );
	$path = str_replace ( '/wp-admin/', '/', $path );
	$path = preg_replace( '|(/[a-z0-9-]+?/).*|', '$1', $path );

	$current_site = wpmu_current_site();
	if ( ! isset( $current_site->blog_id ) )
		$current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) );

	if ( is_subdomain_install() ) {
		$current_blog = wp_cache_get( 'current_blog_' . $domain, 'site-options' );
		if ( !$current_blog ) {
			$current_blog = get_blog_details( array( 'domain' => $domain ), false );
			if ( $current_blog )
				wp_cache_set( 'current_blog_' . $domain, $current_blog, 'site-options' );
		}
		if ( $current_blog && $current_blog->site_id != $current_site->id ) {
			$current_site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->site WHERE id = %d", $current_blog->site_id ) );
			if ( ! isset( $current_site->blog_id ) )
				$current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) );
		} else
			$blogname = substr( $domain, 0, strpos( $domain, '.' ) );
	} else {
		$blogname = htmlspecialchars( substr( $_SERVER[ 'REQUEST_URI' ], strlen( $path ) ) );
		if ( false !== strpos( $blogname, '/' ) )
			$blogname = substr( $blogname, 0, strpos( $blogname, '/' ) );
		if ( false !== strpos( $blogname, '?' ) )
			$blogname = substr( $blogname, 0, strpos( $blogname, '?' ) );
		$reserved_blognames = array( 'page', 'comments', 'blog', 'wp-admin', 'wp-includes', 'wp-content', 'files', 'feed' );
		if ( $blogname != '' && ! in_array( $blogname, $reserved_blognames ) && ! is_file( $blogname ) )
			$path .= $blogname . '/';
		$current_blog = wp_cache_get( 'current_blog_' . $domain . $path, 'site-options' );
		if ( ! $current_blog ) {
			$current_blog = get_blog_details( array( 'domain' => $domain, 'path' => $path ), false );
			if ( $current_blog )
				wp_cache_set( 'current_blog_' . $domain . $path, $current_blog, 'site-options' );
		}
		unset($reserved_blognames);
	}

	if ( ! defined( 'WP_INSTALLING' ) && is_subdomain_install() && ! is_object( $current_blog ) ) {
		if ( defined( 'NOBLOGREDIRECT' ) ) {
			$destination = NOBLOGREDIRECT;
			if ( '%siteurl%' == $destination )
				$destination = "http://" . $current_site->domain . $current_site->path;
		} else {
			$destination = 'http://' . $current_site->domain . $current_site->path . 'wp-signup.php?new=' . str_replace( '.' . $current_site->domain, '', $domain );
		}
		header( 'Location: ' . $destination );
		die();
	}

	if ( ! defined( 'WP_INSTALLING' ) ) {
		if ( $current_site && ! $current_blog ) {
			if ( $current_site->domain != $_SERVER[ 'HTTP_HOST' ] ) {
				header( 'Location: http://' . $current_site->domain . $current_site->path );
				exit;
			}
			$current_blog = get_blog_details( array( 'domain' => $current_site->domain, 'path' => $current_site->path ), false );
		}
		if ( ! $current_blog || ! $current_site )
			ms_not_installed();
	}

	$blog_id = $current_blog->blog_id;
	$public  = $current_blog->public;

	if ( empty( $current_blog->site_id ) )
		$current_blog->site_id = 1;
	$site_id = $current_blog->site_id;

	$current_site = get_current_site_name( $current_site );

	if ( ! $blog_id ) {
		if ( defined( 'WP_INSTALLING' ) ) {
			$current_blog->blog_id = $blog_id = 1;
		} else {
			$msg = ! $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->site'" ) ? ' ' . /*WP_I18N_TABLES_MISSING*/'Database tables are missing.'/*/WP_I18N_TABLES_MISSING*/ : '';
			wp_die( /*WP_I18N_NO_BLOG*/'No site by that name on this system.'/*/WP_I18N_NO_BLOG*/ . $msg );
		}
	}
}
$wpdb->set_prefix( $table_prefix, false ); // $table_prefix can be set in sunrise.php
$wpdb->set_blog_id( $current_blog->blog_id, $current_blog->site_id );
$table_prefix = $wpdb->get_blog_prefix();

// need to init cache again after blog_id is set
wp_start_object_cache();

// Define upload directory constants
ms_upload_constants();


text:
PWD - shows the current directory
LS - lists everything in the directory
cd - puts you in the directory you specify
git - CLI for git
git clone - clones a repository from github
git push - pushes the repository back to its remote (origin)


text:
title: ADAPT
date: 2017-09-01
area: inprogress
subdomain: Mental Health
status: Enrolling
authors:
  -
    authorimage: /img/uploads/marcus.jpg
    authorname: Steven Marcus, PhD
    authorrole: Principal Investigator
  -
    authorimage: /img/uploads/olfson.jpg
    authorname: Mark Olfson, MD
    authorrole: Investigator
summary: >
  Intent of the trial is to assist depressed adults with primary care treatment.
  W2H is used to automate the trial with respect to randomization, measurement of
  medication adherence via electronic pill bottle, and distribution of financial
  incentives to patients.
features:
  -
    feature: 'Adheretech  Bill Bottle Integration '
  -
    feature: 'Bidirectional texting '
  -
    feature: Gamification
---


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.cnd.makeproject</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/make-project/1">
            <name>AprioriAlgo</name>
            <c-extensions>c</c-extensions>
            <cpp-extensions/>
            <header-extensions/>
            <sourceEncoding>UTF-8</sourceEncoding>
            <make-dep-projects/>
            <sourceRootList/>
            <confList>
                <confElem>
                    <name>Debug</name>
                    <type>1</type>
                </confElem>
                <confElem>
                    <name>Release</name>
                    <type>1</type>
                </confElem>
            </confList>
        </data>
    </configuration>
</project>


text:
// -----------------------------------------------------------------------
// <copyright file="DataUpdateJobFactory.cs" company="">
// Copyright 2014 Alexander Soffronow Pagonidis
// </copyright>
// -----------------------------------------------------------------------

using System;
using QDMS.Server.Brokers;
using QDMS.Server.Jobs;
using Quartz;
using Quartz.Spi;

namespace QDMSServer
{
    public class JobFactory : IJobFactory
    {
        private readonly IHistoricalDataBroker _hdb;
        private readonly IEconomicReleaseBroker _erb;

        private string _host;
        private int _port;
        private string _username;
        private string _password;
        private string _sender;
        private string _email;

        private UpdateJobSettings _updateJobSettings;
        private QDMS.IDataStorage _localStorage;
        private IInstrumentSource _instrumentSource;

        public JobFactory(IHistoricalDataBroker hdb,
            string host,
            int port,
            string username,
            string password,
            string sender,
            string email,
            UpdateJobSettings updateJobSettings,
            QDMS.IDataStorage localStorage,
            IInstrumentSource instrumentSource,
            IEconomicReleaseBroker erb) : base()
        {
            _hdb = hdb;

            _host = host;
            _port = port;
            _username = username;
            _password = password;
            _sender = sender;
            _email = email;
            _updateJobSettings = updateJobSettings;
            _localStorage = localStorage;
            _instrumentSource = instrumentSource;
            _erb = erb;
        }

        /// <summary>
        /// Called by the scheduler at the time of the trigger firing, in order to
        ///             produce a <see cref="T:Quartz.IJob"/> instance on which to call Execute.
        /// </summary>
        /// <remarks>
        /// It should be extremely rare for this method to throw an exception -
        ///             basically only the the case where there is no way at all to instantiate
        ///             and prepare the Job for execution.  When the exception is thrown, the
        ///             Scheduler will move all triggers associated with the Job into the
        ///             <see cref="F:Quartz.TriggerState.Error"/> state, which will require human
        ///             intervention (e.g. an application restart after fixing whatever
        ///             configuration problem led to the issue wih instantiating the Job.
        /// </remarks>
        /// <param name="bundle">The TriggerFiredBundle from which the <see cref="T:Quartz.IJobDetail"/>
        ///               and other info relating to the trigger firing can be obtained.
        ///             </param><param name="scheduler">a handle to the scheduler that is about to execute the job</param><throws>SchedulerException if there is a problem instantiating the Job. </throws>
        /// <returns>
        /// the newly instantiated Job
        /// </returns>
        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            string type = bundle.Trigger.Key.Group;

            if (type == JobTypes.DataUpdate)
            {
                return GetDataUpdateJob(bundle, scheduler);
            }
            else if (type == JobTypes.EconomicRelease)
            {
                return GetEconomicReleaseJob(bundle, scheduler);
            }

            throw new Exception("Uknown job type " + type);
        }

        private IJob GetEconomicReleaseJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            return new EconomicReleaseUpdateJob(_erb, GetEmailSender(), _updateJobSettings);
        }

        private IJob GetDataUpdateJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            //only provide the email sender if data exists to properly initialize it with
            return new DataUpdateJob(_hdb, GetEmailSender(), _updateJobSettings, _localStorage, _instrumentSource);
        }

        private EmailSender GetEmailSender()
        {
            if (!string.IsNullOrEmpty(_host) &&
            !string.IsNullOrEmpty(_username) &&
            !string.IsNullOrEmpty(_password) &&
            !string.IsNullOrEmpty(_sender) &&
            !string.IsNullOrEmpty(_email))
            {
                return new EmailSender(
                            _host,
                            _username,
                            _password,
                            _port);
            }

            return null;
        }

        /// <summary>
        /// Allows the the job factory to destroy/cleanup the job if needed.
        /// </summary>
        public void ReturnJob(IJob job)
        {

        }
    }
}


text:
import HomeView from './components/HomeView'
import { injectReducer } from '../../store/reducers'
import reducer from './modules/reducers'

export default (store) => {
  injectReducer(store, { key: 'projects', reducer })
  const route = {
    component : HomeView

  }
  return route
}


text:
package com.ljzh.gamex.worker;

import com.ljzh.gamex.CommonLogger;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class TaskWorkerGroup {
    private String name;
    private TaskWorker[] workers;
    private CountDownLatch shutdownSignal;

    public TaskWorkerGroup(String name, int workerCount, int workerCapacity) {
        this.name = name;
        this.initWorkers(workerCount, workerCapacity);
    }

    private void initWorkers(int workerCount, int workerCapacity) {
        workers = new TaskWorker[workerCount];
        for (int i = 0; i < workerCount; i++) {
            workers[i] = new TaskWorker(name + "-" + i, workerCapacity);
            workers[i].start();
        }
    }

    public boolean addTask(int index, ITask task) {
        TaskWorker worker = workers[index];
        return worker.addTask(task);
    }

    public int getTaskSize() {
        int size = 0;
        for (TaskWorker w : workers) {
            size += w.getTaskSize();
        }
        return size;
    }

    public void shutdown() {
        shutdownSignal = new CountDownLatch(getWorkerCount());
        for (TaskWorker w : workers) {
            w.shutdown(shutdownSignal);
        }
    }

    public boolean awaitTermination(long timeout, TimeUnit unit) {
        try {
            return shutdownSignal.await(timeout, unit);
        } catch (InterruptedException e) {
            CommonLogger.error(e, "InterruptedException of %s", getName());
            return false;
        } finally {
            logShutOk();
        }
    }

    public void shutdownNow() {
        for (TaskWorker w : workers) {
            w.shutdownNow();
        }

        for (TaskWorker w : workers) {
            try {
                w.join();
            } catch (InterruptedException e) {
                CommonLogger.error(e, "InterruptedException of %s", getName());
            }
        }

        logShutOk();
    }

    private void logShutOk() {
        CommonLogger.info("TaskWorkerGroup[%s] shut down.", getName());
    }

    public String getName() {
        return name;
    }

    public int getWorkerCount() {
        return workers.length;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<libraryInfos>
<libraryInfo home="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home" version="1.8.0_60">
<bootpath>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/resources.jar"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/rt.jar"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/sunrsasign.jar"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jsse.jar"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jce.jar"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/charsets.jar"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jfr.jar"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/classes"/>
</bootpath>
<extensionDirs>
<entry path="/Users/madeleine_wittbom/Library/Java/Extensions"/>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext"/>
<entry path="/Library/Java/Extensions"/>
<entry path="/Network/Library/Java/Extensions"/>
<entry path="/System/Library/Java/Extensions"/>
<entry path="/usr/lib/java"/>
</extensionDirs>
<endorsedDirs>
<entry path="/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/endorsed"/>
</endorsedDirs>
</libraryInfo>
</libraryInfos>


text:
                    Name:

 {{user.username}}

                    Email:

 {{user.email}}

                    Description:

 {{user.aboutMe}}

My Boards

                <form class="form-inline">

                        Search Board:

                        <input type="text" class="form-control" name="title"  id="searchTitle" placeholder="Board Title" ng-model="filterParams.title" />

                </form>

            <tabset>

                <tab ng-repeat="category in categories" heading="{{category}}">

                        New Board

                            {{board.category}}

{{board.title}}

{{board.description | limitChar:55}}

                                    Snippets {{board.numberOfSnippets && board.numberOfSnippets || "0"}}

                                    Requests {{board.requestors.length && board.requestors.length || "0"}}

                </tab>
            </tabset>


text:
module.exports = function(app, configurations, express) {
  var clientSessions = require('client-sessions');
  var nconf = require('nconf');
  var requirejs = require('requirejs');

  nconf.argv().env().file({ file: 'local.json' });

  // Configuration

  app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.set('view options', { layout: false });
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    if (!process.env.NODE_ENV) {
      app.use(express.logger('dev'));
      app.use(express.static(__dirname + '/public'));
    } else {
      app.use(express.static(__dirname + '/public_build'));
    }
    app.use(clientSessions({
      cookieName: nconf.get('session_cookie'),
      secret: nconf.get('session_secret'), // MUST be set
      // true session duration:
      // will expire after duration (ms)
      // from last session.reset() or
      // initial cookieing.
      duration: 24 * 60 * 60 * 1000 * 28 // 4 weeks
    }));
    app.use(app.router);
    app.use(function(req, res, next) {
      res.status(404);
      res.render('404', { url: req.url, layout: false });
      return;
    });
    app.use(function(req, res, next) {
      res.status(403);
      res.render('403', { url: req.url, layout: false });
      return;
    });
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('500', { error: err, layout: false });
    });
  });

  app.configure('development, test', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  app.configure('prod', function(){
    app.use(express.errorHandler());

    requirejs.optimize({
      appDir: 'public/',
      baseUrl: 'javascripts/',
      enforceDefine: true,
      dir: "public_build",
      modules: [
        {
          name: 'main'
        }
      ]
    }, function() {
      console.log('Successfully optimized javascript');
    });
  });

  return app;
};


text:
<configuration scan="true" scanPeriod="60 seconds">

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
    <layout class="ch.qos.logback.classic.PatternLayout">
      <Pattern>%d{HH:mm:ss} %-5level %logger{36} - %msg%n</Pattern>
    </layout>
    </encoder>
  </appender>

  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
	<file>${config.dir}/../logs/myproj.log</file>
	<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
	  <!-- daily rollover -->
	  <fileNamePattern>${config.dir}/../logs/myproj.%d{yyyy-MM-dd}.log</fileNamePattern>
	  <!-- keep 30 days' worth of history -->
	  <maxHistory>30</maxHistory>
	</rollingPolicy>

	<encoder>
	  <Pattern>%d{HH:mm:ss} %-5level %logger{36} - %msg%n</Pattern>
	</encoder>
  </appender>

  <logger name="com.mycompany.myproj" level="DEBUG" />

  <logger name="com.mycompany.myproj.shared.util.web" level="WARN" />

  <logger name="org.springframework" level="WARN" />
  <logger name="org.springframework.beans" level="WARN" />
  <logger name="org.springframework.transaction" level="WARN" />
  <logger name="org.springframework.security" level="WARN" />
  <logger name="org.hibernate" level="WARN" />

  <root level="INFO">
    <appender-ref ref="STDOUT" />
	<appender-ref ref="FILE" />
  </root>

</configuration>


text:
class QDomDocument;
class QDomElement;

class AlignmentTool
{
	public:

		AlignmentTool();
		virtual ~AlignmentTool();

		QString name(){return name_;}
		QString version(){return version_;}
		QString executable(){return executable_;}

		void setExecutable(QString e){executable_=e;}

		void setPreferred(bool pref){preferred_=pref;}
		bool preferred(){return preferred_;}

		bool usesStdOut(){return usesStdOut_;} // the alignment is written to stdout

		virtual void makeCommand(QString &, QString &, QString &, QStringList &);

		virtual void writeSettings(QDomDocument &,QDomElement &);
		virtual void readSettings(QDomDocument &);

	protected:

		QString name_;
		QString version_;
		QString executable_;
		bool preferred_;
		bool usesStdOut_;

	private:

		void init();

};

#endif


text:
case "$1" in
	install_alpine)
	    DOCKERIMAGE=http://dl-cdn.alpinelinux.org/alpine/v3.6/releases/armhf/alpine-minirootfs-3.6.2-armhf.tar.gz
	    ;;
	uninstall)
        chmod -R 777 ~/alpine
	    rm -rf ~/alpine
	    rm -f /data/data/com.termux/files/usr/bin/startalpine
	    hash -r
	    exit 0
	    ;;
	*)
	    echo $"Usage: $0 {install_alpine|uninstall}"
	    exit 2
	    ;;
esac

# install necessary packages
apt update
apt install wget proot xz-utils tar -y
hash -r

# get the docker image
mkdir ~/alpine
cd ~/alpine
wget $DOCKERIMAGE -O alpine.tar.xz

# extract the Docker image
tar xpvf alpine.tar.xz

# cleanup
chmod +w .
rm alpine.tar.xz

# fix DNS
echo "nameserver 8.8.8.8" > ~/alpine/etc/resolv.conf

# make a shortcut
cat > /data/data/com.termux/files/usr/bin/startalpine <<- EOM
#!/data/data/com.termux/files/usr/bin/bash
proot --link2symlink -0 -r ~/alpine -b /dev/ -b /sys/ -b /proc/ -w /root /usr/bin/env -i HOME=/root TERM="xterm-256color" PS1='[termux@alpine \W]$ ' LANG=en_US.UTF-8 PATH=/bin:/usr/bin:/sbin:/usr/sbin DISPLAY=:0 /bin/ash --login
EOM

chmod +x /data/data/com.termux/files/usr/bin/startalpine

# all done
echo "All done! Start Alpine 3.6 with 'startalpine'."


text:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:gravity="center_vertical"
  	>
    <View android:background="#ff666666" android:layout_width="fill_parent" android:layout_height="0.6dip" />
    <RelativeLayout
    	android:orientation="horizontal"
    	android:id="@+id/AppAwareHeader"
    	android:background="@drawable/gray_gradient"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:gravity="center_vertical"
    	>
        <TextView android:textSize="25.0sp"
	        android:textStyle="bold"
	        android:textColor="#ffffffff"
	        android:id="@+id/TextViewAppName"
	        android:padding="2.0sp"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_marginLeft="2.0sp"
	        android:text="@string/app_name"
         />
        <TextView
        	android:textSize="14.0sp"
       	 	android:textColor="#ffffffff"
       	 	android:id="@+id/TextViewVersion"
       	 	android:layout_width="wrap_content"
       	 	android:layout_height="wrap_content"
       	 	android:text="Just Share it.."
       	 	android:layout_toRightOf="@id/TextViewAppName"
       	 	android:layout_alignBaseline="@id/TextViewAppName"
       	 />

         <Button
       		android:id="@+id/Button01"
       		android:layout_height="wrap_content"
       		android:layout_width="wrap_content"
       		android:text="分享"
       		android:layout_alignParentRight="true"
       		android:background="@drawable/titlebutton_bg"
       		>
       	</Button>
    </RelativeLayout>
    <View android:id="@+id/ViewBorderMain" android:background="#ff456028" android:layout_width="fill_parent" android:layout_height="1.0sp" android:layout_weight="0.0" />
</LinearLayout>


text:
import { MentionNode, MfmForest } from '../mfm/prelude';
import { preorderF } from '../prelude/tree';

export default function(mfmForest: MfmForest): MentionNode['props'][] {
	// TODO: 重複を削除
	const mentionNodes = preorderF(mfmForest).filter(x => x.type === 'mention') as MentionNode[];
	return mentionNodes.map(x => x.props);
}


text:
angular.module('bobo.controllers', [])

.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
      return JSON.parse($window.localStorage[key] || '{}');
    }
  }
}])

.controller('LoadingCtrl', function($scope, $state) {
  $scope.cancelLoading = function (){
    // goFriend is temp
    $state.go('friend');
  }

})

.controller('LoginCtrl', function($scope, $state, $ionicLoading) {
  $scope.user  = {name:"", phone:""};
  $scope.sendVibrationMsg = function () {
    alert('1')
    // $ionicLoading.show({
      // templateUrl: 'templates/loading.html'
    // });
    console.log($scope.user)
  }
  // setTimeout is temp code
  // setTimeout($scope.sendVibrationMsg, 3000);

  // navigator.notification.vibrate(2500);

  $scope.closeLoading = function(){
    $ionicLoading.hide()
  }

})

.controller('MainCtrl', function($scope, $state) {
  $scope.friends = [
    {name: 'Ariel'},
    {name: 'Kir'},
    {name: 'Mak'},
    {name: 'Caesar'},
    {name: 'Spooky'},
    {name: 'Webber'},
    {name: 'Ivan'},
    {name: 'Ray'},
    {name: 'Matt'},
    {name: 'Jason'},
    {name: 'Vincent'},
    {name: 'Li'}
  ];

  $scope.addMsg = function () {
    // add msg
  }

  $scope.changeCircleStyle = function() {
    var allCircles = document.querySelectorAll('.random-circle')
    var i = 0

    angular.forEach(allCircles, function(circle) {
      var tempDom = angular.element(circle);
      circleSize = Math.random() * 90 + 50;
      tempDom.css('color', '#000')
      tempDom.css('width', circleSize+'px')
      tempDom.css('height', circleSize+'px')
      tempDom.css('line-height', circleSize+'px')
      tempDom.css('background', $scope.getRandomColor(i%3))
      tempDom.css('margin-top', Math.random() * 50 )
      tempDom.css('margin-left', Math.random() * 25 )
      i++
    });
  }

  $scope.getRandomColor = function(randomNum) {
    var color = '#';
    var letters = '0123456789ABCDEF'.split('');
    var letterIndex = 0;

    for (var i = 0; i < 6; i++ ) {
        letterIndex = Math.floor(Math.random() * 15);
        if( i == randomNum || i == randomNum+1) {
          letterIndex = 15;
        }
        color += letters[letterIndex];
    }
    return color;
  }

  $scope.goGroup = function () {
    $state.go('group')
  }

  $scope.goFriend = function () {
    $state.go('friend')
  }

  $scope.selectFriend = function (friend) {
    friend.selected = !friend.selected
  }

  $scope.sendMsg = function () {
    // send msg
  }

  setTimeout($scope.changeCircleStyle, 100);

})


text:
import pyzed.camera as zcam
import pyzed.defines as sl
import pyzed.types as tp
import pyzed.core as core
import math
import numpy as np
import  cv2

def main():
    # Create a PyZEDCamera object
    zed = zcam.PyZEDCamera()

    # Create a PyInitParameters object and set configuration parameters
    init_params = zcam.PyInitParameters()
    init_params.depth_mode = sl.PyDEPTH_MODE.PyDEPTH_MODE_PERFORMANCE  # Use PERFORMANCE depth mode
    init_params.coordinate_units = sl.PyUNIT.PyUNIT_MILLIMETER  # Use milliliter units (for depth measurements)

    # Open the camera
    err = zed.open(init_params)
    if err != tp.PyERROR_CODE.PySUCCESS:
        exit(1)

    # Create and set PyRuntimeParameters after opening the camera
    runtime_parameters = zcam.PyRuntimeParameters()
    runtime_parameters.sensing_mode = sl.PySENSING_MODE.PySENSING_MODE_STANDARD  # Use STANDARD sensing mode

    # Capture 50 images and depth, then stop

    image = core.PyMat()
    depth = core.PyMat()
    point_cloud = core.PyMat()

    while True:
        # A new image is available if grab() returns PySUCCESS
        if zed.grab(runtime_parameters) == tp.PyERROR_CODE.PySUCCESS:
            # Retrieve left image
            zed.retrieve_image(image, sl.PyVIEW.PyVIEW_LEFT)
            # Retrieve depth map. Depth is aligned on the left image
            zed.retrieve_measure(depth, sl.PyMEASURE.PyMEASURE_DEPTH)
            # Retrieve colored point cloud. Point cloud is aligned on the left image.
            zed.retrieve_measure(point_cloud, sl.PyMEASURE.PyMEASURE_XYZRGBA)

            # Get and print distance value in mm at the center of the image
            # We measure the distance camera - object using Euclidean distance
            x = round(image.get_width() / 2)
            y = round(image.get_height() / 2)
            err, point_cloud_value = point_cloud.get_value(x, y)

            distance = math.sqrt(point_cloud_value[0] * point_cloud_value[0] +
                                 point_cloud_value[1] * point_cloud_value[1] +
                                 point_cloud_value[2] * point_cloud_value[2])

            if not np.isnan(distance) and not np.isinf(distance):
                distance = round(distance)
                print("Distance to Camera at ({0}, {1}): {2} mm\n".format(x, y, distance))

                # Increment the loop

    # Close the camera
    zed.close()

if __name__ == "__main__":
    main()


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe AnnotationSecurity::Rule do

  before(:all) do
    AnnotationSecurity.define_relations(:rule_test_res) do
      res_dummy
      sys_dummy(:system) { false }
      pre_dummy :pretest
      noc_dummy :system, :require_credential => false

      res_dummy_test { has_res_dummy }
      sys_dummy_test "if is_sys_dummy"
    end
  end

  it 'should create valid dynamic relations' do
    rule = AnnotationSecurity::Rule.new(:res_proc, RuleTestResPolicy) { |u,r| true }
    rule.to_s.should == '<RuleTestResPolicy#res_proc[--du]>'
    rule = AnnotationSecurity::Rule.new(:res, RuleTestResPolicy, :resource)
    rule.to_s.should == '<RuleTestResPolicy#res[--du]>'
  end

  it 'should create valid static relations' do
    rule = AnnotationSecurity::Rule.new(:sys_proc, RuleTestResPolicy, :system) { true }
    rule.to_s.should == '<RuleTestResPolicy#sys_proc[-s-u]>'
  end

  it 'should create valid pretest relations' do
    rule = AnnotationSecurity::Rule.new(:pre_proc, RuleTestResPolicy, :pretest) { true }
    rule.to_s.should == '<RuleTestResPolicy#pre_proc[-sdu]>'
  end

  it 'should create valid relations without user' do
    rule = AnnotationSecurity::Rule.new(:no_u, RuleTestResPolicy, :require_credential => false)
    rule.to_s.should == '<RuleTestResPolicy#no_u[--d-]>'
    rule = AnnotationSecurity::Rule.new(:no_u, RuleTestResPolicy,
                              :system, :require_credential => false)
    rule.to_s.should == '<RuleTestResPolicy#no_u[-s--]>'
    rule = AnnotationSecurity::Rule.new(:no_u, RuleTestResPolicy,
                              :pretest, :require_credential => false)
    rule.to_s.should == '<RuleTestResPolicy#no_u[-sd-]>'
  end

  it 'should create valid rights' do
    {
      'if res_dummy' => '-du',
      'if sys_dummy' => 's-u',
      'if pre_dummy' => 'sdu',
      'if res_dummy or sys_dummy' => '-du',
      'if res_dummy or pre_dummy' => '-du',
      'if sys_dummy or pre_dummy' => 'sdu',
      'if noc_dummy' => 's--',
      'if noc_dummy or sys_dummy' => 's-u',
      'if noc_dummy or res_dummy' => '-du',
      'if self' => '-du',
      'if other_right: resource_property' => '-du',
      'true' => 's--',
      'false or nil' => 's--'
    }.each_pair do |condition,flags|
      right = AnnotationSecurity::Rule.new(:right, RuleTestResPolicy, :right, condition)
      right.flag_s.should == 'r???'
      right.static? # trigger lazy initialization
      right.flag_s.should == 'r'+flags
    end
  end

  it 'should call referred rules when being executed' do
    policy = RuleTestResPolicy.new(:user,:res)

    policy.expects(:res_dummy).returns(true)
    policy.res_dummy_test.should be_true

    policy.expects(:sys_dummy).returns(false)
    policy.sys_dummy_test?.should be_false
  end

end


text:
package java.sql;

/**
 * A savepoint is an instant during the current transaction that can be utilized
 * by a rollback via the {@link Connection#rollback} command. Rolling back to a
 * particular savepoint means that all changes that occurred after that
 * savepoint are undone.
 */
public interface Savepoint {

    /**
     * Returns the constructed ID for this savepoint.
     *
     * @return the ID for this savepoint.
     * @throws SQLException
     *             if an error occurrs accessing the database.
     */
    public int getSavepointId() throws SQLException;

    /**
     * Returns the name for this savepoint.
     *
     * @return the name of this savepoint.
     * @throws SQLException
     *             if an error occurrs accessing the database.
     */
    public String getSavepointName() throws SQLException;
}


text:
package voldemort.store.stats;

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

import org.junit.Before;
import org.junit.Test;

import voldemort.ServerTestUtils;
import voldemort.client.protocol.RequestFormatType;
import voldemort.store.socket.SocketDestination;
import voldemort.store.socket.clientrequest.ClientRequestExecutor;
import voldemort.utils.pool.KeyedResourcePool;

public class ClientSocketStatsTest {

    private ClientSocketStats masterStats;
    private int port;
    private SocketDestination dest1;
    private SocketDestination dest2;
    private KeyedResourcePool<SocketDestination, ClientRequestExecutor> pool;

    @Before
    public void setUp() throws Exception {
        this.port = ServerTestUtils.findFreePort();
        this.dest1 = new SocketDestination("localhost", port, RequestFormatType.VOLDEMORT_V1);
        this.dest2 = new SocketDestination("localhost", port + 1, RequestFormatType.VOLDEMORT_V1);
        this.masterStats = new ClientSocketStats();
        pool = null;
    }

    @Test
    public void testNewNodeStatsObject() {
        ClientSocketStats stats = new ClientSocketStats(masterStats, dest1, pool);
        assertNotNull(stats);
    }

    @Test
    public void testNewAggrNodeStatsObject() {
        ClientSocketStats stats = masterStats;
        assertNotNull(stats);
        assertEquals(0, stats.getConnectionsCreated());
        assertEquals(0, stats.getConnectionsDestroyed());
        assertEquals(0, stats.getConnectionsCheckedout());
        assertEquals(-1, stats.getAveWaitUs());
    }

    @Test
    public void testConnectionCreate() {
        ClientSocketStats stats = masterStats;
        stats.connectionCreate(dest1);
        stats.connectionCreate(dest2);
        stats.connectionCreate(dest1);
        assertEquals(3, stats.getConnectionsCreated());
        assertEquals(2, stats.getStatsMap().get(dest1).getConnectionsCreated());
        assertEquals(1, stats.getStatsMap().get(dest2).getConnectionsCreated());
    }

    @Test
    public void testConnectionDestroy() {
        ClientSocketStats stats = masterStats;
        stats.connectionDestroy(dest1);
        stats.connectionDestroy(dest2);
        stats.connectionDestroy(dest1);
        assertEquals(3, stats.getConnectionsDestroyed());
        assertEquals(2, stats.getStatsMap().get(dest1).getConnectionsDestroyed());
        assertEquals(1, stats.getStatsMap().get(dest2).getConnectionsDestroyed());
    }

    @Test
    public void testRecordCheckoutTimeNsOnce() {
        ClientSocketStats stats = masterStats;
        assertEquals(0, stats.getConnectionsCheckedout());

        stats.recordCheckoutTimeUs(dest1, 100);
        // check parent
        assertEquals(1, stats.getConnectionsCheckedout());
        assertEquals(100, stats.getWaitHistogram().getQuantile(0.99));

        // check child
        ClientSocketStats child = stats.getStatsMap().get(dest1);
        assertNotNull(child);
        assertEquals(1, child.getConnectionsCheckedout());
        assertEquals(100, child.getWaitHistogram().getQuantile(0.99));
    }

    @Test
    public void testRecordCheckoutTimeNsMultiple() {
        ClientSocketStats stats = masterStats;
        assertEquals(0, stats.getConnectionsCheckedout());

        stats.recordCheckoutTimeUs(dest1, 100);
        stats.recordCheckoutTimeUs(dest1, 200);
        stats.recordCheckoutTimeUs(dest1, 300);
        stats.recordCheckoutTimeUs(dest1, 400);
        stats.recordCheckoutTimeUs(dest2, 500);
        stats.recordCheckoutTimeUs(dest2, 600);
        stats.recordCheckoutTimeUs(dest1, 700);
        stats.recordCheckoutTimeUs(dest1, 800);
        stats.recordCheckoutTimeUs(dest2, 900);

        // check parent
        assertEquals(9, stats.getConnectionsCheckedout());
        assertEquals(900, stats.getWaitHistogram().getQuantile(0.99));

        // check child1
        ClientSocketStats child1 = stats.getStatsMap().get(dest1);
        assertNotNull(child1);
        assertEquals(6, child1.getConnectionsCheckedout());
        assertEquals(100, child1.getWaitHistogram().getQuantile(0.1));
        assertEquals(300, child1.getWaitHistogram().getQuantile(0.5));
        assertEquals(800, child1.getWaitHistogram().getQuantile(0.99));

        // check child2
        ClientSocketStats child2 = stats.getStatsMap().get(dest2);
        assertNotNull(child2);
        assertEquals(3, child2.getConnectionsCheckedout());
        assertEquals(500, child2.getWaitHistogram().getQuantile(0.1));
        assertEquals(600, child2.getWaitHistogram().getQuantile(0.5));
        assertEquals(900, child2.getWaitHistogram().getQuantile(0.99));
    }

    @Test
    public void testSetMonitoringInterval() {
        ClientSocketStats stats = masterStats;
        stats.setMonitoringInterval(9);
        stats.recordCheckoutTimeUs(dest1, 100);
        stats.recordCheckoutTimeUs(dest1, 200);
        stats.recordCheckoutTimeUs(dest1, 300);
        stats.recordCheckoutTimeUs(dest1, 400);
        stats.recordCheckoutTimeUs(dest1, 500);
        stats.recordCheckoutTimeUs(dest1, 600);
        stats.recordCheckoutTimeUs(dest2, 700);
        stats.recordCheckoutTimeUs(dest2, 800);
        // before interval based reset
        // check parent
        assertEquals(8, stats.getConnectionsCheckedout());
        assertEquals(450, stats.getAveWaitUs());
        // check child
        ClientSocketStats child1 = stats.getStatsMap().get(dest1);
        ClientSocketStats child2 = stats.getStatsMap().get(dest2);
        assertEquals(6, child1.getConnectionsCheckedout());
        assertEquals(2, child2.getConnectionsCheckedout());
        assertEquals(350, child1.getAveWaitUs());
        assertEquals(750, child2.getAveWaitUs());

        // after interval based reset
        stats.recordCheckoutTimeUs(dest2, 900000);
        // check parent
        assertEquals(-1, stats.getAveWaitUs());
        assertEquals(0, stats.getConnectionsCheckedout());
        // check child
        assertEquals(-1, child1.getAveWaitUs());
        assertEquals(0, child1.getConnectionsCheckedout());
        assertEquals(-1, child2.getAveWaitUs());
        assertEquals(0, child2.getConnectionsCheckedout());
    }

    @Test
    public void concurrentTest() {
        SocketDestination dest3 = new SocketDestination("localhost",
                                                        dest1.getPort() + 2,
                                                        RequestFormatType.VOLDEMORT_V1);
        SocketDestination dest4 = new SocketDestination("localhost",
                                                        dest1.getPort() + 3,
                                                        RequestFormatType.VOLDEMORT_V1);
        class TestThread implements Runnable {

            SocketDestination dest;

            public TestThread(SocketDestination dest) {
                this.dest = dest;
            }

            public void run() {
                masterStats.recordCheckoutTimeUs(dest, 1000);
                masterStats.recordCheckoutTimeUs(dest, 2000);
                masterStats.recordCheckoutTimeUs(dest, 3000);
                masterStats.recordCheckoutTimeUs(dest, 4000);
                masterStats.recordCheckoutTimeUs(dest, 5000);
                masterStats.recordCheckoutTimeUs(dest, 6000);
                masterStats.recordCheckoutTimeUs(dest, 7000);
                masterStats.recordCheckoutTimeUs(dest, 8000);
                masterStats.recordCheckoutTimeUs(dest, 9000);
            }
        }
        Thread t1 = new Thread(new TestThread(dest1));
        Thread t1_1 = new Thread(new TestThread(dest1));
        Thread t1_2 = new Thread(new TestThread(dest1));
        Thread t1_3 = new Thread(new TestThread(dest1));
        Thread t2 = new Thread(new TestThread(dest2));
        Thread t2_1 = new Thread(new TestThread(dest2));
        t1.start();
        t2.start();
        t2_1.start();
        t1_1.start();
        t1_2.start();
        t1_3.start();
        try {
            t1.join();
            t2.join();
            t2_1.join();
            t1_1.join();
            t1_2.join();
            t1_3.join();
        } catch(Exception e) {}
        assertEquals(masterStats.getWaitHistogram().getQuantile(0.01), 1000);
        assertEquals(masterStats.getWaitHistogram().getQuantile(0.5), 5000);

        assertEquals(masterStats.getStatsMap().get(dest1).getWaitHistogram().getQuantile(0.01),
                     1000);
        assertEquals(masterStats.getStatsMap().get(dest1).getWaitHistogram().getQuantile(0.5), 5000);
        assertEquals(masterStats.getStatsMap().get(dest2).getWaitHistogram().getQuantile(0.01),
                     1000);
        assertEquals(masterStats.getStatsMap().get(dest2).getWaitHistogram().getQuantile(0.5), 5000);
    }
}


text:
import React, { Component } from 'react'
import s from './ServiceEdit.css'
import icons from '../../icons/css/icons.css'
import { gender } from '../../lib/eligibilities'
import { age } from '../../lib/eligibilities'
import { uuid } from '../../lib/uuid'
import TimeRangePicker from '../TimeRangePicker'
import ToggleButton from '../ToggleButton'

/* The existing times range 0-2359. This was the easiest way I could think of to make sure that the previous day always weighted less than the next day. */
const scheduleSorter = {
  "-":        -1,
  "Sunday":    0,
  "Monday":    10000,
  "Tuesday":   20000,
  "Wednesday": 30000,
  "Thursday":  40000,
  "Friday":    50000,
  "Saturday":  60000
}

class ServiceEdit extends Component {

  blankSchedule = () => {
    const { service } = this.props
    return {
      opensAt: "0000",
      closesAt: "0000",
      id: uuid(),
      locationId: service.locationId,
      organizationId: service.organization,
      serviceId: service.id,
      weekday: "-"
    }
  }

  updateService = (field, value) => {
    const { service, handleChange } = this.props
    const newService = service

    newService[field] = value
    handleChange(newService)
  }

  deleteService = () => {
    const { service, handleDelete } = this.props

    handleDelete(service)
  }

  handleServiceChange = (field, event) => {
    this.updateService(field, event.target.value)
  }

  handleGender = (value) => {
    const { eligibility } = this.props.service
    const newEligibility = eligibility

    newEligibility.gender = value.key
    this.updateService('eligibility', newEligibility)
  }

  handleAge = (value) => {
    const { eligibility } = this.props.service
    const newEligibility = eligibility
    let newAge = newEligibility.age || []

    if (newAge.includes(value.key)) {
      newAge = newAge.filter(age => age !== value.key)
    } else {
      newAge = [...newAge, value.key];
    }

    newEligibility.age = newAge
    this.updateService('eligibility', newEligibility)
  }

  handleCPR = (value) => {
    const { eligibility } = this.props.service
    const newEligibility = eligibility

    newEligibility.cpr = value
    this.updateService('eligibility', newEligibility)
  }

  getAgeClass = (value) => {
    let classes = [s.selectableButton]
    const { eligibility } = this.props.service
    let stateVal = eligibility ? (eligibility.age || []) : []

    return stateVal.includes(value.key)
  }

  getGenderClass = (value) => {
    let classes = [s.selectableButton]
    const { eligibility } = this.props.service
    let stateVal = eligibility ? eligibility.gender : ''

    return stateVal == value.key
  }

  getCategoryClass = (value) => {
    let classes = [s.selectableButton]
    const { taxonomy } = this.props.service

    return taxonomy.toLowerCase() == value
  }

  handleTimeChange = (event, value_changed, metadata) => {
    const { schedules } = this.props.service
    const newSchedules = schedules

    if (value_changed == 'start') {
      newSchedules[metadata.scheduleNum]['opensAt'] = event.target.value.replace(':', '')
    } else if (value_changed == 'end') {
      newSchedules[metadata.scheduleNum]['closesAt'] = event.target.value.replace(':', '')
    } else {
      if (event.target.value == '-'){
        window.alert("You must choose a weekday for a schedule")
        return
      }
      newSchedules[metadata.scheduleNum]['weekday'] = event.target.value
    }

    this.updateService('schedules', newSchedules)
  }

  handleTimeDelete = (index) => {
    const { schedules } = this.props.service
    const newSchedules = schedules

    newSchedules.splice(index, 1)

    this.updateService('schedules', newSchedules)
  }

  sortSchedules = (schedules) => {
    return schedules.sort(function(a, b) {
      return (scheduleSorter[a.weekday] + parseInt(a.opensAt)) - (scheduleSorter[b.weekday] + parseInt(b.opensAt))
    })
  }

  newSchedule = () => {
    const { schedules } = this.props.service
    const newSchedules = schedules

    newSchedules.push(this.blankSchedule())

    this.updateService('schedules', newSchedules)
  }

  render() {
    const { service, taxonomies } = this.props

    return (

            Service Name
            <input
              className={s.input}
              type="text"
              value={service.name}
              onChange={(e) => this.handleServiceChange('name', e)}
            />

            Service Description
            <input
              className={s.input}
              type="text"
              value={service.description}
              onChange={(e) => this.handleServiceChange('description', e)}
            />

            Application Process
            <textarea
              className={s.input}
              type="text"
              value={service.applicationProcess}
              onChange={(e) => this.handleServiceChange('applicationProcess', e)}
            />

            Category:
            {(taxonomies).map((category, i) => (

                <ToggleButton
                  key={`category-${i}`}
                  enabled={this.getCategoryClass(category.name.toLowerCase())}
                  extraClasses={`${s.categoryIcon} ${category.icon}`}
                  onClick={(e) => this.updateService('taxonomy', category.name.toLowerCase())}
                  label={category.name}
                />

            ))}

Select all that apply:

          <GenderBox
            gender={service.eligibility && service.eligibility.gender}
            getGenderClass={this.getGenderClass}
            handleGender={this.handleGender}/>

          <AgeBox
            getAgeClass={this.getAgeClass}
            handleAge={this.handleAge} />

          <CPRBox
            value={service.eligibility && service.eligibility.cpr}
            handleCPR={this.handleCPR} />

          Schedules
          <button
            className={s.addToSubsection}
            onClick={this.newSchedule}
            title={`Click to add a new schedule`}>
            + Add
          </button>

            Schedule:
            {(this.sortSchedules(service.schedules)).map((schedule, index) => (
              <ScheduleBox
                key={`schedule-${index}`}
                index={index}
                schedule={schedule}
                handleTimeChange={this.handleTimeChange}
                handleTimeDelete={this.handleTimeDelete} />
            ))}

            <button
              className={s.buttonStyle}
              onClick={this.deleteService}
            >
            Delete this Service
            </button>

    )
  }
}

const GenderBox = (props) => (

    Gender Eligibility:
    {gender.map((gender, i) => (

       <ToggleButton
         key={`gender-${gender.name}`}
         enabled={props.getGenderClass(gender)}
         extraClasses={`${s.categoryIcon} ${gender.icon}`}
         onClick={(e) => props.handleGender(gender)}
         label={gender.name}
       />

    ))}

)

const AgeBox = (props) => (

    Age Eligibility:
    {age.map((age, i) => (

       <ToggleButton
         key={`age-${age.name}`}
         enabled={props.getAgeClass(age)}
         onClick={(e) => props.handleAge(age)}
         label={age.name}
       />

    ))}

)

const CPRBox = ({ value = false, handleCPR }) =>

    CPR Eligibility:

      <ToggleButton
        enabled={value === true}
        onClick={() => handleCPR(true)}
        label="Required"
      />

      <ToggleButton
        enabled={value === false}
        onClick={() => handleCPR(false)}
        label="Not required"
      />

const ScheduleBox = (props) => (

    <TimeRangePicker
      key={`timePicker-${props.index}`}
      weekday={props.schedule.weekday}
      startTime={props.schedule.opensAt}
      endTime={props.schedule.closesAt}
      handleUpdate={props.handleTimeChange}
      handleDelete={props.handleTimeDelete}
      metadata={{ scheduleNum: props.index, day: props.index}}/>

)

export default ServiceEdit


text:
package com.tarena.el.android.compass;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Button;
/**
 * Ö¸ÄÏÕë
 * ´Ë³ÌÐòʹÓÃÊÖ»ú´«¸ÐÆ÷À´ÏÔʾָÄÏÕ룬µ±Óû§Òƶ¯ÊÖ»ú·½Ïòʱ£¬ÈÃÖ¸ÄÏÕë'ÖÕÖ¸ÏòÄÏ·½¡£
 * @author tangliang
 *
 */
public class MainActivity extends Activity {

	private SensorManager mSensorManager;
	private Sensor mSensor;
	private SampleView mView;
	private Button mBtn;
	float[] mValues;
	private final SensorEventListener mListener = new SensorEventListener() {
		public void onSensorChanged(SensorEvent event) {
			mValues = event.values;
			if (mView != null) {
				mView.setValues(mValues);
				mView.invalidate();
			}

			if (mBtn != null) {

				float direction = mValues[0];
				if (direction > 22.5f && direction < 157.5f) {
					// east
					mBtn.setText("¶«");
				} else if (direction > 202.5f && direction < 337.5f) {
					// west
					mBtn.setText("Î÷");
				}else if (direction > 112.5f && direction < 247.5f) {
					// south
					mBtn.setText("ÄÏ");
				} else if (direction < 67.5 || direction > 292.5f) {
					// north
					mBtn.setText("±±");
				}
			}
		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		mView = (SampleView) findViewById(R.id.sampleview01);
		mBtn = (Button) findViewById(R.id.button01);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mSensorManager.registerListener(mListener, mSensor,
				SensorManager.SENSOR_DELAY_GAME);
	}

	@Override
	protected void onStop() {
		super.onStop();
		mSensorManager.unregisterListener(mListener);

	}

}


text:
package io.github.droidkaigi.confsched.model;

import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;

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

import io.github.droidkaigi.confsched.R;

public class PlaceMap {

    @StringRes
    public final int nameRes;

    @StringRes
    public final int buildingNameRes;

    @DrawableRes
    public final int markerRes;

    public final double latitude;

    public final double longitude;

    public PlaceMap(int nameRes, int buildingNameRes, int markerRes, double latitude, double longitude) {
        this.nameRes = nameRes;
        this.buildingNameRes = buildingNameRes;
        this.markerRes = markerRes;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public static List<PlaceMap> createList() {
        List<PlaceMap> list = new ArrayList<>(4);

        list.add(new PlaceMap(R.string.map_main_name, R.string.map_main_building,
                R.drawable.ic_place_red_500_36dp, 35.605899, 139.683541));
        list.add(new PlaceMap(R.string.map_ab_name, R.string.map_ab_building,
                R.drawable.ic_place_green_500_36dp, 35.603012, 139.684206));
        list.add(new PlaceMap(R.string.map_cd_name, R.string.map_cd_building,
                R.drawable.ic_place_blue_500_36dp, 35.603352, 139.684249));
        list.add(new PlaceMap(R.string.map_party_name, R.string.map_party_building,
                R.drawable.ic_place_purple_500_36dp, 35.607513, 139.684689));

        return list;
    }

}


text:
require 'spec_helper'

describe 'Variants', type: :feature do
  stub_authorization!

  let(:product) { create(:product_with_option_types, price: '1.99', cost_price: '1.00', weight: '2.5', height: '3.0', width: '1.0', depth: '1.5') }

  context 'creating a new variant' do
    it 'allows an admin to create a new variant', js: true do
      product.options.each do |option|
        create(:option_value, option_type: option.option_type)
      end

      visit spree.admin_products_path
      within_row(1) { click_icon :edit }
      click_link 'Variants'
      click_on 'Add One'
      expect(page).to have_field(id: 'variant_price', with: '1.99')
      expect(page).to have_field(id: 'variant_cost_price', with: '1.00')
      expect(page).to have_field(id: 'variant_weight', with: '2.50')
      expect(page).to have_field(id: 'variant_height', with: '3.00')
      expect(page).to have_field(id: 'variant_width', with: '1.00')
      expect(page).to have_field(id: 'variant_depth', with: '1.50')
      expect(page).to have_css('.form-group[data-hook="tax_category"]', text: 'None')
    end
  end

  context 'listing variants' do
    context 'currency displaying' do
      context 'using Russian Rubles' do
        before do
          Spree::Config[:currency] = 'RUB'
          create(:store, default: true, default_currency: 'RUB')
          create(:variant, product: product, price: 19.99)
        end

        # Regression test for #2737
        context 'uses руб as the currency symbol' do
          it 'on the products listing page' do
            visit spree.admin_product_variants_path(product)
            within_row(1) { expect(page).to have_content('19.99 ₽') }
          end
        end
      end
    end
  end
end


text:
package org.teavm.jso.dom.xml;

public interface Text extends Node {
    Text splitText(int offset);
}


text:
#import "RNSVGViewBoxManager.h"
#import "RNSVGViewBox.h"
#import "RNSVGVBMOS.h"

@implementation RNSVGViewBoxManager

RCT_EXPORT_MODULE()

- (RNSVGViewBox *)node
{
  return [RNSVGViewBox new];
}

RCT_EXPORT_VIEW_PROPERTY(minX, NSString)
RCT_EXPORT_VIEW_PROPERTY(minY, NSString)
RCT_EXPORT_VIEW_PROPERTY(vbWidth, NSString)
RCT_EXPORT_VIEW_PROPERTY(vbHeight, NSString)
RCT_EXPORT_VIEW_PROPERTY(align, NSString)
RCT_EXPORT_VIEW_PROPERTY(meetOrSlice, RNSVGVBMOS)

@end


text:
<resources>
    <string name="app_name">My App Portfolio</string>

    <string name="my_title">My Nanodegree Apps!</string>
    <string name="action_settings">Settings</string>
    <string name="action_share">Share</string>

    <string name="movie_title">Movie Title</string>
    <string name="movie_overview">OverView</string>

    <!-- GridView of Movie -->
    <string name="sort_by_popularity">Sort by Popularity</string>
    <string name="sort_by_rating">Sort by Rating</string>

    <!-- Movie Defaults -->
    <string name="search_artist_hint">Search Artist</string>
    <string name="no_trailer_found">No trailer(s) found</string>
    <string name="no_movie_found">No movies(s) found</string>

    <string name="search_movie">Search Movie.</string>

    <string name="error">Error</string>
    <string name="null_error">Something went wrong. Please try again.</string>

    <string name="movie_name">Movie name</string>
    <string name="year">Year</string>

    <!-- Dashboard -->
    <string name="popular_movies">Popular Movies</string>
    <string name="scores_app">SCORES APP</string>
    <string name="library_app">LIBRARY APP</string>
    <string name="build_it_bigger">BUILD IT BIGGER</string>
    <string name="bacon_rader">BACON APP</string>
    <string name="capstone_my_own_app">CAPSTONE: MY OWN APP</string>
    <string name="title_activity_movie">Movies</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_movie_detail">MovieDetailActivity</string>

    <!-- Movie Details Activity -->
    <string name="release_date">Release Date</string>
    <string name="rating">Rating</string>

</resources>


text:
const DrawCard = require('../../drawcard.js');
const AbilityDsl = require('../../abilitydsl');

class FingerOfJade extends DrawCard {
    setupCardAbilities() {
        this.attachmentConditions({
            myControl: true
        });

        this.wouldInterrupt({
            title: 'Cancel an ability',
            when: {
                onInitiateAbilityEffects: (event, context) => event.cardTargets.some(card => card === context.source.parent)
            },
            cost: AbilityDsl.costs.sacrificeSelf(),
            gameAction: AbilityDsl.actions.cancel()
        });
    }
}

FingerOfJade.id = 'finger-of-jade';

module.exports = FingerOfJade;


text:
local PANEL = {};

function PANEL:Init ( )
	self:SetVisible(true)
	self.ModelPanel = vgui.Create("DModelPanel", self);

	function self.ModelPanel:LayoutEntity ( ) end
	function self.ModelPanel.OnMousePressed ( _, mc ) self:OnMousePressed(mc) end
	function self.ModelPanel.OnMouseReleased ( _, mc ) self:OnMouseReleased(mc) end

	self.DownTime = 0;
end

function PANEL:PerformLayout ( )
	self.ModelPanel:InvalidateLayout();

	self.ModelPanel:SetPos(3, 3);
	self.ModelPanel:SetSize(self:GetWide() - 6, self:GetTall() - 6);
end

function PANEL:SetItemTable ( itemTable )
	if !itemTable then
	return
	end
	self.itemTable = itemTable;

	self.ModelPanel:SetModel(itemTable.InventoryModel);

	self.ModelPanel:SetCamPos(itemTable.ModelCamPos)
	self.ModelPanel:SetLookAt(itemTable.ModelLookAt)
	self.ModelPanel:SetFOV(itemTable.ModelFOV)

	local iSeq = self.ModelPanel.Entity:LookupSequence('ragdoll');
	self.ModelPanel.Entity:ResetSequence(iSeq);
end

function PANEL:Think ( )
	if (self.mouseDown) then
		if (!input.IsMouseDown(self.mouseCode)) then
			self:OnMouseReleased(MOUSE_LEFT)
			return;
		end

		local mx, my = gui.MousePos();
		self:SetPos(mx + self.InitialOffset_X, my + self.InitialOffset_Y);
	end
end

local OnPress = Sound("UI/buttonclick.wav");
function PANEL:OnMousePressed ( MouseCode )
	if (MouseCode == MOUSE_LEFT) then
		surface.PlaySound(OnPress);

		self.mouseCode = MouseCode;
		self.mouseDown = true;

		local mx, my = gui.MousePos();
		local ox, oy = self:GetPos();

		self.InitialOffset_X, self.InitialOffset_Y = ox - mx, oy - my;
		self.InitialPos_X, self.InitialPos_Y = self:GetPos();

		self.ModelPanel:MoveToFront();

		self.trueParent:SetSuperGlow(true);

		GAMEMODE.DraggingSomething = self;

		if (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_MAIN) then
			self:GetParent().MainWeaponEquip:SetSuperGlow(true);
		elseif (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_SIDE) then
			self:GetParent().SideWeaponEquip:SetSuperGlow(true);
		end

		self.DownTime = CurTime();
	elseif (MouseCode == MOUSE_RIGHT) then
		GAMEMODE.DropItem(self.trueParent.itemID);
	end
end

function PANEL:OnMouseReleased( MouseCode )
	if (MouseCode == MOUSE_LEFT) then
		self.mouseDown = nil;

		if (self.InitialPos_X) then self:SetPos(self.InitialPos_X, self.InitialPos_Y); end
		self.trueParent:SetSuperGlow(false);

		GAMEMODE.DraggingSomething = nil;

		if (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_MAIN) then
			self:GetParent().MainWeaponEquip:SetSuperGlow(false);
		elseif (self.itemTable.EquipZone && self.itemTable.EquipZone == EQUIP_WEAPON_SIDE) then
			self:GetParent().SideWeaponEquip:SetSuperGlow(false);
		end

		realSlot = self:GetParent():GetHoveredItemSlot();

		if (CurTime() - self.DownTime < 1 && realSlot == self.trueParent) then
			GAMEMODE.UseItem(self.trueParent.itemID);
		else
			if (realSlot && self.trueParent.itemID != realSlot.itemID) then
				LocalPlayer():SwapItemPosition(self.trueParent.itemID, realSlot.itemID);
			end
		end
	end
end

vgui.Register("perp2_inventory_block_item", PANEL);