text:
const discord = require ('discord.js');
var Client   =    require('mysql');
var settings = require('../../settings.js');
var randomHex = require('random-hex');
var dbclient = '';
var mysqlPool = '';

exports.init = (client) => {
        dbclient = Client.createConnection({
                    host: settings.dbhost,
                    user: settings.dbuser,
                    password: settings.dbpassword,
                    database: settings.dbdatabase,
        });//client = Client.createConnection

        mysqlPool  = Client.createPool({
            host: settings.dbhost,
            user: settings.dbuser,
            password: settings.dbpassword,
            database: settings.dbdatabase,
            port:3306
        }); //my sql pool
};//init

exports.run = (client, msg) => {
    var uid     = msg.author.id;
    var uidname = msg.author.username;
    var mentionedid   = uid;
    var mentionedname = uidname;
    var uidavatar = msg.author.avatarURL;
    var mentionedavatar = uidavatar;
    var slapdesc = 'No Items in Database';

    if (msg.mentions.users.first()){
        mentionedid   = msg.mentions.users.first().id;
        mentionedname = msg.mentions.users.first().username;
        mentionedavatar = msg.mentions.users.first().avatarURL;
    }//if

    if (uidavatar != null){
        settings.avypic = uidavatar;
    }else {
        settings.avypic = settings.blankpic;
    };//if (uidavatar != null)

    if (mentionedavatar == null){
        mentionedavatar = settings.blankpic;
    };//if (mentionedavatar == null)

    var strtotal = settings.UserList.get(mentionedid).Strength;
    var bonuscarry = 0;
    var UserWeight = 0;
    slapdesc = '';

        for (f = 0; f < settings.UserSkillList.size; f++){
            if (settings.UserSkillList.get(f).PLAYER_ID == mentionedid){
                if (settings.UserSkillList.get(f).PERK_ID == 110){//strength boost
                    strtotal += settings.UserSkillList.get(f).RANKS;
                };//if (settings.UserSkillList.get(f).PERK_ID == 110)
                if (settings.UserSkillList.get(f).PERK_ID == 610){//strong back
                    bonuscarry += settings.UserSkillList.get(f).RANKS;
                };//if (settings.UserSkillList.get(f).PERK_ID == 110)
            };//if (settings.UserSkillList.get(i).PLAYER_ID == uid)
        };//for

        for (var i = 0; i < settings.User_Inventory.size; i++) {
            if (settings.User_Inventory.get(i).Player_ID == mentionedid){
                var InventoryID = settings.User_Inventory.get(i).TABLE_ID;
                var InventoryPlayerID = settings.User_Inventory.get(i).Player_ID;
                var InventoryItemID = settings.User_Inventory.get(i).ID;
                var InventoryRanks = settings.User_Inventory.get(i).RANKS;
                var ItemName = settings.Weapons_Armor_List.get(InventoryItemID).Name;
                    ItemName = settings.ParseName(ItemName);
                var ItemWeight = settings.Weapons_Armor_List.get(InventoryItemID).Weight;
                    UserWeight += (ItemWeight*InventoryRanks);
                    slapdesc += '[ID: ' + InventoryItemID + '] **' + ItemName + '**';
                    if (InventoryRanks > 1){slapdesc += " x"+InventoryRanks}
                    slapdesc += '\n';
            };//if (settings.User_Inventory.get(i).Player_ID = mentionedid)
        };//for

        var powertotal = settings.UserList.get(mentionedid).Power_Mult;
        if (
            (settings.UserList.get(mentionedid).IsLevelCapped == 0) &&
            (settings.UserList.get(mentionedid).Power_Mult_Boost >= settings.UserList.get(mentionedid).Power_Mult)){
            powertotal += settings.UserList.get(mentionedid).Power_Mult;
        } else {
            powertotal += settings.UserList.get(mentionedid).Power_Mult_Boost;
        };//if
        if (powertotal < 1){powertotal = 1};
        strtotal = strtotal*powertotal;
        var carryCapacity = settings.CarryCalculator(strtotal, bonuscarry);
        var EncumberPercent = (UserWeight/carryCapacity)*100;
            slapdesc += '[' + UserWeight.toLocaleString() + '/' + carryCapacity.toLocaleString() + ' Carry Weight {'+EncumberPercent.toLocaleString()+'%}]';
        const RiderEmbed = new discord.RichEmbed()
              RiderEmbed.setColor(randomHex.generate())
              RiderEmbed.setThumbnail(mentionedavatar)
              RiderEmbed.setDescription(slapdesc)
        msg.channel.send({embed: RiderEmbed});
};//exports run

exports.conf = {
  enabled: true,
  runIn: ["text"],
  aliases: ["list-inventory", "inventory", "inv"],
  permLevel: 0,
  botPerms: [],
  requiredFuncs: []
};

exports.help = {
  name: "listinventory",
  description: "",
  usage: "",
  usageDelim: ""
//  extendedHelp: "";
};


text:
announce() {
  travis_time_start
  echo \$ $@
  $@
  travis_time_finish
}

travis_retry() {
  local result=0
  local count=1
  while [ $count -le 3 ]; do
    [ $result -ne 0 ] && {
      echo -e "\n\033[33;1mThe command \"$@\" failed. Retrying, $count of 3.\033[0m\n" >&2
    }
    "$@"
    result=$?
    [ $result -eq 0 ] && break
    count=$(($count + 1))
    sleep 1
  done

  [ $count -eq 3 ] && {
    echo "\n\033[33;1mThe command \"$@\" failed 3 times.\033[0m\n" >&2
  }

  return $result
}

travis_rvm_os_path() {
  if command -v sw_vers >> /dev/null; then
    echo "osx/$(sw_vers -productVersion | cut -d. -f1,2)/$(uname -m)"
  elif command -v freebsd-version >> /dev/null; then
    echo "freebsd/$(freebsd-version | cut -d- -f1)/x86_64"
  else
    echo "$(lsb_release -i -s | tr '[:upper:]' '[:lower:]')/$(lsb_release -r -s)/$(uname -m)"
  fi
}

fold_start() {
  echo -e "travis_fold:start:$1\033[33;1m$2\033[0m"
}

fold_end() {
  echo -e "\ntravis_fold:end:$1\r"
}

function install_awscli() {
  if which sw_vers >> /dev/null; then
    announce brew install awscli
  elif which freebsd-version >> /dev/null; then
    announce sudo pkg install -y awscli
  else
    command -v pip >/dev/null || (curl -sSO https://bootstrap.pypa.io/get-pip.py && python get-pip.py --user)
    pip install --user --upgrade pip
    announce python -m pip install --user awscli
  fi
}

function update_mvn() {
  VERSION=$1
  fold_start mvn.1 "update mvn to $VERSION"
  curl -sSO http://mirrors.ibiblio.org/apache/maven/maven-3/${VERSION}/binaries/apache-maven-${VERSION}-bin.tar.gz
  tar xzf apache-maven-$VERSION-bin.tar.gz
  export PATH=$PWD/apache-maven-$VERSION/bin:$PATH
  export M2_HOME=$PWD/apache-maven-$VERSION
  mvn -version
  fold_end mvn.1
}

travis_time_start() {
  travis_timer_id=$(printf %08x $(( RANDOM * RANDOM )))
  travis_start_time=$(travis_nanoseconds)
  echo -en "travis_time:start:$travis_timer_id\r${ANSI_CLEAR}"
}

travis_time_finish() {
  local result=$?
  travis_end_time=$(travis_nanoseconds)
  local duration=$(($travis_end_time-$travis_start_time))
  echo -en "\ntravis_time:end:$travis_timer_id:start=$travis_start_time,finish=$travis_end_time,duration=$duration\r${ANSI_CLEAR}"
  return $result
}

function travis_nanoseconds() {
  local cmd="date"
  local format="+%s%N"
  local os=$(uname)

  if hash gdate > /dev/null 2>&1; then
    cmd="gdate" # use gdate if available
  elif [[ "$os" = Darwin ]]; then
    format="+%s000000000" # fallback to second precision on darwin (does not support %N)
  fi

  $cmd -u $format
}

function ensure_gpg_key() {
  local key1_id="409B6B1796C275462A1703113804BB82D39DC0E3"
  local key2_id="7D2BAF1CF37B13E2069D6956105BD0E739499BDB"
  local gpg_cmd="gpg"

  if command -v gpg2; then
    gpg_cmd="gpg2"
  fi

  if ! command -v $gpg_cmd; then
    if command -v sw_vers; then
      env HOMEBREW_NO_AUTO_UPDATE=1 brew install $gpg_cmd
    elif which freebsd-version >> /dev/null; then
      sudo pkg install -y $gpg_cmd
    else
      sudo apt-get install $gpg_cmd
    fi
  fi

  $gpg_cmd --list-keys $key1_id || $gpg_cmd --keyserver hkp://keys.gnupg.net --recv-keys $key1_id
  $gpg_cmd --list-keys $key2_id || $gpg_cmd --keyserver hkp://keys.gnupg.net --recv-keys $key2_id
  curl -sSL https://rvm.io/mpapis.asc | $gpg_cmd --import -
}

function install_autoconf() {
  pushd /tmp
  wget http://ftp.gnu.org/gnu/autoconf/autoconf-latest.tar.gz
  tar xvf autoconf-latest.tar.gz
  pushd autoconf-*
  ./configure
  make up
  make && sudo make install
  popd
  popd
}

function install_openssl_10_homebrew() {
  announce brew tap shivammathur/homebrew-openssl-deprecated
  announce brew install openssl@1.0
  OPENSSL_FLAGS="-C --with-openssl-dir=/usr/local/opt/openssl@1.0"
}

function rvm_version() {
  if [[ $VERSION =~ ^3 ]]; then
    echo head
  else
    echo $SAFE_RVM_VERSION
  fi
}

PATH=$HOME/bin:$HOME/.local/bin:$PATH

#######################################################
# update rvm
fold_start rvm.1 "update rvm"
announce rvm remove 1.8.7
ensure_gpg_key
rm -f ~/.rvmrc
announce rvm get $(rvm_version) --auto-dotfiles
announce rvm reload
announce rvm use 2.3
announce rvm cleanup all
fold_end rvm.1

#######################################################
# get rid of binary meta data
fold_start rvm.2 "clean up meta data"
echo -n > $rvm_path/user/md5
echo -n > $rvm_path/user/sha512
echo -n > $rvm_path/user/db || true
echo "done"
fold_end rvm.2

#######################################################
# prepare env
fold_start rvm.3 "set up env for rvm"
if [[ -s "$HOME/.rvm/scripts/rvm" ]]; then
  announce source "$HOME/.rvm/scripts/rvm"
fi
announce unset DYLD_LIBRARY_PATH
announce export rvm_git_clone_depth=1 # speed up git clone
fold_end rvm.3

#######################################################
# install smf etc
if command -v sw_vers >> /dev/null; then
  announce install_autoconf
  fold_start rvm.4 "OSX specific setup"
  announce rvm autolibs homebrew
  announce rvm use --install 2.4
  announce sudo mkdir -p /etc/openssl
  announce sudo chown -R $USER: /etc/openssl
  # announce rvm use 2.0.0 --fuzzy
  announce mkdir -p $rvm_path/patchsets/ruby
  echo '$ echo "" > $rvm_path/patchsets/ruby/osx_static'
  echo "" > $rvm_path/patchsets/ruby/osx_static
  fold_end rvm.4
elif which freebsd-version >> /dev/null; then
  fold_start rvm.4 "FreeBSD specific setup"
  fold_end rvm.4
else
  fold_start rvm.4 "Linux specific setup"
  MOVABLE_FLAG="--movable"
  announce sudo apt-get update
  announce sudo apt-get install libssl1.0.0 openssl
  fold_end rvm.4
fi

#######################################################
# check $RUBY
if [[ -n ${VERSION} ]]; then
  RUBY=${VERSION}
fi
fold_start ruby "check which ruby to build"
if [ -z $RUBY ]; then
  announce source ./build_info.sh
fi
[[ $RUBY ]] || { echo 'please set $RUBY' && exit 1; }
export RUBY=$(rvm strings $RUBY)
announce export RUBY=${RUBY//[[:blank:]]/}
echo "EVERYBODY STAND BACK, WE'RE INSTALLING $RUBY"
announce unset CC
if [ `expr $RUBY : '.*-clang$'` -gt 0 ]; then
  announce export CC=${RUBY##*-}
fi
fold_end ruby

#######################################################
# build the binary
fold_start build "build $RUBY"
announce rvm alias delete $RUBY
announce rvm remove $RUBY

case $RUBY in
mruby*)
  announce export SKIP_CHECK=1
  if which apt-get >> /dev/null; then
    announce sudo apt-get -q install gperf
  fi
  announce rvm install $RUBY --verify-downloads 1;;
ruby-1.*)
  if command -v sw_vers >> /dev/null; then
    echo "not building $RUBY on OSX, can't statically compile it"
    exit
  elif command -v freebsd-version >> /dev/null; then
    echo "not building $RUBY on FreeBSD, can't statically compile it"
    exit
  else
    announce rvm install $RUBY --verify-downloads 1 $MOVABLE_FLAG --disable-install-doc
  fi;;
ruby-2.3*)
  if command -v sw_vers >> /dev/null; then
    install_openssl_10_homebrew
  fi
  announce rvm install $RUBY $EXTRA_FLAGS --verify-downloads 1 $MOVABLE_FLAG --disable-install-doc -C --without-tcl,--without-tk,--without-gmp ${OPENSSL_FLAGS}
  ;;
