text:
```` sql
-- which 20 networks have the most stations, and how many does each have?
SELECT
 top_networks.*
 ,n.city
 ,n.country
 ,n.feed_url
 ,n.system_type
 ,n.feed_format
FROM (
    SELECT network_tag, count(DISTINCT id) AS station_count
    FROM stations
    GROUP BY 1
    ORDER BY 2 DESC
    LIMIT 20
) top_networks
JOIN networks n ON n.tag = top_networks.network_tag
````

```` sql
-- which companies operate the greatest number of bike-share networks?
SELECT
  nc.name AS company_name
  ,count(DISTINCT network_tag) AS network_count
FROM network_companies nc
GROUP BY 1
HAVING network_count > 4
ORDER BY 2 DESC
````

=>

company_name	|	network_count
--- | ---
Nextbike GmbH	|	108
Comunicare S.r.l.	|	99
Domoblue	|	43
Crispin Porter + Bogusky	|	23
Trek Bicycle Corporation	|	23
Humana	|	23
PBSC	|	13
DB Rent GmbH	|	13
Alta Bicycle Share, Inc	|	12
Mobilicidade Tecnologia LTD	|	12
Grupo Serttel LTDA	|	12
Brainbox Technology	|	11
Cyclopolis Systems	|	11
Smoove SAS	|	11
ClearChannel	|	5


text:
<?php

namespace AppBundle\Factory\Item\Main;

use AppBundle\Entity\Main\BenchmarkEnum;
use AppBundle\Factory\Item\Base\ItemFactory;

class BenchmarkEnumFactory extends ItemFactory {

