text:
"""
Compare two callsets against each other where neither is known to be true
"""
# NB: since we're using methods for comparing a callset with ground truth
# some objects will have misleading names like "true positive", "false negative", etc.

# This is also an exercise in better organizing common code from bench.py, which is kind of a mess

from __future__ import division

import os
import vcf
import sys
import argparse

from parsers.genome import Genome
from vcf_eval.chrom_variants import VARIANT_TYPE
from vcf_eval.variants import Variants,evaluate_variants
from vcf_eval.callset_helper import MAX_INDEL_LEN

def perc(first,second):
    if second == 0:
        return 0.0
    else:
        return first/second*100

def print_results(stats,type_name):
    num_one = stats['num_true']
    num_two = stats['num_pred']
    print "\n-----------"
    print("{0} Results".format(type_name))
    print "-----------"
    print("# Callset 1 = {0}; # Callset 2 = {1}".format(num_one, num_two))
    intersection_totals = stats['good_predictions']
    print("# Intersection = {0}".format(intersection_totals))
    print("Callset 1: {0:.2f}% of calls in common with callset 2".format(perc(intersection_totals,num_one)))
    print("Callset 2: {0:.2f}% of calls in common with callset 1".format(perc(intersection_totals,num_two)))

# un-DRY; see similar function in bench.py
def parse_args(params):
    def is_valid_file(parser, arg):
        if not os.path.exists(arg):
            parser.error('The file {} does not exist!'.format(arg))
        else:
            return arg
    parser = argparse.ArgumentParser(description="""
        SMaSH benchmark toolkit for comparing two variant callsets.
        See smash.cs.berkeley.edu for more information, including usage
        """)
    parser.add_argument('callset1_vcf', type=lambda fn: is_valid_file(parser, fn))
    parser.add_argument('callset2_vcf', type=lambda fn: is_valid_file(parser, fn))
    parser.add_argument('reference', type=lambda fn: is_valid_file(parser, fn),
            nargs='?')
    parser.add_argument("--sv_bp",dest="sv_eps",action="store",type=int,
        default=100,
        help="""The maximum distance between SV breakpoints for them
                to be considered the same event""")
    parser.add_argument("-w","--rescue_window_size",dest="window",type=int,
        default=50,help="The size of the window for rescuing")
    args = parser.parse_args(params)
    return args

# also remarkably similar to the main in bench
def main(params):
    args = parse_args(params)
    with open(args.callset1_vcf) as f:
        callset1_vcf = vcf.Reader(f)
        one_vars = Variants(callset1_vcf,MAX_INDEL_LEN)
    with open(args.callset2_vcf) as f:
        callset2_vcf = vcf.Reader(f)
        two_vars = Variants(callset2_vcf,MAX_INDEL_LEN)
    if args.reference:
        ref = Genome(args.reference,abbreviate= lambda ctig: ctig.split()[0])
        window = args.window
    else:
        ref = None
        window = None

    stat_reporter, errors = evaluate_variants(
        one_vars,
        two_vars,
        args.sv_eps,
        args.sv_eps,
        ref,
        window
    )

    print_results(stat_reporter(VARIANT_TYPE.SNP),"SNP")
    print_results(stat_reporter(VARIANT_TYPE.INDEL_DEL),"INDEL DELETIONS")
    print_results(stat_reporter(VARIANT_TYPE.INDEL_INS),"INDEL INSERTIONS")
    print_results(stat_reporter(VARIANT_TYPE.INDEL_OTH),"INDEL OTHER")
    print_results(stat_reporter(VARIANT_TYPE.SV_DEL),"SV DELETIONS")
    print_results(stat_reporter(VARIANT_TYPE.SV_INS),"SV INSERTIONS")
    print_results(stat_reporter(VARIANT_TYPE.SV_OTH),"SV OTHER")

if __name__ == '__main__':
    main(params=sys.argv[1:])


text:
package unluac.decompile.statement;

import unluac.decompile.Decompiler;
import unluac.decompile.Output;
import unluac.decompile.Walker;
import unluac.decompile.expression.FunctionCall;

public class FunctionCallStatement extends Statement {

  private FunctionCall call;

  public FunctionCallStatement(FunctionCall call) {
    this.call = call;
  }

  @Override
  public void walk(Walker w) {
    w.visitStatement(this);
    call.walk(w);
  }

  @Override
  public void print(Decompiler d, Output out) {
    call.print(d, out);
  }

  @Override
  public boolean beginsWithParen() {
    return call.beginsWithParen();
  }

}

redpajama_set_name: RedPajamaGithub


text:
Tune Internals
==============

.. _raytrialexecutor-docstring:

RayTrialExecutor
----------------

.. autoclass:: ray.tune.execution.ray_trial_executor.RayTrialExecutor
    :members:

.. _trialrunner-docstring:

TrialRunner
-----------

.. autoclass:: ray.tune.execution.trial_runner.TrialRunner

.. _trial-docstring:

Trial
-----

.. autoclass:: ray.tune.experiment.trial.Trial

.. _tune-callbacks-docs:

Callbacks
---------

.. autoclass:: ray.tune.callback.Callback
   :members:

.. _resources-docstring:

PlacementGroupFactory
---------------------

.. autoclass:: ray.tune.execution.placement_groups.PlacementGroupFactory

Registry
--------

.. autofunction:: ray.tune.register_trainable

.. autofunction:: ray.tune.register_env


text:
author: Alexandre Archambault
authorURL: https://github.com/alexarchambault
title: 0.3.1
---