ruby-*)
  announce rvm install $RUBY $EXTRA_FLAGS --verify-downloads 1 $MOVABLE_FLAG --disable-install-doc -C --without-tcl,--without-tk,--without-gmp
  ;;
jruby-head)
  update_mvn 3.3.9
  announce rvm install $RUBY --verify-downloads 1;;
*)      announce rvm install $RUBY --verify-downloads 1;;
esac

announce rvm prepare $RUBY
fold_end build

#######################################################
# make sure bundler works
fold_start check.1 "make sure bundler works"
if [ -n "${SKIP_CHECK}" ]; then
  echo '$SKIP_CHECK is set, skipping bundler check'
else
  echo "source 'https://rubygems.org'; gem 'sinatra'" > Gemfile
  announce travis_retry rvm $RUBY do gem install bundler
  announce travis_retry rvm $RUBY do bundle install
fi
fold_end check.1

# make sure ffi works
if [[ $RUBY != jruby* ]]; then
  fold_start check.2 "make sure native extension can be built"
  if [ -n "${SKIP_CHECK}" ]; then
    echo '$SKIP_CHECK is set, skipping ffi check'
  else
    echo "source 'https://rubygems.org'; gem 'sinatra'" > Gemfile
    announce travis_retry rvm $RUBY do gem install ffi
    announce travis_retry rvm $RUBY do gem uninstall -x ffi
  fi
  fold_end check.2
fi

#######################################################
# publish to bucket
fold_start publish "upload to S3"
if [[ $TRAVIS_PULL_REQUEST == 'false' ]]; then
  mkdir -p $HOME/bin
  PATH=$HOME/bin:$HOME/.local/bin:$PATH

  for f in $RUBY.*; do
    base=${f%%.*}
    openssl dgst -sha512 -out ${base}.sha512.txt $f
  done

  command -v aws || install_awscli
  for f in $RUBY.*; do
    aws s3 cp $f s3://travis-rubies/binaries/$(travis_rvm_os_path)/ --acl=public-read
  done
else
  echo "This is a Pull Request, not publishing."
fi
fold_end publish

#######################################################
# make sure it installs
fold_start check.3 "make sure it installs"
if [[ $TRAVIS_PULL_REQUEST == 'false' ]]; then
  announce rvm remove $RUBY
  echo "rvm_remote_server_url3=https://s3.amazonaws.com/travis-rubies/binaries
  rvm_remote_server_type3=rubies
  rvm_remote_server_verify_downloads3=1" > $rvm_path/user/db
  announce cat $rvm_path/user/db
  announce travis_retry rvm install $RUBY --binary
  announce gem env
  announce bundle env
else
  echo "This is a Pull Request, skipping."
fi
fold_end check.3

redpajama_set_name: RedPajamaGithub


text:
<?php

class BlockAdmin extends ModelAdmin {
	public static $managed_models = array(
		'Block'
	);
    private static $menu_title = 'Blocks';
	private static $url_segment = 'blocks';

	//private static $menu_icon = 'sectionmodule/icon.png';
}


text:
"""
Test that the compiled .mo files match the translations in the
uncompiled .po files.

This is required because we are checking in the .mo files into
the repo, but compiling them is a manual process. We want to make
sure that we find out if someone forgets the compilation step.
"""

import ddt
import polib
from unittest import TestCase

from i18n.config import CONFIGURATION, LOCALE_DIR

@ddt.ddt
class TestCompiledMessages(TestCase):
    """
    Test that mo files match their source po files
    """

    PO_FILES = ['django.po', 'djangojs.po']

    @ddt.data(*CONFIGURATION.translated_locales)
    def test_translated_messages(self, locale):
        message_dir = LOCALE_DIR / locale / 'LC_MESSAGES'
        for pofile_name in self.PO_FILES:
            pofile_path = message_dir / pofile_name
            pofile = polib.pofile(pofile_path)
            mofile = polib.mofile(pofile_path.stripext() + '.mo')

            po_entries = {entry.msgid: entry for entry in pofile.translated_entries()}
            mo_entries = {entry.msgid: entry for entry in mofile.translated_entries()}

            # Check that there are no entries in po that aren't in mo, and vice-versa
            self.assertEquals(po_entries.viewkeys(), mo_entries.viewkeys())

            for entry_id, po_entry in po_entries.iteritems():
                mo_entry = mo_entries[entry_id]
                for attr in ('msgstr', 'msgid_plural', 'msgstr_plural', 'msgctxt', 'obsolete', 'encoding'):
                    po_attr = getattr(po_entry, attr)
                    mo_attr = getattr(mo_entry, attr)

                    # The msgstr_plural in the mo_file is keyed on ints, but in the po_file it's
                    # keyed on strings. This normalizes them.
                    if attr == 'msgstr_plural':
                        po_attr = {int(key): val for (key, val) in po_attr.items()}

                    self.assertEquals(
                        po_attr,
                        mo_attr,
                        "When comparing {} for entry {!r}, {!r} from the .po file doesn't match {!r} from the .mo file".format(
                            attr,
                            entry_id,
                            po_attr,
                            mo_attr,
                        )
                    )


text:
package ua.com.glady.uacc.guis;

import android.content.Context;
import android.widget.LinearLayout;

import ua.com.glady.uacc.R;
import ua.com.glady.uacc.model.Constants;
import ua.com.glady.uacc.model.ExcisesRegistry;
import ua.com.glady.uacc.model.types.Age;
import ua.com.glady.uacc.model.types.VehicleType;
import ua.com.glady.uacc.model.vehicle.AVehicle;
import ua.com.glady.uacc.model.vehicle.Bus;
import ua.com.glady.uacc.tools.ToolsView;

/**
 * Implements bus details UI
 *
 * Created by Slava on 10.04.2015.
 */
public class BusDataUi extends VehicleDataUi {

    public BusDataUi(Context context, ExcisesRegistry excisesRegistry) {

        super(context, excisesRegistry);

        LinearLayout lBase = new LinearLayout(context);
        this.addView(lBase);

        this.addEngineList();
        ToolsView.addSeparatorLine(context, llBase, 2,
                context.getResources().getColor(R.color.aqua_gray), 0, 8, 0, 0);

        this.addAgeList();
        ToolsView.addSeparatorLine(context, llBase, 2,
                context.getResources().getColor(R.color.aqua_gray), 0, 8, 0, 8);

        this.addVolumeAndPrice();
    }

    @Override
    protected void initializeConcreteVehicle() {
        vehicleType = VehicleType.Bus;

        defaultVolume = 3500;

        this.availableEngines = new int[2];
        availableEngines[0] = Constants.ENG_GASOLINE;
        availableEngines[1] = Constants.ENG_DIESEL;

        this.availableAges = new int[3];
        availableAges[0] = Age.AGE_0_YEARS;
        availableAges[1] = Age.AGE_NOT_EXCEED_8_YEARS;
        availableAges[2] = Age.AGE_EXCEED_8_YEARS;
    }

    @Override
    public AVehicle getVehicle() {
        Bus result = new Bus(context, excisesRegistry);

        result.getEngine().setType(getEngineType());
        result.getEngine().setVolume(this.getVolume());

        result.setAge(this.getAge());

        // defining price
        result.setBasicPrice(this.getPrice());

        return result;
    }

}


text:
import {Disconnectable, Part} from './lit-html.js';

export {
  AttributePart,
  BooleanAttributePart,
  ChildPart,
  ElementPart,
  EventPart,
  Part,
  PropertyPart,
} from './lit-html.js';

export interface DirectiveClass {
  new (part: PartInfo): Directive;
}

/**
 * This utility type extracts the signature of a directive class's render()
 * method so we can use it for the type of the generated directive function.
 */
export type DirectiveParameters<C extends Directive> = Parameters<C['render']>;

/**
 * A generated directive function doesn't evaluate the directive, but just
 * returns a DirectiveResult object that captures the arguments.
 */
export interface DirectiveResult<C extends DirectiveClass = DirectiveClass> {
  /**
   * This property needs to remain unminified.
   * @internal */
  ['_$litDirective$']: C;
  /** @internal */
  values: DirectiveParameters<InstanceType<C>>;
}

export const PartType = {
  ATTRIBUTE: 1,
  CHILD: 2,
  PROPERTY: 3,
  BOOLEAN_ATTRIBUTE: 4,
  EVENT: 5,
  ELEMENT: 6,
} as const;

export type PartType = typeof PartType[keyof typeof PartType];

export interface ChildPartInfo {
  readonly type: typeof PartType.CHILD;
}

export interface AttributePartInfo {
  readonly type:
    | typeof PartType.ATTRIBUTE
    | typeof PartType.PROPERTY
    | typeof PartType.BOOLEAN_ATTRIBUTE
    | typeof PartType.EVENT;
  readonly strings?: ReadonlyArray<string>;
  readonly name: string;
  readonly tagName: string;
}

export interface ElementPartInfo {
  readonly type: typeof PartType.ELEMENT;
}