	public function __construct() {
		parent::__construct(BenchmarkEnum::class);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.lunatic.mlx.cuisines

/**
  * Some basic paths configuration
  */
case class Configuration(args: Array[String]) {

  // TODO: Refactor and improve

  val argsMap = args.map(_.split("=")).map(x => (x(0), x(1))).toMap

  val inputTrainingData = argsMap.getOrElse("app.input.file.training", "data/cuisines/train.json")

  val inputTestingData = argsMap.getOrElse("app.input.file.test", "data/cuisines/test.json")

  val outputPredictionsPath = argsMap.getOrElse("app.output.file.predictions", "/tmp/predictions")

  private val modelRootPath = argsMap.getOrElse("app.model.dir", "working_model")

  val dataPath = s"$modelRootPath/flow_data"

  val recipesPath = s"$modelRootPath/recipes"

  private val trainingDataRoot = s"$modelRootPath/training/"

  val naiveBayesPath = trainingDataRoot + "naive_bayes.model"

  val logisticRegPath = trainingDataRoot + "logistic_regression.model"

  val decisionTreePath = trainingDataRoot + "decision_tree.model"

  val randomForestPath = trainingDataRoot + "random_forest.model"

  val es_index_auto_create = argsMap.getOrElse("es.index.auto.create", "true")

  val es_nodes = argsMap.getOrElse("es.nodes","localhost")

  val es_port = argsMap.getOrElse("es.port","9200")

}


text:
import {baseResource} from './baseResource';

/**
 * Websudo
 *
 * @constructor Websudo
 * @property {IConnector} connector the jira connector instance
 */

export class Websudo extends baseResource {

    constructor (connector:IConnector,Model:any,settings:any) {
        super(connector,Model,settings);
        this.methods = [];
        this.register();
    }

    /**
     * This method invalidates the any current WebSudo session.
     *
     * @method release
     * @memberOf Websudo#
     * @param {Object} options An object containing options to pass to the Jira API.
     * @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
     * @param [callback] if supplied, called with result of api call
     * @return {Promise.<any>} result of api call
     */

    release = (...args : any[]):Promise<any> => {

        if (args.length === 0) {
            throw new Error("options must be passed");
        }

        let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;

        let options = ((typeof args[0]) === 'object') ? args[0] : {}

        return this.makeRequest('release','DELETE','rest/auth/1/websudo',options,callback)
    };

}


text:
module JazzFingers
  module Commands
    SQL = Pry::CommandSet.new do
      command "sql", "Send sql over AR." do |query|
        if defined?(Rails)
          pp ActiveRecord::Base.connection.select_all(query)
        else
          pp "Rails not defined"
        end
      end
    end
  end
end


text:
The goal of this application is to list the shelters deployed around the world.

The official instance is available [here](https://shelter-database.org).

## Deployment

### Requirements

```bash
$ sudo apt-get install postgresql npm
```

Also it seems that today a proof of good taste is to install first
[pyenv](https://github.com/pyenv/pyenv),
then [pipsi](https://github.com/mitsuhiko/pipsi), and finally
[pew](https://github.com/berdario/pew) and
[pipenv](https://github.com/pypa/pipenv) with pipsi.

### Configure and install the application

### Database configuration

```bash
$ ./create_db.sh shelter pgsqluser pgsqlpwd
```

### Application

```bash
~/git$ git clone https://github.com/rodekruis/shelter-database.git
~/git$ cd shelter-database/
~/git/shelter-database$ cp src/conf/conf.cfg-sample src/conf/conf.cfg
~/git/shelter-database$ pipenv install
✨🍰✨
~/git/shelter-database$ pipenv shell

(shelter-database-JZplA0Yt) ~/git/shelter-database$ npm install

(shelter-database-JZplA0Yt) ~/git/shelter-database$ ./create_db.sh shelter pgsqluser pgsqlpwd
(shelter-database-JZplA0Yt) ~/git/shelter-database$ ./init_db.sh

(shelter-database-JZplA0Yt) ~/git/shelter-database$ python src/runserver.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
```

Read the [documentation](/documentation) for more  information about
the deployment of the application.

## Documentation

To generate the documentation in HTML format:

    ./documentation$ sudo pip install sphinx
    ./documentation$ make html

The result will be in the *_build* folder.

## License

This application is under MIT license.

## Contact

* https://github.com/rodekruis/shelter-database

Browser testing provided by -
[![BrowserStack](https://scottlogic.github.io/d3fc/images/browser-stack.svg)](https://browserstack.com)


text:
namespace remoting {
namespace protocol {

namespace {

const buzz::StaticQName kMethodAttributeQName = { "", "method" };
const buzz::StaticQName kSupportedMethodsAttributeQName =
    { "", "supported-methods" };

const char kSupportedMethodsSeparator = ',';

}  // namespace

// static
scoped_ptr<Authenticator> NegotiatingAuthenticator::CreateForClient(
    const std::string& authentication_tag,
    const FetchSecretCallback& fetch_secret_callback,
    const std::vector<AuthenticationMethod>& methods) {
  scoped_ptr<NegotiatingAuthenticator> result(
      new NegotiatingAuthenticator(MESSAGE_READY));
  result->authentication_tag_ = authentication_tag;
  result->fetch_secret_callback_ = fetch_secret_callback;

  DCHECK(!methods.empty());
  for (std::vector<AuthenticationMethod>::const_iterator it = methods.begin();
       it != methods.end(); ++it) {
    result->AddMethod(*it);
  }

  return scoped_ptr<Authenticator>(result.Pass());
}

// static
scoped_ptr<Authenticator> NegotiatingAuthenticator::CreateForHost(
    const std::string& local_cert,
    scoped_refptr<RsaKeyPair> key_pair,
    const std::string& shared_secret_hash,
    AuthenticationMethod::HashFunction hash_function) {
  scoped_ptr<NegotiatingAuthenticator> result(
      new NegotiatingAuthenticator(WAITING_MESSAGE));
  result->local_cert_ = local_cert;
  result->local_key_pair_ = key_pair;
  result->shared_secret_hash_ = shared_secret_hash;

  result->AddMethod(AuthenticationMethod::Spake2(hash_function));

  return scoped_ptr<Authenticator>(result.Pass());
}

NegotiatingAuthenticator::NegotiatingAuthenticator(
    Authenticator::State initial_state)
    : current_method_(AuthenticationMethod::Invalid()),
      state_(initial_state),
      rejection_reason_(INVALID_CREDENTIALS),
      weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}

NegotiatingAuthenticator::~NegotiatingAuthenticator() {
}

Authenticator::State NegotiatingAuthenticator::state() const {
  return state_;
}

Authenticator::RejectionReason
NegotiatingAuthenticator::rejection_reason() const {
  return rejection_reason_;
}

void NegotiatingAuthenticator::ProcessMessage(
    const buzz::XmlElement* message,
    const base::Closure& resume_callback) {
  DCHECK_EQ(state(), WAITING_MESSAGE);

  std::string method_attr = message->Attr(kMethodAttributeQName);
  AuthenticationMethod method = AuthenticationMethod::FromString(method_attr);

  // Check if the remote end specified a method that is not supported locally.
  if (method.is_valid() &&
      std::find(methods_.begin(), methods_.end(), method) == methods_.end()) {
    method = AuthenticationMethod::Invalid();
  }

  // If the remote peer did not specify auth method or specified unknown
  // method then select the first known method from the supported-methods
  // attribute.
  if (!method.is_valid()) {
    std::string supported_methods_attr =
        message->Attr(kSupportedMethodsAttributeQName);
    if (supported_methods_attr.empty()) {
      // Message contains neither method nor supported-methods attributes.
      state_ = REJECTED;
      rejection_reason_ = PROTOCOL_ERROR;
      resume_callback.Run();
      return;
    }

    // Find the first mutually-supported method in the peer's list of
    // supported-methods.
    std::vector<std::string> supported_methods_strs;
    base::SplitString(supported_methods_attr, kSupportedMethodsSeparator,
                      &supported_methods_strs);
    for (std::vector<std::string>::iterator it = supported_methods_strs.begin();
         it != supported_methods_strs.end(); ++it) {
      AuthenticationMethod list_value = AuthenticationMethod::FromString(*it);
      if (list_value.is_valid() &&
          std::find(methods_.begin(),
                    methods_.end(), list_value) != methods_.end()) {
        // Found common method.
        method = list_value;
        break;
      }
    }

    if (!method.is_valid()) {
      // Failed to find a common auth method.
      state_ = REJECTED;
      rejection_reason_ = PROTOCOL_ERROR;
      resume_callback.Run();
      return;
    }

    // Drop the current message because we've chosen a different
    // method.
    current_method_ = method;
    state_ = PROCESSING_MESSAGE;
    CreateAuthenticator(MESSAGE_READY, base::Bind(
        &NegotiatingAuthenticator::UpdateState,
        base::Unretained(this), resume_callback));
    return;
  }
  if (method != current_method_) {
    current_method_ = method;
    state_ = PROCESSING_MESSAGE;
    // Copy the message since the authenticator may process it asynchronously.
    CreateAuthenticator(WAITING_MESSAGE, base::Bind(
        &NegotiatingAuthenticator::ProcessMessageInternal,
        base::Unretained(this), base::Owned(new buzz::XmlElement(*message)),
        resume_callback));
    return;
  }
  ProcessMessageInternal(message, resume_callback);
}

void NegotiatingAuthenticator::UpdateState(
    const base::Closure& resume_callback) {
  // After the underlying authenticator finishes processing the message, the
  // NegotiatingAuthenticator must update its own state before running the
  // |resume_callback| to resume the session negotiation.
  state_ = current_authenticator_->state();
  if (state_ == REJECTED)
    rejection_reason_ = current_authenticator_->rejection_reason();
  resume_callback.Run();
}

scoped_ptr<buzz::XmlElement> NegotiatingAuthenticator::GetNextMessage() {
  DCHECK_EQ(state(), MESSAGE_READY);

  scoped_ptr<buzz::XmlElement> result;

  // No method yet, just send a message with the list of supported methods.
  // Normally happens only on client.
  if (!current_method_.is_valid()) {
    result = CreateEmptyAuthenticatorMessage();
    std::stringstream supported_methods(std::stringstream::out);
    for (std::vector<AuthenticationMethod>::iterator it = methods_.begin();
         it != methods_.end(); ++it) {
      if (it != methods_.begin())
        supported_methods << kSupportedMethodsSeparator;
      supported_methods << it->ToString();
    }
    result->AddAttr(kSupportedMethodsAttributeQName, supported_methods.str());
    state_ = WAITING_MESSAGE;
  } else {
    if (current_authenticator_->state() == MESSAGE_READY) {
      result = current_authenticator_->GetNextMessage();
    } else {
      result = CreateEmptyAuthenticatorMessage();
    }
    state_ = current_authenticator_->state();
    DCHECK(state_ == ACCEPTED || state_ == WAITING_MESSAGE);
    result->AddAttr(kMethodAttributeQName, current_method_.ToString());
  }

  return result.Pass();
}

void NegotiatingAuthenticator::AddMethod(const AuthenticationMethod& method) {
  DCHECK(method.is_valid());
  methods_.push_back(method);
}

scoped_ptr<ChannelAuthenticator>
NegotiatingAuthenticator::CreateChannelAuthenticator() const {
  DCHECK_EQ(state(), ACCEPTED);
  return current_authenticator_->CreateChannelAuthenticator();
}

bool NegotiatingAuthenticator::is_host_side() const {
  return local_key_pair_.get() != NULL;
}

void NegotiatingAuthenticator::CreateAuthenticator(
    Authenticator::State preferred_initial_state,
    const base::Closure& resume_callback) {
  if (is_host_side()) {
    current_authenticator_ = V2Authenticator::CreateForHost(
        local_cert_, local_key_pair_, shared_secret_hash_,
        preferred_initial_state);
    resume_callback.Run();
  } else {
    fetch_secret_callback_.Run(base::Bind(
        &NegotiatingAuthenticator::CreateV2AuthenticatorWithSecret,
        weak_factory_.GetWeakPtr(), preferred_initial_state, resume_callback));
  }
}

void NegotiatingAuthenticator::ProcessMessageInternal(
    const buzz::XmlElement* message,
    const base::Closure& resume_callback) {
  if (current_authenticator_->state() == WAITING_MESSAGE) {
    // If the message was not discarded and the authenticator is waiting for it,
    // give it to the underlying authenticator to process.
    // |current_authenticator_| is owned, so Unretained() is safe here.
    current_authenticator_->ProcessMessage(message, base::Bind(
        &NegotiatingAuthenticator::UpdateState,
        base::Unretained(this), resume_callback));
  }
}

void NegotiatingAuthenticator::CreateV2AuthenticatorWithSecret(
    Authenticator::State initial_state,
    const base::Closure& resume_callback,
    const std::string& shared_secret) {
  current_authenticator_ = V2Authenticator::CreateForClient(
      AuthenticationMethod::ApplyHashFunction(
          current_method_.hash_function(), authentication_tag_, shared_secret),
      initial_state);
  resume_callback.Run();
}

}  // namespace protocol
}  // namespace remoting


text:
package org.nisshiee.crowd4s

import scalaz._, Scalaz._
import org.json4s._
import org.json4s.jackson.JsonMethods._
import scala.util.control.Exception.allCatch

trait Authorize {

  import Authorize._

  def authorize
    (username: String, password: Password)
    (implicit authorizedGroup: AuthorizedGroup, conn: CrowdConnection, http: CrowdHttp) =
      Crowd.authenticate(username, password) flatMap checkAuthenticationResult(authorizedGroup)
}

object Authorize {

  import AuthenticationResult.{ Success => AtSuccess, Failure => AtFailure }
  import AuthorizationResult.{ Success => ArSuccess }
  import AuthorizationResult.{ AuthenticationFailure => AAFailure }
  import AuthorizationResult.{ AuthorizationFailure => ArFailure }

  def checkAuthenticationResult
      (authorized: AuthorizedGroup)
      (res: AuthenticationResult)
      (implicit conn: CrowdConnection, http: CrowdHttp)
      : Validation[CrowdError, AuthorizationResult] = res match {
        case AtSuccess(u) => Crowd.getDirectGroupList(u.name) flatMap { belonged =>
          searchAuthorizedGroup(authorized, belonged)(u)
        }
        case e: AtFailure => AAFailure(e).success
      }

  def searchAuthorizedGroup
      (authorized: AuthorizedGroup, belonged: Seq[String])
      (user: User)
      (implicit conn: CrowdConnection, http: CrowdHttp)
      : Validation[CrowdError, AuthorizationResult] =
        authorized.names.toStream filter (belonged contains _) map checkActive collectFirst {
          case Success(Some(g)) => ArSuccess(user, g).success
          case Failure(e) => e.failure
        } getOrElse ArFailure(user).success

  def checkActive(groupname: String)(implicit conn: CrowdConnection, http: CrowdHttp) =
    Crowd.getGroup(groupname) map { g => g.active option g }
}


text:
class Parent

	def override()
		puts "PARENT override()"
	end

	def implicit()
		puts "PARENT implicit()"
	end

	def altered()
		puts "PARENT altered()"
	end
end

class Child < Parent

	def override()
		puts "CHILD override()"
	end

	def altered()
		puts "CHILD, BEFORE PARENT altered()"
		super()
		puts "CHILD, AFTER PARENT altered()"
	end

end

dad = Parent.new()
son = Child.new()

dad.implicit()
son.implicit()

dad.override()
son.override()

dad.altered()
son.altered()


text:
class ImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick
  include CarrierWave::BombShelter

  # Choose what kind of storage to use for this uploader:
  storage :file

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process resize_to_fit: [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_whitelist
    %w[jpg jpeg gif png]
  end

  def max_pixel_dimensions
    [8192, 8192]
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here,
  #  see uploader/store.rb for details.
  # def filename
  #   super
  # end
end


text:
<?php namespace Larapress\Tests\Commands;

use Cartalyst\Sentry\Groups\GroupNotFoundException;
use Cartalyst\Sentry\Users\UserExistsException;
use Larapress\Tests\Commands\Proxies\GroupProxy;
use Larapress\Tests\Commands\Proxies\InstallCommandProxy;
use Larapress\Tests\TestCase;
use Mockery;
use Mockery\Mock;

class InstallCommandTest extends TestCase {

	/**
	 * @var Mock
	 */
	private $sentry;

	/**
	 * @var Mock
	 */
	private $mockably;

	public function setUp()
	{
		parent::setUp();

		$this->sentry = Mockery::mock('\Cartalyst\Sentry\Sentry');
		$this->mockably = Mockery::mock('\Larapress\Services\Mockably');
	}

	public function tearDown()
	{
		parent::tearDown();

		$_SERVER['error'] = array();
		$_SERVER['info'] = array();
		$_SERVER['call'] = array();
	}

	protected function getInstallCommandInstance()
	{
		$this->mockably->shouldReceive('route')->with('larapress.home.login.get')->once()->andReturn('url');

		return new InstallCommandProxy($this->sentry, $this->mockably);
	}

	/**
	 * @test abort_command()
	 */
	public function abort_command()
	{
		$this->mockably->shouldReceive('mockable_die')->once();
		$installCommand = $this->getInstallCommandInstance();

		$installCommand->abort_command('foo');

		$this->assertEquals('migrate:reset', $_SERVER['call'][0]);
		$this->assertEquals('foo', $_SERVER['error'][0]);
	}

	/**
	 * @test create_user_groups() can return the admin group
	 */
	public function create_user_groups_can_return_the_admin_group()
	{
		$this->assertClassHasAttribute('groups', 'Larapress\Commands\InstallCommand');
		$this->sentry->shouldReceive('createGroup')->times(3)->andReturn('foo');
		$installCommand = $this->getInstallCommandInstance();

		$this->assertEquals('foo', $installCommand->create_user_groups());
	}

	/**
	 * @test create_user_groups() can abort on name required exception
	 */
	public function create_user_groups_can_abort_on_name_required_exception()
	{
		$this->mockably->shouldReceive('mockable_die')->once();
		$this->sentry->shouldReceive('createGroup')->once()
			->andThrow('Cartalyst\Sentry\Groups\NameRequiredException');
		$installCommand = $this->getInstallCommandInstance();

		$installCommand->create_user_groups();

		$this->assertEquals('migrate:reset', $_SERVER['call'][0]);
		$this->assertEquals('Name field is required', $_SERVER['error'][0]);
	}

	/**
	 * @test create_user_groups() can abort on group exists exception
	 */
	public function create_user_groups_can_abort_on_group_exists_exception()
	{
		$this->mockably->shouldReceive('mockable_die')->once();
		$this->sentry->shouldReceive('createGroup')->once()
			->andThrow('Cartalyst\Sentry\Groups\GroupExistsException');
		$installCommand = $this->getInstallCommandInstance();

		$installCommand->create_user_groups();

		$this->assertEquals('migrate:reset', $_SERVER['call'][0]);
		$this->assertEquals('Group already exists', $_SERVER['error'][0]);
	}

	/**
	 * @test handle_unexpected_value_exception() can handle user exists exception
	 */
	public function handle_unexpected_value_exception_can_handle_user_exists_exception()
	{
		$this->mockably->shouldReceive('mockable_die')->atLeast()->once();
		$installCommand = $this->getInstallCommandInstance();

		$exception = new UserExistsException;
		$installCommand->handle_unexpected_value_exception($exception);

		$this->assertEquals('migrate:reset', $_SERVER['call'][0]);
		$this->assertEquals('User with this login already exists.', $_SERVER['error'][0]);
	}

	/**
	 * @test handle_unexpected_value_exception() can handle group not found exception
	 */
	public function handle_unexpected_value_exception_can_handle_group_not_found_exception()
	{
		$this->mockably->shouldReceive('mockable_die')->atLeast()->once();
		$installCommand = $this->getInstallCommandInstance();

		$exception = new GroupNotFoundException;
		$installCommand->handle_unexpected_value_exception($exception);

		$this->assertEquals('migrate:reset', $_SERVER['call'][0]);
		$this->assertEquals('Group was not found.', $_SERVER['error'][0]);
	}

	/**
	 * @test handle_unexpected_value_exception() can handle random exceptions
	 */
	public function handle_unexpected_value_exception_can_handle_random_exceptions()
	{
		$this->mockably->shouldReceive('mockable_die')->atLeast()->once();
		$installCommand = $this->getInstallCommandInstance();

		$exception = Mockery::mock();
		$installCommand->handle_unexpected_value_exception($exception);

		$this->assertEquals('migrate:reset', $_SERVER['call'][0]);
		$this->assertEquals('Unexpected value error.', $_SERVER['error'][0]);
	}

	/**
	 * @test add_the_admin_user() can create user
	 */
	public function add_the_admin_user_can_create_user()
	{
		$credentials = array(
			'email'     => 'admin@example.com',
			'password'  => 'password',
			'activated' => true,
		);

		$user = Mockery::mock();
		$user->shouldReceive('addGroup')->with('foo')->once();
		$this->sentry->shouldReceive('createUser')->with($credentials)->once()->andReturn($user);
		$installCommand = $this->getInstallCommandInstance();

		$installCommand->add_the_admin_user('foo');
	}

	/**
	 * @test add_the_admin_user() can handle unexpected value exceptions
	 */
	public function add_the_admin_user_can_handle_unexpected_value_exceptions()
	{
		$this->sentry->shouldReceive('createUser')->withAnyArgs()->once()->andThrow('UnexpectedValueException');
		$this->mockably->shouldReceive('mockable_die')->once();
		$installCommand = $this->getInstallCommandInstance();

		$installCommand->add_the_admin_user('foo');

		$this->assertEquals('migrate:reset', $_SERVER['call'][0]);
		$this->assertEquals('Unexpected value error.', $_SERVER['error'][0]);
	}

	/**
	 * @test fire() can abort if group creation failed
	 */
	public function fire_can_abort_if_group_creation_failed()
	{
		$this->assertClassHasAttribute('groups', 'Larapress\Commands\InstallCommand');
		$this->sentry->shouldReceive('createGroup')->times(3)->andReturn('foo');
		$this->mockably->shouldReceive('mockable_die')->once();
		$installCommand = $this->getInstallCommandInstance();

		$installCommand->fire();

		$this->assertEquals('migrate', $_SERVER['call'][0]);
		$this->assertEquals('Installing larapress ...' . PHP_EOL, $_SERVER['info'][0]);
		$this->assertEquals('Failed creating the user groups.', $_SERVER['error'][0]);
	}

	/**
	 * @test fire() can install larapress successfully
	 */
	public function fire_can_install_larapress_successfully()
	{
		$admin_group = new GroupProxy;
		$this->assertClassHasAttribute('groups', 'Larapress\Commands\InstallCommand');
		$this->sentry->shouldReceive('createGroup')->times(3)->andReturn($admin_group);
		$user = Mockery::mock();
		$user->shouldReceive('addGroup')->once();
		$this->sentry->shouldReceive('createUser')->withAnyArgs()->once()->andReturn($user);
		$installCommand = $this->getInstallCommandInstance();

		$installCommand->fire();

		$this->assertEquals('migrate', $_SERVER['call'][0]);
		$this->assertEquals('Installing larapress ...' . PHP_EOL, $_SERVER['info'][0]);
		$this->assertEquals(PHP_EOL . 'Installation complete!' . PHP_EOL, $_SERVER['info'][1]);
		$this->assertEquals('Now please visit url and login.' . PHP_EOL, $_SERVER['info'][2]);
		$this->assertEquals('Credentials:', $_SERVER['info'][3]);
		$this->assertEquals('E-Mail: admin@example.com', $_SERVER['info'][4]);
		$this->assertEquals('Password: password' . PHP_EOL, $_SERVER['info'][5]);
		$this->assertEquals('Make sure you instantly update your credentials!', $_SERVER['info'][6]);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data>

        <import type="android.view.View"/>

        <import type="pl.droidsonroids.beerapp.viewmodel.BeerDetailsViewModel"/>

        <variable
            name="viewModel"
            type="BeerDetailsViewModel"/>

    </data>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".BeerActivity"
        tools:showIn="@layout/activity_beer">

        <LinearLayout
            android:id="@+id/beer_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="@dimen/text_margin"
            app:products="@{viewModel.beer.products}">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/margin_normal"
                android:text="@string/not_available"
                android:textColor="@android:color/holo_red_dark"
                android:visibility="@{viewModel.beer.onSale ? View.GONE : View.VISIBLE}"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/margin_normal"
                android:text='@{String.format("I'm a %s brewed in %s", viewModel.beer.type, viewModel.beer.country)}'
                android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
                tools:text="I'm a Golden Lager brewed in Germany."/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/margin_small"
                android:text="@{@string/category(viewModel.beer.category)}"
                tools:text="Category: Imported"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/margin_small"
                android:text="@{@string/brewer(viewModel.beer.brewer)}"
                tools:text="Brewer: Brauerei Beck & Company"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/margin_normal"
                android:text='@{String.format("Alcohol Content (ABV): %.2f%%", viewModel.beer.alcoholByVolume)}'
                tools:text="Alcohol Content (ABV): 5.0%"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/margin_normal"
                android:text="@{@string/products(viewModel.beer.products.size)}"
                android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
                tools:text="Products (5)"/>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</layout>


text:
package br.furb.packing;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections.buffer.CircularFifoBuffer;

public class TabuList<T> {

	private final CircularFifoBuffer tabuList;

	private final Set<Entry<T>> auxTabuList;

	public TabuList(int tabuLenght) {
		tabuList = new CircularFifoBuffer(tabuLenght);
		auxTabuList = new HashSet<Entry<T>>(tabuLenght);
	}

	public boolean contains(T[] generatedNeighbour) {
		Entry<T> entry = new Entry<T>(generatedNeighbour);
		boolean contains = auxTabuList.contains(entry);
		return contains;
	}

	public void add(T[] generatedNeighbour) {
		Entry<T> entry = new Entry<T>(generatedNeighbour);
		if (tabuList.isFull()) {
			Object removed = tabuList.remove();
			auxTabuList.remove(removed);
		}
		tabuList.add(entry);
		auxTabuList.add(entry);
	}

	private static class Entry<T> {
		private final T[] array;

		public Entry(T[] array) {
			this.array = array;
		}

		@Override
		public int hashCode() {
			return Arrays.hashCode(array);
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Entry<?> other = (Entry<?>) obj;
			return Arrays.equals(array, other.array);
		}
	}

}


text:
namespace maps
{
    namespace multi
    {
        template <typename T, int DIMS, int ITEMS_PER_THREAD = 1, int ROWS_PER_THREAD = 1, ::maps::ILPScheme ILP_SCHEME = ::maps::ILP_CONTINUOUS>
        struct StructuredInjectiveOutput
        {
            MAPS_STATIC_ASSERT(DIMS >= 1 && DIMS <= 4, "A structured injective array can only exist in 1 to 4 dimensions");

            IDatum *datum;
            StructuredInjectiveOutput(Datum<T, DIMS>& dat) : datum(&dat) {}
            StructuredInjectiveOutput(ColVector<T>& dat) : datum(&dat) {}

            class Segmenter : public ISegmenter
            {
            protected:
                IDatum *datum;
            public:
                Segmenter(IDatum *inDatum) : datum(inDatum) {}

                virtual unsigned int ItemsPerThread(unsigned int dimension) const override
                {
                    switch (dimension)
                    {
                    default:
                        return 1;
                    case 0:
                        return ITEMS_PER_THREAD;
                    case 1:
                        return ROWS_PER_THREAD;
                    }
                }

                virtual void Segment(const std::vector<GridSegment>& segments,
                                     std::vector< std::vector<DatumSegment> >& out_data_segments) const override
                {
                    out_data_segments.reserve(segments.size());

                    for (const auto& seg : segments)
                    {
                        std::vector<DatumSegment> datasegs (1);

                        DatumSegment dataseg(DIMS);
                        dataseg.m_borders = WB_NOCHECKS;

                        if (seg.blocks == 0)
                        {
                            printf("SANITY CHECK FAILED: Zero blocks requested!\n");
                            return;
                        }

                        // Compute start and end positions
                        switch (DIMS)
                        {
                        default:
                            break;
                        case 1:
                            dataseg.m_offset[0] = seg.offset * seg.block_dims.x * ITEMS_PER_THREAD;
                            dataseg.m_dimensions[0] = seg.blocks * seg.block_dims.x * ITEMS_PER_THREAD;
                            break;
                        case 2:
                            {
                                unsigned int xoff_begin = seg.offset % seg.total_grid_dims.x;
                                unsigned int yoff_begin = seg.offset / seg.total_grid_dims.x;
                                unsigned int xoff_end   = (seg.offset + seg.blocks - 1) % seg.total_grid_dims.x;
                                unsigned int yoff_end   = (seg.offset + seg.blocks - 1) / seg.total_grid_dims.x;
                                if (xoff_begin != 0 || xoff_end != (seg.total_grid_dims.x - 1))
                                {
                                    printf("ERROR: Uneven segmentation of matrix to rows\n");
                                    out_data_segments.clear();
                                    return;
                                }

                                dataseg.m_offset[0] = 0;
                                dataseg.m_offset[1] = yoff_begin * seg.block_dims.y * ROWS_PER_THREAD;
                                dataseg.m_dimensions[0] = seg.block_dims.x * seg.total_grid_dims.x * ITEMS_PER_THREAD;
                                dataseg.m_dimensions[1] = std::max(seg.block_dims.y * ROWS_PER_THREAD,
                                                                   (yoff_end - yoff_begin + 1) * seg.block_dims.y * ROWS_PER_THREAD);
                                break;
                            }
                        case 3:
                            {
                                unsigned int xoff_begin =   seg.offset % seg.total_grid_dims.x;
                                unsigned int yoff_begin =  (seg.offset / seg.total_grid_dims.x) % seg.total_grid_dims.y;
                                unsigned int zoff_begin =  (seg.offset / seg.total_grid_dims.x) / seg.total_grid_dims.y;
                                unsigned int xoff_end   =  (seg.offset + seg.blocks - 1) % seg.total_grid_dims.x;
                                unsigned int yoff_end   = ((seg.offset + seg.blocks - 1) / seg.total_grid_dims.x) % seg.total_grid_dims.y;
                                unsigned int zoff_end   = ((seg.offset + seg.blocks - 1) / seg.total_grid_dims.x) / seg.total_grid_dims.y;
                                if (xoff_begin != 0 || xoff_end != (seg.total_grid_dims.x - 1) ||
                                    yoff_begin != 0 || yoff_end != (seg.total_grid_dims.y - 1))
                                {
                                    printf("ERROR: Uneven segmentation of tensor to slices\n");
                                    out_data_segments.clear();
                                    return;
                                }

                                dataseg.m_offset[0] = 0;
                                dataseg.m_offset[1] = 0;
                                dataseg.m_offset[2] = zoff_begin * seg.block_dims.z;
                                dataseg.m_dimensions[0] = seg.block_dims.x * seg.total_grid_dims.x * ITEMS_PER_THREAD;
                                dataseg.m_dimensions[1] = seg.block_dims.y * seg.total_grid_dims.y * ROWS_PER_THREAD;
                                dataseg.m_dimensions[2] = std::max(seg.block_dims.z,
                                                                   (zoff_end - zoff_begin + 1) * seg.block_dims.z);
                                break;
                            }
                        case 4:
                            {
                                int blocks_x = (int)datum->GetDataDimension(0) / seg.block_dims.x / ITEMS_PER_THREAD;
                                int blocks_y = (int)datum->GetDataDimension(1) / seg.block_dims.y / ROWS_PER_THREAD;
                                int blocks_z = (int)datum->GetDataDimension(2) / seg.block_dims.z;

                                unsigned int xoff_begin = seg.offset % blocks_x;
                                unsigned int yoff_begin = (seg.offset / blocks_x) % blocks_y;
                                unsigned int zoff_begin = ((seg.offset / blocks_x) / blocks_y) % blocks_z;
                                unsigned int woff_begin = ((seg.offset / blocks_x) / blocks_y) / blocks_z;
                                unsigned int xoff_end = (seg.offset + seg.blocks - 1) % blocks_x;
                                unsigned int yoff_end = ((seg.offset + seg.blocks - 1) / blocks_x) % blocks_y;
                                unsigned int zoff_end = (((seg.offset + seg.blocks - 1) / blocks_x) / blocks_y) % blocks_z;
                                unsigned int woff_end = (((seg.offset + seg.blocks - 1) / blocks_x) / blocks_y) / blocks_z;
                                if (xoff_begin != 0 || xoff_end != (blocks_x - 1) ||
                                    yoff_begin != 0 || yoff_end != (blocks_y - 1) ||
                                    zoff_begin != 0 || zoff_end != (blocks_z - 1))
                                {
                                    printf("ERROR: Uneven segmentation of tensor to slices\n");
                                    out_data_segments.clear();
                                    return;
                                }

                                dataseg.m_offset[0] = 0;
                                dataseg.m_offset[1] = 0;
                                dataseg.m_offset[2] = 0;
                                dataseg.m_offset[3] = woff_begin;
                                dataseg.m_dimensions[0] = seg.block_dims.x * blocks_x * ITEMS_PER_THREAD;
                                dataseg.m_dimensions[1] = seg.block_dims.y * blocks_y * ROWS_PER_THREAD;
                                dataseg.m_dimensions[2] = seg.block_dims.z * blocks_z;
                                dataseg.m_dimensions[3] = std::max(1U, (woff_end - woff_begin + 1));
                                break;
                            }
                        }

                        // Multiply dimensions by ITEMS PER THREAD and ROWS PER THREAD
                        // (they are divided in segmentation)
                        if (datum->GetDataDimension(0) % ITEMS_PER_THREAD != 0)
                        {
                            printf("WARNING: Width is not a multiple of items per thread\n");
                        }

                        if (DIMS > 1)
                        {
                            if (datum->GetDataDimension(1) % ROWS_PER_THREAD != 0)
                            {
                                printf("WARNING: Height is not a multiple of rows per thread\n");
                            }
                        }

                        // Avoid unnecessary overflows due to block size
                        for (int d = 0; d < DIMS; ++d)
                        {
                            if (dataseg.m_offset[d] + dataseg.m_dimensions[d] >= datum->GetDataDimension(d))
                            {
                                dataseg.m_dimensions[d] = datum->GetDataDimension(d) - dataseg.m_offset[d];
                            }
                        }

                        datasegs[0] = dataseg;
                        out_data_segments.push_back(datasegs);
                    }
                }
            };

            class ContainerFactory : public IContainerFactory
            {
            public:
                virtual std::shared_ptr<::maps::IOutputContainer>
                    CreateOutputContainer(IDatum *datum, Memory& buff, const DatumSegment& seg, const GridSegment& grid_seg) const override
                {
#ifndef NDEBUG
                    if (!datum || datum->GetDataDimensions() != DIMS)
                    {
                        printf("Invalid datum dimensions for structured injective array (dimensions: %d, expected %d)\n",
                               datum->GetDataDimensions(), DIMS);
                        return nullptr;
                    }
#endif
                    enum
                    {
                        CONTAINER_DIMS = (DIMS > 3) ? 3 : DIMS,
                    };
                    typedef ::maps::StructuredInjectiveOutput<T, CONTAINER_DIMS, 1,1,1, ITEMS_PER_THREAD, ROWS_PER_THREAD, ILP_SCHEME> ContainerType;
                    ContainerType *cont = new ContainerType();
                    cont->m_ptr = (T *)buff.ptr;
                    cont->m_stride = buff.stride_bytes / datum->GetElementSize();
                    cont->grid_dims = grid_seg.total_grid_dims;
                    for (unsigned int i = 0; i < CONTAINER_DIMS; ++i)
                        cont->m_dimensions[i] = (int)seg.GetDimension(i);

                    // The rest of the dimensions are located at Z
                    for (unsigned int i = 3; i < DIMS; ++i)
                        cont->m_dimensions[2] *= (int)seg.GetDimension(i);

                    return std::shared_ptr<::maps::IOutputContainer>(cont);
                }
            };

            std::shared_ptr<ISegmenter> CreateSegmenter() const { return std::shared_ptr<ISegmenter>(new Segmenter(datum)); }
            std::shared_ptr<IContainerFactory> CreateContainerFactory() const { return std::shared_ptr<IContainerFactory>(new ContainerFactory()); }
        };

        template <typename T, int ITEMS_PER_THREAD = 1, int ROWS_PER_THREAD = 1, ::maps::ILPScheme ILP_SCHEME = ::maps::ILP_CONTINUOUS>
        using StructuredInjectiveVectorO = StructuredInjectiveOutput<T, 1, ITEMS_PER_THREAD, ROWS_PER_THREAD, ILP_SCHEME>;

        template <typename T, int ITEMS_PER_THREAD = 1, int ROWS_PER_THREAD = 1, ::maps::ILPScheme ILP_SCHEME = ::maps::ILP_CONTINUOUS>
        using StructuredInjectiveMatrixO = StructuredInjectiveOutput<T, 2, ITEMS_PER_THREAD, ROWS_PER_THREAD, ILP_SCHEME>;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Reductive-static
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////

        template <typename T, int LENGTH, int BLOCK_WIDTH, int ITEMS_PER_THREAD = 1, typename Agg = PlusAggregator<T> >
        struct ReductiveStaticOutput
        {
            MAPS_STATIC_ASSERT(LENGTH > 0, "Reductive (static) output must have a positive, fixed size");
            MAPS_STATIC_ASSERT(ITEMS_PER_THREAD > 0, "Reductive (static) output must have a positive amount of items per thread");

            IDatum *datum;
            ReductiveStaticOutput(Vector<T>& dat) : datum(&dat) {}
            ReductiveStaticOutput(ColVector<T>& dat) : datum(&dat) {}

            class Segmenter : public ISegmenter
            {
                IDatum *datum;
            public:
                Segmenter(IDatum *inDatum) : datum(inDatum) {}

                virtual unsigned int ItemsPerThread(unsigned int dimension) const override
                {
                    switch (dimension)
                    {
                    default:
                        return 1;
                    case 0:
                        return ITEMS_PER_THREAD;
                    }
                }

                virtual void Segment(const std::vector<GridSegment>& segments,
                                     std::vector< std::vector<DatumSegment> >& out_data_segments) const override
                {
                    out_data_segments.reserve(segments.size());

                    for (const auto& seg : segments)
                    {
                        std::vector<DatumSegment> datasegs (1);

                        DatumSegment dataseg(1);
                        dataseg.m_borders = WB_NOCHECKS;

                        dataseg.m_offset[0] = 0;
                        dataseg.m_dimensions[0] = datum->GetDataDimension(0);

                        datasegs[0] = dataseg;
                        out_data_segments.push_back(datasegs);
                    }
                }
            };

            class ContainerFactory : public IContainerFactory
            {
            public:
                virtual std::shared_ptr<::maps::IOutputContainer>
                    CreateOutputContainer(IDatum *datum, Memory& buff, const DatumSegment& seg, const GridSegment& grid_seg) const override
                {
#ifndef NDEBUG
                    if (!datum || datum->GetDataDimensions() != 1)
                    {
                        printf("Invalid datum dimensions for reductive static output (dimensions: %d, expected %d)\n",
                               datum->GetDataDimensions(), 1);
                        return nullptr;
                    }
#endif
                    typedef ::maps::ReductiveStaticOutput<T, LENGTH, BLOCK_WIDTH, ITEMS_PER_THREAD> ContainerType;
                    ContainerType *cont = new ContainerType();
                    cont->m_ptr = (T *)buff.ptr;

                    return std::shared_ptr<::maps::IOutputContainer>(cont);
                }
            };

            std::shared_ptr<ISegmenter> CreateSegmenter() const { return std::shared_ptr<ISegmenter>(new Segmenter(datum)); }
            std::shared_ptr<IContainerFactory> CreateContainerFactory() const { return std::shared_ptr<IContainerFactory>(new ContainerFactory()); }
            std::shared_ptr<IAggregator> CreateAggregator() const { return std::shared_ptr<IAggregator>(new Agg()); }
        };

    } // namespace multi

} // namespace maps

#endif // __MAPS_MULTI_OUTPUT_CONTAINERS_H


text:
<!DOCTYPE html>

	<title>Login - Timpani</title>
	<link href="/static/libs/pure/pure-min.css" rel="stylesheet">
	<link href="/static/css/login.css" rel="stylesheet">

Welcome to Timpani

Log In

			{% if get_flashed_messages()|length > 0 %}

				{{get_flashed_messages()[0]}}

			{% endif %}
			<form class="pure-form" id="login-form" action="/login" method="POST">
				<input type="text" id="username-field" name="username" placeholder="Username" required>
				<input type="password" id="password-field" name="password" placeholder="Password" required>
				<button type="submit" class="pure-button pure-button-primary">Log In</button>
			</form>


text:
package com.google.gdata.data.analytics;

import com.google.gdata.data.AttributeGenerator;
import com.google.gdata.data.AttributeHelper;
import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.data.ExtensionPoint;
import com.google.gdata.util.ParseException;

/**
 * Data about a user-defined custom variable.
 *
 *
 */
@ExtensionDescription.Default(
    nsAlias = AnalyticsNamespace.GA_ALIAS,
    nsUri = AnalyticsNamespace.GA,
    localName = CustomVariable.XML_NAME)
public class CustomVariable extends ExtensionPoint {

  /** XML element name */
  static final String XML_NAME = "customVariable";

  /** XML "index" attribute name */
  private static final String INDEX = "index";

  /** XML "name" attribute name */
  private static final String NAME = "name";

  /** XML "scope" attribute name */
  private static final String SCOPE = "scope";

  /** Index */
  private Integer index = null;

  /** Name */
  private String name = null;

  /** Scope */
  private String scope = null;

  /** Scope. */
  public static final class Scope {

    /** Hit custom variable. */
    public static final String HIT = "hit";

    /** Visit custom variable. */
    public static final String VISIT = "visit";

    /** Visitor custom variable. */
    public static final String VISITOR = "visitor";

  }

  /**
   * Default mutable constructor.
   */
  public CustomVariable() {
    super();
  }

  /**
   * Immutable constructor.
   *
   * @param index index.
   * @param name name.
   * @param scope scope.
   */
  public CustomVariable(Integer index, String name, String scope) {
    super();
    setIndex(index);
    setName(name);
    setScope(scope);
    setImmutable(true);
  }

  /**
   * Returns the index.
   *
   * @return index
   */
  public Integer getIndex() {
    return index;
  }

  /**
   * Sets the index.
   *
   * @param index index or null to reset
   */
  public void setIndex(Integer index) {
    throwExceptionIfImmutable();
    this.index = index;
  }

  /**
   * Returns whether it has the index.
   *
   * @return whether it has the index
   */
  public boolean hasIndex() {
    return getIndex() != null;
  }

  /**
   * Returns the name.
   *
   * @return name
   */
  public String getName() {
    return name;
  }

  /**
   * Sets the name.
   *
   * @param name name or null to reset
   */
  public void setName(String name) {
    throwExceptionIfImmutable();
    this.name = name;
  }

  /**
   * Returns whether it has the name.
   *
   * @return whether it has the name
   */
  public boolean hasName() {
    return getName() != null;
  }

  /**
   * Returns the scope.
   *
   * @return scope
   */
  public String getScope() {
    return scope;
  }

  /**
   * Sets the scope.
   *
   * @param scope scope or null to reset
   */
  public void setScope(String scope) {
    throwExceptionIfImmutable();
    this.scope = scope;
  }

  /**
   * Returns whether it has the scope.
   *
   * @return whether it has the scope
   */
  public boolean hasScope() {
    return getScope() != null;
  }

  @Override
  protected void validate() {
    if (index == null) {
      throwExceptionForMissingAttribute(INDEX);
    }
    if (name == null) {
      throwExceptionForMissingAttribute(NAME);
    }
    if (scope == null) {
      throwExceptionForMissingAttribute(SCOPE);
    }
  }

  /**
   * Returns the extension description, specifying whether it is required, and
   * whether it is repeatable.
   *
   * @param required   whether it is required
   * @param repeatable whether it is repeatable
   * @return extension description
   */
  public static ExtensionDescription getDefaultDescription(boolean required,
      boolean repeatable) {
    ExtensionDescription desc =
        ExtensionDescription.getDefaultDescription(CustomVariable.class);
    desc.setRequired(required);
    desc.setRepeatable(repeatable);
    return desc;
  }

  @Override
  protected void putAttributes(AttributeGenerator generator) {
    generator.put(INDEX, index);
    generator.put(NAME, name);
    generator.put(SCOPE, scope);
  }

  @Override
  protected void consumeAttributes(AttributeHelper helper) throws ParseException
      {
    index = helper.consumeInteger(INDEX, true);
    name = helper.consume(NAME, true);
    scope = helper.consume(SCOPE, true);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (!sameClassAs(obj)) {
      return false;
    }
    CustomVariable other = (CustomVariable) obj;
    return eq(index, other.index)
        && eq(name, other.name)
        && eq(scope, other.scope);
  }

  @Override
  public int hashCode() {
    int result = getClass().hashCode();
    if (index != null) {
      result = 37 * result + index.hashCode();
    }
    if (name != null) {
      result = 37 * result + name.hashCode();
    }
    if (scope != null) {
      result = 37 * result + scope.hashCode();
    }
    return result;
  }

  @Override
  public String toString() {
    return "{CustomVariable index=" + index + " name=" + name + " scope=" +
        scope + "}";
  }

}


text:
package controllers

import (
	"github.com/astaxie/beego"
	"github.com/freeznet/tomato/types"
)

// HealthController 检测服务器健康状态
type HealthController struct {
	beego.Controller
}

// Get 直接返回状态 200
// @router / [get]
func (h *HealthController) Get() {
	h.Data["json"] = types.M{
		"status": "ok",
	}
	h.ServeJSON()
}


text:
package org.gluu.oxauth.client.conf;

import java.io.File;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.lang.StringUtils;
import org.gluu.oxauth.client.OpenIdClient;
import org.gluu.oxauth.client.exception.ConfigurationException;
import org.gluu.site.ldap.LDAPConnectionProvider;
import org.gluu.site.ldap.OperationsFacade;
import org.gluu.site.ldap.persistence.LdapEntryManager;
import org.gluu.site.ldap.persistence.exception.LdapMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xdi.util.StringHelper;
import org.xdi.util.properties.FileConfiguration;
import org.xdi.util.security.PropertiesDecrypter;

/**
 * Base OpenId configuration
 *
 * @author Yuriy Movchan
 * @version 0.1, 11/02/2015
 */
public abstract class Configuration<C extends AppConfiguration, L extends LdapAppConfiguration> {

	private final Logger logger = LoggerFactory.getLogger(Configuration.class);

	static {
		if ((System.getProperty("catalina.base") != null) && (System.getProperty("catalina.base.ignore") == null)) {
			BASE_DIR = System.getProperty("catalina.base");
		} else if (System.getProperty("catalina.home") != null) {
			BASE_DIR = System.getProperty("catalina.home");
		} else if (System.getProperty("jboss.home.dir") != null) {
			BASE_DIR = System.getProperty("jboss.home.dir");
		} else {
			BASE_DIR = null;
		}
	}

	private static final String BASE_DIR;
	private static final String DIR = BASE_DIR + File.separator + "conf" + File.separator;

	private static final String SALT_FILE_NAME = "salt";

	private String confDir;
	private String saltFilePath;

	private FileConfiguration ldapConfiguration;
	private C appConfiguration;
	private OpenIdClient openIdClient;

	private String cryptoConfigurationSalt;

	private LdapEntryManager ldapEntryManager;

	private long ldapFileLastModifiedTime;

	private AtomicBoolean isActive;

	protected Configuration() {
		this.isActive = new AtomicBoolean(true);
		try {
			create();
		} finally {
			this.isActive.set(false);
		}
	}

	private void create() {
		this.ldapConfiguration = loadLdapConfiguration();

		this.confDir = confDir();
		this.saltFilePath = confDir + SALT_FILE_NAME;

		this.cryptoConfigurationSalt = loadCryptoConfigurationSalt();

		this.ldapEntryManager = createLdapEntryManager();

		if (!createFromLdap()) {
			logger.error("Failed to load configuration from Ldap. Please fix it!!!.");
			throw new ConfigurationException("Failed to load configuration from Ldap.");
		} else {
			logger.info("Configuration loaded successfully.");
		}

		this.openIdClient = createAuthClient();
	}

	public void destroy() {
		if (this.ldapEntryManager != null) {
			destroyLdapEntryManager(this.ldapEntryManager);
		}
	}

	private FileConfiguration loadLdapConfiguration() {
		String ldapConfigurationFileName = getLdapConfigurationFileName();
		try {
			if (StringHelper.isEmpty(ldapConfigurationFileName)) {
				throw new ConfigurationException("Failed to load Ldap configuration file!");
			}

			String ldapConfigurationFilePath = DIR + ldapConfigurationFileName;

			FileConfiguration ldapConfiguration = new FileConfiguration(ldapConfigurationFilePath);
			if (ldapConfiguration.isLoaded()) {
				File ldapFile = new File(ldapConfigurationFilePath);
				if (ldapFile.exists()) {
					this.ldapFileLastModifiedTime = ldapFile.lastModified();
				}

				return ldapConfiguration;
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			throw new ConfigurationException("Failed to load Ldap configuration from " + ldapConfigurationFileName, ex);
		}

		throw new ConfigurationException("Failed to load Ldap configuration from " + ldapConfigurationFileName);
	}

	private String loadCryptoConfigurationSalt() {
		try {
			FileConfiguration cryptoConfiguration = new FileConfiguration(this.saltFilePath);

			return cryptoConfiguration.getString("encodeSalt");
		} catch (Exception ex) {
			logger.error("Failed to load configuration from {}", saltFilePath, ex);
			throw new ConfigurationException("Failed to load configuration from " + saltFilePath, ex);
		}
	}

	private String confDir() {
		final String confDir = getLdapConfiguration().getString("confDir");
		if (StringUtils.isNotBlank(confDir)) {
			return confDir;
		}

		return DIR;
	}

	private boolean createFromLdap() {
		logger.info("Loading configuration from Ldap...");
		try {
			final L ldapConf = loadConfigurationFromLdap();
			if (ldapConf != null) {
				this.appConfiguration = initAppConfiguration(ldapConf);
				return true;
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		return false;
	}

	private L loadConfigurationFromLdap(String... returnAttributes) {
		try {
			final String dn = getLdapConfiguration().getString("configurationEntryDN");

			final L ldapConf = this.ldapEntryManager.find(getAppConfigurationType(), dn, returnAttributes);
			return ldapConf;
		} catch (LdapMappingException ex) {
			logger.error(ex.getMessage());
		}

		return null;
	}

	private LdapEntryManager createLdapEntryManager() {
		Properties connectionProperties = (Properties) this.ldapConfiguration.getProperties();
		Properties decryptedConnectionProperties = PropertiesDecrypter.decryptProperties(connectionProperties, this.cryptoConfigurationSalt);

		LDAPConnectionProvider connectionProvider = new LDAPConnectionProvider(decryptedConnectionProperties);
		LdapEntryManager ldapEntryManager = new LdapEntryManager(new OperationsFacade(connectionProvider, null));

		logger.debug("Created LdapEntryManager: {}", ldapEntryManager);

		return ldapEntryManager;
	}

	private void destroyLdapEntryManager(final LdapEntryManager ldapEntryManager) {
		boolean result = ldapEntryManager.destroy();
		if (result) {
			logger.debug("Destoyed LdapEntryManager: {}", ldapEntryManager);
		} else {
			logger.error("Failed to destoy LdapEntryManager: {}", ldapEntryManager);
		}
	}

	private OpenIdClient createAuthClient() {
		OpenIdClient openIdClient = new OpenIdClient(this.appConfiguration);
		openIdClient.init();

		return openIdClient;
	}

	public FileConfiguration getLdapConfiguration() {
		return ldapConfiguration;
	}

	public String getCryptoConfigurationSalt() {
		return cryptoConfigurationSalt;
	}

	public OpenIdClient getOpenIdClient() {
		return openIdClient;
	}

	protected abstract String getLdapConfigurationFileName();

	protected abstract Class<L> getAppConfigurationType();

	protected abstract C initAppConfiguration(L ldapAppConfiguarion);

}


text:
namespace swift {

class GenericCloner : public TypeSubstCloner<GenericCloner> {
  const ReabstractionInfo &ReInfo;
  CloneCollector::CallbackType Callback;

public:
  friend class SILCloner<GenericCloner>;

  GenericCloner(SILFunction *F,
                const ReabstractionInfo &ReInfo,
                TypeSubstitutionMap &ContextSubs,
                StringRef NewName,
                ArrayRef<Substitution> ApplySubs,
                CloneCollector::CallbackType Callback)
  : TypeSubstCloner(*initCloned(F, ReInfo, NewName), *F, ContextSubs,
                    ApplySubs), ReInfo(ReInfo), Callback(Callback) {
    assert(F->getDebugScope()->Parent != getCloned()->getDebugScope()->Parent);
  }
  /// Clone and remap the types in \p F according to the substitution
  /// list in \p Subs. Parameters are re-abstracted (changed from indirect to
  /// direct) according to \p ReInfo.
  static SILFunction *cloneFunction(SILFunction *F,
                                    const ReabstractionInfo &ReInfo,
                                    TypeSubstitutionMap &ContextSubs,
                                    StringRef NewName, ApplySite Caller,
                            CloneCollector::CallbackType Callback =nullptr) {
    // Clone and specialize the function.
    GenericCloner SC(F, ReInfo, ContextSubs, NewName,
                     Caller.getSubstitutions(), Callback);
    SC.populateCloned();
    SC.cleanUp(SC.getCloned());
    return SC.getCloned();
  }

protected:
  // FIXME: We intentionally call SILClonerWithScopes here to ensure
  //        the debug scopes are set correctly for cloned
  //        functions. TypeSubstCloner, SILClonerWithScopes, and
  //        SILCloner desperately need refactoring and/or combining so
  //        that the obviously right things are happening for cloning
  //        vs. inlining.
  void postProcess(SILInstruction *Orig, SILInstruction *Cloned) {
    // Call client-supplied callback function.
    if (Callback)
      Callback(Orig, Cloned);

    SILClonerWithScopes<GenericCloner>::postProcess(Orig, Cloned);
  }

private:
  static SILFunction *initCloned(SILFunction *Orig,
                                 const ReabstractionInfo &ReInfo,
                                 StringRef NewName);
  /// Clone the body of the function into the empty function that was created
  /// by initCloned.
  void populateCloned();
  SILFunction *getCloned() { return &getBuilder().getFunction(); }
};

} // end namespace swift

#endif


text:
import lcm

def stripLog(inFile, outFile):
    channels = {'CAMERA':True, 'SCAN':True, 'PRE_SPINDLE_TO_POST_SPINDLE':True}

    inLog = lcm.EventLog(inFile, 'r')
    outLog = lcm.EventLog(outFile, 'w', overwrite=True)

    for event in inLog:
        if event.channel in channels:
            outLog.write_event(event.timestamp, event.channel, event.data)
    print 'done'

if __name__=='__main__':
    inFile = '/home/antone/data/2015-02-11_multisense-02-calib/lcmlog-2015-02-11.00'
    outFile = '/home/antone/data/2015-02-11_multisense-02-calib/lcmlog-2015-02-11.00.stripped'
    stripLog(inFile, outFile)


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

namespace LionFire.Logging
{
    public interface IAppStartLogger
    {

        /// <summary>
        /// Applies to start log message
        /// </summary>
        bool? LogSucceeded { get; }

        /// <summary>
        /// Exception or error if start log message fails
        /// </summary>
        object LogError { get; }
    }

}


text:
<?php

namespace Sylius\Bundle\CoreBundle\Fixture\Factory;

use Sylius\Component\Core\Formatter\StringInflector;
use Sylius\Component\Product\Model\ProductAssociationTypeInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com>
 */
class ProductAssociationTypeExampleFactory extends AbstractExampleFactory implements ExampleFactoryInterface
{
    /**
     * @var FactoryInterface
     */
    private $productAssociationTypeFactory;

    /**
     * @var \Faker\Generator
     */
    private $faker;

    /**
     * @var OptionsResolver
     */
    private $optionsResolver;

    /**
     * @param FactoryInterface $productAssociationTypeFactory
     */
    public function __construct(FactoryInterface $productAssociationTypeFactory)
    {
        $this->productAssociationTypeFactory = $productAssociationTypeFactory;

        $this->faker = \Faker\Factory::create();
        $this->optionsResolver = new OptionsResolver();

        $this->configureOptions($this->optionsResolver);
    }

    /**
     * {@inheritdoc}
     */
    public function create(array $options = [])
    {
        $options = $this->optionsResolver->resolve($options);

        /** @var ProductAssociationTypeInterface $productAssociationType */
        $productAssociationType = $this->productAssociationTypeFactory->createNew();
        $productAssociationType->setName($options['name']);
        $productAssociationType->setCode($options['code']);

        return $productAssociationType;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefault('name', function (Options $options) {
                return $this->faker->words(3, true);
            })
            ->setDefault('code', function (Options $options) {
                return StringInflector::nameToCode($options['name']);
            })
        ;
    }
}


text:
package de.mpicbg.knime.hcs.core.math;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import de.mpicbg.knime.hcs.core.math.Interval.Mode;

/**
 * Binning analysis for double arrays follows this concept:
 * TODO: enter description here
 * <p/>
 * Created by IntelliJ IDEA.
 * User: Antje Niederlein
 * Date: 2/27/12
 * Time: 9:57 AM
 */

public class BinningAnalysis {

	// name of the parameter
	private String parameterName;

	// list of bins
	private LinkedList<Interval> bins;

	// reference data, Key: group (e.g. well), Values: data points of this group
	private HashMap<Object, List<Double>> refData;

	// Key: Interval, Values: Mean, Sd
	private HashMap<Interval, Double[]> refStats;

	// hashmap which contains the binning analysis results per group
	private HashMap<Object, List<BinningData>> zScoreData;

	// number of Bins
	int nBins;

	public BinningAnalysis(HashMap<Object, List<Double>> refData, int nBins, String parameterName) {
		this.parameterName = parameterName;
		this.nBins = nBins;

		this.bins = new LinkedList<Interval>();
		this.refStats = new HashMap<Interval, Double[]>();
		this.zScoreData = new HashMap<Object, List<BinningData>>();

		this.refData = refData;

		createBins();
		calculateRefStats();
	}

	public BinningAnalysis(HashMap<Object, List<Double>> refData, int nBins, String parameterName, boolean opt) {
		this.parameterName = parameterName;
		this.nBins = nBins;

		this.bins = new LinkedList<Interval>();
		this.refStats = new HashMap<Interval, Double[]>();
		this.zScoreData = new HashMap<Object, List<BinningData>>();

		this.refData = refData;

		createBins();

	}

	private void createBins() {
		double[] percentiles = new double[nBins + 1];

		double delta = (double) 100 / nBins;

		// create a sequence of breaks from 0 - 100 to calculate the percentiles
		percentiles[0] = 0;
		for (int i = 1; i < percentiles.length; i++) {
			percentiles[i] = percentiles[i - 1] + delta;
		}

		double[] data = {};

		// extract all data values into a double vector
		for (List<Double> values : refData.values()) {
			double[] groupData = new double[values.size()];
			int i = 0;
			for (Double val : values) {
				groupData[i] = val;
				i++;
			}
			data = ArrayUtils.addAll(data, groupData);
		}

		// Each bin is defined like an Interval with upper and lower bound
		double maxValue = NumberUtils.max(data);
		double lowerBreak = NumberUtils.min(data);
		double upperBreak;

		// sort data
		Arrays.sort(data);

		// calculate the percentiles
		// comment: add minBin and maxBin [-Infinity,minRef] and [maxRef,Infinity] does not make sense
		// as the z-score could not be calculated for these bins (no data points present in referenceData)
		for (int i = 1; i < percentiles.length; i++) {

			// tried to use Percentile class of commons-Math but it was much too slow for the example data
			// therefor the calculation was reimplemented
			upperBreak = evalPercentile(percentiles[i], data);

			// only keep bin, if the bounds differ
			if (upperBreak > lowerBreak) {
				if(upperBreak == maxValue){
					bins.add(new Interval(lowerBreak, upperBreak, percentiles[i] + "%", Mode.INCL_BOTH));
				}
				else {
					bins.add(new Interval(lowerBreak, upperBreak, percentiles[i] + "%", Mode.INCL_LEFT));
				}
			}

			lowerBreak = upperBreak;
		}
	}

	/**
	 * creates percentile labels based on the number of bins
	 * like [20%,40%,60%,80%,100%]
	 * starting from 0 + 100/nBins
	 *
	 * @return String array with percentile labels
	 */
	public String[] getPercentileLabels() {
		String[] percentiles = new String[nBins];

		double delta = (double) 100 / nBins;

		// create a sequence of breaks from 0 - 100 to calculate the percentiles
		for (int i = 0; i < percentiles.length; i++) {
			if(i == 0)
				percentiles[i] = (delta) + "%";
			else
				percentiles[i] = ((i + 1 ) * delta) + "%";
		}
		return percentiles;
	}

	/**
	 * method = R6 in
	 * Hyndman, R.J. and Fan, Y. (November 1996).
	 * "Sample Quantiles in Statistical Packages",
	 * The American Statistician 50 (4): pp. 361–365.
	 *
	 * @param p		percentile to calculate, 0 < p <= 10
	 * @param data
	 * @return percentile
	 */
	private double evalPercentile(double p, double[] data) {
		// implementation until 2018-11
		/**int n = data.length;
		//double kd = p * (n + 1) / 100;	// percentile position (starting from 1)
		double kd = (p / 100 * (n + 1)) - 1;	// percentile position (starting from 0)
		double k = Math.floor(kd);
		double d = kd - k;				// difference

		double getFromMath = StatUtils.percentile(data, p);

		if (Double.compare(k, 0) == 0) return data[0];
		if (Double.compare(k, n) >= 0) return data[n - 1];

		int ik = (int) k;
		return data[ik] + d * (data[ik + 1] - data[ik]);*/

		assert p > 0 && p <= 100;

		DescriptiveStatistics stats = new DescriptiveStatistics(data);
		stats.setPercentileImpl(new Percentile().withEstimationType(Percentile.EstimationType.R_6));
		return stats.getPercentile(p);
	}

	/**
	 * Calculates the percentage of datapoints falling into each of the bins for each group
	 * and get statistics (mean + sd) of all values per bin
	 */
	private void calculateRefStats() {
		HashMap<Interval, List<Double>> ratios = new HashMap<Interval, List<Double>>();

		// iterate through all groups
		for (List<Double> values : refData.values()) {
			double n = values.size();

			// sort data acsending
			Collections.sort(values);

			// iterate through intervals, use right open intervals except for the last bin (use closed interval)
			int nBins = bins.size();
			Interval.Mode inclMode = Interval.Mode.INCL_LEFT;
			for (int i = 0; i < nBins; i++) {
				// current interval
				Interval iv = bins.get(i);
				// check for last interval
				if (i == nBins - 1) inclMode = Interval.Mode.INCL_BOTH;

				double[] ratio = calculateRatios(values, iv, inclMode, n);

				// update list: add the ratio of the current well
				List<Double> ratioList;
				if (ratios.containsKey(iv)) ratioList = ratios.get(iv);
				else ratioList = new ArrayList<Double>();

				ratioList.add(ratio[0]);
				ratios.put(iv, ratioList);
			}
		}

		// calculate mean and standard deviation
		for (Interval iv : ratios.keySet()) {
			List<Double> ivList = ratios.get(iv);

			DescriptiveStatistics stats = new DescriptiveStatistics();
			for (Double val : ivList) {
				stats.addValue(val);
			}
			// update statistics
			Double[] ivStats = {stats.getMean(), stats.getStandardDeviation()};
			refStats.put(iv, ivStats);
		}
	}

	private double[] calculateRatios(List<Double> values, Interval iv, Interval.Mode inclMode, double n) {
		// count values
		double m = 0;
		for (Double val : values) {
			if (iv.contains(val, inclMode)) m++;
		}

		return new double[]{m / n * 100, m};
	}

	/**
	 * @param data
	 * @return Key: Group, Value: a List of Measurements (with name and value)
	 *         interval
	 *         percentage
	 *         count
	 *         z-score
	 */
	public HashMap<Object, List<BinningData>> getZscore(HashMap<Object, List<Double>> data) {
		// clear zscore-list
		zScoreData.clear();

		// iterate over groups
		for (Object currentGroup : data.keySet()) {
			List<Double> values = data.get(currentGroup);
			double n = values.size();
			Collections.sort(values);

			// iterate through intervals, use right open intervals except for the last bin (use closed interval)
			int nBins = bins.size();
			Interval.Mode inclMode = Interval.Mode.INCL_LEFT;
			List<BinningData> entryList = new ArrayList<BinningData>();
			for (int i = 0; i < nBins; i++) {
				// current interval
				Interval iv = bins.get(i);

				// modify first and last interval that the bounds are extended to Infinity to catch all data points
				// last interval has to use a closed interval
				if (i == 0) iv.setLowerBound(Double.NEGATIVE_INFINITY);
				if (i == nBins - 1) {
					iv.setUpperBound(Double.POSITIVE_INFINITY);
					inclMode = Interval.Mode.INCL_BOTH;
				}

				double[] ratio = calculateRatios(values, iv, inclMode, n);
				double mean = refStats.get(iv)[0];
				double sd = refStats.get(iv)[1];

				double zscore = (ratio[0] - mean) / sd;

				BinningData entry = new BinningData(iv, zscore, ratio[0], ratio[1]);
				entryList.add(entry);
			}
			zScoreData.put(currentGroup, entryList);
		}
		return zScoreData;
	}

	public LinkedList<Interval> getBins() {
		return bins;
	}

	public String getParameterName() {
		return parameterName;
	}

	public static void main(String[] args) {

		/**
		 * This example reads in 252618 lines with 115 parameters = 29,556,306 data points
		 * To load the data into the memory approximately 1.4 GB RAM
		 * --> should be better to collect data and process parameter by parameter
		 * processing time : 13 seconds (1/4 th of the time needed by R (excluding time for data transfer from/to R-server)
		 */

		// test file located in resources/BinningAnalysis
		String fileLocation = "/Users/niederle/projects/knime/hcscore/resources/BinningAnalysis/exportData.csv";

		// parameter / well / values
		HashMap<String, HashMap<Object, List<Double>>> refData = new HashMap<String, HashMap<Object, List<Double>>>();
		HashMap<String, HashMap<Object, List<Double>>> allData = new HashMap<String, HashMap<Object, List<Double>>>();

		try {
			CSVReader reader = new CSVReader(new FileReader(fileLocation));
			String[] nextLine;
			List<Double> doubleList;

			// skip column header
			String[] parameters = reader.readNext();
			while ((nextLine = reader.readNext()) != null) {

				String well = nextLine[0];
				String compound = nextLine[1];

				for (int i = 2; i < nextLine.length; i++) {
					if (nextLine[i].equals("NA")) continue;
					double val = new Double(nextLine[i]);
					String param = parameters[i];

					// fill refData List
					if (compound.equals("DMSO")) {
						if (!refData.containsKey(param)) refData.put(param, new HashMap<Object, List<Double>>());

						if (refData.get(param).containsKey(well)) doubleList = refData.get(param).get(well);
						else doubleList = new ArrayList<Double>();

						doubleList.add(val);
						refData.get(param).put(well, doubleList);
					}

					// fill allData List
					if (!allData.containsKey(param)) allData.put(param, new HashMap<Object, List<Double>>());

					if (allData.get(param).containsKey(well)) doubleList = allData.get(param).get(well);
					else doubleList = new ArrayList<Double>();

					doubleList.add(val);
					allData.get(param).put(well, doubleList);
				}
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println(new Date());
		HashMap<String, HashMap<Object, List<BinningData>>> binResults = new HashMap<String, HashMap<Object, List<BinningData>>>();
		for (String param : refData.keySet()) {
			BinningAnalysis binAnalysis = new BinningAnalysis(refData.get(param), 10, param);
			HashMap<Object, List<BinningData>> ret = binAnalysis.getZscore(allData.get(param));
			binResults.put(param, ret);
		}
		System.out.println(new Date());

		String destLocation = "/Users/niederle/Desktop/temp-files/proMebs_binData.csv";

		try {
			CSVWriter writer = new CSVWriter(new FileWriter(destLocation));
			ArrayList<String> nextLine = new ArrayList<String>();
			for (String parameter : binResults.keySet()) {
				System.out.println(parameter);
				for (Object well : binResults.get(parameter).keySet()) {
					for (BinningData binData : binResults.get(parameter).get(well)) {
						nextLine.add(parameter);
						nextLine.add((String) well);
						nextLine.add(binData.getInterval().getLabel());
						nextLine.add(Double.toString(binData.getPercentage()));
						nextLine.add(Double.toString(binData.getZscore()));
						nextLine.add(Double.toString(binData.getCount()));

						writer.writeNext(nextLine.toArray(new String[nextLine.size()]));
						nextLine.clear();
					}
				}
			}
			writer.close();

		} catch (IOException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		}

		// just useful to place a breakpoint for debugging
		int k = 0;
	}
}


text:
<?php

namespace Doctrine\ORM\Query\AST;

/**
 * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END"
 *
 * @since   2.2
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class GeneralCaseExpression extends Node
{
    public $whenClauses = array();
    public $elseScalarExpression = null;

    public function __construct(array $whenClauses, $elseScalarExpression)
    {
        $this->whenClauses = $whenClauses;
        $this->elseScalarExpression = $elseScalarExpression;
    }

    public function dispatch($sqlWalker)
    {
        return $sqlWalker->walkGeneralCaseExpression($this);
    }
}


text:
package com.demo.service;

import com.demo.base.service.BaseService;
import com.demo.entity.BoAttachUrl;
import com.demo.entity.BoAttachUrlExample;

public interface BoAttachUrlService extends BaseService<BoAttachUrl, BoAttachUrlExample> {

}


text:
module.exports = client => {
  console.log(`Reconnected at ${new Date()}`);
};


text:
title: Themes in Opera 18+
authors:
- andreas-bovens
intro: 'Due to the major architectural changes we've been going through recently, the first versions of our Chromium/Blink based Opera browser (versions 15, 16 and 17) do not support themes. However, from Opera 18 onward, themes are supported again! This article explains you how to create themes for Opera 18+.'
tags:
- themes
- opera
cover: jpg
license: cc-by-3.0
---

Due to the major architecture changes we've been going through recently, the first versions of our Chromium/Blink based Opera browser (versions 15, 16 and 17) do not support themes. However, from Opera 18 onward, themes are supported again! This article explains you how to create themes for Opera 18+.

## How to

In short, the steps to create a theme are as follows:

1. Find two images you want to use and place them in a folder — I found two nice ones on [Unsplash][1]
2. Create a persona.ini file with your text editor, and add the necessary meta data
3. Compress/archive the content of the folder as a zip file
4. Test if the theme works by dragging it to opera:themes
5. Upload the theme to [our addons catalog][2]

[1]: http://unsplash.com
[2]: https://addons.opera.com/en/themes/

I've created a [test theme][3] for you to play with. Just download and unzip it to inspect what's inside. You find extensive details in the following sections.

[3]: {{ page.id }}/yellow_sf.zip

Yellow SF theme applied on Opera 18

## Images

You'll need to pick two images: one will function as the background for Speed Dial, the other one as background for pages like opera:extensions, opera:settings, opera:about, etc.

Make sure the images you use are of sufficient size and quality as they'll need to be rescaled to fit on different screen resolutions. In order to reduce file size as much as possible without sacrificing quality, run your images through a tool like [ImageOptim][5], which shaves off unnecessary bytes from PNG and JPG files.

[5]: http://imageoptim.com

## Persona.ini details

The content of the persona.ini file is as follows:

	[Info]
	Name				= Yellow SF
	Author			 	= Andreas Bovens
	Author URL			= http://bovens.net/
	Version				= 2

	[Start Page]
	Background			= 01.jpg
	Position			= center bottom
	Title Text Color	= #ffffff
	Title Text shadow	= #261712

	[Web UI Pages]
	Background			= 02.jpg
	Position			= center top

	; images by Charlie Foster, found on http://unsplash.com

This should be quite self explanatory, but just in case, here are the details line per line:

- **[Info]**: info section
	- **Name**: Title of the theme
	- **Author**: Author name
	- **Author URL**: A URI that points to the author's home page or e-mail. Valid schemes are http, https, and mailto
	- **Version**: Version 2 indicates Opera 18+ themes
- **[Start Page]**: section with settings for Speed Dial
	- **Background**: File name of the image that goes behind Speed Dial.
	- **Position**: Position of the start page image — optional, any CSS keyword for position: left, top, right, bottom, center.
	- **Title Text Color**: Color of the text — optional, HEX notation, without alpha
	- **Title Text Shadow**: Color of the text shadow — optional. If set, will be applied as `text-shadow: 1px 1px 1px Value`
- **[Web UI Pages]**: section with settings for opera:settings, opera:about, etc.
	- **Background**: File name of the image that goes behind other pages
	- **Position**: See above for positioning details

In the end I've added a comment. You can put comments anywhere you like in the file, as long as they are on a separate line and start with a semicolon (;). You can do this for instance to give attribution to the photographer or designer who made the background images.

## Compression, testing and upload

Make sure there are no unnecessary files inside the zip file, like source files for graphics, .git folders or .DS_Store files, for instance.

To test the theme, load opera:themes in the browser, and drag and drop the ZIP file onto the opera:themes page. If everything is right, the theme will be installed in the Themes Manager's My Themes section.

To upload the theme, log into the [Opera Add-ons catalog][6], go to [My uploads][7], and submit your theme.

[6]: https://addons.opera.com/
[7]: https://addons.opera.com/en/developer/

## Previous theme format and legacy features

Themes made for Opera 12 and 12.1 also work in Opera 18+, but not all features have a visual effect. The theme will not expand under the tabs for instance, and settings like "Tint Color" are no longer supported.

## Summary

As you can see, making themes for Opera is very easy. Try it out for yourself!


text:
"""Convert string based value to a datetime instance."""

import pathlib
import re

import dateutil.parser
import dateutil.tz

from ._misc import parameters

@parameters(
    fallback={"timezone": "metadata://#/timezone"},
    jsonschema={
        "type": "object",
        "properties": {
            "todatetime": {
                "anyOf": [
                    {"type": "string"},
                    {"type": "array", "items": {"type": "string"}},
                ]
            },
            "parsearea": {"type": "string"},
            "timezone": {"type": "string", "format": "timezone"},
            "fuzzy": {"type": "boolean"},
        },
    },
)
def process(app, stream, *, todatetime, parsearea=".*", fuzzy=False, timezone="UTC"):
    tzinfo = dateutil.tz.gettz(timezone)
    re_parsearea = re.compile(parsearea)

    for item in stream:
        # Todatetime option may be a string, which means convert and save a
        # property under the same name, or pair, which means convert and save
        # properties under the given names. The latter may be handy in cases
        # when you want to extract a datetime string, let's say, from a
        # filename.
        if isinstance(todatetime, str):
            parsein, saveto = todatetime, todatetime
        else:
            parsein, saveto = todatetime

        # Usually raising an error when contract is violated is a preferred
        # option. However, taking into account the use case of 'todatetime'
        # processor, we better ignore such items in the stream to save users
        # from wrapping this processor with 'when' processor.
        if parsein not in item:
            yield item
            continue

        parsein = item[parsein]

        # Cast the path object to string for user, because it's a behaviour a
        # user would expect anyway. Besides, I personally require such
        # behaviour because I prefer to have a datetime encoded in path.
        if isinstance(parsein, pathlib.Path):
            parsein = str(parsein)

        # Reduce a parse area by applying a regular expression. May be handy if
        # you want to extract a datetime from, let's say, a filename. If a
        # regular expression matches nothing, ignore and skip an item to avoid
        # using 'when' processor to make things *safe*.
        parsearea = re_parsearea.search(parsein)
        if not parsearea:
            yield item
            continue

        parsearea = parsearea.group(0)
        converted = dateutil.parser.parse(parsearea, fuzzy=fuzzy)

        # Attach passed timezone to a parsed datetime instance if tzinfo
        # hasn't been found.
        if not converted.tzinfo:
            converted = converted.replace(tzinfo=tzinfo)
        item[saveto] = converted

        yield item


text:
<?php

namespace ClashOfClans\Api\Clan;

use ClashOfClans\Api\AbstractResource;

class MemberList extends AbstractResource
{

    protected $casts = [
        'all' => Player::class
    ];

    /**
     * @return Player|null
     */
    public function first()
    {
        return $this->get(0);
    }

    /**
     * @return Player|null
     */
    public function nth($i)
    {
        return $this->get($i);
    }

    /**
     * @return array
     */
    public function all()
    {
        return $this->get();
    }

    /**
     * @return Player
     */
    public function leader()
    {
        $members = $this->all();

        return array_filter($members, function ($player) {
            return $player->isLeader();
        })[0];
    }

    /**
     * @return array
     */
    public function elders()
    {
        $members = $this->all();

        return array_filter($members, function ($player) {
            return $player->isElder();
        });
    }

    /**
     * @return array
     */
    public function coLeaders()
    {
        $members = $this->all();

        return array_filter($members, function ($player) {
            return $player->isCoLeader();
        });
    }
}


text:
                                    {   return [=](PType v)->bool{ return (*this)(v) op cmp; };   }

#define BWAPI_ARITHMATIC_FILTER_OP(op) template <typename T>                                            \
                                       CompareFilter<PType,RType,std::function<RType(PType)> > operator op(const T &other) const     \
                                       {   return [=](PType v)->int{ return (*this)(v) op other(v); };   }    \
                                       CompareFilter<PType,RType,std::function<RType(PType)> > operator op(RType other) const     \
                                       {   return [=](PType v)->int{ return (*this)(v) op other; };   }

namespace BWAPI
{
  /// <summary>The CompareFilter is a container in which a stored function predicate returns a
  /// value.</summary> Arithmetic and bitwise operators will return a new CompareFilter that
  /// applies the operation to the result of the original functor. If any relational operators are
  /// used, then it creates a UnaryFilter that returns the result of the operation.
  ///
  /// @tparam PType
  ///   The parameter type, which is the type passed into the functor.
  /// @tparam RType (optional)
  ///   The functor's return type. It is int by default.
  /// @tparam Container (optional)
  ///   Storage container for the function predicate. It is std::function<RType(PType)> by default.
  template < typename PType, typename RType=int, class Container = std::function<RType(PType)> >
  class CompareFilter
  {
  private:
    Container pred;
  public:
    // ctor
    template <typename T>
    CompareFilter(const T &predicate) : pred(predicate) {}

    // Default copy/move ctor/assign and dtor

    // Comparison operators
    BWAPI_COMPARE_FILTER_OP(==);
    BWAPI_COMPARE_FILTER_OP(!=);
    BWAPI_COMPARE_FILTER_OP(<=);
    BWAPI_COMPARE_FILTER_OP(>=);
    BWAPI_COMPARE_FILTER_OP(<);
    BWAPI_COMPARE_FILTER_OP(>);

    // Arithmetic operators
    BWAPI_ARITHMATIC_FILTER_OP(+);
    BWAPI_ARITHMATIC_FILTER_OP(-);
    BWAPI_ARITHMATIC_FILTER_OP(|);
    BWAPI_ARITHMATIC_FILTER_OP(&);
    BWAPI_ARITHMATIC_FILTER_OP(*);
    BWAPI_ARITHMATIC_FILTER_OP(^);

    // Division
    template <typename T>
    CompareFilter<PType,RType,std::function<RType(PType)> > operator /(const T &other) const
    {
      return [=](PType v)->int{ int rval = other(v);
                                 return rval == 0 ? std::numeric_limits<int>::max() : (*this)(v) / rval;
                               };
    };

    // Modulus
    template <typename T>
    CompareFilter<PType,RType,std::function<RType(PType)> > operator %(const T &other) const
    {
      return [=](PType v)->int{ int rval = other(v);
                                 return rval == 0 ? 0 : (*this)(v) % rval;
                               };
    };

    // call
    inline RType operator()(PType u) const
    {
      return pred(u);
    };

    inline bool isValid() const
    {
      return (bool)pred;
    };
  };
}


text:
/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 *    InstanceSavePanel.java
 *    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.gui.streams;

import weka.core.Instance;
import weka.core.Instances;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.io.FileOutputStream;
import java.io.PrintWriter;

/**
 * A bean that saves a stream of instances to a file.
 *
 * @author Len Trigg (trigg@cs.waikato.ac.nz)
 * @version $Revision: 7059 $
 */
public class InstanceSavePanel
  extends Panel
  implements InstanceListener {

  /** for serialization */
  private static final long serialVersionUID = -6061005366989295026L;

  private Label count_Lab;
  private int m_Count;
  private TextField arffFile_Tex;
  private boolean b_Debug;
  private PrintWriter outputWriter;

  public void input(Instance instance) throws Exception {

    if (b_Debug)
      System.err.println(Messages.getInstance().getString("InstanceSavePanel_Input_Error_Text_First") + instance + Messages.getInstance().getString("InstanceSavePanel_Input_Error_Text_Second"));
    m_Count++;
    count_Lab.setText(""+m_Count+Messages.getInstance().getString("InstanceSavePanel_Input_Count_Lab_SetText_Second"));
    if (outputWriter != null)
      outputWriter.println(instance.toString());
  }

  public void inputFormat(Instances instanceInfo) {

    if (b_Debug)
      System.err.println(Messages.getInstance().getString("InstanceSavePanel::inputFormat()\n") + instanceInfo.toString());
    m_Count = 0;
    count_Lab.setText(""+m_Count+Messages.getInstance().getString("InstanceSavePanel_InputFormat_Count_Lab_SetText_Second"));
    try {
      outputWriter = new PrintWriter(new FileOutputStream(arffFile_Tex.getText()));
      outputWriter.println(instanceInfo.toString());
      if (b_Debug)
	System.err.println(Messages.getInstance().getString("InstanceSavePanel_InputFormat_Error_Text_Second"));
    } catch (Exception ex) {
      outputWriter = null;
      System.err.println(Messages.getInstance().getString("InstanceSavePanel_InputFormat_Error_Text_Third") + ex.getMessage());
    }
  }

  public void batchFinished() {

    if (b_Debug)
      System.err.println(Messages.getInstance().getString("InstanceSavePanel_BatchFinished_Error_Text_First"));
    if (outputWriter != null)
      outputWriter.close();
  }

  public InstanceSavePanel() {

    setLayout(new BorderLayout());
    arffFile_Tex = new TextField("arffoutput.arff");
    add("Center", arffFile_Tex);
    count_Lab = new Label(Messages.getInstance().getString("InstanceSavePanel_Count_Lab_Label_Text"));
    add(Messages.getInstance().getString("InstanceSavePanel_Count_Lab_Label_Add_Text"), count_Lab);
    //    setSize(60,40);
    setBackground(Color.lightGray);
  }

  public void setDebug(boolean debug) {
    b_Debug = debug;
  }

  public boolean getDebug() {
    return b_Debug;
  }

  public void setArffFile(String newArffFile) {
    arffFile_Tex.setText(newArffFile);
  }

  public String getArffFile() {
    return arffFile_Tex.getText();
  }

  public void instanceProduced(InstanceEvent e) {

    Object source = e.getSource();
    if (source instanceof InstanceProducer) {
      try {
	InstanceProducer a = (InstanceProducer) source;
	switch (e.getID()) {
	case InstanceEvent.FORMAT_AVAILABLE:
	  inputFormat(a.outputFormat());
	  break;
	case InstanceEvent.INSTANCE_AVAILABLE:
	  input(a.outputPeek());
	  break;
	case InstanceEvent.BATCH_FINISHED:
	  batchFinished();
	  break;
	default:
	  System.err.println(Messages.getInstance().getString("InstanceSavePanel_InstanceProduced_InstanceProducerDEFAULT_Error_Text"));
	  break;
	}
      } catch (Exception ex) {
	System.err.println(ex.getMessage());
      }
    } else {
      System.err.println(Messages.getInstance().getString("InstanceSavePanel_InstanceProduced_Error_Text"));
    }
  }
}


text:
package com.bazomatic.components;

import com.badlogic.ashley.core.Component;

public class Selectable implements Component {

}


text:
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.api.query;

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

import com.cloud.exception.InvalidParameterValueException;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.SearchCriteria;

public class MutualExclusiveIdsManagerBase extends ManagerBase {

    /***
     * Include ids list in query criteria if ids is not null
     * @param sc search criteria, class type SearchCriteria<Z>
     * @param ids ids list, class type List<T>
     */
    protected <Z,T> void setIdsListToSearchCriteria(SearchCriteria<Z> sc, List<T> ids){
        if (ids != null && !ids.isEmpty()) {
            sc.setParameters("idIN", ids.toArray());
        }
    }

    /***
     * Mutually exclusive parameters id and ids for API calls.<br/>
     * Retrieve a list of ids or a list containing id depending on which of them is not null, or null if both are null
     * @param id entity id, class type T
     * @param ids entities ids, class type List<T>
     * @return if id is not null return a list containing id else return ids, if both parameters are null -> return null
     * @throws InvalidParameterValueException - if id and ids are both not null
     */
    protected <T> List<T> getIdsListFromCmd(T id, List<T> ids){
        List<T> idsList = null;
        if (id != null) {
            if (ids != null && !ids.isEmpty()) {
                throw new InvalidParameterValueException("Specify either id or ids but not both parameters");
            }
            idsList = new ArrayList<T>();
            idsList.add(id);
        } else {
            idsList = ids;
        }
        return idsList;
    }
}


text:
package gootp

import "time"

// TOTP implementation
type TOTP struct {
	*HOTP
	x int64
}

// NewTOTP generate new TOTP instance
func NewTOTP(secret []byte, digits, x int) (t *TOTP) {
	t = new(TOTP)
	t.HOTP = NewHOTP(secret, digits)
	t.x = int64(x)
	return t
}

// At get OTP at specific timestamp
func (t TOTP) At(timestamp int64) string {
	counter := uint64(timestamp / t.x)
	return t.HOTP.At(counter)
}

// Now get current TOTP
func (t TOTP) Now() string {
	now := time.Now()
	timestamp := now.Unix()
	return t.At(timestamp)
}

// Verify verify OTP code
func (t TOTP) Verify(code string) bool {
	return t.Now() == code
}


text:
class CreateSpreeEmailLogs < ActiveRecord::Migration
  def change
    create_table :spree_email_logs do |t|
      t.string :mail_type
      t.integer :loggable_id
      t.string :loggable_type

      t.timestamps
    end
  end
end


text:
export {version} from "./build/package";
export {default as drag} from "./src/drag";
export {default as dragDisable, yesdrag as dragEnable} from "./src/nodrag";