almond `0.3.1` was just released.
This release contains updates along with a fix to have almond work
on [Colaboratory](https://colab.research.google.com), thanks to
the only [Shadaj Laddad](https://github.com/shadaj)!

## Updates

This release switches to [Ammonite](https://ammonite.io) `1.6.4`,
fs2 `1.0.4`, and jeromq `0.5.0`, among others.

Ammonite `1.6.4` mainly replaced scalaj-http by requests-scala in the
classpath it exposes. It also
doesn't print back private values, e.g.
```scala
private val n = 2
val m = n + 1
```
just prints back
```
m: Int = 3
```
rather than
```
n: Int = 2
m: Int = 3
```
(`n` isn't accessible in subsequent code, so it doesn't make much sense to pretty-print it.)

## Colaboratory

[Shadaj Laddad](https://github.com/shadaj) contributed a fix allowing almond
to run fine on [Colaboratory](https://colab.research.google.com).

For the braves, the [following notebook](https://github.com/alexarchambault/almond-examples/blob/colab/notebooks/colab/install-almond.ipynb) ([more
stable link](https://github.com/alexarchambault/almond-examples/blob/89eed0ff78b0b1018154ec8b391afc48a6439999/notebooks/colab/install-almond.ipynb))
allows one to setup almond in a [Colaboratory](https://colab.research.google.com) environment.

As using custom kernels isn't an official feature of Colaboratory yet, one
cannot start almond sessions straightaway. Instead, an almond notebook has to
be imported. Imported notebooks will have the right kernel.
For example, notebooks from
the [almond examples repository](https://github.com/almond-sh/examples),
can be imported, and modified / run, once almond is installed.


text:
""" Allows use of Nescient from the command line. """
# TODO: Document STDIN functionality, make ArgumentParsers hierarchical
import os
import sys
import glob
from getpass import getpass
from argparse import ArgumentParser, RawTextHelpFormatter
from multiprocessing import freeze_support

from nescient import __version__, __doc__ as description
from nescient.packer import PACKING_MODES, DEFAULT_PACKING_MODE, NescientPacker, PackingError
from nescient.timing import estimate_time, EstimatedTimer, load_benchmarks, benchmark_mode
from nescient.process import process_sync_execute
from nescient.gui import main as start_gui

# Prompt the user with a yes-no question
def ask_yesno(prompt, default=True, newline=False, noprompt=False):
    if noprompt:
        print(prompt + ' Y' if default else prompt + ' N')
        if newline:
            print()
        return default
    if default:
        result = input(prompt + ' (Y/n): ')
        if newline:
            print()
        return result not in ['N', 'n']
    else:
        result = input(prompt + ' (y/N): ')
        if newline:
            print()
        return result in ['Y', 'y']

# Main program entrypoint
def main():
    # If run with no arguments, start the GUI
    if len(sys.argv) == 1:
        start_gui()
        sys.exit(0)
    parser = ArgumentParser(prog='nescient', description=description, formatter_class=RawTextHelpFormatter)
    parser.add_argument('packing_choice', choices=['pack', 'unpack'], metavar='pack|unpack',
                        help='Whether to pack or unpack the specified files.')
    parser.add_argument('patterns', nargs='+', help='File paths or patterns to process. Accepts wildcards like * or ?.',
                        type=str, metavar='paths')
    parser.add_argument('-o', dest='out_path', metavar='output path',
                        help='The path to write the processed files to.\n'
                             'By default, files are processed and written to their containing directory.\n'
                             'If a directory, each file will be processed as if it were in that directory.\n'
                             'Must be a directory if multiple files are specified.\n'
                             'If only one file is specified, this argument may be a filename, in which case\n'
                             'the processed file will be written directly to that path.')
    parser.add_argument('-m', choices=PACKING_MODES, default=DEFAULT_PACKING_MODE, dest='mode',
                        help='The algorithm, cipher mode, and authentication mode to use when packing.')
    parser.add_argument('-nr', '-norecursive', dest='recursive', action='store_false', default=True,
                        help='If wildcards are used as input paths, prevents recursively checking subdirectories.')
    parser.add_argument('-np', '-noprompt', dest='noprompt', action='store_true', default=False,
                        help='Prevent Nescient from prompting the user and forces the use of default options.')
    parser.add_argument('-nd', '-nodelete', dest='overwrite', action='store_false', default=True,
                        help='Prevent Nescient from overwriting the original file during processing.')
    args = parser.parse_args()
    noprompt, overwrite, recursive = args.noprompt, args.overwrite, args.recursive
    # Retrieve packer mode information
    alg, mode, auth = args.mode.split('-', 2)
    packing_choice, patterns, out_path = args.packing_choice, args.patterns, args.out_path
    # Build paths and ensure they are valid
    paths = [path for pattern in patterns for path in glob.glob(pattern, recursive=recursive) if os.path.isfile(path)]
    if len(paths) == 0:
        print('No file(s) found with the path(s) specified.')
        sys.exit(1)
    if len(paths) > 1 and out_path is not None and not os.path.isdir(out_path):
        print('Output path must be a directory when specifying multiple input files.')
        sys.exit(1)
    # Create Nescient header
    print('== Nescient v' + __version__ + ' ==\n')
    print('Packing mode:', args.mode + '\n')
    # Prompt for password
    if sys.stdin.isatty():  # If reading from a terminal, prompt for the password
        password = getpass('Insert password: ')
        password2 = getpass('Verify password: ')
        if password != password2:
            print('\nPasswords do not match!')
            sys.exit(1)
        print()
    else:  # Otherwise read from STDIN and do not prompt
        password = input('')
        noprompt = True
    # Build the packer, and check for benchmarks
    packer = NescientPacker(password, alg, mode, auth)
    benchmarks = load_benchmarks()
    if benchmarks is None or benchmarks.get(args.mode) is None:  # Ask to generate benchmarks if there are none
        if ask_yesno('No current benchmarks for these settings. Generate some?', noprompt=noprompt):
            print('Generating benchmarks...')
            benchmark_mode(args.mode)
            print()
    prompt_each = ask_yesno('Confirm each file?', default=False, newline=True, noprompt=noprompt)
    print('Packing:' if packing_choice == 'pack' else 'Unpacking:')
    for file_path in paths:
        try:
            # Fix the out path and set up display text
            file_out_path = NescientPacker.fix_out_path(file_path, out_path, packing_choice)
            display_text = file_path + ' > ' + file_out_path
            print(display_text, end='')
            if prompt_each:
                process_file = ask_yesno('')
                if not process_file:
                    continue
            display_text = os.path.split(file_path)[1] + ' > ' + os.path.split(file_out_path)[1]
            # Determine estimated time
            if packing_choice == 'pack':
                packing_mode = packer.alg + '-' + packer.mode + '-' + packer.auth
            else:
                parsed = NescientPacker.parse_nescient_header(file_path)
                packing_mode = parsed['alg'] + '-' + parsed['mode'] + '-' + parsed['auth']
            est_time = estimate_time(os.path.getsize(file_path), packing_mode)
            # Set up the timer and packing process
            timer = EstimatedTimer(display_text, est_time)
            timer.start()
            try:
                process_sync_execute(packer.pack_or_unpack_file, file_path, file_out_path, packing_choice,
                                     overwrite=overwrite)
            except Exception as e:
                timer.stop(error=True)
                print(e.__class__.__name__ + ':', e)
            else:
                timer.stop()
        except PackingError as e:
            print(e.__class__.__name__ + ':', e)

if __name__ == '__main__':
    # Call multiprocessing freeze support when bundled
    if getattr(sys, 'frozen', False):
        freeze_support()
    main()


text:
package com.github.clans.daviart.util;

import rx.Observer;
import timber.log.Timber;

public class ObserverImpl<T> implements Observer<T> {

    @Override
    public void onCompleted() {
        Timber.d("Loading completed");
    }

    @Override
    public void onError(Throwable e) {
        Timber.e(e, "An error occurred");
    }

    @Override
    public void onNext(T t) {
        Timber.d("onNext()");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class LogsAggregator
{
    static void Main()
    {
        int numberLines = int.Parse(Console.ReadLine());
        var logs = new SortedDictionary<string, SortedDictionary<string, long>>();

        for (int i = 0; i < numberLines; i++)
        {
            var separateLine = Console.ReadLine().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
            string ip = separateLine[0];
            string user = separateLine[1];
            long duration = long.Parse(separateLine[2]);

            if (!logs.ContainsKey(user))
            {
                logs[user] = new SortedDictionary<string, long>();
                logs[user].Add(ip, duration);

            }
            else
            {
                if (!logs[user].ContainsKey(ip))
                {
                    logs[user].Add(ip, duration);
                }
                else
                {
                    logs[user][ip] += duration;
                }
            }
        }

        Console.WriteLine();
        StringBuilder listOfIPs = new StringBuilder();

        foreach (var user in logs)
        {
            Console.Write(user.Key + ": ");
            Console.Write(user.Value.Sum(n => n.Value) + " [");
            foreach (var ip in user.Value)
            {
                listOfIPs.Append(ip.Key + ", ");

            }
            listOfIPs.Remove(listOfIPs.Length - 2, 2);
            Console.Write(listOfIPs);
            Console.WriteLine("]");
            listOfIPs.Clear();
        }
    }
}


text:
title: "Δημοσιεύσεις"
layout: content/papers
permalink: /gr/papers-all/
tag: publications, sidebar
data-content: published-articles
---


text:
Vagrant LAMPP
=============

Vagrant box with Puppet Standalone provisioner. Install Apache2, MySQL, PHP and
a couple of tools needed for PHP development.

For convenience, Puppet configures the default VHost for Apache2 to point to
the project root directory and creates a MySQL database.

The box is using Ubuntu 12.04 Server (Precise) 32bit as base box.

Preconditions
-------------

 * Vagrant 1.2.7 (Not tested on different version)
 * VirtualBox

Usage
-----

### Adding To A Project

This is intended to be used as drop-in sub-module for an PHP development
project. To add this box to a project, either clone it into a sub-folder of
your project root or preferrable add it as a submodule if you are already
using Git on the project:

````
git submodule add git@github.com:joerx/vagrant-lampp.git vagrant
````

The above command will create a new folder 'vagrant' inside your project
containing the contents of this repository. The folder name 'vagrant' is not
technically required, but recommended.

More on Git submodules here: http://git-scm.com/book/ch6-6.html

### Folder Structure

It is required to located the contents of this repository into a folder
directly below the project root of your web application (see below why).

### Environment variables

Some customization of the Vagrant box can be achieved by setting environment
variables before booting or provisioning the box:
 * V_SITE_NAME: override the site name to be used (see below), otherwise the
   name of the parent folder is used
 * V_APT_MIRROR: allows to use an alternative apt-mirror for performance
   improvements. Defaults to 'archive.ubuntu.com'.

Project Assumptions
-------------------

The box will set up the document root for the web servers default vhost and a
MySQL database for the project automatically. It will do this based on an
internal variable SITE_NAME. The SITE_NAME will be the base name of the parent
of the folder the Vagrant file is located in. This can be overridden using the
environment variable V_SITE_NAME.

Assuming you add this to a project called 'my_project', and given the directory
structure below, SITE_NAME would be set to 'my_project'.

````
.
|-- ...
`-- my_project
    |-- vagrant
    |   |-- puppet
    |   |-- README.md
    |   `-- Vagrantfile
    `-- ...
````

Based on this, the following configuration will be applied:
 * A shared folder 'my_project' --> '/var/www/my_project'
 * Folder '/var/www/my_project' as document root for Apache2
 * A MySQL database 'my_project', user 'my_project', pass 'my_project'

Limitations
-----------

 * Cannot push to Git from inside the box as public SSL key is missing.
   Branch, commit, etc. works though. Copy the SSH-public/private key pair
   your are using on Github to /home/vagrant/.ssh if you want to push from
   inside the box

License
-------

Copyright 2013 Jörg Henning <henning.joerg@gmail.com>

Licensed under the BSD License. (the "License"); you may not use this file
except in compliance with the License. See the LICENSE file for details.


text:
<?php
namespace Instrument\Form;

use Zend\Form\Form;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use DluTwBootstrapDemo\Form\BlockForm;

class EquipfeatForm extends Form implements ServiceLocatorAwareInterface {

    protected $v_serviceLocator;
    protected $v_equipfeaTable;

       public function __construct(\Zend\Db\Adapter\Adapter $x_adapter) {
        parent::__construct('equipfeat');
        $this->setAttribute('method', 'post');

        /* Valid Features */
        $v_valid_features = array();
        $results = $x_adapter->query("SELECT ibacode AS CodeVal, CONCAT('(',ibacode,') ',ibadesc) as DescVal FROM ibafea WHERE ibaactive = 'Y'", $x_adapter::QUERY_MODE_EXECUTE)->toArray();
        foreach ($results as $rowlist) {
            $v_valid_features[$rowlist['CodeVal']] = $rowlist['DescVal'];
        }

        /* Valid Equipment Codes */
        $v_valid_equipment = array();
        $results = $x_adapter->query("SELECT iadid AS CodeVal, CONCAT('(', iadid, ') ', iaddesc) AS DescVal FROM iadins WHERE iadactive = 'Y'", $x_adapter::QUERY_MODE_EXECUTE)->toArray();
        foreach ($results as $rowlist) {
            $v_valid_equipment[$rowlist['CodeVal']] = $rowlist['DescVal'];
        }

        $this->add(array(
            'name' => 'ibbfeacode',
            'type' => 'Zend\Form\Element\Select',
            'options' => array(
                'label' => 'Feature',
                'value_options' => $v_valid_features,
            ),
        ));
        $this->add(array(
            'name' => 'ibbinsid',
            'type' => 'Zend\Form\Element\Select',
            'options' => array(
                'label' => 'Equipment ID',
                'value_options' => $v_valid_equipment,
            ),
        ));

        $this->add(array(
            'name' => 'ibbstartval',
            'attributes' => array(
                'type' => 'text',
                'size' => 11,
            ),
            'options' => array(
                'label' => 'Feature amount'
            ),
        ));

        $this->add(array(
            'id' => 'ibbactive',
            'name' => 'ibbactive',
            'type' => 'radio',
            'attributes' => array(
                'label' => 'Active',
                'value' => 'Y',
            ),
            'options' => array(
                'value_options' => array(
                    'Y' => 'Yes',
                    'N' => 'No',
                ),
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type' => 'submit',
                'value' => 'Go',
                'id' => 'submitbutton',
            ),
        ));
        $this->add(array(
            'name' => 'cancel',
            'attributes' => array(
                'type' => 'cancel',
                'value' => 'Cancel',
                'id' => 'cancelbutton',
            ),
        ));
    }

    public function getServiceLocator() {
        return $this->v_serviceLocator;
    }

    public function setServiceLocator(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator) {
        $this->v_serviceLocator = $serviceLocator;
    }

}


text:
* Deploy a Dockerised Kubernetes cluster (Hyperkube)

## Run an etcd container

```
docker run \
--net=host \
-d gcr.io/google_containers/etcd:2.0.9 \
/usr/local/bin/etcd --addr=127.0.0.1:4001 --bind-addr=0.0.0.0:4001 --data-dir=/var/etcd/data
```

## Run a kubelet master

The kubelet will start the API server, controller manager and scheduler as containers in a pod (declared in `/etc/kubernetes/manifests`).

```
docker run \
--net=host \
-d \
-v /var/run/docker.sock:/var/run/docker.sock \
jetstack/hyperkube:v1.0.3 \
/hyperkube kubelet --api_servers=http://127.0.0.1:8080 --v=2 --address=0.0.0.0 --enable_server --hostname_override=127.0.0.1 --config=/etc/kubernetes/manifests --cluster_dns=10.0.0.10 --cluster_domain=cluster.local
```

## Run a kube-proxy

```
docker run \
-d \
--net=host \
--privileged \
jetstack/hyperkube:v1.0.3 \
/hyperkube proxy --master=http://127.0.0.1:8080 --v=2
```

Note the IP address ($IP).

## See the Docker containers start

```
docker ps
```

## Download the kubectl CLI tool

```
wget https://storage.googleapis.com/kubernetes-release/release/v1.0.3/bin/linux/amd64/kubectl
chmod u+x kubetctl
sudo mv kubectl /usr/local/bin/
```

## Verify the Kubernetes cluster is running

```
kubectl cluster-info
```

Now to [deploy a first pod](deploy-first-pod.md).

Read more at the Jetstack blog - [Kubernetes: Getting Started With a Local Deployment](http://www.jetstack.io/new-blog/2015/7/6/getting-started-with-a-local-deployment).


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
TestAuthenticationAspect
</TITLE>

<META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.security.TestAuthenticationAspect class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cabig.caaers.security

Class TestAuthenticationAspect

java.lang.Object
  gov.nih.nci.cabig.caaers.security.TestAuthenticationAspect

public class TestAuthenticationAspect
extends java.lang.Object

The purpose of this class is to intercept calls to JUnit test methods which would fail unless an
 appropriate Authentication object existed in the SecurityContext.

Author:

Joshua Phillips

Constructor Summary

TestAuthenticationAspect()

Method Summary

 void
advise()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TestAuthenticationAspect

public TestAuthenticationAspect()

Method Detail

advise

public void advise()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
"""
A simple collector to gather hypervisor resource usage stats

#### Dependencies

 * python-novaclient

"""

import diamond.collector
from novaclient import client

class NovaHypervisorStatsCollector(diamond.collector.Collector):

    def get_default_config_help(self):
        config_help = super(NovaHypervisorStatsCollector,
                            self).get_default_config_help()
        config_help.update({
            'username':   'User to auth with',
            'password':   'Password to auth with',
            'tenant':     'Tenancy to use',
            'auth_url':   'Keystone ip or hostname',
            'auth_proto': 'HTTP protocol to use',
            'cpu_allocation_ratio': 'As per nova.conf, '
                                    'the allocation ratio of '
                                    'real to virtual cores',
            'ram_allocation_ratio': 'As per nova.conf, '
                                    'the allocation ratio '
                                    'of real to virtual ram',
        })
        return config_help

    def get_default_config(self):
        """
        Returns the default collector settings
        """
        config = super(NovaHypervisorStatsCollector, self).get_default_config()
        config.update({
            'path':           'nova.hypervisorstats',
            'username':   'admin',
            'password':   'admin',
            'tenant':     'admin',
            'auth_url':   '127.0.0.1',
            'auth_proto': 'http',
            'cpu_allocation_ratio': '16',
            'ram_allocation_ratio': '1.5',
        })
        return config

    def collect(self):
        url = self.config['auth_proto'] + '://' + \
            self.config['auth_url'] + ':5000/v2.0/'

        nova = client.Client('2', self.config['username'],
                             self.config['password'],
                             self.config['tenant'],
                             url, timeout=120,
                             service_type="compute",
                             no_cache=True)

        s = []

        rollup = nova.hypervisors.statistics()._info
        s.append({rollup + '.disk.local_gb': rollup['local_gb']})
        s.append({rollup + '.disk.local_gb_used': rollup['local_gb_used']})
        s.append({rollup + '.disk.free_disk_gb': rollup['free_disk_gb']})
        s.append({rollup + '.disk.disk_available_least':
                  rollup['disk_available_least']})
        s.append({rollup + '.memory.total':
                  rollup['memory_mb'] * ram_allocation_ratio})
        s.append({rollup + '.memory.real': rollup['memory_mb']})
        s.append({rollup + '.memory.used': rollup['memory_mb_used']})
        s.append({rollup + '.memory.free_real': rollup['free_ram_mb']})
        s.append({rollup + '.memory.free':
                  rollup['memory_mb'] * ram_allocation_ratio -
                  rollup['memory_mb_used']})
        s.append({rollup + '.running_vms': rollup['running_vms']})
        s.append({rollup + '.vcpus.total':
                  rollup['vcpus'] * cpu_allocation_ratio})
        s.append({rollup + '.vcpus.used':
                  rollup['vcpus_used'] * cpu_allocation_ratio})
        s.append({rollup + '.vcpus.real':
                  rollup['vcpus'] * cpu_allocation_ratio})
        hypervisors = nova.hypervisors.list()
        if hypervisors:
            for h in hypervisors:
                hv = nova.hypervisors.get(h.id)
                stats = hv._info.copy()
                hostname = stats['hypervisor_hostname'].split('.')

                max_vcpus = (int(stats['vcpus']) *
                             float(self.config['cpu_allocation_ratio']))
                vcpus_percent_used = ((stats['vcpus_used']/max_vcpus) * 100)

                s.append({hostname[0] + '.max_vcpus': max_vcpus})
                s.append({hostname[0] + '.vcpus_percent_used':
                          vcpus_percent_used})

                max_ram = (int(stats['memory_mb']) *
                           float(self.config['ram_allocation_ratio']))
                ram_percent_used = ((stats['memory_mb_used']/max_ram) * 100)
                s.append({hostname[0] + '.max_ram': max_ram})
                s.append({hostname[0] + '.ram_percent_used':
                          ram_percent_used})

                for k, v in sorted(stats.items()):
                    hostname = h.hypervisor_hostname.split('.')
                    metric_name = ("%s.%s") % (hostname[0], k)
                    s.append({metric_name: v})

        for metric in s:
            for key, val in metric.items():
                self.publish(key, val)


text:
if (document.readyState != 'loading'){
  onDocumentReady();
} else {
  document.addEventListener('DOMContentLoaded', onDocumentReady);
}

// Page is loaded!  The code above runs this function when the page is fully loaded
//Now events can be wired-up
function onDocumentReady() {
  console.log('Document ready.');
  //Here add all things you want to happen when the page is loaded like listening for keypress
  //Get a handle to the button
  var el = document.getElementById('button1');
  // Listen to any click that happens on button1 if a click is parformed
  //the onButtonClick function is called.
  el.addEventListener('click', onButtonClicked);
  //Bellow is the ending Måsvinge for the onDocumentReady function
}

// Called according to 'click' event
function onButtonClicked(e) {
  console.log('onButtonClicked.');
  window.open("other.html","_self");
}


text:
'use strict';

/**
 * @ngdoc function
 * @name eversnapApp.controller:AlbumCtrl
 * @description
 * Controller of the eversnapApp.controllers.
 * Handle modal open passing a callback to inner directive.
 *
 * @requires $routeParams
 * @requires $modal
 * @requires templates
 * @requires Album
 * @requires $rootScope
 * @requires $location
 * @requires Session
 */
angular.module('eversnapApp.controllers')
  .controller('AlbumCtrl', AlbumCtrl);

AlbumCtrl.$inject = ['$routeParams', '$modal', 'templates', 'Album', '$rootScope', '$location', 'Session'];

function AlbumCtrl($routeParams, $modal, templates, Album, $rootScope, $location, Session) {

  var vm = this;

  vm.albumId = $routeParams.albumId;
  vm.session = Session.get();
  vm.photos = [];

  $rootScope.$on('SESSION_STARTED', fetchPhotos);

  function fetchPhotos() {
    Album.fetchPhotos(vm.albumId).then(function(response){
      vm.photos = response.data;
      if (Album.get().data) {
        vm.album = Album.get(vm.albumId);
        if(!vm.album){
          goHome();
        }
      }
    });
  }

  vm.open = function (id) {
    var modalInstance = $modal.open({
      animation: true,
      templateUrl: templates.photoModal,
      controller: 'ModalInstanceCtrl as vm',
      size: 'lg',
      resolve: {
        photoId: function () {
          return id;
        }
      }
    });

    modalInstance.result.then(function (photoId) {
      vm.selected = photoId;
    });
  };

  function goHome() {
    $location.path('/');
  }

  Session.started().then(fetchPhotos, goHome);
}


text:
package com.clicktravel.cheddar.infrastructure.persistence.document.search.exception;

/**
 * Represents a search that failed to return any results due to issue for example bad request / malformed query etc
 *
 *
 */
public class UnsuccessfulSearchException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public UnsuccessfulSearchException(final String message) {
        super(message);
    }

}


text:
<?php

namespace Minsal\GinecologiaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * SrgConsultaGinePf
 *
 * @ORM\Table(name="srg_consulta_gine_pf", indexes={@ORM\Index(name="IDX_D676C7BE643FF516", columns={"id_historial_clinico"})})
 * @ORM\Entity
 */
class SrgConsultaGinePf
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="srg_consulta_gine_pf_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fecha_consulta", type="date", nullable=false)
     */
    private $fechaConsulta;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="hora_inicio", type="time", nullable=true)
     */
    private $horaInicio;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="hora_fin", type="time", nullable=true)
     */
    private $horaFin;

    /**
     * @var string
     *
     * @ORM\Column(name="estado_consulta", type="string", length=1, nullable=false)
     */
    private $estadoConsulta;

    /**
     * @var string
     *
     * @ORM\Column(name="especialidad_consulta", type="string", length=2, nullable=false)
     */
    private $especialidadConsulta;

    /**
     * @var boolean
     *
     * @ORM\Column(name="referencia_recibida", type="boolean", nullable=true)
     */
    private $referenciaRecibida;

    /**
     * @var boolean
     *
     * @ORM\Column(name="retorno_recibido", type="boolean", nullable=true)
     */
    private $retornoRecibido;

    /**
     * @var \SecHistorialClinico
     *
     * @ORM\OneToOne(targetEntity="Minsal\SiapsBundle\Entity\SecHistorialClinico")
     *   @ORM\JoinColumn(name="id_historial_clinico", referencedColumnName="id")
     */
    private $idHistorialClinico;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set fechaConsulta
     *
     * @param \DateTime $fechaConsulta
     * @return SrgConsultaGinePf
     */
    public function setFechaConsulta($fechaConsulta)
    {
        $this->fechaConsulta = $fechaConsulta;

        return $this;
    }

    /**
     * Get fechaConsulta
     *
     * @return \DateTime
     */
    public function getFechaConsulta()
    {
        return $this->fechaConsulta;
    }

    /**
     * Set horaInicio
     *
     * @param \DateTime $horaInicio
     * @return SrgConsultaGinePf
     */
    public function setHoraInicio($horaInicio)
    {
        $this->horaInicio = $horaInicio;

        return $this;
    }

    /**
     * Get horaInicio
     *
     * @return \DateTime
     */
    public function getHoraInicio()
    {
        return $this->horaInicio;
    }

    /**
     * Set horaFin
     *
     * @param \DateTime $horaFin
     * @return SrgConsultaGinePf
     */
    public function setHoraFin($horaFin)
    {
        $this->horaFin = $horaFin;

        return $this;
    }

    /**
     * Get horaFin
     *
     * @return \DateTime
     */
    public function getHoraFin()
    {
        return $this->horaFin;
    }

    /**
     * Set estadoConsulta
     *
     * @param string $estadoConsulta
     * @return SrgConsultaGinePf
     */
    public function setEstadoConsulta($estadoConsulta)
    {
        $this->estadoConsulta = $estadoConsulta;

        return $this;
    }

    /**
     * Get estadoConsulta
     *
     * @return string
     */
    public function getEstadoConsulta()
    {
        return $this->estadoConsulta;
    }

    /**
     * Set especialidadConsulta
     *
     * @param string $especialidadConsulta
     * @return SrgConsultaGinePf
     */
    public function setEspecialidadConsulta($especialidadConsulta)
    {
        $this->especialidadConsulta = $especialidadConsulta;

        return $this;
    }

    /**
     * Get especialidadConsulta
     *
     * @return string
     */
    public function getEspecialidadConsulta()
    {
        return $this->especialidadConsulta;
    }

    /**
     * Set referenciaRecibida
     *
     * @param boolean $referenciaRecibida
     * @return SrgConsultaGinePf
     */
    public function setReferenciaRecibida($referenciaRecibida)
    {
        $this->referenciaRecibida = $referenciaRecibida;

        return $this;
    }

    /**
     * Get referenciaRecibida
     *
     * @return boolean
     */
    public function getReferenciaRecibida()
    {
        return $this->referenciaRecibida;
    }

    /**
     * Set retornoRecibido
     *
     * @param boolean $retornoRecibido
     * @return SrgConsultaGinePf
     */
    public function setRetornoRecibido($retornoRecibido)
    {
        $this->retornoRecibido = $retornoRecibido;

        return $this;
    }

    /**
     * Get retornoRecibido
     *
     * @return boolean
     */
    public function getRetornoRecibido()
    {
        return $this->retornoRecibido;
    }

    /**
     * Set idSecHistorialClinico
     *
     * @param \Minsal\SiapsBundle\Entity\SecHistorialClinico $idHistorialClinico
     * @return SrgConsultaGinePf
     */
    public function setIdHistorialClinico(\Minsal\SiapsBundle\Entity\SecHistorialClinico $idHistorialClinico = null)
    {
        $this->idHistorialClinico = $idHistorialClinico;

        return $this;
    }

    /**
     * Get idHistorialClinico
     *
     * @return \Minsal\SiapsBundle\Entity\SecHistorialClinico
     */
    public function getIdHistorialClinico()
    {
        return $this->idHistorialClinico;
    }

}


text:
(function(window){

    /**
     * 关于选择器的方法 放在这里
     */
    class Selector{
        //实例化时的选择器 $(function(){}) $(object) $('selector')
        Selector(selector){
            //$(function(){})
            if(typeof selector === 'function'){
                if ( document.readyState === "complete" ||
                    ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
                    window.setTimeout( this.Selector(selector) );
                } else {
                    function completed() {
                        document.removeEventListener( "DOMContentLoaded", completed );
                        selector();
                    }
                    document.addEventListener( "DOMContentLoaded", completed );
                }
            }else if(typeof selector === 'object'){//$(object)
                this.elements = [].concat([...selector]);
            }else{//$('selector')
                this.elements = [...document.querySelectorAll(selector)];
            }
        }

        find(selector){
            //这里因该是能找到所有elements下面的元素
            this.elements = this.elements.map(item => {
                return [...item.querySelectorAll(selector)];
            }).reduce((arr,item)=>{
                return arr.concat(item);
            });
            return this;
        }

        /**
         * 选择这个对象中的元素
         * @param index
         * @returns {Selector}
         */
        eq(index = 0){
            this.elements = this.elements.splice(index,1)
            return this;
        }

        /**
         * 获取真正的DOM元素
         * @param index     按index获取,默认为0
         * @returns {*}
         */
        get(index=0){
            return this.elements[index];
        }

        /**
         * 获取子节点    默认不选正常获取子节点 , 传值将会进行过滤(慎用)
         * @param selector
         * @returns {Selector}
         */
        childrens(selector = null){
            //如果存在参数 依然决定用querySelectorAll
            //思路
            //1.给当前elements中的元素添加一个 random class名
            //2.用 documnet.querySelectorAll() '>selector' 来实现选择(性能会存在一些问题)
            //3.删除之前添加的 random class
            if(selector){
                let random = `es6query_${Math.ceil(Math.random()*1000)}`;
                let arr = this.elements;
                arr.map(item=>item.classList.add(random));
                this.elements = [...document.querySelectorAll(`.${random}>${selector}`)];
                arr.map(item=>item.classList.remove(random));
            }else{
                this.elements = this.elements.map(item=>{
                    return [...item.children];
                }).reduce((arr,item)=>{
                    return arr.concat(item);
                });
            }
            return this;
        }

        /**
         * 获取兄弟节点   注:无法传参 个人感觉没用到过
         * @returns {Selector}
         */
        siblings(){
            //思路    有点随意啊
            //1. this.childrens()方法获取子节点
            //2. 删除自己
            let myself = this.elements[0];//保存自己
            //获取父类
            this.elements = [this.elements[0].parentElement];//只获取第一个
            this.childrens();
            //执行第 2 步 删除自己
            this.elements.splice(this.elements.findIndex(value => {return value === myself}), 1);
            return this;
        }
    }

    /**
     * 关于样式操作的方法 放在这里
     */
    class Style{
        /**
         * 对样式的操作
         * 1. css('background')
         * 2. css('background','red')
         * 3. css({'background':'red','font-size':'14px'})  注:能传 14
         * @param key
         * @param value
         * @returns {Style}
         */
        css(key,value = null){
            //第3种情况
            if(value === null){
                if(typeof key == 'object'){
                    this.elements.map(item=>{
                        for(let name in key){
                            item.style[name] = key[name];
                        }
                        return this;
                    })
                }else{//第1种 这里只返回第一个
                    return this.elements[0].style[key];
                }
            }else{//第2种情况
                this.elements.map(item=>item.style[key] = value);
                return this;
            }
        }
    }

    /**
     * 关于事件的方法 放在这里
     */
    class Event{
        /**
         * 给 this.elements 对象循环添加事件
         * @param type      事件类型
         * @param callback  回调函数
         * @param foam      false表示冒泡 , true 代表捕获
         */
        addEvent(type,callback,foam = false){
            this.elements.map(item => item.addEventListener(type,callback,foam));
        }
    }

    /**
     * 关于动画的方法 放在这里
     */
    class Animate{
        /**
         * 通过切换class名称触发transition动画,动画结束时将触发一个回调函数,并返回'transition' 的event对象
         * @param className         触发动画的class名
         * @param callback          动画完成后的回调函数
         * @returns {ES6Query}
         */
        changeClassAnimate(className,callback){
            this.elements.map(item=>{
                item.addEventListener('transitionend',function fn(event){
                    callback && callback(event);
                    item.removeEventListener('transitionend',fn,false);
                },false);
                item.offsetLeft;//力回流
                item.classList.toggle(className);
            });
            return this;
        };

        /**
         * 通过display:show 显示元素 接受一个参数 渐隐 时间
         * @param time      动画执行时间
         * @returns {ES6Query}
         */
        show(time = null){
            if(time){
                this.elements.map(item=>{
                    item.addEventListener('transitionend',callback,false);
                    //执行渐隐动画
                    item.style.opacity = 0;
                    item.style.display = 'block';
                    item.style.transition = `${time}s linear`;
                    item.offsetWidth;//力回流
                    item.style.opacity = 1;
                    function callback(){
                        item.style.transition = '0s';
                        item.removeEventListener('transitionend',callback,false);
                    }
                });
            }else{
                this.elements.map(item=>item.style.display = 'block');
            }
            return this;
        }

        /**
         * 通过display : none 隐藏掉一个元素
         * @param time          渐隐时间过渡
         * @returns {Animate}
         */
        hide(time = null){
            if(time){
                this.elements.map(item=>{
                    item.addEventListener('transitionend',callback,false);
                    //执行渐隐动画
                    item.style.opacity = 1;
                    item.style.transition = `${time}s linear`;
                    item.offsetWidth;//力回流
                    item.style.opacity = 0;
                    function callback(){
                        item.style.display = 'none';
                        item.style.transition = '0s';
                        item.removeEventListener('transitionend',callback,false);
                    }
                });
            }else{
                this.elements.map(item=>item.style.display = 'none');
            }
            return this;
        }
    }

    /**
     * 关于异步的操作 放在这里
     */
    class Ajax{
        /**
         * 封装 get Promise
         * @param url       访问地址
         * @param dataType  数据类型
         */
        static get(url,dataType = 'json'){
            let promise = new Promise((resolve,reject)=>{
                let client = new XMLHttpRequest();
                client.open("GET",url);
                client.onreadystatechange = handler;
                client.responseType = dataType;
                client.setRequestHeader("Accept","application/json");
                client.send();
                function handler(){
                    if(this.readyState !== 4)return;
                    this.status === 200 ? resolve(this.response) : reject(new Error(this.statusText));
                }
            });
            return promise;
        }
    }

    /**
     * 关于常用的操作方法 放在这里
     */
    class Tool{
        /**
         * 添加class名称
         * $(selector).addClass('name','name2','name3')
         * @param className
         * @returns {ES6Query}
         */
        addClass(...className){
            this.elements.map(item=>item.classList.add(...className));
            return this;
        }

        /**
         * 删除class名称
         * $(selector).removeClass('name','name2','name3')
         * @param className
         * @returns {ES6Query}
         */
        removeClass(...className){
            this.elements.map(item=>item.classList.remove(...className));
            return this;
        }

        /**
         * 切换class名称
         * $(selector).toggleClass('name','name2','name3');
         * @param className
         * @returns {ES6Query}
         */
        toggleClass(...className){
            this.elements.map(item=>item.classList.toggle(...className));
            return this;
        }
    }

    /**
     * 处理 Promise对象的方法放在这里
     */
    class Promises{

    }

    class ES6Query extends mix(Selector,Event,Animate,Ajax,Tool,Promises,Style){
        constructor(selector){
            super();
            this.Selector(selector);
            //执行初始化函数
            this.init();
            return this;
        }

        init(){
            //添加一些事件处理方法
            `blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu`.split(" ").map(item=>{
                this.__proto__.__proto__[item] = (callback,foam = false) =>{
                    this.addEvent(item,callback,foam);
                };
            });
        }

    }

    window.$http = Ajax;
    window.$ = (selector) => { return new ES6Query(selector)};
    //混入函数 , 见ES6入门258页
    function mix(...mixins){
        class Mix{}

        let copeProperties = (target,source) =>{
            for(let key of Reflect.ownKeys(source)){
                if(key !== "constructor" && key !== "prototype" && key !== "name"){
                    let desc = Object.getOwnPropertyDescriptor(source,key);
                    Object.defineProperty(target,key,desc);
                }
            }
        }

        for(let mixin of mixins){
            copeProperties(Mix,mixin);
            copeProperties(Mix.prototype,mixin.prototype)
        }
        return Mix;
    }
})(window);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using OpenTK.Compute.CL10;
using System.Text;
using System.Runtime.InteropServices;

namespace scallion
{
	public unsafe class CLContext
	{
		public readonly IntPtr DeviceId;
		public readonly CLDeviceInfo Device;
		public readonly IntPtr ContextId;
		public readonly IntPtr CommandQueueId;
		public unsafe CLContext(IntPtr deviceId)
		{
			DeviceId = deviceId;
			Device = new CLDeviceInfo(DeviceId);
			ErrorCode error;
			ErrorCode[] errors = new ErrorCode[1];
			ContextId = CL.CreateContext(null, 1, new IntPtr[] { DeviceId }, IntPtr.Zero, IntPtr.Zero, errors);
			if (errors[0] != ErrorCode.Success) throw new System.InvalidOperationException("Error calling CreateContext");
			CommandQueueId = CL.CreateCommandQueue(ContextId, DeviceId, (CommandQueueFlags)0, &error);
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateCommandQueue: {0}",error));
		}
		public IntPtr CreateAndCompileProgram(string source)
		{
			ErrorCode error;
			IntPtr programId;
			programId = CL.CreateProgramWithSource(ContextId, 1, new string[] { source }, null, &error);
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateProgramWithSource: {0}",error));
			error = (ErrorCode)CL.BuildProgram(programId, 0, (IntPtr[])null, null, IntPtr.Zero, IntPtr.Zero);
			if (error != ErrorCode.Success)
			{
				uint parmSize;
				CL.GetProgramBuildInfo(programId, DeviceId, ProgramBuildInfo.ProgramBuildLog, IntPtr.Zero, IntPtr.Zero, (IntPtr*)&parmSize);
				byte[] value = new byte[parmSize];
				fixed (byte* valuePtr = value)
				{
					error = (ErrorCode)CL.GetProgramBuildInfo(programId, DeviceId, ProgramBuildInfo.ProgramBuildLog, new IntPtr(&parmSize), new IntPtr(valuePtr), (IntPtr*)IntPtr.Zero.ToPointer());
				}
				if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling GetProgramBuildInfo: {0}",error));
				throw new System.InvalidOperationException(Encoding.ASCII.GetString(value).Trim('\0'));
			}
			return programId;
		}
		public CLKernel CreateKernel(IntPtr programId, string kernelName)
		{
			return new CLKernel(DeviceId, ContextId, CommandQueueId, programId, kernelName);
		}
		public CLBuffer<T> CreateBuffer<T>(MemFlags memFlags, T[] data) where T : struct
		{
			return new CLBuffer<T>(ContextId, CommandQueueId, memFlags, data);
		}
		private bool disposed = false;
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}
		protected virtual void Dispose(bool disposing)
		{
			if (!this.disposed)
			{
				if (disposing) { /*Dispose managed resources*/ }
				CL.ReleaseCommandQueue(CommandQueueId);
				CL.ReleaseContext(ContextId);
			}
		}
		~CLContext()
        {
            Dispose(false);
        }
	}
	public unsafe class CLBuffer<T> : IDisposable where T : struct
	{
		public GCHandle Handle { get; private set; }
		public readonly IntPtr BufferId;
		public readonly IntPtr CommandQueueId;
		public readonly bool IsDevice64Bit;
		public readonly int BufferSize;
		private T[] _data;
		public T[] Data
		{
			get { return _data;}
			set
			{
				if (_data == value) return;
				if (Handle.IsAllocated) Handle.Free();
				_data = value;
				Handle = GCHandle.Alloc(_data, GCHandleType.Pinned);
				if (BufferSize != Marshal.SizeOf(typeof(T)) * _data.Length) throw new System.Exception("Data's length is not the same as the original buffer.");
			}
		}

		public CLBuffer(IntPtr contextId, IntPtr commandQueueId, MemFlags memFlags, T[] data)
		{
			CommandQueueId = commandQueueId;
			ErrorCode error = ErrorCode.Success;
			BufferSize = Marshal.SizeOf(typeof(T)) * data.Length;
			Data = data;
			BufferId = CL.CreateBuffer(contextId, memFlags, new IntPtr(BufferSize), Handle.AddrOfPinnedObject(), &error);
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateBuffer: {0}",error));
		}

		public void EnqueueWrite()
		{
			EnqueueWrite(false);
		}

		public void EnqueueRead()
		{
			EnqueueRead(false);
		}

		public void EnqueueWrite(bool async)
		{
			ErrorCode error;
			error = (ErrorCode)CL.EnqueueWriteBuffer(CommandQueueId, BufferId, !async, new IntPtr(0), new IntPtr(BufferSize),
				Handle.AddrOfPinnedObject(), 0, (IntPtr*)IntPtr.Zero.ToPointer(), (IntPtr*)IntPtr.Zero.ToPointer());
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling EnqueueWriteBuffer: {0}",error));
		}

		public void EnqueueRead(bool async)
		{
			ErrorCode error;
			error = (ErrorCode)CL.EnqueueReadBuffer(CommandQueueId, BufferId, !async, new IntPtr(0), new IntPtr(BufferSize),
				Handle.AddrOfPinnedObject(), 0, (IntPtr*)IntPtr.Zero.ToPointer(), (IntPtr*)IntPtr.Zero.ToPointer());
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling EnqueueReadBuffer: {0}",error));
		}

		private bool disposed = false;
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}
		protected virtual void Dispose(bool disposing)
		{
			if (!this.disposed)
			{
				if (disposing) { /*Dispose managed resources*/ }
				// Dispose unmanaged resources.
				CL.ReleaseMemObject(BufferId);
				Handle.Free();
			}
		}
		~CLBuffer()
        {
            Dispose(false);
        }
	}
	public unsafe class CLKernel
	{
		public readonly IntPtr KernelId;
		public readonly IntPtr ContextId;
		public readonly IntPtr CommandQueueId;
		public readonly IntPtr ProgramId;
		public readonly string KernelName;
		public readonly IntPtr DeviceId;
		public CLKernel(IntPtr deviceId, IntPtr contextId, IntPtr commandQueueId, IntPtr programId, string kernelName)
		{
			DeviceId = deviceId;
			ContextId = contextId;
			CommandQueueId = commandQueueId;
			ProgramId = programId;
			KernelName = kernelName;

			ErrorCode error;
			KernelId = CL.CreateKernel(ProgramId, KernelName, out error);
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling CreateKernel: {0}",error));
		}
		public void EnqueueNDRangeKernel(int globalWorkSize, int localWorkSize)
		{
			ErrorCode error;
			IntPtr pglobalWorkSize = new IntPtr(globalWorkSize);
			IntPtr plocalWorkSize = new IntPtr(localWorkSize);
			error = (ErrorCode)CL.EnqueueNDRangeKernel(CommandQueueId, KernelId, 1, null, &pglobalWorkSize, &plocalWorkSize, 0, null, null);
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling EnqueueNDRangeKernel: {0}",error));
		}
		public void SetKernelArgLocal(int argIndex, int size)
		{
			ErrorCode error;
			error = (ErrorCode)CL.SetKernelArg(KernelId, argIndex, new IntPtr(size), IntPtr.Zero);
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling SetKernelArg: {0}",error));
		}
		public void SetKernelArg<T>(int argIndex, T value) where T : struct
		{
			ErrorCode error;
			var handle = GCHandle.Alloc(value, GCHandleType.Pinned);
			int size = Marshal.SizeOf(typeof(T));
			error = (ErrorCode)CL.SetKernelArg(KernelId, argIndex, new IntPtr(size), handle.AddrOfPinnedObject());
			handle.Free();
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling SetKernelArg: {0}",error));
		}
		public void SetKernelArg<T>(int argIndex, CLBuffer<T> value) where T : struct
		{
			ErrorCode error;
			IntPtr bufferId = value.BufferId;
			error = (ErrorCode)CL.SetKernelArg(KernelId, argIndex, new IntPtr(sizeof(IntPtr)), new IntPtr(&bufferId));
			if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling SetKernelArg: {0}",error));
		}
		public ulong KernelPreferredWorkGroupSizeMultiple
		{
			get
			{
				ErrorCode error;
				ulong ret = 0;
				error = (ErrorCode)CL.GetKernelWorkGroupInfo(KernelId, DeviceId, KernelWorkGroupInfo.KernelPreferredWorkGroupSizeMultiple, new IntPtr(sizeof(IntPtr)), ref ret, (IntPtr*)IntPtr.Zero.ToPointer());
				if (error != ErrorCode.Success) throw new System.InvalidOperationException(String.Format("Error calling GetKernelWorkGroupInfo: {0}",error));
				return ret;
			}
		}
		private bool disposed = false;
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}
		protected virtual void Dispose(bool disposing)
		{
			if (!this.disposed)
			{
				if (disposing) { /*Dispose managed resources*/ }
				CL.ReleaseKernel(KernelId);
			}
		}
		~CLKernel()
        {
            Dispose(false);
        }
	}
}


text:
import {Component} from 'angular2/core'
import {NewSprint} from 'shared/directives/NewSprint'

@Component({
  selector: 'home',
  template: require('./Home.jade')(),
  styles: [require('./Home.scss')],
  directives: [NewSprint]
})
export class HomeComponent {
}


text:
package com.yahoo.athenz.auth.token;

import static org.testng.Assert.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.yahoo.athenz.auth.util.CryptoException;

public class RoleTokenTest {

    private final String rolVersion = "Z1";
    private final String svcDomain = "sports";
    private final String salt = "aAkjbbDMhnLX";

    private final long expirationTime = 10; // 10 seconds

    private String ztsPublicKeyStringK0 = null;
    private String ztsPrivateKeyStringK0 = null;
    private String ztsPublicKeyStringK1 = null;
    private String ztsPrivateKeyStringK1 = null;

    @BeforeTest
    private void loadKeys() throws IOException {

        Path path = Paths.get("./src/test/resources/zts_public_k0.key");
        ztsPublicKeyStringK0 = new String(Files.readAllBytes(path));

        path = Paths.get("./src/test/resources/zts_public_k1.key");
        ztsPublicKeyStringK1 = new String(Files.readAllBytes(path));

        path = Paths.get("./src/test/resources/unit_test_zts_private_k0.key");
        ztsPrivateKeyStringK0 = new String(Files.readAllBytes(path));

        path = Paths.get("./src/test/resources/unit_test_zts_private_k1.key");
        ztsPrivateKeyStringK1 = new String(Files.readAllBytes(path));
    }

    private RoleToken createRoleTokenToValidate(List<String> roles) throws CryptoException {
        // Create token and sign
        RoleToken rollTokenToSign = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .salt(salt).expirationWindow(expirationTime).build();

        rollTokenToSign.sign(ztsPrivateKeyStringK0);

        return new RoleToken(rollTokenToSign.getSignedToken());
    }

    private RoleToken createRoleTokenToValidate(List<String> roles, String keyVersion)
            throws CryptoException {
        // Create token and sign
        RoleToken rollTokenToSign = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .salt(salt).expirationWindow(expirationTime).keyId(keyVersion).build();

        String privateKey = null;
        if ("0".equals(keyVersion)) {
            privateKey = ztsPrivateKeyStringK0;
        } else  if ("1".equals(keyVersion)) {
            privateKey = ztsPrivateKeyStringK1;
        }

        rollTokenToSign.sign(privateKey);

        return new RoleToken(rollTokenToSign.getSignedToken());
    }

    @Test
    public void testRoleToken() throws CryptoException {
        // Add some roles
        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");
        roles.add("fantasy.tenant.sports.admin");
        roles.add("fantasy.tenant.sports.reader");
        roles.add("fantasy.tenant.sports.writer");
        roles.add("fantasy.tenant.sports.scanner");

        // Create a token for validation using the signed data
        String testKeyVersionK1 = "1";
        RoleToken rollTokenToValidate = createRoleTokenToValidate(roles, testKeyVersionK1);
        assertNotNull(rollTokenToValidate.getSignedToken());

        // Validate all input data
        assertEquals(rollTokenToValidate.getVersion(), rolVersion);
        assertEquals(rollTokenToValidate.getDomain(), svcDomain);
        List<String> rolesToValidate = rollTokenToValidate.getRoles();
        assertEquals(rolesToValidate.size(), roles.size());
        assertEquals(rolesToValidate, roles);
        assertEquals(rollTokenToValidate.getKeyId(), testKeyVersionK1);

        // Validate the signature and that expiration time had not elapsed
        assertTrue(rollTokenToValidate.validate(ztsPublicKeyStringK1, 300, false));

        // Create ServiceToken with null keyVersion which should default to 0
        rollTokenToValidate = createRoleTokenToValidate(roles);
        assertEquals(rollTokenToValidate.getKeyId(), "0");

        // Validate the signature using key(k0) and that expiration time had not elapsed
        assertTrue(rollTokenToValidate.validate(ztsPublicKeyStringK0, 300, false));
    }

    @Test
    public void testRoleTokenInvalidParamsAtEnd() throws CryptoException {
        // Add some roles
        List<String> roles = new ArrayList<>();
        roles.add("reader");
        roles.add("writer");

        // Create a token for validation using the signed data
        String testKeyVersionK1 = "1";

        // Create token and sign
        RoleToken rollTokenToSign = new RoleToken.Builder(rolVersion, svcDomain, roles)
                .salt(salt).expirationWindow(expirationTime).keyId(testKeyVersionK1).build();

        rollTokenToSign.sign(ztsPrivateKeyStringK1);
        String signedToken = rollTokenToSign.getSignedToken() + ";d=newdomain;r=newroles";

        RoleToken rollTokenToValidate = new RoleToken(signedToken);

        assertNotNull(rollTokenToValidate.getSignedToken());

        // Validate all input data, we'll be ignoring the data
        // after the signature

        assertEquals(rollTokenToValidate.getDomain(), svcDomain);
        List<String> rolesToValidate = rollTokenToValidate.getRoles();
        assertEquals(rolesToValidate.size(), roles.size());
        assertEquals(rolesToValidate, roles);
        assertEquals(rollTokenToValidate.getKeyId(), testKeyVersionK1);

        // Validate the signature and that expiration time had not elapsed
        // we should get invalid validation due to extra arguments at
        // end of the string

        assertFalse(rollTokenToValidate.validate(ztsPublicKeyStringK1, 300, false));
    }

    @Test
    public void testRoleToken_Expired() throws InterruptedException, CryptoException {
        // Add some roles
        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");
        roles.add("fantasy.tenant.sports.admin");
        roles.add("fantasy.tenant.sports.reader");
        roles.add("fantasy.tenant.sports.writer");
        roles.add("fantasy.tenant.sports.scanner");

        // Create a token for validation using the signed data
        String testKeyVersionK0 = "0";
        RoleToken rollTokenToValidate = createRoleTokenToValidate(roles, testKeyVersionK0);

        // Let expiration time elapse
        Thread.sleep((expirationTime + 10) * 1000);

        // Validate that the expiration time has elapsed
        assertFalse(rollTokenToValidate.validate(ztsPublicKeyStringK0, 300, false));
    }

    @Test
    public void testTokenStringConstructor() {
        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.activator.actionmap.w");
        RoleToken rToken = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .salt(salt).expirationWindow(expirationTime).build();

        rToken.sign(ztsPrivateKeyStringK0); // now its signed
        String signedToken = rToken.getSignedToken();
        RoleToken sigToken1 = new RoleToken(signedToken);
        assertEquals(sigToken1.getSignedToken(), signedToken);

        String unsignedTok = rToken.getUnsignedToken();
        String signature   = rToken.getSignature();
        String newSignedToken = unsignedTok + ";s=" + signature;
        assertEquals(newSignedToken, signedToken);

        // instantiate a Token with the unsigned token + signature
        RoleToken sigToken2 = new RoleToken(newSignedToken);
        assertEquals(sigToken2.getSignedToken(), signedToken);
        assertEquals(sigToken2.getUnsignedToken(), unsignedTok);
        assertEquals(sigToken2.getSignature(), signature);
    }

    @Test
    public void testEmptyToken() {

        try {
            new RoleToken("");
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testNullToken() {

        try {
            new RoleToken(null);
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testTokenWithoutSignature() {

        RoleToken token = new RoleToken("v=S1;d=coretech;r=role1,role2");
        assertEquals(token.getDomain(), "coretech");
        assertNotNull(token.getRoles());
        assertEquals(token.getVersion(), "S1");
        assertNull(token.getUnsignedToken());
    }

    @Test
    public void testTokenWithExtraArgsAfterSignature() {

        RoleToken token = new RoleToken("v=Z1;d=coretech;r=role1,role2;s=signature;d=sports;r=api");
        assertEquals(token.getDomain(), "coretech");
        assertNotNull(token.getRoles());
        assertEquals(token.getRoles().size(), 2);
        assertTrue(token.getRoles().contains("role1"));
        assertTrue(token.getRoles().contains("role2"));
        assertEquals(token.getVersion(), "Z1");
        assertEquals(token.getSignature(), "signature;d=sports;r=api");
        assertEquals(token.getUnsignedToken(), "v=Z1;d=coretech;r=role1,role2");
    }

    @Test
    public void testTokenInvalidVersionValue() {

        RoleToken token = new RoleToken("v=S1=S2;d=coretech;r=role1,role2");
        assertNull(token.getVersion());
    }

    @Test
    public void testTokenDomainNull() {

        try {
            new RoleToken("v=S1;r=role1,role2;s=signature");
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testTokenDomainEmpty() {

        try {
            new RoleToken("v=S1;d=;r=role1,role2;s=signature");
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testTokenRolesNull() {

        try {
            new RoleToken("v=S1;d=coretech;s=signature");
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testTokenRolesEmpty() {

        try {
            new RoleToken("v=S1;d=coretech;r=;s=signature");
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testBuilderRequiredVersionNull() {

        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");
        try {
            new RoleToken.Builder(null, svcDomain, roles);
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testBuilderRequiredVersionEmptyString() {

        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");
        try {
            new RoleToken.Builder("", svcDomain, roles);
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testBuilderRequiredDomainNull() {

        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");
        try {
            new RoleToken.Builder(rolVersion, null, roles);
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testBuilderRequiredDomainEmptyString() {

        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");
        try {
            new RoleToken.Builder(rolVersion, "", roles);
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testBuilderRequiredRoleNull() {

        try {
            new RoleToken.Builder(rolVersion, svcDomain, null);
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testBuilderRequiredRoleEmptyString() {

        List<String> roles = new ArrayList<>();
        try {
            new RoleToken.Builder(rolVersion, svcDomain, roles);
            fail();
        } catch (Exception ex) {
            assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
        }
    }

    @Test
    public void testBuilderDefaultOptionalValues() {

        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");

        RoleToken token = new RoleToken.Builder(rolVersion, svcDomain, roles).build();
        assertEquals(token.getVersion(), rolVersion);
        assertEquals(token.getDomain(), svcDomain);
        assertEquals(token.getRoles(), roles);
        assertNull(token.getHost());
        assertNotNull(token.getSalt());
        assertEquals(token.getKeyId(), "0");
        assertNull(token.getIP());
        long timestamp = token.getTimestamp();
        assertTrue(timestamp != 0);
        assertEquals(token.getExpiryTime(), timestamp + 3600);
    }

    @Test
    public void testBuilderAllValues() {

        List<String> roles = new ArrayList<>();
        roles.add("storage.tenant.weather.updater");

        RoleToken token = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .issueTime(36000).expirationWindow(100).host("localhost").ip("127.0.0.1")
            .salt("salt").keyId("zone1").principal("user.joe").build();

        assertEquals(token.getVersion(), rolVersion);
        assertEquals(token.getDomain(), svcDomain);
        assertEquals(token.getRoles(), roles);
        assertEquals(token.getHost(), "localhost");
        assertEquals(token.getSalt(), "salt");
        assertEquals(token.getKeyId(), "zone1");
        assertEquals(token.getIP(), "127.0.0.1");
        assertEquals(token.getPrincipal(), "user.joe");
        assertEquals(token.getTimestamp(), 36000);
        assertEquals(token.getExpiryTime(), 36000 + 100);
    }

    @Test
    public void testRoleTokenWithPrincipal() {

        List<String> roles = new ArrayList<>();
        roles.add("reader");

        RoleToken token = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .issueTime(36000).expirationWindow(100).host("localhost").ip("127.0.0.1")
            .salt("salt").keyId("zone1").principal("coretech.storage").build();
        token.sign(ztsPrivateKeyStringK0);

        assertTrue(token.getSignedToken().contains(";p=coretech.storage;"));
    }

    @Test
    public void testRoleTokenWithNullPrincipal() {

        List<String> roles = new ArrayList<>();
        roles.add("reader");

        RoleToken token = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .issueTime(36000).expirationWindow(100).host("localhost").ip("127.0.0.1")
            .salt("salt").keyId("zone1").principal(null).build();
        token.sign(ztsPrivateKeyStringK0);

        assertFalse(token.getSignedToken().contains(";p="));
    }

    @Test
    public void testRoleTokenWithEmptyPrincipal() {

        List<String> roles = new ArrayList<>();
        roles.add("reader");

        RoleToken token = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .issueTime(36000).expirationWindow(100).host("localhost").ip("127.0.0.1")
            .salt("salt").keyId("zone1").principal("").build();
        token.sign(ztsPrivateKeyStringK0);

        assertFalse(token.getSignedToken().contains(";p="));
    }

    @Test
    public void testRoleTokenWithoutPrincipal() {

        List<String> roles = new ArrayList<>();
        roles.add("reader");

        RoleToken token = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .issueTime(36000).expirationWindow(100).host("localhost").ip("127.0.0.1")
            .salt("salt").keyId("zone1").build();
        token.sign(ztsPrivateKeyStringK0);

        assertFalse(token.getSignedToken().contains(";p="));
    }

    @Test
    public void testRoleTokenWithProxyUser() {

        List<String> roles = new ArrayList<>();
        roles.add("reader");

        RoleToken token = new RoleToken.Builder(rolVersion, svcDomain, roles)
            .issueTime(36000).expirationWindow(100).host("localhost").ip("127.0.0.1")
            .salt("salt").keyId("zone1").principal("coretech.storage")
            .proxyUser("user.user3").domainCompleteRoleSet(true).build();
        token.sign(ztsPrivateKeyStringK0);

        assertTrue(token.getSignedToken().contains(";proxy=user.user3;"));
        assertTrue(token.getSignedToken().contains(";c=1"));
    }

    @Test
    public void testRoleTokenParseWithProxyUser() {

        RoleToken token = new RoleToken("v=S1;d=coretech;r=role1,role2;proxy=user.user3;c=1;s=signature");
        assertEquals(token.getDomain(), "coretech");
        assertEquals(token.getProxyUser(), "user.user3");
        assertTrue(token.getDomainCompleteRoleSet());
    }

    @Test
    public void testRoleTokenWithNotCompleteRoleSet() {
        RoleToken token = new RoleToken("v=S1;d=coretech;r=role1,role2;proxy=user.user3;c=0;s=signature");
        assertEquals(token.getDomain(), "coretech");
        assertEquals(token.getProxyUser(), "user.user3");
        assertFalse(token.getDomainCompleteRoleSet());
    }

    @Test
    public void testRoleTokenParseWithoutProxyUser() {

        RoleToken token = new RoleToken("v=S1;d=coretech;r=role1,role2;s=signature");
        assertEquals(token.getDomain(), "coretech");
        assertNull(token.getProxyUser());
        assertFalse(token.getDomainCompleteRoleSet());
    }

    @Test
    public void testRoleTokenHost() {

        RoleToken token = new RoleToken("v=S1;d=coretech;h=host;r=role1,role2;s=signature");
        assertEquals(token.getHost(), "host");
        assertNull(token.getProxyUser());
    }
}


text:
.. include:: /defs.txt
.. |tick_props| image:: TickProps.png

.. _vi_yticks:

Set Y Ticks
===========

Set the Y axis tick locations, and optionally labels, for linear axis scales.

.. image:: YTicks.png

.. include:: /stdid.txt

|double_1d_in| **Tick Locations**
    Locations of Y-axis ticks (in data units).

|string_1d_in| **Tick Labels**
    Labels for the ticks.  By default, appropriate labels are chosen based
    on the type of data plotted and its range.

|tick_props| **Properties**
    Property cluster, available under the "Properties" subpalette.

    |cluster_in| **Text**
        Controls display of the tick labels.

        .. include:: /stdtext.txt

.. include:: /stderr.txt

.. include:: /stdpolar_ok.txt

Errors
------

* :ref:`error_scale`
* :ref:`error_invalid`
* :ref:`error_plotting`
* :ref:`error_init`

Other information
-----------------

If tick values are given which are offscreen, the plot will be expanded to
display them.  See :ref:`vi_limits` to set the X and Y axis ranges explicitly.

Non-finite (NaN or Inf) entries in **Tick Locations** are ignored, as are
corresponding entries in **Tick Labels**.

If the axis scale is log or symlog, error :ref:`error_scale` will result.


text:
require "#{Omnibus::Config.project_root}/lib/gitlab/version"
version = Gitlab::Version.new('gitlab-pages')

name 'gitlab-pages'
default_version version.print

license 'MIT'
license_file 'LICENSE'

skip_transitive_dependency_licensing true

source git: version.remote
relative_path 'src/gitlab.com/gitlab-org/gitlab-pages'

build do
  # This is required for GO15VENDOREXPERIMENT=1 to work properly,
  # since it requires the package to be in $GOPATH/src/package
  env = { 'GOPATH' => "#{Omnibus::Config.source_dir}/gitlab-pages" }

  # Pages compiles with CGO_ENABLED=0 by default, so we need to activate
  # FIPS mode explicitly.
  env['FIPS_MODE'] = '1' if Build::Check.use_system_ssl?

  make 'gitlab-pages', env: env

  mkdir "#{install_dir}/embedded/bin/"
  move 'gitlab-pages', "#{install_dir}/embedded/bin/gitlab-pages"

  command "license_finder report --enabled-package-managers godep gomodules --decisions-file=#{Omnibus::Config.project_root}/support/dependency_decisions.yml --format=json --columns name version licenses texts notice --save=license.json"
  copy "license.json", "#{install_dir}/licenses/gitlab-pages.json"
end


text:
function problem7() {
    var outputString,
        inputArray = document.getElementById('problem-7-input').value.split(' '),
        outputField = document.getElementById('problem-7-output');

    inputArray = inputArray.map(function(element) {
        return element * 1;
    });

    function indexOfFirstBigger(array) {
        var i,
            defaultIndex = -1;
        for (i = 1; i < array.length - 1; i+=1) {
            if(isBiggerThanNeighbours(array, i)) {
                return i;
            }
        }

        return defaultIndex;
    }

    outputString = "Index of the first number(" + inputArray[indexOfFirstBigger(inputArray)] +
        ") larger than it's neighbours is " + indexOfFirstBigger(inputArray) + '.';

    console.log('Problem 7');
    console.log(outputString);
    console.log('\n');

    outputField.innerHTML = outputString;
}


text:
package com.ealva.ealvalog.util;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import static java.util.FormattableFlags.ALTERNATE;
import static java.util.FormattableFlags.LEFT_JUSTIFY;
import static java.util.FormattableFlags.UPPERCASE;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.FormattableFlags;
import java.util.Formatter;

/**
 * Contains an optional {@link Throwable} for formatting on log record output. Will format to {@link Throwable#toString()} except if the
 * {@link FormattableFlags#ALTERNATE} is specified ($#), then the stack trace is included.
 * <p>
 * Created by Eric A. Snell on 3/8/17.
 */
@SuppressWarnings("unused")
public class FormattableThrowable extends BaseFormattable {
  private static final ThreadLocal<StringBuilder> threadLocalStringBuilder =
      new ThreadLocal<StringBuilder>() {
        @Override
        protected StringBuilder initialValue() {
          return new StringBuilder(1024);
        }

        @Override
        public StringBuilder get() {
          StringBuilder builder = super.get();
          builder.setLength(0);
          return builder;
        }
      };

  @SuppressWarnings("SameParameterValue")
  public static @NotNull FormattableThrowable make(final @Nullable Throwable throwable) {
    return new FormattableThrowable(throwable);
  }

  private @Nullable Throwable realThrowable;

  private FormattableThrowable(final @Nullable Throwable throwable) {
    realThrowable = throwable;
  }

  @Override
  public void formatTo(final Formatter formatter,
                       final int flags,
                       final int width,
                       final int precision) {
    final boolean useAlternate = (flags & ALTERNATE) == ALTERNATE;
    final boolean leftJustify = (flags & LEFT_JUSTIFY) == LEFT_JUSTIFY;
    final boolean upperCase = (flags & UPPERCASE) == UPPERCASE;
    final StringBuilder builder = threadLocalStringBuilder.get();

    if (realThrowable != null) {
      if (useAlternate) {
        getStackTraceAsString(builder, realThrowable);
      } else {
        builder.append(realThrowable.toString());
      }
      if (precision != -1 && builder.length() > precision) {
        builder.setLength(precision - 1);
        builder.append('…');
      }
    } else {
      formatter.format("");
    }
    maybePadAndJustify(width, leftJustify, builder);
    formatter.format(upperCase ? builder.toString().toUpperCase() : builder.toString());
  }

  public @Nullable Throwable getRealThrowable() {
    return realThrowable;
  }

  public void setRealThrowable(final @Nullable Throwable realThrowable) {
    this.realThrowable = realThrowable;
  }

  /**
   * Later we may find a better way to do this, such as a PrintWriter impl that writes to a StringBuilder. So, we'll pass in the
   * StringBuilder to this method instead of returning a string.
   */
  private static void getStackTraceAsString(final StringBuilder builder, Throwable throwable) {
    StringWriter stringWriter = new StringWriter();
    throwable.printStackTrace(new PrintWriter(stringWriter));
    builder.append(stringWriter.toString());
  }
}


text:
<?php

namespace BinSoul\Db\Orm;

use BinSoul\Common\Equatable;
use BinSoul\Common\Nullable;
use BinSoul\Common\Identifiable;

/**
 * Represents an object built from the data of a database table row.
 */
interface Entity extends Identifiable, Equatable, Nullable
{
    /**
     * Constructs an instance.
     *
     * @param int|string|null $id
     * @param mixed[]         $data
     */
    public function __construct($id, array $data);

    /**
     * Returns the identifier the entity.
     *
     * @return int|string|null
     */
    public function getId();

    /**
     * Returns the data of the entity.
     *
     * @return mixed[]
     */
    public function getData();
}


text:
from nose.tools import assert_equals
from tests import with_database
from acoustid.data.source import find_or_insert_source

@with_database
def test_find_or_insert_source(conn):
    rows = conn.execute("SELECT id, account_id, application_id FROM source ORDER BY id").fetchall()
    expected_rows = [
        (1, 1, 1),
        (2, 2, 2),
    ]
    assert_equals(expected_rows, rows)
    id = find_or_insert_source(conn, 1, 1)
    assert_equals(1, id)
    id = find_or_insert_source(conn, 2, 2)
    assert_equals(2, id)
    id = find_or_insert_source(conn, 1, 2)
    assert_equals(3, id)
    rows = conn.execute("SELECT id, account_id, application_id FROM source ORDER BY id").fetchall()
    expected_rows = [
        (1, 1, 1),
        (2, 2, 2),
        (3, 2, 1),
    ]
    assert_equals(expected_rows, rows)


text:
describe("$.unbind", function () {

	helpers.fixture("events.html");
	var spy1, spy2, spy3, subject;

	beforeEach(function () {
		spy1 = sinon.spy();
		spy2 = sinon.spy();
		spy3 = sinon.spy();
		subject = document.querySelector("#simpleDiv");
	});

	it("exists", function () {
		expect($.unbind).to.exist;
	});

	it("unbinds events using namespaces", function (done) {
		// Setup
		subject.addEventListener("click.namespace1", spy1);
		subject.addEventListener("click.namespace1", spy2);
		subject.addEventListener("click.namespace2", spy3);

		// Exercise
		$.unbind(subject, ".namespace1");
		fireEvent(subject, "click");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.notCalled).to.be.ok;
		expect(spy3.calledOnce).to.be.ok;

		done();
	});

	it("unbinds a single event listener", function (done) {
		// Setup
		subject.addEventListener("click", spy1);
		subject.addEventListener("click", spy2);
		subject.addEventListener("change", spy3);

		// Exercise
		$.unbind(subject, "click", spy1);
		fireEvent(subject, "click");
		fireEvent(subject, "change");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.calledOnce).to.be.ok;
		expect(spy3.calledOnce).to.be.ok;

		done();
	});

	it("unbinds a single event listener when passed an object", function (done) {
		// Setup
		subject.addEventListener("click", spy1);
		subject.addEventListener("click", spy2);
		subject.addEventListener("change", spy3);

		// Exercise
		$.unbind(subject, {click: spy1});
		fireEvent(subject, "click");
		fireEvent(subject, "change");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.calledOnce).to.be.ok;
		expect(spy3.calledOnce).to.be.ok;

		done();
	});

	it("unbinds listeners when only type passed", function (done) {
		// Setup
		subject.addEventListener("click", spy1);
		subject.addEventListener("click", spy2);
		subject.addEventListener("change", spy3);

		// Exercise
		$.unbind(subject, "click");
		fireEvent(subject, "click");
		fireEvent(subject, "change");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.notCalled).to.be.ok;
		expect(spy3.calledOnce).to.be.ok;

		done();
	});

	it("unbinds listeners when only type and options passed", function (done) {
		// Setup
		subject.addEventListener("click", spy1, true);
		subject.addEventListener("click", spy2, {once: true});
		subject.addEventListener("change", spy3);

		// Exercise
		$.unbind(subject, "click", {capture: true});
		fireEvent(subject, "click");
		fireEvent(subject, "change");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.calledOnce).to.be.ok;
		expect(spy3.calledOnce).to.be.ok;

		done();
	});

	it("unbinds multiple event listeners", function (done) {
		// Setup
		subject.addEventListener("click", spy1);
		subject.addEventListener("change", spy1);
		subject.addEventListener("click", spy2);
		subject.addEventListener("change", spy2);

		// Exercise
		$.unbind(subject, "click change", spy1);
		fireEvent(subject, "click");
		fireEvent(subject, "change");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.calledTwice).to.be.ok;

		done();
	});

	it("unbinds multiple event listeners when passed object", function (done) {
		// Setup
		subject.addEventListener("click", spy1);
		subject.addEventListener("change", spy1);
		subject.addEventListener("click", spy2);
		subject.addEventListener("change", spy2);

		// Exercise
		$.unbind(subject, {"click change": spy1});
		fireEvent(subject, "click");
		fireEvent(subject, "change");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.calledTwice).to.be.ok;

		done();
	});

	it("unbinds all event listeners", function (done) {
		// Setup
		subject.addEventListener("click", spy1);
		subject.addEventListener("change", spy1);
		subject.addEventListener("click", spy2);
		subject.addEventListener("change", spy3);
		subject.addEventListener("click.namespace1.bar", spy2);

		// Exercise
		$.unbind(subject);
		fireEvent(subject, "click");
		fireEvent(subject, "change");

		// Verify
		expect(spy1.notCalled).to.be.ok;
		expect(spy2.notCalled).to.be.ok;
		expect(spy3.notCalled).to.be.ok;

		done();
	});

	function fireEvent(target, eventName) {
		var event = new Event(eventName, {"bubbles": true, "cancelable": true});
		target.dispatchEvent(event);
	}

});


text:
package org.cryptoworkshop.ximix.node.crypto.operator;

import org.bouncycastle.crypto.params.ECDomainParameters;
import org.cryptoworkshop.ximix.node.service.PrivateKeyOperator;

/**
 * Base interface for an Elliptic Curve operator.
 */
public interface ECPrivateKeyOperator
    extends PrivateKeyOperator
{
    ECDomainParameters getDomainParameters();

    <T> T transform(T value);
}


text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.us.Common;
using OpenADK.Library.us.Gradebook;
using OpenADK.Library.us.Student;

namespace OpenADK.Library.us.Etranscripts{

/// A Term
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.0</para>
/// </remarks>
[Serializable]
public class Term : SifElement
{
	///
	/// Creates an instance of a Term
	///
	public Term() : base ( EtranscriptsDTD.TERM ){}

	///
	/// Constructor used by the .Net Serialization formatter
	///
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected Term( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	///Sets the value of the <c><TermInfoData></c> element.
	/// <param name="SchoolAttendedRefId">Reference to the school of record for the courses being taken (see SchoolAttended).</param>
	///<remarks>
	/// <para>This form of <c>setTermInfoData</c> is provided as a convenience method
	/// that is functionally equivalent to the <c>TermInfoData</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.0</para>
	/// </remarks>
	public void SetTermInfoData( string SchoolAttendedRefId ) {
		RemoveChild( EtranscriptsDTD.TERM_TERMINFODATA);
		AddChild( EtranscriptsDTD.TERM_TERMINFODATA, new TermInfoData( SchoolAttendedRefId ) );
	}

	///
	/// Gets or sets the value of the <c><TermInfoData></c> element.
	///
	/// <value> A TermInfoData </value>
	/// <remarks>
	/// <para>To remove the <c>TermInfoData</c>, set <c>TermInfoData</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.0</para>
	/// </remarks>
	public TermInfoData TermInfoData
	{
		get
		{
			return (TermInfoData)GetChild( EtranscriptsDTD.TERM_TERMINFODATA);
		}
		set
		{
			RemoveChild( EtranscriptsDTD.TERM_TERMINFODATA);
			if( value != null)
			{
				AddChild( EtranscriptsDTD.TERM_TERMINFODATA, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><Courses></c> element.
	///
	/// <value> A Courses </value>
	/// <remarks>
	/// <para>To remove the <c>Courses</c>, set <c>Courses</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.0</para>
	/// </remarks>
	public Courses Courses
	{
		get
		{
			return (Courses)GetChild( EtranscriptsDTD.TERM_COURSES);
		}
		set
		{
			RemoveChild( EtranscriptsDTD.TERM_COURSES);
			if( value != null)
			{
				AddChild( EtranscriptsDTD.TERM_COURSES, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><SIF_ExtendedElements></c> element.
	///
	/// <value> A SIF_ExtendedElements </value>
	/// <remarks>
	/// <para>To remove the <c>SIF_ExtendedElements</c>, set <c>SIF_ExtendedElements</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.4</para>
	/// </remarks>
	public SIF_ExtendedElements SIF_ExtendedElements
	{
		get
		{
			return (SIF_ExtendedElements)GetChild( EtranscriptsDTD.TERM_SIF_EXTENDEDELEMENTS);
		}
		set
		{
			RemoveChild( EtranscriptsDTD.TERM_SIF_EXTENDEDELEMENTS);
			if( value != null)
			{
				AddChild( EtranscriptsDTD.TERM_SIF_EXTENDEDELEMENTS, value );
			}
		}
	}

}}


text:
require 'spec_helper'

module SpreeImportExportProducts
  describe ImportProducts do
    describe '#parse_file' do
      it 'parse a csv file' do
        subject.parse_file(Rails.root.join('spec','test.csv'))
        expect(subject.instance_variable_get(:@products)).to eq [{ name: 'Test name', price: '20', shipping_category_id: '1'}]
        expect(subject.instance_variable_get(:@associations)).to eq [{ taxons: 'brand:test_brand'}]
      end
    end

    describe '#load' do
      it 'creates a new product' do
        expect do
          subject.load(Rails.root.join('spec','test.csv'))
        end.to change{Spree::Product.count}.from(0).to(1)
      end
    end

    describe '#create_taxon' do
      let(:product){ FactoryGirl.create :product }

      before do
        subject.create_taxon([product], 'brand:test_brand')
      end

      it 'creates a taxonomy' do
        expect(Spree::Taxonomy.count).to eq 1
      end

      it 'creates a taxon' do
        expect(Spree::Taxon.count).to eq 1
      end
    end
  end
end


text:
var repo = function () {

    var db = process.env.CONSTRING || '';
    //var mongodb = require('mongodb').MongoClient;
    //var objectId = require('mongodb').ObjectID;

    var save = function (menu) {
        console.log('Saving menu db' + this.name);
        return {
            completed: true
        };
    };
    var deleteMenu = function (menu) {
        console.log('Deleting menu db' + this.name);
        return {
            completed: true
        };

    };
    var update = function (menu) {
        console.log('Updateing Menu db' + this.name);
        return {
            completed: true
        };

    };
    var getAll = function () {
        var lsmenu = null;

        console.log('getAll Menu db');

        return {
            menus: lsmenu
        };
    };
    var getById = function (id) {
        var menu = {};
        console.log('getById Menu db');
        return {
            menu: menu
        };
    };
    var getByName = function (name) {
        var menu = {};
        console.log('getByName Menu db');
        return {
            menu: menu
        };
    };

    return {
        getById: getById,
        getByName: getByName,
        getAll: getAll,
        save: save,
        delete:deleteMenu,
        update:update
    };

};

module.exports = repo();

// var mongodb = require('mongodb').MongoClient;
// var objectId = require('mongodb').ObjectID;

// var personaController = function (personaService, nav) {

//     var middleware = function (req, res, next) {
//         if (!req.user) {
//             res.redirect('/Autenticacion');
//         }
//         next();
//     }
//     var getIndex = function (req, res) {
//         var url =
//             'mongodb://localhost:27017/prnodejs01db';

//         mongodb.connect(url, function (err, db) {
//             var collection = db.collection('Personas');
//             collection.find({}).toArray(
//                 function (err, results) {
//                     res.render('Personas', {
//                         title: 'Personas Catálogo',
//                         nav: nav,
//                         list: ['1a', '2b', '3c'],
//                         personas: results
//                     });

//                 });
//         });
//     }

//     var getById = function (req, res) {

//         var id = new objectId(req.params.id);
//         var url =
//             'mongodb://localhost:27017/prnodejs01db';

//         mongodb.connect(url, function (err, db) {
//             var collection = db.collection('Personas');

//             collection.findOne({ _id: id }, function (err, results) {
//                // console.log(results);
//                 res.render('Dtpersona', {
//                     title: 'Detalles personas',
//                     nav: nav,
//                     list: ['1a', '2b', '3c'],
//                     persona: results
//                 });

//             });
//         });

//     }

//     return {
//         getIndex: getIndex,
//         getById: getById,
//         middleware: middleware
//     };
// };

// module.exports = personaController;