/**
 * Information about the part a directive is bound to.
 *
 * This is useful for checking that a directive is attached to a valid part,
 * such as with directive that can only be used on attribute bindings.
 */
export type PartInfo = ChildPartInfo | AttributePartInfo | ElementPartInfo;

/**
 * Creates a user-facing directive function from a Directive class. This
 * function has the same parameters as the directive's render() method.
 */
export const directive =
  <C extends DirectiveClass>(c: C) =>
  (...values: DirectiveParameters<InstanceType<C>>): DirectiveResult<C> => ({
    // This property needs to remain unminified.
    ['_$litDirective$']: c,
    values,
  });

/**
 * Base class for creating custom directives. Users should extend this class,
 * implement `render` and/or `update`, and then pass their subclass to
 * `directive`.
 */
export abstract class Directive implements Disconnectable {
  //@internal
  __part!: Part;
  //@internal
  __attributeIndex: number | undefined;
  //@internal
  __directive?: Directive;

  //@internal
  _$parent!: Disconnectable;

  // These will only exist on the AsyncDirective subclass
  //@internal
  _$disconnectableChildren?: Set<Disconnectable>;
  // This property needs to remain unminified.
  //@internal
  ['_$notifyDirectiveConnectionChanged']?(isConnected: boolean): void;

  constructor(_partInfo: PartInfo) {}

  // See comment in Disconnectable interface for why this is a getter
  get _$isConnected() {
    return this._$parent._$isConnected;
  }

  /** @internal */
  _$initialize(
    part: Part,
    parent: Disconnectable,
    attributeIndex: number | undefined
  ) {
    this.__part = part;
    this._$parent = parent;
    this.__attributeIndex = attributeIndex;
  }
  /** @internal */
  _$resolve(part: Part, props: Array<unknown>): unknown {
    return this.update(part, props);
  }

  abstract render(...props: Array<unknown>): unknown;

  update(_part: Part, props: Array<unknown>): unknown {
    return this.render(...props);
  }
}


text:
use lib 'lib';

use IO::Socket;
use RPC::Scarab::Manager;

my $object = Echo->new;

my $server = RPC::Scarab::Manager->new('root' => $object);

print "connect to me on port " . $server->receive_port->sockport . "\n";

$server->run_loop;

######################################################################
###
### This is the class that the client talks to
###

# Echo has one method, `echo'.  `echo' returns it's first argument
# back to the caller.

package Echo;

sub new {
    my $type = shift;

    bless {}, $type;
}

sub echo {
    my $self = shift;
    my $string = shift;

    return $string;
}


text:
package org.daisy.pipeline.braille.common;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.AbstractIterator;

import org.daisy.pipeline.braille.common.Query.Feature;
import org.daisy.pipeline.braille.common.Query.MutableQuery;
import static org.daisy.pipeline.braille.common.Query.util.mutableQuery;
import org.daisy.pipeline.braille.common.util.Function0;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractTransformProvider<T extends Transform> implements TransformProvider<T> {

	private Map<Query,Iterable<T>> transformCache = new HashMap<Query,Iterable<T>>();

	private Map<Logger,TransformProvider<T>> providerCache = new HashMap<Logger,TransformProvider<T>>();

	protected abstract Iterable<T> _get(Query query);

	// WARNING: using "(id:<ID>)" in a query where <ID> is the result of a
	// call to AbstractTransform#getIdentifier() will only work when that
	// transformer came from the exact same provider and its cache is not
	// cleared in the meantime.
	private final java.lang.Iterable<T> get(Query query, Logger context) {
		MutableQuery q = mutableQuery(query);
		if (q.containsKey("id")) {
			Feature f = q.removeOnly("id");
			if (q.isEmpty())
				return Optional.fromNullable(fromId(f.getValue().get())).asSet(); }
		Iterable<T> i;
		if (transformCache.containsKey(query))
			i = transformCache.get(query);
		else {
			// memoize() doesn't make sense
			i = util.Iterables.memoize(_get(query));
			transformCache.put(query, i); }
		return rememberId(i.apply(context));
	}

	public java.lang.Iterable<T> get(Query query) {
		return get(query, null);
	}

	public final TransformProvider<T> withContext(Logger context) {
		if (providerCache.containsKey(context))
			return providerCache.get(context);
		TransformProvider<T> provider = new DerivativeProvider(context);
		providerCache.put(context, provider);
		return provider;
	}

	public void invalidateCache() {
		transformCache.clear();
	}

	public ToStringHelper toStringHelper() {
		return MoreObjects.toStringHelper(this);
	}

	@Override
	public String toString() {
		return toStringHelper().add("context", null).toString();
	}

	private class DerivativeProvider implements TransformProvider<T> {
		private final Logger context;
		private DerivativeProvider(final Logger context) {
			this.context = context;
		}
		public java.lang.Iterable<T> get(Query query) {
			return AbstractTransformProvider.this.get(query, context);
		}
		public TransformProvider<T> withContext(Logger context) {
			return AbstractTransformProvider.this.withContext(context);
		}
		@Override
		public String toString() {
			return AbstractTransformProvider.this.toStringHelper().add("context", context).toString();
		}
	}

	private Map<String,T> fromId = new HashMap<String,T>();

	protected T fromId(String id) {
		return fromId.get(id);
	}

	private java.lang.Iterable<T> rememberId(final java.lang.Iterable<T> iterable) {
		return new java.lang.Iterable<T>() {
			public Iterator<T> iterator() {
				return new Iterator<T>() {
					Iterator<T> i = iterable.iterator();
					public boolean hasNext() {
						return i.hasNext();
					}
					public T next() {
						T t = i.next();
						fromId.put(t.getIdentifier(), t);
						return t;
					}
					public void remove() {
						i.remove();
					}
				};
			}
		};
	}

	protected Function0<Void> provideTemporarily(T t) {
		// assumes t is not in cache yet and is unique to this call
		fromId.put(t.getIdentifier(), t);
		return () -> {
			fromId.remove(t.getIdentifier());
			// also remove from transformCache
			transformCache.remove(mutableQuery().add("id", t.getIdentifier()));
			return null;
		};
	}

	/* -------- */
	/* Iterable */
	/* -------- */

	protected interface Iterable<T> extends WithSideEffect.util.Iterable<T,Logger>,
	                                        java.lang.Iterable<WithSideEffect<T,Logger>> {}

	/* ================== */
	/*       UTILS        */
	/* ================== */

	public static abstract class util {

		/* ------------------------ */
		/* logCreate(), logSelect() */
		/* ------------------------ */

		public static <T extends Transform> WithSideEffect<T,Logger> logCreate(final T t) {
			return new WithSideEffect<T,Logger>() {
				public T _apply() {
					__apply(debug("Created " + t));
					return t; }};
		}

		public static <T extends Transform> Iterable<T> logSelect(final Query query,
		                                                          final TransformProvider<T> provider) {
			// not using provider.withContext() because memoizing only makes sense if sub-providers
			// have no side-effects and provided transformers have no context
			return logSelect(query, provider.withContext(null).get(query));
		}

		public static <T extends Transform> Iterable<T> logSelect(final Query query,
		                                                          final java.lang.Iterable<T> iterable) {
			return Iterables.of(
				new java.lang.Iterable<WithSideEffect<T,Logger>>() {
					public Iterator<WithSideEffect<T,Logger>> iterator() {
						return new Iterator<WithSideEffect<T,Logger>>() {
							Iterator<T> i = iterable.iterator();
							boolean first = true;
							public boolean hasNext() {
								if (i == null)
									return true;
								return i.hasNext();
							}
							public WithSideEffect<T,Logger> next() {
								final T t;
								if (first) {
									first = false;
									try { t = i.next(); }
									catch (final NoSuchElementException e) {
										return new WithSideEffect<T,Logger>() {
											public T _apply() {
												__apply(debug("No match for query " + query));
												throw e;
											}
										};
									}
								} else
									t = i.next();
								return new WithSideEffect<T,Logger>() {
									public T _apply() {
										__apply(info("Selected " + t + " for query " + query));
										return t;
									}
								};
							}
							public void remove() {
								throw new UnsupportedOperationException();
							}
						};
					}
				}
			);
		}

		private static final Logger fallbackLogger = LoggerFactory.getLogger(AbstractTransformProvider.class);

		public static com.google.common.base.Function<Logger,Void> debug(final String message) {
			return new com.google.common.base.Function<Logger,Void>() {
				public Void apply(Logger logger) {
					if (logger != null)
						logger.debug(message);
					else
						fallbackLogger.debug(message);
					return null;
				}
			};
		}

		public static com.google.common.base.Function<Logger,Void> info(final String message) {
			return new com.google.common.base.Function<Logger,Void>() {
				public Void apply(Logger logger) {
					if (logger != null)
						logger.info(message);
					else
						fallbackLogger.debug(message);
					return null;
				}
			};
		}

		public static com.google.common.base.Function<Logger,Void> warn(final String message) {
			return new com.google.common.base.Function<Logger,Void>() {
				public Void apply(Logger logger) {
					if (logger != null)
						logger.warn(message);
					else
						fallbackLogger.debug(message);
					return null;
				}
			};
		}

		/* -------- */
		/* Function */
		/* -------- */

		public static abstract class Function<F,T> extends WithSideEffect.util.Function<F,T,Logger> {}

		/* --------- */
		/* Iterables */
		/* --------- */

		public static abstract class Iterables {

			/* memoize() */

			public static <T> Iterable<T> memoize(Iterable<T> iterable) {
				return of(org.daisy.pipeline.braille.common.util.Iterables.memoize(iterable));
			}

			/* empty() */

			public static <T> Iterable<T> empty() {
				return of(Optional.<WithSideEffect<T,Logger>>absent().asSet());
			}

			/* fromNullable() */

			public static <T> Iterable<T> fromNullable(T element) {
				return of(WithSideEffect.<T,Logger>fromNullable(element));
			}

			/* of() */

			public static <T> Iterable<T> of(T element) {
				return of(WithSideEffect.<T,Logger>of(element));
			}

			public static <T> Iterable<T> of(WithSideEffect<T,Logger> element) {
				return of(Optional.of(element).asSet());
			}

			public static <T> Iterable<T> of(final java.lang.Iterable<WithSideEffect<T,Logger>> iterable) {
				return new Of<T>(iterable);
			}

			private static class Of<T> extends WithSideEffect.util.Iterables.Of<T,Logger> implements Iterable<T> {
				protected Of(java.lang.Iterable<WithSideEffect<T,Logger>> iterable) {
					super(iterable);
				}
				public Iterator<WithSideEffect<T,Logger>> iterator() {
					return iterable.iterator();
				}
			}

			/* transform() */

			public static <F,T> Iterable<T> transform(Iterable<F> from,
			                                          final com.google.common.base.Function<F,T> function) {
				return transform(
					from,
					new Function<F,T>() {
						public T _apply(F from) {
							return function.apply(from);
						}
					}
				);
			}

			public static <F,T> Iterable<T> transform(Iterable<F> from, final Function<F,T> function) {
				return of(
					com.google.common.collect.Iterables.transform(
						from,
						new Function<WithSideEffect<F,Logger>,T>() {
							public T _apply(WithSideEffect<F,Logger> from) {
								return __apply(function.apply(__apply(from)));
							}
						}
					)
				);
			}

			public static <F,T> Iterable<T> transform(final java.lang.Iterable<F> from, final Function<F,T> function) {
				return of(
					com.google.common.collect.Iterables.transform(from, function)
				);
			}

			/* concat() */

			public static <T> Iterable<T> concat(Iterable<T> a, T b) {
				return of(
					com.google.common.collect.Iterables.concat(a, of(b))
				);
			}

			public static <T> Iterable<T> concat(Iterable<T> a, WithSideEffect<T,Logger> b) {
				return of(
					com.google.common.collect.Iterables.concat(a, of(b))
				);
			}

			public static <T> Iterable<T> concat(Iterable<T> a, Iterable<T> b) {
				return of(
					com.google.common.collect.Iterables.concat(a, b)
				);
			}

			public static <T> Iterable<T> concat(final java.lang.Iterable<? extends Iterable<T>> inputs) {
				return of(
					com.google.common.collect.Iterables.concat(inputs)
				);
			}

			public static <T> Iterable<T> concat(final Iterable<? extends Iterable<T>> inputs) {
				return new Concat<T>() {
					protected Iterator<? extends Iterable<T>> iterator(Logger context) {
						return inputs.apply(context).iterator();
					}
					public Iterator<WithSideEffect<T,Logger>> iterator() {
						return new AbstractIterator<WithSideEffect<T,Logger>>() {
							Iterator<? extends WithSideEffect<? extends Iterable<T>,Logger>> iterableIterator = inputs.iterator();
							Iterator<WithSideEffect<T,Logger>> current;
							WithSideEffect<T,Logger> nextEvaluate;
							boolean evaluated = true;
							protected WithSideEffect<T,Logger> computeNext() {
								if (!evaluated)
									throw new RuntimeException("Previous element must be evaluated first");
								if (current != null && current.hasNext())
									return current.next();
								else if (!iterableIterator.hasNext())
									return endOfData();
								nextEvaluate = new WithSideEffect<T,Logger>() {
									public T _apply() throws Throwable {
										if (nextEvaluate == this)
											evaluated = true;
										while (current == null || !current.hasNext()) {
											try {
												current = __apply(iterableIterator.next()).iterator();
												break; }
											catch (WithSideEffect.Exception e) {
												continue; }}
										try {
											return __apply(current.next()); }
										catch (WithSideEffect.Exception e) {
											throw e.getCause(); }
									}
								};
								evaluated = false;
								return nextEvaluate;
							}
						};
					}
				};
			}

			protected static abstract class Concat<T> extends WithSideEffect.util.Iterables.Concat<T,Logger>
			                                          implements Iterable<T> {}

			/* intersection() */

			public static <T> Iterable<T> intersection(Iterable<T> a, Iterable<T> b) {
				return of(
					new java.lang.Iterable<WithSideEffect<T,Logger>>() {
						public Iterator<WithSideEffect<T,Logger>> iterator() {
							return new AbstractIterator<WithSideEffect<T,Logger>>() {
								Iterator<WithSideEffect<T,Logger>> itrA = a.iterator();
								Iterator<WithSideEffect<T,Logger>> itrB = b.iterator();
								Set<T> returned = new HashSet<>();
								Set<T> setB = new HashSet<>();
								protected WithSideEffect<T,Logger> computeNext() {
									if (!itrA.hasNext())
										return endOfData();
									return new WithSideEffect<T,Logger>() {
										public T _apply() throws Throwable {
											while (itrA.hasNext()) {
												T nextA; {
													try {
														nextA = __apply(itrA.next()); }
													catch (WithSideEffect.Exception e) {
														continue; }}
												if (returned.contains(nextA))
													continue;
												if (setB.contains(nextA)) {
													returned.add(nextA);
													return nextA; }
												while (itrB.hasNext())
													try {
														T nextB = __apply(itrB.next());
														setB.add(nextB);
														if (Objects.equal(nextA, nextB)) {
															returned.add(nextA);
															return nextA; }}
													catch (WithSideEffect.Exception e) {}
											}
											throw new NoSuchElementException();
										}
									};
								}
							};
						}
					}
				);
			}
		}
	}
}


text:
package com.amazonaws.services.worklink.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.worklink.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DescribeIdentityProviderConfigurationResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeIdentityProviderConfigurationResultJsonUnmarshaller implements
        Unmarshaller<DescribeIdentityProviderConfigurationResult, JsonUnmarshallerContext> {

    public DescribeIdentityProviderConfigurationResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        DescribeIdentityProviderConfigurationResult describeIdentityProviderConfigurationResult = new DescribeIdentityProviderConfigurationResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return describeIdentityProviderConfigurationResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("IdentityProviderType", targetDepth)) {
                    context.nextToken();
                    describeIdentityProviderConfigurationResult.setIdentityProviderType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ServiceProviderSamlMetadata", targetDepth)) {
                    context.nextToken();
                    describeIdentityProviderConfigurationResult.setServiceProviderSamlMetadata(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("IdentityProviderSamlMetadata", targetDepth)) {
                    context.nextToken();
                    describeIdentityProviderConfigurationResult.setIdentityProviderSamlMetadata(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return describeIdentityProviderConfigurationResult;
    }

    private static DescribeIdentityProviderConfigurationResultJsonUnmarshaller instance;

    public static DescribeIdentityProviderConfigurationResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DescribeIdentityProviderConfigurationResultJsonUnmarshaller();
        return instance;
    }
}


text:
package e2e

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"path/filepath"

	"k8s.io/kubernetes/pkg/api"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/fields"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/util/wait"
	utilyaml "k8s.io/kubernetes/pkg/util/yaml"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

// getLoadBalancerControllers returns a list of LBCtesters.
func getLoadBalancerControllers(repoRoot string, client *client.Client) []LBCTester {
	return []LBCTester{
		&haproxyControllerTester{
			name:   "haproxy",
			cfg:    filepath.Join(repoRoot, "test", "e2e", "testing-manifests", "haproxyrc.yaml"),
			client: client,
		},
	}
}

// getIngManagers returns a list of ingManagers.
func getIngManagers(repoRoot string, client *client.Client) []*ingManager {
	return []*ingManager{
		{
			name:        "netexec",
			rcCfgPaths:  []string{filepath.Join(repoRoot, "test", "e2e", "testing-manifests", "netexecrc.yaml")},
			svcCfgPaths: []string{filepath.Join(repoRoot, "test", "e2e", "testing-manifests", "netexecsvc.yaml")},
			svcNames:    []string{},
			client:      client,
		},
	}
}

// LBCTester is an interface used to test loadbalancer controllers.
type LBCTester interface {
	// start starts the loadbalancer controller in the given namespace
	start(namespace string) error
	// lookup returns the address (ip/hostname) associated with ingressKey
	lookup(ingressKey string) string
	// stop stops the loadbalancer controller
	stop() error
	// name returns the name of the loadbalancer
	getName() string
}

// haproxyControllerTester implements LBCTester for bare metal haproxy LBs.
type haproxyControllerTester struct {
	client      *client.Client
	cfg         string
	rcName      string
	rcNamespace string
	name        string
	address     []string
}

func (h *haproxyControllerTester) getName() string {
	return h.name
}

func (h *haproxyControllerTester) start(namespace string) (err error) {

	// Create a replication controller with the given configuration.
	rc := rcFromManifest(h.cfg)
	rc.Namespace = namespace
	rc.Spec.Template.Labels["rcName"] = rc.Name

	// Add the --namespace arg.
	// TODO: Remove this when we have proper namespace support.
	for i, c := range rc.Spec.Template.Spec.Containers {
		rc.Spec.Template.Spec.Containers[i].Args = append(
			c.Args, fmt.Sprintf("--namespace=%v", namespace))
		Logf("Container args %+v", rc.Spec.Template.Spec.Containers[i].Args)
	}

	rc, err = h.client.ReplicationControllers(rc.Namespace).Create(rc)
	if err != nil {
		return
	}
	if err = waitForRCPodsRunning(h.client, namespace, h.rcName); err != nil {
		return
	}
	h.rcName = rc.Name
	h.rcNamespace = rc.Namespace

	// Find the pods of the rc we just created.
	labelSelector := labels.SelectorFromSet(
		labels.Set(map[string]string{"rcName": h.rcName}))
	pods, err := h.client.Pods(h.rcNamespace).List(
		labelSelector, fields.Everything())
	if err != nil {
		return err
	}

	// Find the external addresses of the nodes the pods are running on.
	for _, p := range pods.Items {
		wait.Poll(pollInterval, serviceRespondingTimeout, func() (bool, error) {
			address, err := getHostExternalAddress(h.client, &p)
			if err != nil {
				Logf("%v", err)
				return false, nil
			}
			h.address = append(h.address, address)
			return true, nil
		})
	}
	if len(h.address) == 0 {
		return fmt.Errorf("No external ips found for loadbalancer %v", h.getName())
	}
	return nil
}

func (h *haproxyControllerTester) stop() error {
	return h.client.ReplicationControllers(h.rcNamespace).Delete(h.rcName)
}

func (h *haproxyControllerTester) lookup(ingressKey string) string {
	// The address of a service is the address of the lb/servicename, currently.
	return fmt.Sprintf("http://%v/%v", h.address[0], ingressKey)
}

// ingManager starts an rc and the associated service.
type ingManager struct {
	rcCfgPaths  []string
	svcCfgPaths []string
	ingCfgPath  string
	name        string
	namespace   string
	client      *client.Client
	svcNames    []string
}

func (s *ingManager) getName() string {
	return s.name
}

func (s *ingManager) start(namespace string) (err error) {
	// Create rcs
	for _, rcPath := range s.rcCfgPaths {
		rc := rcFromManifest(rcPath)
		rc.Namespace = namespace
		rc.Spec.Template.Labels["rcName"] = rc.Name
		rc, err = s.client.ReplicationControllers(rc.Namespace).Create(rc)
		if err != nil {
			return
		}
		if err = waitForRCPodsRunning(s.client, rc.Namespace, rc.Name); err != nil {
			return
		}
	}
	// Create services.
	// Note that it's up to the caller to make sure the service actually matches
	// the pods of the rc.
	for _, svcPath := range s.svcCfgPaths {
		svc := svcFromManifest(svcPath)
		svc.Namespace = namespace
		svc, err = s.client.Services(svc.Namespace).Create(svc)
		if err != nil {
			return
		}
		// TODO: This is short term till we have an Ingress.
		s.svcNames = append(s.svcNames, svc.Name)
	}
	s.name = s.svcNames[0]
	s.namespace = namespace
	return nil
}

func (s *ingManager) test(path string) error {
	url := fmt.Sprintf("%v/hostName", path)
	httpClient := &http.Client{}
	return wait.Poll(pollInterval, serviceRespondingTimeout, func() (bool, error) {
		body, err := simpleGET(httpClient, url, "")
		if err != nil {
			Logf("%v\n%v\n%v", url, body, err)
			return false, nil
		}
		return true, nil
	})
}

var _ = Describe("ServiceLoadBalancer", func() {
	// These variables are initialized after framework's beforeEach.
	var ns string
	var repoRoot string
	var client *client.Client

	framework := NewFramework("servicelb")

	BeforeEach(func() {
		client = framework.Client
		ns = framework.Namespace.Name
		repoRoot = testContext.RepoRoot
	})

	It("should support simple GET on Ingress ips", func() {
		for _, t := range getLoadBalancerControllers(repoRoot, client) {
			By(fmt.Sprintf("Starting loadbalancer controller %v in namespace %v", t.getName(), ns))
			Expect(t.start(ns)).NotTo(HaveOccurred())

			for _, s := range getIngManagers(repoRoot, client) {
				By(fmt.Sprintf("Starting ingress manager %v in namespace %v", s.getName(), ns))
				Expect(s.start(ns)).NotTo(HaveOccurred())

				for _, sName := range s.svcNames {
					path := t.lookup(sName)
					Logf("Testing path %v", path)
					Expect(s.test(path)).NotTo(HaveOccurred())
				}
			}

			Expect(t.stop()).NotTo(HaveOccurred())
		}
	})
})

// simpleGET executes a get on the given url, returns error if non-200 returned.
func simpleGET(c *http.Client, url, host string) (string, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}
	req.Host = host
	res, err := c.Do(req)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	rawBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	body := string(rawBody)
	if res.StatusCode != http.StatusOK {
		err = fmt.Errorf(
			"GET returned http error %v", res.StatusCode)
	}
	return body, err
}

// rcFromManifest reads a .json/yaml file and returns the rc in it.
func rcFromManifest(fileName string) *api.ReplicationController {
	var controller api.ReplicationController
	Logf("Parsing rc from %v", fileName)
	data, err := ioutil.ReadFile(fileName)
	Expect(err).NotTo(HaveOccurred())

	json, err := utilyaml.ToJSON(data)
	Expect(err).NotTo(HaveOccurred())

	Expect(api.Scheme.DecodeInto(json, &controller)).NotTo(HaveOccurred())
	return &controller
}

// svcFromManifest reads a .json/yaml file and returns the rc in it.
func svcFromManifest(fileName string) *api.Service {
	var svc api.Service
	Logf("Parsing service from %v", fileName)
	data, err := ioutil.ReadFile(fileName)
	Expect(err).NotTo(HaveOccurred())

	json, err := utilyaml.ToJSON(data)
	Expect(err).NotTo(HaveOccurred())

	Expect(api.Scheme.DecodeInto(json, &svc)).NotTo(HaveOccurred())
	return &svc
}


text:
Mousetrap is a simple library for handling keyboard shortcuts in Javascript.

It is licensed under the Apache 2.0 license.

It is around **2kb** minified and gzipped and **4.5kb** minified, has no external dependencies, and has been tested in the following browsers:

- Internet Explorer 6+
- Safari
- Firefox
- Chrome

It has support for ``keypress``, ``keydown``, and ``keyup`` events on specific keys, keyboard combinations, or key sequences.

## Getting started

1.  Include mousetrap on your page before the closing ```` tag

    ```html
    <script src="/path/to/mousetrap.min.js"></script>
    ```

2.  Add some keyboard events to listen for

    ```html
    <script>
        // single keys
        Mousetrap.bind('4', function() { console.log('4'); });
        Mousetrap.bind("?", function() { console.log('show shortcuts!'); });
        Mousetrap.bind('esc', function() { console.log('escape'); }, 'keyup');

        // combinations
        Mousetrap.bind('command+shift+k', function() { console.log('command shift k'); });

        // map multiple combinations to the same callback
        Mousetrap.bind(['command+k', 'ctrl+k'], function() {
            console.log('command k or control k');

            // return false to prevent default browser behavior
            // and stop event from bubbling
            return false;
        });

        // gmail style sequences
        Mousetrap.bind('g i', function() { console.log('go to inbox'); });
        Mousetrap.bind('* a', function() { console.log('select all'); });

        // konami code!
        Mousetrap.bind('up up down down left right left right b a enter', function() {
            console.log('konami code');
        });
    </script>
    ```

## Why Mousetrap?

There are a number of other similar libraries out there so what makes this one different?

- There are no external dependencies, no framework is required
- You are not limited to ``keydown`` events (You can specify ``keypress``, ``keydown``, or ``keyup`` or let Mousetrap choose for you).
- You can bind key events directly to special keys such as ``?`` or ``*`` without having to specify ``shift+/`` or ``shift+8`` which are not consistent across all keyboards
- It works with international keyboard layouts
- You can bind Gmail like key sequences in addition to regular keys and key combinations
- You can programatically trigger key events with the ``trigger()`` method
- It works with the numeric keypad on your keyboard
- The code is well documented/commented

## Tests

Unit tests run via mocha.

### Running in browser

[View it online](http://rawgit.com/ccampbell/mousetrap/master/tests/mousetrap.html) to check your browser compatibility. You may also download the repo and open `tests/mousetrap.html` in your browser.

### Running with Grunt and PhantomJS

1.  Install grunt-cli

    ```bash
    npm install -g grunt-cli
    ```

2.  Install npm packages

    ```bash
    cd /path/to/repo
    npm install
    ```

3.  Run tests

    ```bash
    grunt mocha
    ```

## Documentation

Full documentation can be found at https://craig.is/killing/mice


text:
from __future__ import print_function
import contextlib
import errno
import functools
import logging
import multiprocessing
import os
import shutil
import socket
import sys
import tempfile
import threading
import time
try:
    from unittest import mock  # py3
except ImportError:
    import mock  # NOQA - requires "pip install mock"

from pyftpdlib._compat import getcwdu
from pyftpdlib._compat import u
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import _import_sendfile
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.ioloop import IOLoop
from pyftpdlib.servers import FTPServer

import psutil

if sys.version_info < (2, 7):
    import unittest2 as unittest  # pip install unittest2
else:
    import unittest

if not hasattr(unittest.TestCase, "assertRaisesRegex"):
    unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp

sendfile = _import_sendfile()

# Attempt to use IP rather than hostname (test suite will run a lot faster)
try:
    HOST = socket.gethostbyname('localhost')
except socket.error:
    HOST = 'localhost'
USER = 'user'
PASSWD = '12345'
HOME = getcwdu()
TESTFN = 'tmp-pyftpdlib'
TESTFN_UNICODE = TESTFN + '-unicode-' + '\xe2\x98\x83'
TESTFN_UNICODE_2 = TESTFN_UNICODE + '-2'
TIMEOUT = 2
BUFSIZE = 1024
INTERRUPTED_TRANSF_SIZE = 32768
NO_RETRIES = 5
OSX = sys.platform.startswith("darwin")
POSIX = os.name == 'posix'
WINDOWS = os.name == 'nt'
TRAVIS = bool(os.environ.get('TRAVIS'))
VERBOSITY = 1 if os.getenv('SILENT') else 2

class TestCase(unittest.TestCase):

    def __str__(self):
        return "%s.%s.%s" % (
            self.__class__.__module__, self.__class__.__name__,
            self._testMethodName)

# Hack that overrides default unittest.TestCase in order to print
# a full path representation of the single unit tests being run.
unittest.TestCase = TestCase

def close_client(session):
    """Closes a ftplib.FTP client session."""
    try:
        if session.sock is not None:
            try:
                resp = session.quit()
            except Exception:
                pass
            else:
                # ...just to make sure the server isn't replying to some
                # pending command.
                assert resp.startswith('221'), resp
    finally:
        session.close()

def try_address(host, port=0, family=socket.AF_INET):
    """Try to bind a socket on the given host:port and return True
    if that has been possible."""
    try:
        with contextlib.closing(socket.socket(family)) as sock:
            sock.bind((host, port))
    except (socket.error, socket.gaierror):
        return False
    else:
        return True

SUPPORTS_IPV4 = try_address('127.0.0.1')
SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
SUPPORTS_SENDFILE = hasattr(os, 'sendfile') or sendfile is not None

def safe_remove(*files):
    "Convenience function for removing temporary test files"
    for file in files:
        try:
            os.remove(file)
        except OSError as err:
            if os.name == 'nt':
                return
            if err.errno != errno.ENOENT:
                raise

def safe_rmdir(dir):
    "Convenience function for removing temporary test directories"
    try:
        os.rmdir(dir)
    except OSError as err:
        if os.name == 'nt':
            return
        if err.errno != errno.ENOENT:
            raise

def safe_mkdir(dir):
    "Convenience function for creating a directory"
    try:
        os.mkdir(dir)
    except OSError as err:
        if err.errno != errno.EEXIST:
            raise

def touch(name):
    """Create a file and return its name."""
    with open(name, 'w') as f:
        return f.name

def remove_test_files():
    """Remove files and directores created during tests."""
    for name in os.listdir(u('.')):
        if name.startswith(tempfile.template):
            if os.path.isdir(name):
                shutil.rmtree(name)
            else:
                safe_remove(name)

def configure_logging():
    """Set pyftpdlib logger to "WARNING" level."""
    channel = logging.StreamHandler()
    logger = logging.getLogger('pyftpdlib')
    logger.setLevel(logging.WARNING)
    logger.addHandler(channel)

def disable_log_warning(fun):
    """Temporarily set FTP server's logging level to ERROR."""
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        logger = logging.getLogger('pyftpdlib')
        level = logger.getEffectiveLevel()
        logger.setLevel(logging.ERROR)
        try:
            return fun(self, *args, **kwargs)
        finally:
            logger.setLevel(level)
    return wrapper

def cleanup():
    """Cleanup function executed on interpreter exit."""
    remove_test_files()
    map = IOLoop.instance().socket_map
    for x in list(map.values()):
        try:
            sys.stderr.write("garbage: %s\n" % repr(x))
            x.close()
        except Exception:
            pass
    map.clear()

def retry_on_failure(ntimes=None):
    """Decorator to retry a test in case of failure."""
    def decorator(fun):
        @functools.wraps(fun)
        def wrapper(*args, **kwargs):
            for x in range(ntimes or NO_RETRIES):
                try:
                    return fun(*args, **kwargs)
                except AssertionError as _:
                    err = _
            raise err
        return wrapper
    return decorator

def call_until(fun, expr, timeout=TIMEOUT):
    """Keep calling function for timeout secs and exit if eval()
    expression is True.
    """
    stop_at = time.time() + timeout
    while time.time() < stop_at:
        ret = fun()
        if eval(expr):
            return ret
        time.sleep(0.001)
    raise RuntimeError('timed out (ret=%r)' % ret)

def get_server_handler():
    """Return the first FTPHandler instance running in the IOLoop."""
    ioloop = IOLoop.instance()
    for fd in ioloop.socket_map:
        instance = ioloop.socket_map[fd]
        if isinstance(instance, FTPHandler):
            return instance
    raise RuntimeError("can't find any FTPHandler instance")

# commented out as per bug http://bugs.python.org/issue10354
# tempfile.template = 'tmp-pyftpdlib'

def setup_server(handler, server_class, addr=None):
    addr = (HOST, 0) if addr is None else addr
    authorizer = DummyAuthorizer()
    # full perms
    authorizer.add_user(USER, PASSWD, HOME, perm='elradfmwMT')
    authorizer.add_anonymous(HOME)
    handler.authorizer = authorizer
    handler.auth_failed_timeout = 0.001
    # lower buffer sizes = more "loops" while transfering data
    # = less false positives
    handler.dtp_handler.ac_in_buffer_size = 4096
    handler.dtp_handler.ac_out_buffer_size = 4096
    server = server_class(addr, handler)
    return server

def assert_free_resources():
    ts = threading.enumerate()
    assert len(ts) == 1, ts
    p = psutil.Process()
    children = p.children()
    if children:
        for p in children:
            p.kill()
            p.wait(1)
        assert not children, children
    cons = [x for x in p.connections('tcp')
            if x.status != psutil.CONN_CLOSE_WAIT]
    assert not cons, cons

def reset_server_opts():
    # Since all pyftpdlib configurable "options" are class attributes
    # we reset them at module.class level.
    import pyftpdlib.handlers
    import pyftpdlib.servers
    from pyftpdlib.handlers import _import_sendfile

    # Control handlers.
    tls_handler = getattr(pyftpdlib.handlers, "TLS_FTPHandler",
                          pyftpdlib.handlers.FTPHandler)
    for klass in (pyftpdlib.handlers.FTPHandler, tls_handler):
        klass.auth_failed_timeout = 0.001
        klass.authorizer = DummyAuthorizer()
        klass.banner = "pyftpdlib ready."
        klass.masquerade_address = None
        klass.masquerade_address_map = {}
        klass.max_login_attempts = 3
        klass.passive_ports = None
        klass.permit_foreign_addresses = False
        klass.permit_privileged_ports = False
        klass.tcp_no_delay = hasattr(socket, 'TCP_NODELAY')
        klass.timeout = 300
        klass.unicode_errors = "replace"
        klass.use_gmt_times = True
        klass.use_sendfile = _import_sendfile() is not None
        klass.ac_in_buffer_size = 4096
        klass.ac_out_buffer_size = 4096
        if klass.__name__ == 'TLS_FTPHandler':
            klass.tls_control_required = False
            klass.tls_data_required = False

    # Data handlers.
    tls_handler = getattr(pyftpdlib.handlers, "TLS_DTPHandler",
                          pyftpdlib.handlers.DTPHandler)
    for klass in (pyftpdlib.handlers.DTPHandler, tls_handler):
        klass.timeout = 300
        klass.ac_in_buffer_size = 4096
        klass.ac_out_buffer_size = 4096
    pyftpdlib.handlers.ThrottledDTPHandler.read_limit = 0
    pyftpdlib.handlers.ThrottledDTPHandler.write_limit = 0
    pyftpdlib.handlers.ThrottledDTPHandler.auto_sized_buffers = True

    # Acceptors.
    ls = [pyftpdlib.servers.FTPServer,
          pyftpdlib.servers.ThreadedFTPServer]
    if os.name == 'posix':
        ls.append(pyftpdlib.servers.MultiprocessFTPServer)
    for klass in ls:
        klass.max_cons = 0
        klass.max_cons_per_ip = 0

class ThreadedTestFTPd(threading.Thread):
    """A threaded FTP server used for running tests.
    This is basically a modified version of the FTPServer class which
    wraps the polling loop into a thread.
    The instance returned can be start()ed and stop()ped.
    """
    handler = FTPHandler
    server_class = FTPServer
    poll_interval = 0.001 if TRAVIS else 0.000001
    # Makes the thread stop on interpreter exit.
    daemon = True

    def __init__(self, addr=None):
        super(ThreadedTestFTPd, self).__init__(name='test-ftpd')
        self.server = setup_server(self.handler, self.server_class, addr=addr)
        self.host, self.port = self.server.socket.getsockname()[:2]

        self.lock = threading.Lock()
        self._stop_flag = False
        self._event_stop = threading.Event()

    def run(self):
        try:
            while not self._stop_flag:
                with self.lock:
                    self.server.serve_forever(timeout=self.poll_interval,
                                              blocking=False)
        finally:
            self._event_stop.set()

    def stop(self):
        self._stop_flag = True  # signal the main loop to exit
        self._event_stop.wait()
        self.server.close_all()
        self.join()
        reset_server_opts()
        assert_free_resources()

class MProcessTestFTPd(multiprocessing.Process):
    """Same as above but using a sub process instead."""
    handler = FTPHandler
    server_class = FTPServer

    def __init__(self, addr=None):
        super(MProcessTestFTPd, self).__init__(name='test-ftpd')
        self.server = setup_server(self.handler, self.server_class, addr=addr)
        self.host, self.port = self.server.socket.getsockname()[:2]
        self._started = False

    def run(self):
        assert not self._started
        self._started = True
        self.server.serve_forever()

    def stop(self):
        self.server.close_all()
        self.terminate()
        self.join()
        reset_server_opts()
        assert_free_resources()


text:
import asyncio, json, utils
from asyncio_redis import Pool
from aiohttp import web
from os import path

from mivb import Model, Operator, Line, Route, RoutePresent, Stop

HOME_FILE = path.join(path.dirname(__file__), 'index.html')
STATIC_PATH = path.join(path.dirname(__file__), 'static')

class Aerial:
    def __init__(self, loop, address='127.0.0.1', port=8080):
        self.loop = loop
        self.address = address
        self.port = port
        self.sockets = []
        self.app = web.Application(loop=self.loop)
        self.app.router.add_static('/static/', STATIC_PATH)
        self.app.router.add_route('GET', '/', self.homehandler)
        self.app.router.add_route('GET', '/lines/', self.lineshandler)
        self.app.router.add_route('GET', '/present/', self.presenthandler)
        self.app.router.add_route('GET', '/socket/', self.sockethandler)
        self.srv_handler = self.app.make_handler()

    @asyncio.coroutine
    def run(self):
        self.srv = yield from self.loop.create_server(self.srv_handler,
                                                      self.address, self.port)
        self.redis = yield from Pool.create(poolsize=100)
        Model.redis = self.redis
        self.mivb = Operator()

        for line in (yield from self.mivb):
            for route in (yield from line):
                # TODO: Gracefully cancel tasks when killing the serever
                asyncio.async(utils.run_periodically(route.update, 5, 5))

        print('Running server on http://%s:%s' % (self.address, self.port))

    @asyncio.coroutine
    def finish(self):
        yield from self.srv_handler.finish_connections()
        self.srv.close()
        yield from self.srv.wait_closed()

        Model.redis.close()
        yield # Hack to avoid bug in asyncio_redis

    @asyncio.coroutine
    def homehandler(self, request):
        with open(HOME_FILE, 'rb') as f:
            return web.Response(body=f.read(), content_type='text/html')

    @asyncio.coroutine
    def lineshandler(self, request):
        lines_list = [((yield from line.get('id')), (yield from line.getall()))
                      for line in (yield from self.mivb)]
        lines_dict = dict((yield from lines_list))
        body = json.dumps(lines_dict).encode('utf-8')
        return web.Response(body=body, content_type='application/javascript')

    @asyncio.coroutine
    def presenthandler(self, request):
        present = []

        for line in (yield from self.mivb):
            for route in (yield from line):
                for stop in (yield from RoutePresent(route)):
                    present.append({'line': (yield from line.get('id')),
                                    'route': (yield from route.getall()),
                                    'stop': (yield from stop.getall())})

        body = json.dumps(present).encode('utf-8')

        return web.Response(body=body, content_type='application/javascript')

    @asyncio.coroutine
    def sockethandler(self, request):
        response = web.WebSocketResponse()
        ok, protocol = response.can_start(request)

        if not ok:
            return web.Response(status=404)

        response.start(request)
        self.sockets.append(response)

        subscriber = yield from self.redis.start_subscribe()
        yield from subscriber.subscribe(['mivb'])

        while True:
            reply = yield from subscriber.next_published()
            response.send_str(reply.value)

        return response

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    aerial = Aerial(loop)
    loop.run_until_complete(aerial.run())

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete(aerial.finish())


text:
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api.urlfetch import DownloadError

from library import loginelb
from library import login

class DeleteLoadBalancer(webapp.RequestHandler):
    def get(self):
        mobile = self.request.get('mobile')
        if mobile != "true":
            mobile = "false"
        # Name des zu löschenden Load Balancers holen
        name = self.request.get('name')
        # Den Usernamen erfahren
        username = users.get_current_user()

        conn_region, regionname = login(username)
        # Mit ELB verbinden
        conn_elb = loginelb(username)

        try:
          # Volume löschen
          conn_elb.delete_load_balancer(name)
        except EC2ResponseError:
          # Wenn es nicht klappt...
          fehlermeldung = "71"
          self.redirect('/loadbalancer?mobile='+str(mobile)+'&message='+fehlermeldung)
        except DownloadError:
          # Diese Exception hilft gegen diese beiden Fehler:
          # DownloadError: ApplicationError: 2 timed out
          # DownloadError: ApplicationError: 5
          fehlermeldung = "8"
          self.redirect('/loadbalancer?mobile='+str(mobile)+'&message='+fehlermeldung)
        else:
          # Wenn es geklappt hat...
          fehlermeldung = "70"
          self.redirect('/loadbalancer?mobile='+str(mobile)+'&message='+fehlermeldung)


text:
class PublicOwner < ActiveRecord::Base
   include ActiveRecord::Singleton

   has_many :documents, :as => 'owner'
   has_many :published_documents, :as => 'owner', :conditions => {:published => true}, :class_name => 'Document'
   has_many :faqs, :as => 'owner'
   has_many :published_faqs, :as => 'owner', :conditions => {:published => true}, :class_name => 'Faq'

   def name
     "Public Owner"
   end

#   def add_an_avatar(filename)
#     basename = File.basename(filename)
#     unless avatars.find_by_image_filename(basename)
#      a = avatars.create!(:image_file => File.new(filename, 'rb'))
#      a.image_filename = basename
#      a.save
#     end
#   end
#
#   def self.default_avatar_ids
#     @_default_avatar_ids ||= self.instance.avatar_ids
#   end
#
#   def self.avatar_id_for(i)
#     default_avatar_ids[ i % default_avatar_ids.size ]
#   end
#
#
#   def pic_id
#     avatar_ids.last
#   end
#
#  def pic
#    Avatar.find(pic_id)
#  end

end


text:
<?php

Class User extends Model{

    public function getByLogin($login){
        $login = $this->db->escape($login);
        $sql = "select * from users where login = '{$login}' limit 1 ";
        $result = $this->db->query($sql);

        if( isset($result[0]) ){
            return $result[0];
        }

        return false;
    }

}


text:
namespace OPS
{
	namespace Shared
	{
		OPS::Reprise::SubroutineDeclaration* findSubroutineWithImplementationByName(OPS::Reprise::ProgramUnit* pProgramUnit, std::string subroutineName);

		OPS::Reprise::SubroutineDeclaration* findSubroutineWithImplementationByName(OPS::Reprise::TranslationUnit* pTranslationUnit, std::string subroutineName);

		OPS::Reprise::SubroutineDeclaration* findSubroutineByName(OPS::Reprise::TranslationUnit* pTranslationUnit, std::string subroutineName);

		OPS::Reprise::TranslationUnit* getTranslationUnitBySubroutineDeclaration(OPS::Reprise::SubroutineDeclaration* pSubroutineDeclaration);

		OPS::Reprise::SubroutineDeclaration* getSubroutineDeclarationByStatement(OPS::Reprise::StatementBase* pStatement);

		OPS::Reprise::TypeDeclaration* findTypeDeclarationByName(OPS::Reprise::TranslationUnit* ptranslationUnit, std::string typeName);

		OPS::Reprise::TypeBase* findDeclaredTypeByName(OPS::Reprise::TranslationUnit* ptranslationUnit, std::string typeName);

        OPS::Reprise::TypeBase* getArgumentPointedType(OPS::Reprise::SubroutineDeclaration* pSubroutineDeclaration, int argumentIndex);
	}
}

#endif


text:
enum statement_type {
    STMT_NULL = 0,
    STMT_INVALID = 37,

    STMT_COMPOUND,
    STMT_DECLARATION,
    STMT_EXPR,
    STMT_IF,
    STMT_IF_ELSE,
    STMT_WHILE,
    STMT_DO_WHILE,
    STMT_FOR,
    STMT_GOTO,
    STMT_BREAK,
    STMT_CONTINUE,
    STMT_LABEL,
    STMT_CASE,
    STMT_DEFAULT,
    STMT_RETURN,
};

struct statement {
    magic_t magic;
    enum statement_type statement_type;
    void (*codegen) (struct statement *);
    char *code;

    union {
        const struct list *stmt_list; // for compound
        const struct list *symbol_list; // for declaration
        const struct expression *expr;  // return / expression statement
        struct {
            const struct expression *if_cond; // if
            const struct statement *then;
            const struct statement *eelse;
        };
        struct {
            const struct expression *init;      // loops
            const struct expression *loop_cond;
            const struct expression *next;
            const struct statement *body;
        };
        struct {
            char *label;
            struct statement *labeled_stmt;
        };
        struct {
            const struct expression *const_expr;
            struct statement *case_stmt;
        };
        struct statement *default_stmt;
    };
};

const char *decl_init_list(const struct list *decl_list);

struct statement *stmt_void(void);
struct statement *stmt_expression(const struct expression *expr);
struct statement *stmt_declaration(struct list *declarator_list);

struct statement *stmt_compound(const struct list *stmts);

struct statement *stmt_if(const struct expression *cond,
                          const struct statement *then);

struct statement *stmt_if_else(const struct expression *cond,
                               const struct statement *then,
                               const struct statement *eelse);
struct statement *stmt_for(const struct expression *init,
                           const struct expression *cond,
                           const struct expression *next,
                           const struct statement *body);

struct statement *stmt_while(const struct expression *cond,
                             const struct statement *body);

struct statement *stmt_do_while(const struct expression *cond,
                                const struct statement *body);

struct statement *stmt_return(const struct expression *expr);
struct statement *stmt_continue(void);
struct statement *stmt_break(void);
struct statement *stmt_goto(const char *label);
struct statement *stmt_switch(const struct expression *test,
                              const struct statement *body);

struct statement *stmt_label(struct statement *stmt, const char *label);
struct statement *stmt_case(struct statement *stmt,
                            const struct expression *const_expr);
struct statement *stmt_default(struct statement *stmt);

#endif // BCC_STATEMENT_H


text:
// @flow
import deepmerge from 'deepmerge';
import is from 'is-lite';

import { getElement, hasCustomScrollParent } from './dom';
import { log } from './helpers';
import getStyles from '../styles';

import DEFAULTS from '../config/defaults';

function getTourProps(props: Object): Object {
  const sharedTourProps = [
    'beaconComponent',
    'disableCloseOnEsc',
    'disableOverlay',
    'disableOverlayClose',
    'disableScrolling',
    'disableScrollParentFix',
    'floaterProps',
    'hideBackButton',
    'hideCloseButton',
    'locale',
    'showProgress',
    'showSkipButton',
    'spotlightClicks',
    'spotlightPadding',
    'styles',
    'tooltipComponent',
  ];

  return Object.keys(props)
    .filter(d => sharedTourProps.includes(d))
    .reduce((acc, i) => {
      acc[i] = props[i]; //eslint-disable-line react/destructuring-assignment

      return acc;
    }, {});
}

export function getMergedStep(step: StepProps, props: JoyrideProps): ?StepProps {
  if (!step) return null;

  const mergedStep = deepmerge.all([getTourProps(props), DEFAULTS.step, step], {
    isMergeableObject: is.plainObject,
  });
  const mergedStyles = getStyles(deepmerge(props.styles || {}, step.styles || {}));
  const scrollParent = hasCustomScrollParent(
    getElement(step.target),
    mergedStep.disableScrollParentFix,
  );
  const floaterProps = deepmerge.all([
    props.floaterProps || {},
    DEFAULTS.floaterProps,
    mergedStep.floaterProps || {},
  ]);

  // Set react-floater props
  floaterProps.offset = mergedStep.offset;
  floaterProps.styles = deepmerge(floaterProps.styles || {}, mergedStyles.floaterStyles || {});

  delete mergedStyles.floaterStyles;

  floaterProps.offset += props.spotlightPadding || step.spotlightPadding || 0;

  if (step.placementBeacon) {
    floaterProps.wrapperOptions.placement = step.placementBeacon;
  }

  if (scrollParent) {
    floaterProps.options.preventOverflow.boundariesElement = 'window';
  }

  return {
    ...mergedStep,
    locale: deepmerge.all([DEFAULTS.locale, props.locale || {}, mergedStep.locale || {}]),
    floaterProps,
    styles: mergedStyles,
  };
}

/**
 * Validate if a step is valid
 *
 * @param {Object} step - A step object
 * @param {boolean} debug
 *
 * @returns {boolean} - True if the step is valid, false otherwise
 */
export function validateStep(step: StepProps, debug: boolean = false): boolean {
  if (!is.plainObject(step)) {
    log({
      title: 'validateStep',
      data: 'step must be an object',
      warn: true,
      debug,
    });
    return false;
  }

  if (!step.target) {
    log({
      title: 'validateStep',
      data: 'target is missing from the step',
      warn: true,
      debug,
    });
    return false;
  }

  return true;
}

/**
 * Validate if steps is valid
 *
 * @param {Array} steps - A steps array
 * @param {boolean} debug
 *
 * @returns {boolean} - True if the steps are valid, false otherwise
 */
export function validateSteps(steps: Array<Object>, debug: boolean = false): boolean {
  if (!is.array(steps)) {
    log({
      title: 'validateSteps',
      data: 'steps must be an array',
      warn: true,
      debug,
    });

    return false;
  }

  return steps.every(d => validateStep(d, debug));
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2013, The Sporting Exchange Limited
  ~
  ~ 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.
  -->

<!DOCTYPE beans PUBLIC  "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans default-autowire="no">

    <bean id="monitorA" class="com.betfair.tornjak.monitor.DefaultMonitor">
        <constructor-arg index="0" value="monitorA" />
    </bean>

    <bean id="monitorB" class="com.betfair.tornjak.monitor.DefaultMonitor">
        <constructor-arg index="0" value="monitorB" />
    </bean>

    <bean id="monitorC" class="com.betfair.tornjak.monitor.DefaultMonitor">
        <constructor-arg index="0" value="monitorC" />
    </bean>

    <bean id="reg" class="com.betfair.tornjak.monitor.DefaultMonitorRegistry" />

</beans>


text:
package edwardwang.bouncingball.Interaction.EScreenBlock;

import android.content.Context;
import android.view.View;

import edwardwang.bouncingball.Interaction.InteractionSetup;
import edwardwang.bouncingball.PhysicsEngine.Vector.Vector3DInt;

/**
 * Before any further development, find if this would be valuable for devs
 *
 * Set the number of screen blocks before calling setupSensors. By default
 * there will always be one screen block.
 * Created by edwardwang on 8/8/16.
 */
public class EScreenBlockManager implements InteractionSetup{

    private Context context;
    private View view;

    private int[][] screenBlockList;
    private int numOfScreenBlocksWidth = 1;
    private int numOfScreenBlocksHeight = 1;

    //ScreenBlock settings
    private int screenWidth;
    private int screenHeight;
    private Vector3DInt screenBlockSize;
    private Vector3DInt screenBlockPosition;

    public EScreenBlockManager(Context context, View view){
        this.context = context;
        this.view = view;
    }

    public void setNumOfScreenBlocks(int numOfScreenBlocksWidth,
                                     int numOfScreenBlocksHeight){
        this.numOfScreenBlocksWidth = numOfScreenBlocksWidth;
        this.numOfScreenBlocksHeight = numOfScreenBlocksHeight;
        screenBlockList = new int[numOfScreenBlocksWidth][numOfScreenBlocksHeight];
    }

    @Override
    public void setupInteraction() {

    }

    //////////////////////////////////////////////////////////////////
    private void calcScreenBlockWidthAndHeight(){

    }

    //////////////////////////////////////////////////////////////////
    //Getter
}


text:
package io.druid.query.topn;

import io.druid.query.aggregation.BufferAggregator;
import io.druid.segment.Cursor;
import io.druid.segment.DimensionSelector;
import io.druid.segment.data.IndexedInts;

import java.nio.ByteBuffer;

public final class Generic2AggPooledTopNScannerPrototype implements Generic2AggPooledTopNScanner
{
  /**
   * Any changes to this method should be coordinated with {@link TopNUtils}, {@link
   * PooledTopNAlgorithm#computeSpecializedScanAndAggregateImplementations} and downstream methods.
   *
   * It should be checked with a tool like https://github.com/AdoptOpenJDK/jitwatch that C2 compiler output for this
   * method doesn't have any method calls in the while loop, i. e. all method calls are inlined. To be able to see
   * assembly of this method in JITWatch and other similar tools, {@link
   * PooledTopNAlgorithm#specializeGeneric2AggPooledTopN} should be turned off. Note that in this case the benchmark
   * should be "naturally monomorphic", i. e. execute this method always with the same runtime shape.
   *
   * If the while loop contains not inlined method calls, it should be considered as a performance bug.
   */
  @Override
  public long scanAndAggregate(
      DimensionSelector dimensionSelector,
      BufferAggregator aggregator1,
      int aggregator1Size,
      BufferAggregator aggregator2,
      int aggregator2Size,
      Cursor cursor,
      int[] positions,
      ByteBuffer resultsBuffer
  )
  {
    int totalAggregatorsSize = aggregator1Size + aggregator2Size;
    long processedRows = 0;
    int positionToAllocate = 0;
    while (!cursor.isDoneOrInterrupted()) {
      final IndexedInts dimValues = dimensionSelector.getRow();
      final int dimSize = dimValues.size();
      for (int i = 0; i < dimSize; i++) {
        int dimIndex = dimValues.get(i);
        int position = positions[dimIndex];
        if (position >= 0) {
          aggregator1.aggregate(resultsBuffer, position);
          aggregator2.aggregate(resultsBuffer, position + aggregator1Size);
        } else if (position == TopNAlgorithm.INIT_POSITION_VALUE) {
          positions[dimIndex] = positionToAllocate;
          position = positionToAllocate;
          aggregator1.init(resultsBuffer, position);
          aggregator1.aggregate(resultsBuffer, position);
          position += aggregator1Size;
          aggregator2.init(resultsBuffer, position);
          aggregator2.aggregate(resultsBuffer, position);
          positionToAllocate += totalAggregatorsSize;
        }
      }
      processedRows++;
      cursor.advanceUninterruptibly();
    }
    return processedRows;
  }
}


text:
package com.dremio.dac.util;

import static java.util.Arrays.asList;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Set;

import com.dremio.common.SentinelSecure;
import com.dremio.common.logical.FormatPluginConfigBase;
import com.dremio.common.logical.StoragePluginConfigBase;
import com.dremio.common.logical.data.LogicalOperatorBase;
import com.dremio.common.scanner.persistence.ScanResult;
import com.dremio.dac.explore.model.ExpressionBase;
import com.dremio.dac.explore.model.ExtractListRuleBase;
import com.dremio.dac.explore.model.FieldTransformationBase;
import com.dremio.dac.explore.model.FilterBase;
import com.dremio.dac.explore.model.FromBase;
import com.dremio.dac.explore.model.TransformBase;
import com.dremio.dac.model.common.Acceptor;
import com.dremio.dac.proto.model.dataset.Order;
import com.dremio.dac.proto.model.dataset.TransformConvertCase;
import com.dremio.dac.proto.model.dataset.TransformSorts;
import com.dremio.dac.server.SentinelSecureFilter;
import com.dremio.dac.server.socket.SocketMessage;
import com.dremio.datastore.Converter;
import com.dremio.exec.catalog.ConnectionReader;
import com.dremio.exec.catalog.conf.ConnectionConf;
import com.dremio.service.users.SimpleUser;
import com.dremio.service.users.User;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MappingJsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

/**
 * turn stuff into pretty JSON
 */
public class JSONUtil {

  /**
   * default indent output represents arrays on one line
   * so we want more than just mapper.enable(SerializationFeature.INDENT_OUTPUT);
   */
  private static final class PrettyPrintMappingJsonFactory extends MappingJsonFactory {
    private final DefaultPrettyPrinter pp;
    private static final long serialVersionUID = 1L;

    private PrettyPrintMappingJsonFactory() {
      this.pp = new DefaultPrettyPrinter();
      pp.indentArraysWith(new DefaultIndenter());
    }

    @Override
    public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException {
      JsonGenerator generator = super.createGenerator(out, enc);
      generator.setPrettyPrinter(pp);
      return generator;
    }

    @Override
    public PrettyPrintMappingJsonFactory copy() {
      return new PrettyPrintMappingJsonFactory();
    }
  }

  private static final ObjectMapper PRETTY_MAPPER = new ObjectMapper(new PrettyPrintMappingJsonFactory());
  private static final ObjectMapper INLINE_MAPPER = new ObjectMapper();

  static {
    for (ObjectMapper m : asList(INLINE_MAPPER, PRETTY_MAPPER)) {
      // omit fields when they are null
      m.setFilterProvider(new SimpleFilterProvider().addFilter(SentinelSecure.FILTER_NAME, SentinelSecureFilter.SECURE));
      m.setSerializationInclusion(Include.NON_NULL);
      m.registerSubtypes(SocketMessage.getImplClasses());
      m.registerModule(new SimpleModule().addAbstractTypeMapping(User.class, SimpleUser.class));
      // Turns out you can annotate generated classes using mixins!
      m.addMixIn(TransformConvertCase.class, TransformConvertCaseMixin.class);
      m.addMixIn(TransformSorts.class, TransformSortsMixin.class);
      //m.addMixIn(UnknownConfig.class, UnknownConfigMixIn.class);
      Acceptor<?, ?, ?>[] acceptors = {
          ExpressionBase.acceptor,
          ExtractListRuleBase.acceptor,
          FieldTransformationBase.acceptor,
          FilterBase.acceptor,
          FromBase.acceptor,
          TransformBase.acceptor
      };
      for (Acceptor<?, ?, ?> acceptor : acceptors) {
        m.registerModule(newWrappingModule(acceptor));
      }
    }
  }

  private static <C, W> SimpleModule newWrappingModule(Acceptor<C, ?, W> acceptor) {
    return newWrappingModule(acceptor.getBaseType(), acceptor.getWrapperType(), acceptor.converter());
  }

  private static <T1, T2> SimpleModule newWrappingModule(final Class<T1> wrapped, final Class<T2> wrapper, final Converter<T1, T2> converter) {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(wrapper, new JsonDeserializer<T2>() {
      @Override
      public T2 deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return converter.convert(ctxt.readValue(p, wrapped));
      }
    });
    module.addSerializer(wrapper, new JsonSerializer<T2>() {
      @Override
      public void serialize(T2 value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        serializers.defaultSerializeValue(converter.revert(value), gen);
      }
    });
    return module;
  }

  private interface TransformConvertCaseMixin {
    @JsonProperty("case") String getConvertCase();
  }

  private interface TransformSortsMixin {
    @JsonProperty("columns") List<Order> getColumnsList();
  }

  public static ObjectMapper prettyMapper() {
    return PRETTY_MAPPER.copy();
  }

  public static ObjectMapper mapper() {
    return INLINE_MAPPER.copy();
  }

  public static ObjectMapper registerStorageTypes(ObjectMapper mapper, ScanResult scanResult, ConnectionReader connectionReader) {
    registerSubtypes(mapper, LogicalOperatorBase.getSubTypes(scanResult));
    registerSubtypes(mapper, StoragePluginConfigBase.getSubTypes(scanResult));
    registerSubtypes(mapper, FormatPluginConfigBase.getSubTypes(scanResult));
    ConnectionConf.registerSubTypes(mapper, connectionReader);
    return mapper;
  }

  private static <T> void registerSubtypes(ObjectMapper mapper, Set<Class<? extends T>> types) {
    for (Class<? extends T> type : types) {
      mapper.registerSubtypes(type);
    }
  }

  private static final ObjectWriter writer = PRETTY_MAPPER.writerWithDefaultPrettyPrinter();

  public static String toString(Object o) {
    try {
      return writer.writeValueAsString(o);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }
}


text:
(function() {
  'use strict';
  angular.module('Calculator', ['ngMaterial'])
    .controller('AppCtrl', function($scope) {
      $scope.output = '0';
      $scope.result = '0';
      $scope.updateOutput = function(val){
        if ($scope.output === '0') {
          $scope.output = val.toString();
        }else {
          $scope.output += val.toString();
          $scope.result = eval($scope.output);
        }
      };
      $scope.add = function() {
        $scope.output += '+';
      };
      $scope.substract = function() {
        $scope.output += '-';
      };
      $scope.divide = function() {
        $scope.output += '/';
      };
      $scope.multiply = function() {
        $scope.output += '*';
      };
      $scope.equal = function() {
        $scope.result = eval($scope.output);
        $scope.output = '0';
      };
      $scope.clear = function() {
        $scope.output = $scope.result = '0';
      }
    });
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Druid - a distributed column store.
  ~ Copyright 2012 - 2015 Metamarkets Group Inc.
  ~
  ~ 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.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>druid-services</artifactId>
    <name>druid-services</name>
    <description>druid-services</description>

    <parent>
        <groupId>io.druid</groupId>
        <artifactId>druid</artifactId>
        <version>0.7.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <!-- include druid-common to prevent older versions of dependencies
        from being pulled in by airline and dependencies of druid-server -->
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-common</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-server</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-indexing-hadoop</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>io.druid</groupId>
            <artifactId>druid-indexing-service</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>airline</artifactId>
        </dependency>

        <!-- Test Dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <outputFile>
                                ${project.build.directory}/${project.artifactId}-${project.version}-selfcontained.jar
                            </outputFile>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <id>distro-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <finalName>${project.parent.artifactId}-${project.parent.version}</finalName>
                            <descriptors>
                                <descriptor>src/assembly/assembly.xml</descriptor>
                            </descriptors>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>download-licenses</id>
                        <goals>
                            <goal>download-licenses</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
    Controla como Hudson permite lançamentos via JNLP.

            Lançar apenas a partir de "Detalhes do Computador". Requer Login se a
            segurança estiver habilitada.

            Esta é a configuração normal e padrão.
            Neste modo, Hudson fornece um link de lançamento JNLP na visualização do computador.
            Se a segurança estiver habilitada, então o link apenas estará disponível para
            usuário autenticados.

            Lançar da página inicial. Requer Login se a
            segurança estiver habilitada.

            Neste modo, Hudson fornece um link de lançamento JNLP em na visualização do computador e
            no painel lateral "Estado do Executor de Construção".
            Se a segurança estiver habilitada, então o link apenas estará disponível para
            usuário autenticados.

            Lançar apenas a partir de "Detalhes do Computador". Nunca requer Login.

            Neste modo, Hudson fornece um link de lançamento JNLP na visualização do computador.
            O link estará sempre disponível mesmo quando o slave estiver desligado.

            AVISO! Neste modo a segurança é desabilitada.  Assim os slaves podem ser iniciados por qualquer um
            que tenha acesso a este servidor.  Os slaves têm a habilidade de executar código arbitrário no
            master.  Não selecione esta opção a menos que você esteja completamente ciente dos riscos


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/bg_welcome"
        android:id="@+id/splash_image"/>

    <TextView
        android:id="@+id/splash_app_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="50sp"
        android:textStyle="bold"
        android:textColor="@android:color/white"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="125dp"/>

    <TextView
        android:id="@+id/splash_slogan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="漂亮的不像实力派"
        android:textSize="14sp"
        android:textColor="#E6FFFFFF"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_below="@id/splash_app_name"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:background="#1AFFFFFF"
        android:layout_alignParentBottom="true"
        android:padding="10dp"
        android:layout_marginBottom="40dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:textSize="15sp"
            android:gravity="center"
            android:text="V 1.0.0"
            android:id="@+id/splash_version_name"/>

        <TextView
            android:text="Copyright © 2015 鼠绘漫画 All Rights Reserved\nPowered by CJJ"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:textSize="12sp"
            android:gravity="center"
            android:lineSpacingExtra="2dp"
            android:id="@+id/splash_copyright"
            android:layout_marginTop="10dp"/>
    </LinearLayout>

</RelativeLayout>


text:
//
//  LButton.hpp
//  GemsArr
//
//  Created by José Ricardo de Sousa Coutinho on 16/09/15.
//  Copyright © 2015 jrsc. All rights reserved.
//

#ifndef __GemsArr__LButton__
#define __GemsArr__LButton__

#ifdef _WIN32
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#endif
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC

#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>

#else
// Unsupported platform
#endif
#elif __linux

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#elif __unix // all unices not caught above
// Unix
#elif __posix
// POSIX
#endif

#include <stdio.h>
#include <string>

#include "Texture.hpp"

enum LButtonState
{
    BUTTON_STATE_MOUSE_OUT = 0,
    BUTTON_STATE_MOUSE_OVER_MOTION = 1,
    BUTTON_STATE_MOUSE_DOWN = 2,
    BUTTON_STATE_MOUSE_UP = 3,
    BUTTON_STATE_TOTAL = 4
};

class LButton
{
    int size;
    bool isDown;

public:

    SDL_Point position;
    LButtonState currentState;

    LButton();

    void setPosition( int x, int y );
    void setSize(int size);

    void handleEvent( SDL_Event * e );
    void render( SDL_Renderer * renderer );
};

#endif /* defined(__GemsArr__LButton__) */