text:
.. _installation:

Installation
============

.. contents::
    :local:
    :depth: 1

Install from Conda
------------------

.. warning::

   TODO: Prepare Conda package.

Install from GitHub
-------------------

Check out code from the Flyingpigeon GitHub repo and start the installation:

.. code-block:: console

   $ git clone https://github.com/bird-house/flyingpigeon.git
   $ cd flyingpigeon

Create Conda environment named `flyingpigeon`:

.. code-block:: console

   $ conda env create -f environment.yml
   $ source activate flyingpigeon

Install Flyingpigeon app:

.. code-block:: console

  $ pip install -e .
  OR
  make install

For development you can use this command:

.. code-block:: console

  $ pip install -e .[dev]
  OR
  $ make develop

Start Flyingpigeon PyWPS service
--------------------------------

After successful installation you can start the service using the ``flyingpigeon`` command-line.

.. code-block:: console

   $ flyingpigeon --help # show help
   $ flyingpigeon start  # start service with default configuration

   OR

   $ flyingpigeon start --daemon # start service as daemon
   loading configuration
   forked process id: 42

The deployed WPS service is by default available on:

http://localhost:8093/wps?service=WPS&version=1.0.0&request=GetCapabilities.

.. NOTE:: Remember the process ID (PID) so you can stop the service with ``kill PID``.

You can find which process uses a given port using the following command (here for port 5000):

.. code-block:: console

   $ netstat -nlp | grep :5000

Check the log files for errors:

.. code-block:: console

   $ tail -f  pywps.log

... or do it the lazy way
+++++++++++++++++++++++++

You can also use the ``Makefile`` to start and stop the service:

.. code-block:: console

  $ make start
  $ make status
  $ tail -f pywps.log
  $ make stop

Run Flyingpigeon as Docker container
------------------------------------

You can also run Flyingpigeon as a Docker container.

.. warning::

  TODO: Describe Docker container support.

Use Ansible to deploy Flyingpigeon on your System
-------------------------------------------------

Use the `Ansible playbook`_ for PyWPS to deploy Flyingpigeon on your system.

.. _Ansible playbook: http://ansible-wps-playbook.readthedocs.io/en/latest/index.html

redpajama_set_name: RedPajamaGithub


text:
const { oneLine, stripIndents } = require('common-tags');
const Command = require('../base');
const disambiguation = require('../../util').disambiguation;

module.exports = class EnableCommandCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'enable',
			aliases: ['enable-command', 'cmd-on', 'command-on'],
			group: 'commands',
			memberName: 'enable',
			description: 'Enables a command or command group.',
			details: oneLine`
				The argument must be the name/ID (partial or whole) of a command or command group.
				Only administrators may use this command.
			`,
			examples: ['enable util', 'enable Utility', 'enable prefix'],
			guarded: true,

			args: [
				{
					key: 'cmdOrGrp',
					label: 'command/group',
					prompt: 'Which command or group would you like to toggle?',
					validate: val => {
						if(!val) return false;
						const groups = this.client.registry.findGroups(val);
						if(groups.length === 1) return true;
						const commands = this.client.registry.findCommands(val);
						if(commands.length === 1) return true;
						if(commands.length === 0 && groups.length === 0) return false;
						return stripIndents`
							${commands.length > 1 ? disambiguation(commands, 'commands') : ''}
							${groups.length > 1 ? disambiguation(groups, 'groups') : ''}
						`;
					},
					parse: val => this.client.registry.findGroups(val)[0] || this.client.registry.findCommands(val)[0]
				}
			]
		});
	}

	hasPermission(msg) {
		if(!msg.guild) return this.client.isOwner(msg.author);
		return msg.member.hasPermission('ADMINISTRATOR');
	}

	async run(msg, args) {
		if(args.cmdOrGrp.isEnabledIn(msg.guild)) {
			return msg.reply(
				`The \`${args.cmdOrGrp.name}\` ${args.cmdOrGrp.group ? 'command' : 'group'} is already enabled.`
			);
		}
		args.cmdOrGrp.setEnabledIn(msg.guild, true);
		return msg.reply(`Enabled the \`${args.cmdOrGrp.name}\` ${args.cmdOrGrp.group ? 'command' : 'group'}.`);
	}
};


text:
package org.apache.hadoop.hive.ql.exec.vector.wrapper;

import org.apache.hive.common.util.HashCodeUtil;

public abstract class VectorHashKeyWrapperTwoBase extends VectorHashKeyWrapperBase {

  protected boolean isNull0;
  protected boolean isNull1;

  protected static final int null0Hashcode =
      HashCodeUtil.calculateLongHashCode(8893L);
  protected static final int null1Hashcode =
      HashCodeUtil.calculateLongHashCode(255533L);
  protected static final int twoNullHashcode =
      HashCodeUtil.calculateLongHashCode(7566L);

  protected VectorHashKeyWrapperTwoBase() {
    super();
    isNull0 = false;
    isNull1 = false;
  }

  @Override
  public void clearIsNull() {
    isNull0 = false;
    isNull1 = false;
  }

  @Override
  public void setNull() {
    isNull0 = true;
    isNull1 = true;
  }

  @Override
  public boolean isNull(int keyIndex) {
    if (keyIndex == 0) {
      return isNull0;
    } else if (keyIndex == 1) {
      return isNull1;
    } else {
      throw new ArrayIndexOutOfBoundsException();
    }
  }
}


text:
window.addEventListener('DOMContentLoaded', function() {

  // We'll ask the browser to use strict code to help us catch errors earlier.
  // https://developer.mozilla.org/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
  'use strict';

  var db = null;
  var DBOpenRequest = window.indexedDB.open("slack", 4);

  DBOpenRequest.onerror = function(event) {
    console.log('Error loading database.');
  };

  DBOpenRequest.onsuccess = function(event) {
    console.log('Database initialised.');

    // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
    db = DBOpenRequest.result;
  };

  var token = "xoxp-YOURTOKENHERE"

  var channelList = document.getElementById('channels');
  var userList = document.getElementById('users');
  var messageList = document.getElementById('messages');

  var appHeader = document.getElementById('current');

  var refresher = document.getElementById('refresh');

  var postForm = document.getElementById('post-to-channel');
  var postMessage = document.getElementById('postmessage');

  var activeChannel = {};

  function setHeader(value){
    appHeader.innerHTML = value;
  }

  function clearMessageList(){
    while (messageList.firstChild) {
        messageList.removeChild(messageList.firstChild);
    }
  }

  var activeUsers = {};

  function rtmStart(){
    var url = "https://slack.com/api/rtm.start?token=" + token
     var request = new XMLHttpRequest({ mozSystem: true });
    request.open("get", url)

    request.responseType = 'json';
    request.addEventListener('error', function(){
      console.log("error");
      console.log(request.response);
    });
    request.addEventListener('load', function(){
      console.log("finished rtm.start");
      var resp = request.response

      if(resp.ok){

        // Load up the channels
        for (var i = 0; i < resp.channels.length; i++) {

          var channel = resp.channels[i]

          if(channel.is_member){
            var listItem = document.createElement('li');
            listItem.innerHTML = "#" + channel.name + "";
            listItem.channel = channel
            listItem.onclick = function(){
              channelHistory(this.channel);
            }
            channelList.appendChild(listItem);

            if(channel.name == "general"){
              channelHistory(channel);
            }
          }
        };

        // Load up all the users
        for (var i=0; i < resp.users.length; i ++){
          activeUsers[resp.users[i].id] = resp.users[i];
        }

        // And the IM channels

        for(var i=0;i<resp.ims.length; i++){

          var user = activeUsers[resp.ims[i].user];

          if(!resp.ims[i].is_user_deleted && resp.ims[i].is_open){
            var listItem = document.createElement('li');
            listItem.innerHTML = "" + user.name + "";
            listItem.user = user
            listItem.im = resp.ims[i]
            listItem.onclick = function(){
              userHistory(this.im, this.user);
            }
            userList.appendChild(listItem);
          }
        }
      }
    });
    request.send();
  }

  rtmStart();

  function getChannels(){
    var url = "https://slack.com/api/channels.list?token=" + token + "&exclude_archived=1"

    var request = new XMLHttpRequest({ mozSystem: true });
    request.open("get", url)

    request.responseType = 'json';
    request.addEventListener('error', function(){
      console.log("error");
      console.log(request.response);
    });
    request.addEventListener('load', function(){
      console.log("loaded");
      console.log(request.response);
      if(request.response.ok){
        console.log(request.response.latest)

        for (var i = 0; i < request.response.channels.length; i++) {
          var listItem = document.createElement('li');
          listItem.innerHTML = "#" + request.response.channels[i].name + "";
          listItem.channel = request.response.channels[i]
          listItem.onclick = function(){
            channelHistory(this.channel);
          }
          channelList.appendChild(listItem);
        };
      }
    });
    request.send();
  }

  function getUsername(msg){
    if(activeUsers[msg.user]){
      return activeUsers[msg.user].name
    }else if(msg.username){
      return msg.username
    }else{
      return "unknown"
    }
  }

  function sendMessage(channel, message){
    var url = "https://slack.com/api/chat.postMessage?token="+token + "&channel=" + channel.id

     var request = new XMLHttpRequest({ mozSystem: true });
    request.open("post", url, true)

    var data = new FormData();
    data.append("text", message);
    data.append("as_user", true);

    request.responseType = 'json';
    request.addEventListener('error', function(){
      console.log("error");
      console.log(request.response);
    });
    request.addEventListener('load', function(){
      console.log("loaded");
      console.log(request.response);
      if(request.response.ok){
        console.log(request.response.latest)

          var msgDiv = document.createElement('div');
          msgDiv.innerHTML = "" + "hownowstephen" + "
" + message;
          messageList.appendChild(msgDiv);
        messageList.scrollTop = messageList.scrollHeight + 10000;
      }
    });
    request.send(data);
  }

  postForm.onsubmit = function(e){
    if(activeChannel){
      e.preventDefault();
      sendMessage(activeChannel, postMessage.value);
      postMessage.value = "";
    }
  };

  function channelHistory(channel){
    var url = "https://slack.com/api/channels.history?token=" + token + "&channel=" + channel.id

    setHeader("#" + channel.name);
    clearMessageList();

    var request = new XMLHttpRequest({ mozSystem: true });
    request.open("post", url)

    request.responseType = 'json';
    request.addEventListener('error', function(){
      console.log("error");
      console.log(request.response);
    });
    request.addEventListener('load', function(){

      console.log("loaded channel history for channel ", channel);
      if(request.response.ok){
        console.log(request.response.latest)

        for (var i = request.response.messages.length-1; i >= 0; i--) {

          var msg = request.response.messages[i]
          var msgDiv = document.createElement('div');
          msgDiv.innerHTML = "" + getUsername(msg) + "
" + msg.text;
          msgDiv.message = msg

          messageList.appendChild(msgDiv);

        };

        activeChannel = channel;

        refresher.onclick = function(){
          channelHistory(channel);
        };

        messageList.scrollTop = messageList.scrollHeight + 10000;
      }
    });
    request.send();
  }

  function userHistory(im, user){
    var url = "https://slack.com/api/im.history?token=" + token + "&channel=" + im.id

    setHeader("Direct: " + user.name);
    clearMessageList();

    var request = new XMLHttpRequest({ mozSystem: true });
    request.open("post", url)

    request.responseType = 'json';
    request.addEventListener('error', function(){
      console.log("error");
      console.log(request.response);
    });
    request.addEventListener('load', function(){
      console.log("loaded IM history for user ", user);
      console.log(request.response);
      for (var i = request.response.messages.length-1; i >= 0; i--) {
        var msg = request.response.messages[i]
        var msgDiv = document.createElement('div');

        msgDiv.innerHTML = "" + getUsername(msg) + "
" + msg.text;
        msgDiv.message = request.response.messages[i]
        messageList.appendChild(msgDiv);
      };

      activeChannel = im;

      refresher.onclick = function(){
          userHistory(im, user);
        };

      console.log(messageList.scrollTop, messageList.scrollHeight);

      messageList.scrollTop = messageList.scrollHeight + 100000;
    });
    request.send();
  }

});


text:
using System;

using NUnit.Framework;

using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;

namespace Lucene.Net.Util
{

	/// <version>  $Id$
	/// </version>
	[TestFixture]
	public class TestOpenBitSet:LuceneTestCase
	{
		internal System.Random rand;

		internal virtual void  DoGet(System.Collections.BitArray a, OpenBitSet b)
		{
			int max = a.Count;
			for (int i = 0; i < max; i++)
			{
				if (a.Get(i) != b.Get(i))
				{
					Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.Get(i));
				}
			}
		}

		internal virtual void  DoNextSetBit(System.Collections.BitArray a, OpenBitSet b)
		{
			int aa = - 1, bb = - 1;
			do
			{
				aa = SupportClass.BitSetSupport.NextSetBit(a, aa + 1);
				bb = b.NextSetBit(bb + 1);
				Assert.AreEqual(aa, bb);
			}
			while (aa >= 0);
		}

		// test interleaving different OpenBitSetIterator.next()/skipTo()
		internal virtual void  DoIterate(System.Collections.BitArray a, OpenBitSet b, int mode)
		{
			if (mode == 1)
				DoIterate1(a, b);
			if (mode == 2)
				DoIterate2(a, b);
		}

		internal virtual void  DoIterate1(System.Collections.BitArray a, OpenBitSet b)
		{
			int aa = - 1, bb = - 1;
			OpenBitSetIterator iterator = new OpenBitSetIterator(b);
			do
			{
				aa = SupportClass.BitSetSupport.NextSetBit(a, aa + 1);
				bb = rand.NextDouble() > 0.5 ? iterator.NextDoc() : iterator.Advance(bb + 1);
				Assert.AreEqual(aa == - 1?DocIdSetIterator.NO_MORE_DOCS:aa, bb);
			}
			while (aa >= 0);
		}

		internal virtual void  DoIterate2(System.Collections.BitArray a, OpenBitSet b)
		{
			int aa = - 1, bb = - 1;
			OpenBitSetIterator iterator = new OpenBitSetIterator(b);
			do
			{
				aa = SupportClass.BitSetSupport.NextSetBit(a, aa + 1);
				bb = rand.NextDouble() > 0.5 ? iterator.NextDoc() : iterator.Advance(bb + 1);
				Assert.AreEqual(aa == - 1?DocIdSetIterator.NO_MORE_DOCS:aa, bb);
			}
			while (aa >= 0);
		}

		internal virtual void  DoRandomSets(int maxSize, int iter, int mode)
		{
			System.Collections.BitArray a0 = null;
			OpenBitSet b0 = null;

			for (int i = 0; i < iter; i++)
			{
				int sz = rand.Next(maxSize);
				System.Collections.BitArray a = new System.Collections.BitArray(sz);
				OpenBitSet b = new OpenBitSet(sz);

				// test the various ways of setting bits
				if (sz > 0)
				{
					int nOper = rand.Next(sz);
					for (int j = 0; j < nOper; j++)
					{
						int idx;

						idx = rand.Next(sz);
						a.Set(idx, true);
						b.FastSet(idx);
						idx = rand.Next(sz);
						a.Set(idx, false);
						b.FastClear(idx);
						idx = rand.Next(sz);
						a.Set(idx, !a.Get(idx));
						b.FastFlip(idx);

						bool val = b.FlipAndGet(idx);
						bool val2 = b.FlipAndGet(idx);
						Assert.IsTrue(val != val2);

						val = b.GetAndSet(idx);
						Assert.IsTrue(val2 == val);
						Assert.IsTrue(b.Get(idx));

						if (!val)
							b.FastClear(idx);
						Assert.IsTrue(b.Get(idx) == val);
					}
				}

				// test that the various ways of accessing the bits are equivalent
				DoGet(a, b);

                // {{dougsale-2.4.0}}
                //
                // Java's java.util.BitSet automatically grows as needed - i.e., when a bit is referenced beyond
                // the size of the BitSet, an exception isn't thrown - rather, the set grows to the size of the
                // referenced bit.
                //
                // System.Collections.BitArray does not have this feature, and thus I've faked it here by
                // "growing" the array explicitly when necessary (creating a new instance of the appropriate size
                // and setting the appropriate bits).
                //

                // test ranges, including possible extension
                int fromIndex, toIndex;
                fromIndex = rand.Next(sz + 80);
                toIndex = fromIndex + rand.Next((sz >> 1) + 1);

                // {{dougsale-2.4.0}}:
                // The following commented-out, compound statement's 'for loop' implicitly grows the Java BitSets 'a'
                // and 'aa' to the same cardinality as 'j+1' when 'a.Count < j+1' and 'fromIndex < toIndex':
                //BitArray aa = (BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, !a.Get(j));
                // So, if necessary, lets explicitly grow 'a' now; then 'a' and its clone, 'aa', will be of the required size.
                if (a.Count < toIndex && fromIndex < toIndex)
                {
                    System.Collections.BitArray tmp = new System.Collections.BitArray(toIndex, false);
                    for (int k = 0; k < a.Count; k++)
                        tmp.Set(k, a.Get(k));
                    a = tmp;
                }
                // {{dougsale-2.4.0}}: now we can invoke this statement without going 'out-of-bounds'
                System.Collections.BitArray aa = (System.Collections.BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, !a.Get(j));
                OpenBitSet bb = (OpenBitSet)b.Clone(); bb.Flip(fromIndex, toIndex);

                DoIterate(aa, bb, mode); // a problem here is from flip or doIterate

                fromIndex = rand.Next(sz + 80);
                toIndex = fromIndex + rand.Next((sz >> 1) + 1);
                // {{dougsale-2.4.0}}:
                // The following commented-out, compound statement's 'for loop' implicitly grows the Java BitSet 'aa'
                // when 'a.Count < j+1' and 'fromIndex < toIndex'
                //aa = (BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, false);
                // So, if necessary, lets explicitly grow 'aa' now
                if (a.Count < toIndex && fromIndex < toIndex)
                {
                    aa = new System.Collections.BitArray(toIndex);
                    for (int k = 0; k < a.Count; k++)
                        aa.Set(k, a.Get(k));
                }
                else
                {
                    aa = (System.Collections.BitArray)a.Clone();
                }
                for (int j = fromIndex; j < toIndex; j++) aa.Set(j, false);
                bb = (OpenBitSet)b.Clone(); bb.Clear(fromIndex, toIndex);

                DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit

                fromIndex = rand.Next(sz + 80);
                toIndex = fromIndex + rand.Next((sz >> 1) + 1);
                // {{dougsale-2.4.0}}:
                // The following commented-out, compound statement's 'for loop' implicitly grows the Java BitSet 'aa'
                // when 'a.Count < j+1' and 'fromIndex < toIndex'
                //aa = (BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, false);
                // So, if necessary, lets explicitly grow 'aa' now
                if (a.Count < toIndex && fromIndex < toIndex)
                {
                    aa = new System.Collections.BitArray(toIndex);
                    for (int k = 0; k < a.Count; k++)
                        aa.Set(k, a.Get(k));
                }
                else
                {
                    aa = (System.Collections.BitArray)a.Clone();
                }
                for (int j = fromIndex; j < toIndex; j++) aa.Set(j, true);
                bb = (OpenBitSet)b.Clone(); bb.Set(fromIndex, toIndex);

				DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit

				if (a0 != null)
				{
                    Assert.AreEqual(a.Equals(a0), b.Equals(b0));

                    Assert.AreEqual(SupportClass.BitSetSupport.Cardinality(a), b.Cardinality());

                    // {{dougsale-2.4.0}}
                    //
                    // The Java code used java.util.BitSet, which grows as needed.
                    // When a bit, outside the dimension of the set is referenced,
                    // the set automatically grows to the necessary size.  The
                    // new entries default to false.
                    //
                    // BitArray does not grow automatically and is not growable.
                    // Thus when BitArray instances of mismatched cardinality
                    // interact, we must first explicitly "grow" the smaller one.
                    //
                    // This growth is acheived by creating a new instance of the
                    // required size and copying the appropriate values.
                    //

                    //BitArray a_and = (BitArray)a.Clone(); a_and.And(a0);
                    //BitArray a_or = (BitArray)a.Clone(); a_or.Or(a0);
                    //BitArray a_xor = (BitArray)a.Clone(); a_xor.Xor(a0);
                    //BitArray a_andn = (BitArray)a.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);

                    System.Collections.BitArray a_and;
                    System.Collections.BitArray a_or;
                    System.Collections.BitArray a_xor;
                    System.Collections.BitArray a_andn;

                    if (a.Count < a0.Count)
                    {
                        // the Java code would have implicitly resized 'a_and', 'a_or', 'a_xor', and 'a_andn'
                        // in this case, so we explicitly create a resized stand-in for 'a' here, allowing for
                        // a to keep its original size while 'a_and', 'a_or', 'a_xor', and 'a_andn' are resized
                        System.Collections.BitArray tmp = new System.Collections.BitArray(a0.Count, false);
                        for (int z = 0; z < a.Count; z++)
                            tmp.Set(z, a.Get(z));

                        a_and = (System.Collections.BitArray)tmp.Clone(); a_and.And(a0);
                        a_or = (System.Collections.BitArray)tmp.Clone(); a_or.Or(a0);
                        a_xor = (System.Collections.BitArray)tmp.Clone(); a_xor.Xor(a0);
                        a_andn = (System.Collections.BitArray)tmp.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);
                    }
                    else if (a.Count > a0.Count)
                    {
                        // the Java code would have implicitly resized 'a0' in this case, so
                        // we explicitly do so here:
                        System.Collections.BitArray tmp = new System.Collections.BitArray(a.Count, false);
                        for (int z = 0; z < a0.Count; z++)
                            tmp.Set(z, a0.Get(z));
                        a0 = tmp;

                        a_and = (System.Collections.BitArray)a.Clone(); a_and.And(a0);
                        a_or = (System.Collections.BitArray)a.Clone(); a_or.Or(a0);
                        a_xor = (System.Collections.BitArray)a.Clone(); a_xor.Xor(a0);
                        a_andn = (System.Collections.BitArray)a.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);
                    }
                    else
                    {
                        // 'a' and 'a0' are the same size, no explicit growing necessary
                        a_and = (System.Collections.BitArray)a.Clone(); a_and.And(a0);
                        a_or = (System.Collections.BitArray)a.Clone(); a_or.Or(a0);
                        a_xor = (System.Collections.BitArray)a.Clone(); a_xor.Xor(a0);
                        a_andn = (System.Collections.BitArray)a.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);
                    }

                    OpenBitSet b_and = (OpenBitSet)b.Clone(); Assert.AreEqual(b, b_and); b_and.And(b0);
                    OpenBitSet b_or = (OpenBitSet)b.Clone(); b_or.Or(b0);
                    OpenBitSet b_xor = (OpenBitSet)b.Clone(); b_xor.Xor(b0);
                    OpenBitSet b_andn = (OpenBitSet)b.Clone(); b_andn.AndNot(b0);

                    DoIterate(a_and, b_and, mode);
                    DoIterate(a_or, b_or, mode);
                    DoIterate(a_xor, b_xor, mode);
                    DoIterate(a_andn, b_andn, mode);

                    Assert.AreEqual(SupportClass.BitSetSupport.Cardinality(a_and), b_and.Cardinality());
                    Assert.AreEqual(SupportClass.BitSetSupport.Cardinality(a_or), b_or.Cardinality());
                    Assert.AreEqual(SupportClass.BitSetSupport.Cardinality(a_xor), b_xor.Cardinality());
                    Assert.AreEqual(SupportClass.BitSetSupport.Cardinality(a_andn), b_andn.Cardinality());

                    // test non-mutating popcounts
                    Assert.AreEqual(b_and.Cardinality(), OpenBitSet.IntersectionCount(b, b0));
                    Assert.AreEqual(b_or.Cardinality(), OpenBitSet.UnionCount(b, b0));
                    Assert.AreEqual(b_xor.Cardinality(), OpenBitSet.XorCount(b, b0));
                    Assert.AreEqual(b_andn.Cardinality(), OpenBitSet.AndNotCount(b, b0));
                }

				a0 = a;
				b0 = b;
			}
		}

		// large enough to flush obvious bugs, small enough to run in <.5 sec as part of a
		// larger testsuite.
		[Test]
		public virtual void  TestSmall()
		{
			rand = NewRandom();
			DoRandomSets(1200, 1000, 1);
			DoRandomSets(1200, 1000, 2);
		}

		[Test]
		public virtual void  TestBig()
		{
			// uncomment to run a bigger test (~2 minutes).
			// rand = newRandom();
			// doRandomSets(2000,200000, 1);
			// doRandomSets(2000,200000, 2);
		}

		[Test]
		public virtual void  TestEquals()
		{
			rand = NewRandom();
			OpenBitSet b1 = new OpenBitSet(1111);
			OpenBitSet b2 = new OpenBitSet(2222);
			Assert.IsTrue(b1.Equals(b2));
			Assert.IsTrue(b2.Equals(b1));
			b1.Set(10);
			Assert.IsFalse(b1.Equals(b2));
			Assert.IsFalse(b2.Equals(b1));
			b2.Set(10);
			Assert.IsTrue(b1.Equals(b2));
			Assert.IsTrue(b2.Equals(b1));
			b2.Set(2221);
			Assert.IsFalse(b1.Equals(b2));
			Assert.IsFalse(b2.Equals(b1));
			b1.Set(2221);
			Assert.IsTrue(b1.Equals(b2));
			Assert.IsTrue(b2.Equals(b1));

			// try different type of object
			Assert.IsFalse(b1.Equals(new System.Object()));
		}

		[Test]
		public virtual void  TestBitUtils()
		{
			rand = NewRandom();
			long num = 100000;
			Assert.AreEqual(5, BitUtil.Ntz(num));
			Assert.AreEqual(5, BitUtil.Ntz2(num));
			Assert.AreEqual(5, BitUtil.Ntz3(num));

			num = 10;
			Assert.AreEqual(1, BitUtil.Ntz(num));
			Assert.AreEqual(1, BitUtil.Ntz2(num));
			Assert.AreEqual(1, BitUtil.Ntz3(num));

			for (int i = 0; i < 64; i++)
			{
				num = 1L << i;
				Assert.AreEqual(i, BitUtil.Ntz(num));
				Assert.AreEqual(i, BitUtil.Ntz2(num));
				Assert.AreEqual(i, BitUtil.Ntz3(num));
			}
		}

        [Test]
        public void TestHashCodeEquals()
        {
            OpenBitSet bs1 = new OpenBitSet(200);
            OpenBitSet bs2 = new OpenBitSet(64);
            bs1.Set(3);
            bs2.Set(3);
            Assert.AreEqual(bs1, bs2);
            Assert.AreEqual(bs1.GetHashCode(), bs2.GetHashCode());
        }
	}

}


text:
module WrapNilables
  def self.included(base)
    base.send(:include, InstanceMethods)
  end

  module InstanceMethods
    def read_attribute(attr_name)
      wrap_attributes!
      super(attr_name)
    end

    private

    def wrap_attributes!
      @attributes.each do |attr_name, value|
        if nilable?(attr_name)
          self.class.send(:define_method, attr_name.to_sym) do
            send(:"_#{attr_name}").wrapped
          end
        end
      end
    end

    def nilable?(attr_name)
      attr_name != 'id' &&
        !presence_validated?(attr_name) &&
        !null_constraint?(attr_name)
    end

    def presence_validated?(attr_name)
      self.class.validators_on(attr_name).any? do |v|
        v.is_a?(ActiveModel::Validations::PresenceValidator)
      end
    end

    def null_constraint?(attr_name)
      !self.class.columns_hash[attr_name].default.nil?
    end
  end
end


text:
/**
 * 使用宿主系统的context的repl
 * 是系统中集成的repl
 */
var stream = require('stream');
var repl = require('repl');
var Writable = stream.Writable;
var Readable = stream.Readable;
var EventEmitter = require('events');
var REPLEmitter = new EventEmitter();
var logger = require('../logger');

var replWrite = new Writable({
    objectMode: true,
    decodeStrings: false,
    write(chunk, encoding, callback) {

        // console.log(chunk.toString());
        // REPLEmitter.emit('output', chunk.toString());

        REPLEmitter.emit('output', chunk);
        callback();
    },
    writev(chunks, callback) {
        REPLEmitter.emit('output', chunk.toString());
        callback();
    }
});

replWrite.on('error', (error) => {
    logger.error('appContext REPL write has error');
    logger.error(error);
});

var replReadable = new Readable({read(size) {}});

replReadable.on('readable', function() {});

replReadable.on('error', (error) => {
    logger.error('appContext REPL read has error');
    logger.error(error);
});

function myWriter(output) {
    // console.log('myWriter ', output);
    // TODO
    // write(chunk, encoding, callback)
    // 这个方法,比如调用dawan.config 的时候
    // chunk的值 会是[object Object] 目前没有找到原因
    // objectMode: true,
    // decodeStrings: false, 这两个参数并不能解决掉这个问题
    // 因此在写入之前 先将对象序列化
    return JSON.stringify(output,null,4);
}

exports.start = function() {
    repl.start({writer: myWriter, useGlobal: true, input: replReadable, output: replWrite});

    // repl.start({useGlobal: true});
}

/**
 * repl的input
 * @param  {[type]} sentence [description]
 * @return {[type]}          [description]
 */
exports.input = function(sentence) {
    let tempBuffer = Buffer.from('' + sentence + '\n', 'utf8');
    replReadable.push(tempBuffer);
}

exports.REPLEmitter = REPLEmitter;


text:
namespace sf
{
////////////////////////////////////////////////////////////
Music::Music() :
m_file    (new priv::SoundFile),
m_duration()
{

}

////////////////////////////////////////////////////////////
Music::~Music()
{
    // We must stop before destroying the file
    stop();

    delete m_file;
}

////////////////////////////////////////////////////////////
bool Music::openFromFile(const std::string& filename)
{
    // First stop the music if it was already running
    stop();

    // Open the underlying sound file
    if (!m_file->openRead(filename))
        return false;

    // Perform common initializations
    initialize();

    return true;
}

////////////////////////////////////////////////////////////
bool Music::openFromMemory(const void* data, std::size_t sizeInBytes)
{
    // First stop the music if it was already running
    stop();

    // Open the underlying sound file
    if (!m_file->openRead(data, sizeInBytes))
        return false;

    // Perform common initializations
    initialize();

    return true;
}

////////////////////////////////////////////////////////////
bool Music::openFromStream(InputStream& stream)
{
    // First stop the music if it was already running
    stop();

    // Open the underlying sound file
    if (!m_file->openRead(stream))
        return false;

    // Perform common initializations
    initialize();

    return true;
}

////////////////////////////////////////////////////////////
Time Music::getDuration() const
{
    return m_duration;
}

////////////////////////////////////////////////////////////
bool Music::onGetData(SoundStream::Chunk& data)
{
    Lock lock(m_mutex);

    // Fill the chunk parameters
    data.samples     = &m_samples[0];
    data.sampleCount = m_file->read(&m_samples[0], m_samples.size());

    // Check if we have reached the end of the audio file
    return data.sampleCount == m_samples.size();
}

////////////////////////////////////////////////////////////
void Music::onSeek(Time timeOffset)
{
    Lock lock(m_mutex);

    m_file->seek(timeOffset);
}

////////////////////////////////////////////////////////////
void Music::initialize()
{
    // Compute the music duration
    m_duration = seconds(static_cast<float>(m_file->getSampleCount()) / m_file->getSampleRate() / m_file->getChannelCount());

    // Resize the internal buffer so that it can contain 1 second of audio samples
    m_samples.resize(m_file->getSampleRate() * m_file->getChannelCount());

    // Initialize the stream
    SoundStream::initialize(m_file->getChannelCount(), m_file->getSampleRate());
}

} // namespace sf


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

<title>org.ojalgo.constant</title>
<meta name="date" content="2013-04-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.ojalgo.constant

Classes

BigMath

BigPrefix

PrimitiveMath

PrimitivePrefix


text:
'use strict';

var config = require('../src/config');
var client = require('../src/client')();

client.indices.delete({
    index: config.elasticsearch.index
}, function() {
    client.indices.create({
        index: config.elasticsearch.index
    }, function() {
        createMappings();
    });
});

function createMappings() {
    client.indices.putMapping({
        index: config.elasticsearch.index,
        type: 'products',
        body: {
            products: {
                properties: getProductsMapping()
            }
        }
    }, function(err) {
        if (err) {
            throw err;
        }

        /* eslint no-console: 0 */
        console.log('Products type created');
    });

    client.indices.putMapping({
        index: config.elasticsearch.index,
        type: 'stores',
        body: {
            stores: {
                properties: getStoresMapping()
            }
        }
    }, function(err) {
        if (err) {
            throw err;
        }

        /* eslint no-console: 0 */
        console.log('Stores type created');
    });
}

function getProductsMapping() {
    return {
        sku: { type: 'integer' },
        title: { type: 'string' },
        containerSize: { type: 'double' },
        price: { type: 'double' },
        pricePerLiter: { type: 'double' },
        productType: { type: 'string', index: 'not_analyzed' },
        productSelection: { type: 'string', index: 'not_analyzed' },
        storeCategory: { type: 'string', index: 'not_analyzed' },
        fullness: { type: 'integer' },
        freshness: { type: 'integer' },
        tannins: { type: 'integer' },
        bitterness: { type: 'integer' },
        sweetness: { type: 'integer' },
        color: { type: 'string' },
        aroma: { type: 'string' },
        taste: { type: 'string' },
        foodPairings: { type: 'string', index: 'not_analyzed' },
        country: { type: 'string', index: 'not_analyzed' },
        region: { type: 'string', index: 'not_analyzed' },
        subRegion: { type: 'string', index: 'not_analyzed' },
        vintage: { type: 'integer' },
        ingredients: { type: 'string' },
        method: { type: 'string' },
        abv: { type: 'double' },
        ibu: { type: 'double' },
        sugar: { type: 'double' },
        acid: { type: 'double' },
        storable: { type: 'string' },
        manufacturer: { type: 'string' },
        wholesaler: { type: 'string' },
        distributor: { type: 'string' },
        containerType: { type: 'string', index: 'not_analyzed' },
        corkType: { type: 'string', index: 'not_analyzed' },
        url: { type: 'string', index: 'not_analyzed' },

        imageIdentifier: { type: 'string', index: 'not_analyzed' },
        imageLastFetched: { type: 'date' },

        rateBeerId: { type: 'integer' },
        rateBeerLastFetch: { type: 'date' },
        rateBeerScores: {
            type: 'object',
            dynamic: false,
            properties: {
                overall: { type: 'integer' },
                style: { type: 'integer' }
            }
        }
    };
}

function getStoresMapping() {
    var openingHours = {
        type: 'object',
        dynamic: false,
        properties: {
            opens: { type: 'integer' },
            closes: { type: 'integer' }
        }
    };

    return {
        name: { type: 'string' },
        streetAddress: { type: 'string' },
        streetZip: { type: 'string' },
        streetCity: { type: 'string' },
        postalAddress: { type: 'string' },
        postalZip: { type: 'string' },
        postalCity: { type: 'string' },
        phoneNumber: { type: 'string' },
        category: { type: 'string', index: 'not_analyzed' },
        gpsCoordinates: { type: 'geo_point' },
        weekNumber: { type: 'integer' },
        openingHoursMonday: openingHours,
        openingHoursTuesday: openingHours,
        openingHoursWednesday: openingHours,
        openingHoursThursday: openingHours,
        openingHoursFriday: openingHours,
        openingHoursSaturday: openingHours,
        weekNumberNext: { type: 'integer' },
        openingHoursNextMonday: openingHours,
        openingHoursNextTuesday: openingHours,
        openingHoursNextWednesday: openingHours,
        openingHoursNextThursday: openingHours,
        openingHoursNextFriday: openingHours,
        openingHoursNextSaturday: openingHours
    };
}


text:
'use strict';

flowableAdminApp.controller('DeploymentController', ['$scope', '$rootScope', '$http', '$timeout','$location','$routeParams', '$modal', '$translate', '$q',
    function ($scope, $rootScope, $http, $timeout, $location, $routeParams, $modal, $translate, $q) {

        $rootScope.navigation = {main: 'process-engine', sub: 'deployments'};

		$scope.returnToList = function() {
			$location.path("/deployments");
		};

		$scope.openDefinition = function(definition) {
			if (definition && definition.getProperty('id')) {
				$location.path("/process-definition/" + definition.getProperty('id'));
			}
		};

		$scope.showAllDefinitions = function() {
		    // Populate the process-filter with parentId
		    $rootScope.filters.forced.processDefinitionFilter = {
		            deploymentId: $scope.deployment.id
		    };
		    $location.path("/process-definitions");
		};

		$q.all([$translate('PROCESS-DEFINITIONS.HEADER.ID'),
            $translate('PROCESS-DEFINITIONS.HEADER.NAME'),
            $translate('PROCESS-DEFINITIONS.HEADER.VERSION'),
            $translate('PROCESS-DEFINITIONS.HEADER.KEY')])
            .then(function(headers) {

                $scope.gridDefinitions = {
                    data: 'definitions.data',
                    enableRowReordering: false,
                    multiSelect: false,
                    keepLastSelected : false,
                    enableSorting: false,
                    rowHeight: 36,
                    afterSelectionChange: $scope.openDefinition,
                    columnDefs: [
                          { field: 'id', displayName: headers[0]},
                          { field: 'name', displayName: headers[1]},
                          { field: 'version', displayName: headers[2]},
                          { field: 'key', displayName: headers[3]}
                    ]
                };
        });

		$scope.deleteDeployment = function() {
		    var modalInstance = $modal.open({
                templateUrl: 'views/confirm-popup.html',
                controller: 'ConfirmPopupCtrl',
                resolve: {
                    model: function () {
                      return {
                          confirm: $translate.instant('DEPLOYMENTS.ACTION.DELETE'),
                          title: $translate.instant('DEPLOYMENTS.ACTION.DELETE'),
                          message: $translate.instant('DEPLOYMENTS.POPUP.DELETE.CONFIRM-MESSAGE', $scope.deployment)
                          };
                    }
                }

            });

            modalInstance.result.then(function (result) {
                if (result === true) {
                    $http({method: 'DELETE', url: '/app/rest/admin/deployments/' + $routeParams.deploymentId}).
                    success(function(data, status, headers, config) {
                        $scope.addAlert($translate.instant('ALERT.DEPLOYMENT.DELETED-DEPLOYMENT', $scope.deployment), 'info');
                        $scope.returnToList();
                    }).
                    error(function(data, status, headers, config) {
                        $scope.addAlert($translate.instant('ALERT.DEPLOYMENT.DELETE-ERROR', data), 'error');
                    });
                }
            });

        };

		$scope.executeWhenReady(function() {
		    // Load deployment
		    $http({method: 'GET', url: '/app/rest/admin/deployments/' + $routeParams.deploymentId}).
  	    	    success(function(data, status, headers, config) {
  	    	        $scope.deployment = data;
  	    	        console.log($scope.deployment);
  	    	    }).
  	    	    error(function(data, status, headers, config) {
                    if (data && data.message) {
                        // Extract error-message
                        $rootScope.addAlert(data.message, 'error');
                    } else {
                        // Use default error-message
                        $rootScope.addAlert($translate.instant('ALERT.GENERAL.HTTP-ERROR'), 'error');
                    }
  	    	    });

		    // Load process definitions
		    $http({method: 'GET', url: '/app/rest/admin/process-definitions?deploymentId=' + $routeParams.deploymentId}).
  	    	    success(function(data, status, headers, config) {
  	    	        $scope.definitions = data;
  	    	    });

  	     });
}]);


text:
function New-JenkinsFolder
{
    [CmdLetBinding(SupportsShouldProcess = $true)]
    [OutputType([System.String])]
    param
    (
        [parameter(
            Position = 1,
            Mandatory = $true)]
        [System.String]
        $Uri,

        [parameter(
            Position = 2,
            Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.CredentialAttribute()]
        $Credential,

        [parameter(
            Position = 3,
            Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Crumb,

        [parameter(
            Position = 4,
            Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Folder,

        [parameter(
            Position = 5,
            Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,

        [parameter(
            Position = 6,
            Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Description,

        [parameter(
            Position = 7,
            Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $XML
    )

    $null = $PSBoundParameters.Add('Type', 'Command')
    if (-not ($PSBoundParameters.ContainsKey('XML')))
    {
        # Generate the XML we need to use to create the job
        $XML = @"
<?xml version='1.0' encoding='UTF-8'?>
<com.cloudbees.hudson.plugins.folder.Folder plugin="cloudbees-folder">
  <actions/>
  <description>$Description</description>
  <properties/>
</com.cloudbees.hudson.plugins.folder.Folder>
"@
    }
    $null = $PSBoundParameters.Remove('XML')

    $Command = Resolve-JenkinsCommandUri -Folder $Folder -Command "createItem?name=$Name"

    $null = $PSBoundParameters.Remove('Name')
    $null = $PSBoundParameters.Remove('Description')
    $null = $PSBoundParameters.Remove('Folder')
    $null = $PSBoundParameters.Remove('Confirm')
    $null = $PSBoundParameters.Add('Command', $Command)
    $null = $PSBoundParameters.Add('Method', 'post')
    $null = $PSBoundParameters.Add('ContentType', 'application/xml')
    $null = $PSBoundParameters.Add('Body', $XML)
    if ($PSCmdlet.ShouldProcess(`
                $URI, `
            $($LocalizedData.NewFolderMessage -f $Name)))
    {
        $null = Invoke-JenkinsCommand @PSBoundParameters
    } # if
} # New-JenkinsFolder


text:
const mockGet = jest.fn()
jest.mock('@/history/api/history', () => ({ get: mockGet }))
jest.mock('@/base/i18n', () => ({ t: jest.fn() }))

import { createDatastore, throws, createValidationError } from '>/helpers'

describe('history module', () => {
  beforeEach(() => jest.resetModules())

  let datastore

  beforeEach(() => {
    datastore = createDatastore({
      history: require('./history').default,
      places: { getters: { get: () => jest.fn() } },
      users: { getters: { get: () => jest.fn() } },
      groups: { getters: { get: () => jest.fn() } },
    })
  })

  it('updates the history list with correct sorting', () => {
    datastore.commit('history/update', [
      { id: 3, date: new Date('2017-11-21') },
      { id: 4, date: new Date('2017-11-20') },
    ])
    datastore.commit('history/update', [
      { id: 5, date: new Date('2017-10-21') },
      { id: 6, date: new Date('2017-10-20') },
    ])
    datastore.commit('history/update', [
      { id: 1, date: new Date('2017-12-21') },
      { id: 2, date: new Date('2017-12-20') },
    ])
    expect(datastore.getters['history/all'].map(e => e.id)).toEqual([6, 5, 4, 3, 2, 1])
  })

  it('can add a history entry', () => {
    const entry = { id: 10, group: 1, place: 1, users: [1], date: new Date('2018-01-20') }

    datastore.commit('history/update', [entry])
    expect(datastore.getters['history/all'][0].id).toEqual(entry.id)
  })

  it('throws routeError if historyId is not available', async () => {
    mockGet.mockImplementationOnce(throws(createValidationError({ detail: 'Not found' })))
    await expect(datastore.dispatch('history/setActive', { historyId: 9999 }))
      .rejects.toHaveProperty('type', 'RouteError')
    expect(datastore.getters['history/active']).toBeUndefined()
  })
})


text:
package pl.tiffviewer.client;

public interface IntegerListener {
	public void valueChange(Integer value);
}


text:
package com.elmakers.mine.bukkit.action.builtin;

import java.util.Arrays;
import java.util.Collection;
import java.util.Random;

import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;

import com.elmakers.mine.bukkit.action.CompoundAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.spell.BaseSpell;
import com.elmakers.mine.bukkit.utility.random.RandomUtils;

public class SpreadAction extends CompoundAction
{
    private int radius;
    private float centerProbability;
    private float outerProbability;
    private float yawMax;
    private float pitchMax;

    @Override
    public void prepare(CastContext context, ConfigurationSection parameters) {
        super.prepare(context, parameters);
        radius = parameters.getInt("radius", 2);
        yawMax = (float)parameters.getDouble("yaw_max", 0);
        pitchMax = (float)parameters.getDouble("pitch_max", 0);
        centerProbability = (float)parameters.getDouble("probability", 1);
        outerProbability = (float)parameters.getDouble("probability", 1);
        centerProbability = (float)parameters.getDouble("center_probability", centerProbability);
        outerProbability = (float)parameters.getDouble("outer_probability", outerProbability);
    }

    @Override
    public SpellResult step(CastContext context) {
        Location sourceLocation = context.getCastLocation();
        Entity source = context.getEntity();
        Random random = context.getRandom();
        if (pitchMax > 0 || yawMax > 0)
        {
            sourceLocation = sourceLocation.clone();
            if (pitchMax > 0)
            {
                sourceLocation.setPitch(sourceLocation.getPitch() + pitchMax * random.nextFloat() - pitchMax / 2);
            }
            if (yawMax > 0)
            {
                sourceLocation.setYaw(sourceLocation.getYaw() + yawMax * random.nextFloat() - yawMax / 2);
            }
        }
        createActionContext(context, source, sourceLocation);
        Location targetLocation = actionContext.getTargetLocation();
        if (targetLocation != null)
        {
            targetLocation = targetLocation.clone();
            double weight = RandomUtils.lerp(centerProbability - outerProbability, centerProbability + outerProbability, random.nextFloat());
            double xOffset = radius * weight;
            xOffset = xOffset - radius;
            weight = RandomUtils.lerp(centerProbability - outerProbability, centerProbability + outerProbability, random.nextFloat());
            double zOffset = radius * weight;
            zOffset = zOffset - radius;
            targetLocation.setX(targetLocation.getX() + xOffset);
            targetLocation.setZ(targetLocation.getZ() + zOffset);
            actionContext.setTargetLocation(targetLocation);
        }
        return startActions();
    }

    @Override
    public boolean requiresTarget() {
        return false;
    }

    @Override
    public void getParameterNames(Spell spell, Collection<String> parameters)
    {
        super.getParameterNames(spell, parameters);
        parameters.add("radius");
        parameters.add("probability");
        parameters.add("center_probability");
        parameters.add("outer_probability");
        parameters.add("yaw_max");
        parameters.add("pitch_max");
    }

    @Override
    public void getParameterOptions(Spell spell, String parameterKey, Collection<String> examples)
    {
        if (parameterKey.equals("radius")) {
            examples.addAll(Arrays.asList(BaseSpell.EXAMPLE_SIZES));
        } else if (parameterKey.equals("probability") || parameterKey.equals("center_probability") || parameterKey.equals("outer_probability")) {
            examples.addAll(Arrays.asList(BaseSpell.EXAMPLE_PERCENTAGES));
        } else if (parameterKey.equals("yaw_max") || parameterKey.equals("pitch_max")) {
            examples.addAll(Arrays.asList(BaseSpell.EXAMPLE_VECTOR_COMPONENTS));
        } else {
            super.getParameterOptions(spell, parameterKey, examples);
        }
    }
}


text:
var Class = require('../../utils/Class');
var FileTypesManager = require('../FileTypesManager');
var GetFastValue = require('../../utils/object/GetFastValue');
var ImageFile = require('./ImageFile.js');
var IsPlainObject = require('../../utils/object/IsPlainObject');
var JSONFile = require('./JSONFile.js');
var MultiFile = require('../MultiFile.js');

/**
 * @typedef {object} Phaser.Loader.FileTypes.MultiAtlasFileConfig
 *
 * @property {string} key - The key of the file. Must be unique within both the Loader and the Texture Manager.
 * @property {string} [atlasURL] - The absolute or relative URL to load the multi atlas json file from. Or, a well formed JSON object.
 * @property {string} [atlasExtension='json'] - The default file extension to use for the atlas json if no url is provided.
 * @property {XHRSettingsObject} [atlasXhrSettings] - Extra XHR Settings specifically for the atlas json file.
 * @property {string} [path] - Optional path to use when loading the textures defined in the atlas data.
 * @property {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data.
 * @property {XHRSettingsObject} [textureXhrSettings] - Extra XHR Settings specifically for the texture files.
 */

/**
 * @classdesc
 * A single Multi Texture Atlas File suitable for loading by the Loader.
 *
 * These are created when you use the Phaser.Loader.LoaderPlugin#multiatlas method and are not typically created directly.
 *
 * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#multiatlas.
 *
 * @class MultiAtlasFile
 * @extends Phaser.Loader.MultiFile
 * @memberOf Phaser.Loader.FileTypes
 * @constructor
 * @since 3.7.0
 *
 * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
 * @param {string} key - The key of the file. Must be unique within both the Loader and the Texture Manager.
 * @param {string} [atlasURL] - The absolute or relative URL to load the multi atlas json file from.
 * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data.
 * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data.
 * @param {XHRSettingsObject} [atlasXhrSettings] - Extra XHR Settings specifically for the atlas json file.
 * @param {XHRSettingsObject} [textureXhrSettings] - Extra XHR Settings specifically for the texture files.
 */
var MultiAtlasFile = new Class({

    Extends: MultiFile,

    initialize:

    function MultiAtlasFile (loader, key, atlasURL, path, baseURL, atlasXhrSettings, textureXhrSettings)
    {
        if (IsPlainObject(key))
        {
            var config = key;

            key = GetFastValue(config, 'key');
            atlasURL = GetFastValue(config, 'url');
            atlasXhrSettings = GetFastValue(config, 'xhrSettings');
            path = GetFastValue(config, 'path');
            baseURL = GetFastValue(config, 'baseURL');
            textureXhrSettings = GetFastValue(config, 'textureXhrSettings');
        }

        var data = new JSONFile(loader, key, atlasURL, atlasXhrSettings);

        MultiFile.call(this, loader, 'multiatlas', key, [ data ]);

        this.config.path = path;
        this.config.baseURL = baseURL;
        this.config.textureXhrSettings = textureXhrSettings;
    },

    /**
     * Called by each File when it finishes loading.
     *
     * @method Phaser.Loader.MultiFile#onFileComplete
     * @since 3.7.0
     *
     * @param {Phaser.Loader.File} file - The File that has completed processing.
     */
    onFileComplete: function (file)
    {
        var index = this.files.indexOf(file);

        if (index !== -1)
        {
            this.pending--;

            if (file.type === 'json' && file.data.hasOwnProperty('textures'))
            {
                //  Inspect the data for the files to now load
                var textures = file.data.textures;

                var config = this.config;
                var loader = this.loader;

                var currentBaseURL = loader.baseURL;
                var currentPath = loader.path;
                var currentPrefix = loader.prefix;

                var baseURL = GetFastValue(config, 'baseURL', currentBaseURL);
                var path = GetFastValue(config, 'path', currentPath);
                var prefix = GetFastValue(config, 'prefix', currentPrefix);
                var textureXhrSettings = GetFastValue(config, 'textureXhrSettings');

                loader.setBaseURL(baseURL);
                loader.setPath(path);
                loader.setPrefix(prefix);

                for (var i = 0; i < textures.length; i++)
                {
                    //  "image": "texture-packer-multi-atlas-0.png",
                    var textureURL = textures[i].image;

                    var key = '_MA_' + textureURL;

                    var image = new ImageFile(loader, key, textureURL, textureXhrSettings);

                    this.addToMultiFile(image);

                    loader.addFile(image);

                    //  "normalMap": "texture-packer-multi-atlas-0_n.png",
                    if (textures[i].normalMap)
                    {
                        var normalMap = new ImageFile(loader, key, textures[i].normalMap, textureXhrSettings);

                        normalMap.type = 'normalMap';

                        image.setLink(normalMap);

                        this.addToMultiFile(normalMap);

                        loader.addFile(normalMap);
                    }
                }

                //  Reset the loader settings
                loader.setBaseURL(currentBaseURL);
                loader.setPath(currentPath);
                loader.setPrefix(currentPrefix);
            }
        }
    },

    /**
     * Adds this file to its target cache upon successful loading and processing.
     *
     * @method Phaser.Loader.MultiFile#addToCache
     * @since 3.7.0
     */
    addToCache: function ()
    {
        if (this.isReadyToProcess())
        {
            var fileJSON = this.files[0];

            fileJSON.addToCache();

            var data = [];
            var images = [];
            var normalMaps = [];

            for (var i = 1; i < this.files.length; i++)
            {
                var file = this.files[i];

                if (file.type === 'normalMap')
                {
                    continue;
                }

                var key = file.key.substr(4);
                var image = file.data;

                //  Now we need to find out which json entry this mapped to
                for (var t = 0; t < fileJSON.data.textures.length; t++)
                {
                    var item = fileJSON.data.textures[t];

                    if (item.image === key)
                    {
                        images.push(image);

                        data.push(item);

                        if (file.linkFile)
                        {
                            normalMaps.push(file.linkFile.data);
                        }

                        break;
                    }
                }
            }

            if (normalMaps.length === 0)
            {
                normalMaps = undefined;
            }

            this.loader.textureManager.addAtlasJSONArray(this.key, images, data, normalMaps);

            this.complete = true;

            for (i = 0; i < this.files.length; i++)
            {
                this.files[i].pendingDestroy();
            }
        }
    }

});

/**
 * Adds a Multi Texture Atlas, or array of multi atlases, to the current load queue.
 *
 * You can call this method from within your Scene's `preload`, along with any other files you wish to load:
 *
 * ```javascript
 * function preload ()
 * {
 *     this.load.multiatlas('level1', 'images/Level1.json');
 * }
 * ```
 *
 * The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
 * or if it's already running, when the next free load slot becomes available. This happens automatically if you
 * are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
 * it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
 * The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
 * Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
 * loaded.
 *
 * If you call this from outside of `preload` then you are responsible for starting the Loader afterwards and monitoring
 * its events to know when it's safe to use the asset. Please see the Phaser.Loader.LoaderPlugin class for more details.
 *
 * Phaser expects the atlas data to be provided in a JSON file as exported from the application Texture Packer,
 * version 4.6.3 or above, where you have made sure to use the Phaser 3 Export option.
 *
 * The way it works internally is that you provide a URL to the JSON file. Phaser then loads this JSON, parses it and
 * extracts which texture files it also needs to load to complete the process. If the JSON also defines normal maps,
 * Phaser will load those as well.
 *
 * The key must be a unique String. It is used to add the file to the global Texture Manager upon a successful load.
 * The key should be unique both in terms of files being loaded and files already present in the Texture Manager.
 * Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
 * then remove it from the Texture Manager first, before loading a new one.
 *
 * Instead of passing arguments you can pass a configuration object, such as:
 *
 * ```javascript
 * this.load.multiatlas({
 *     key: 'level1',
 *     atlasURL: 'images/Level1.json'
 * });
 * ```
 *
 * See the documentation for `Phaser.Loader.FileTypes.MultiAtlasFileConfig` for more details.
 *
 * Instead of passing a URL for the atlas JSON data you can also pass in a well formed JSON object instead.
 *
 * Once the atlas has finished loading you can use frames from it as textures for a Game Object by referencing its key:
 *
 * ```javascript
 * this.load.multiatlas('level1', 'images/Level1.json');
 * // and later in your game ...
 * this.add.image(x, y, 'level1', 'background');
 * ```
 *
 * To get a list of all available frames within an atlas please consult your Texture Atlas software.
 *
 * If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this files
 * key. For example, if the prefix was `MENU.` and the key was `Background` the final key will be `MENU.Background` and
 * this is what you would use to retrieve the image from the Texture Manager.
 *
 * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
 *
 * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
 * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension, although
 * this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
 *
 * Note: The ability to load this type of file will only be available if the Multi Atlas File type has been built into Phaser.
 * It is available in the default build but can be excluded from custom builds.
 *
 * @method Phaser.Loader.LoaderPlugin#multiatlas
 * @fires Phaser.Loader.LoaderPlugin#addFileEvent
 * @since 3.7.0
 *
 * @param {(string|Phaser.Loader.FileTypes.MultiAtlasFileConfig|Phaser.Loader.FileTypes.MultiAtlasFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
 * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
 * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data.
 * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data.
 * @param {XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings.
 *
 * @return {Phaser.Loader.LoaderPlugin} The Loader instance.
 */
FileTypesManager.register('multiatlas', function (key, atlasURL, path, baseURL, atlasXhrSettings)
{
    var multifile;

    //  Supports an Object file definition in the key argument
    //  Or an array of objects in the key argument
    //  Or a single entry where all arguments have been defined

    if (Array.isArray(key))
    {
        for (var i = 0; i < key.length; i++)
        {
            multifile = new MultiAtlasFile(this, key[i]);

            this.addFile(multifile.files);
        }
    }
    else
    {
        multifile = new MultiAtlasFile(this, key, atlasURL, path, baseURL, atlasXhrSettings);

        this.addFile(multifile.files);
    }

    return this;
});

module.exports = MultiAtlasFile;


text:
@implementation CardLayout

- (void)setupItemAttributes:(UICollectionViewLayoutAttributes *) attributes {
    int r = rand() % 4;

    //    CGFloat radian = M_PI / 180.0f * 30.0f;
    CGFloat radian = M_PI / 180.0f * 10.0f * r;
    attributes.transform = CGAffineTransformMakeRotation(radian);
    attributes.zIndex = attributes.indexPath.item;
}

- (void)setupSupplementaryViewAttributes:(UICollectionViewLayoutAttributes *) attributes{
    if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]){
        attributes.zIndex = -1;
    }
}

// 表示領域のレイアウト属性を返す
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {

    NSArray *allAttributes = [ super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes * attributes in allAttributes){
        if (attributes.representedElementCategory == UICollectionElementCategoryCell){
            // セルのレイアウト属性
            [self setupItemAttributes:attributes];
        } else if (attributes.representedElementCategory == UICollectionElementCategorySupplementaryView){
            // 補助ビューのレイアウト属性
            [self setupSupplementaryViewAttributes:attributes];
        }
    }
    return allAttributes;

}

// セルのレイアウト属性を返す
- (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    [self setupItemAttributes:attributes];
    return attributes;
}

// 補助ビューのレイアウト属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes * attributes = [super layoutAttributesForSupplementaryViewOfKind:elementKind atIndexPath:indexPath];
    [self setupSupplementaryViewAttributes:attributes];
    return attributes;
}

@end


text:
<?php

namespace Symfony\Bridge\Monolog\Tests\Handler;

use Monolog\Formatter\HtmlFormatter;
use Monolog\Formatter\LineFormatter;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Monolog\Handler\MailerHandler;
use Symfony\Bridge\Monolog\Logger;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

class MailerHandlerTest extends TestCase
{
    /** @var MockObject|MailerInterface */
    private $mailer = null;

    protected function setUp(): void
    {
        $this->mailer = $this->createMock(MailerInterface::class);
    }

    public function testHandle()
    {
        $handler = new MailerHandler($this->mailer, (new Email())->subject('Alert: %level_name% %message%'));
        $handler->setFormatter(new LineFormatter());
        $this->mailer
            ->expects($this->once())
            ->method('send')
            ->with($this->callback(function (Email $email) {
                return 'Alert: WARNING message' === $email->getSubject() && null === $email->getHtmlBody();
            }))
        ;
        $handler->handle($this->getRecord(Logger::WARNING, 'message'));
    }

    public function testHandleBatch()
    {
        $handler = new MailerHandler($this->mailer, (new Email())->subject('Alert: %level_name% %message%'));
        $handler->setFormatter(new LineFormatter());
        $this->mailer
            ->expects($this->once())
            ->method('send')
            ->with($this->callback(function (Email $email) {
                return 'Alert: ERROR error' === $email->getSubject() && null === $email->getHtmlBody();
            }))
        ;
        $handler->handleBatch($this->getMultipleRecords());
    }

    public function testMessageCreationIsLazyWhenUsingCallback()
    {
        $this->mailer
            ->expects($this->never())
            ->method('send')
        ;

        $callback = function () {
            throw new \RuntimeException('Email creation callback should not have been called in this test');
        };
        $handler = new MailerHandler($this->mailer, $callback, Logger::ALERT);

        $records = [
            $this->getRecord(Logger::DEBUG),
            $this->getRecord(Logger::INFO),
        ];
        $handler->handleBatch($records);
    }

    public function testHtmlContent()
    {
        $handler = new MailerHandler($this->mailer, (new Email())->subject('Alert: %level_name% %message%'));
        $handler->setFormatter(new HtmlFormatter());
        $this->mailer
            ->expects($this->once())
            ->method('send')
            ->with($this->callback(function (Email $email) {
                return 'Alert: WARNING message' === $email->getSubject() && null === $email->getTextBody();
            }))
        ;
        $handler->handle($this->getRecord(Logger::WARNING, 'message'));
    }

    /**
     * @return array Record
     */
    protected function getRecord($level = Logger::WARNING, $message = 'test', $context = [])
    {
        return [
            'message' => $message,
            'context' => $context,
            'level' => $level,
            'level_name' => Logger::getLevelName($level),
            'channel' => 'test',
            'datetime' => \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true))),
            'extra' => [],
        ];
    }

    /**
     * @return array
     */
    protected function getMultipleRecords()
    {
        return [
            $this->getRecord(Logger::DEBUG, 'debug message 1'),
            $this->getRecord(Logger::DEBUG, 'debug message 2'),
            $this->getRecord(Logger::INFO, 'information'),
            $this->getRecord(Logger::WARNING, 'warning'),
            $this->getRecord(Logger::ERROR, 'error'),
        ];
    }
}


text:
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.

using System.IO;
using System.Text;
using Geb.Image.Formats.Quantization;

namespace Geb.Image.Formats.Gif
{
    /// <summary>
    /// Image encoder for writing image data to a stream in gif format.
    /// </summary>
    public sealed class GifEncoder : IGifEncoderOptions
    {
        /// <summary>
        /// Gets or sets a value indicating whether the metadata should be ignored when the image is being encoded.
        /// </summary>
        public bool IgnoreMetadata { get; set; } = false;

        /// <summary>
        /// Gets or sets the encoding that should be used when writing comments.
        /// </summary>
        public Encoding TextEncoding { get; set; } = GifConstants.DefaultEncoding;

        /// <summary>
        /// Gets or sets the quantizer for reducing the color count.
        /// Defaults to the <see cref="OctreeQuantizer"/>
        /// </summary>
        public IQuantizer Quantizer { get; set; } /*= new OctreeQuantizer();*/

        /// <inheritdoc/>
        public void Encode(ImageBgra32 image, Stream stream)
        {
            //var encoder = new GifEncoderCore(image.GetConfiguration().MemoryManager, this);
            //encoder.Encode(image, stream);
        }
    }
}


text:
var util = require("util"),
    testUtil = require("./testUtil");

describe("defaultProjectPath", function () {
	it("returns default project path", function () {
        var cb = jasmine.createSpy().andCallFake(function (res, body) {
                var result = JSON.parse(body);
                expect(result.path).toMatch(/WebWorks Projects/);
            });

        testUtil.httpGet(testUtil.getTestURL("defaultProjectPath", {}), cb);

        waitsFor(function () {
            return cb.wasCalled;
        }, "callback never called", 15000);
	});
});


text:
package depav.results.parser.service.printer.formatter;

import depav.results.parser.model.Result;

public class CVSFormatter implements Formatter<Result> {

    enum Mode {
        COMMA(','), SEMICOLON(';');

        final char character;

        Mode(char character) {
            this.character = character;
        }

        public char getCharacter() {
            return character;
        }
    }

    private static final String STRING_PLACEHOLDER = "%s";

    private Mode mode = Mode.SEMICOLON;

    @Override
    public String format(Result result) {
        String epsilonT = getValue(result.getEpsilonT());
        String letterEpsilonT = getLetter(result.getEpsilonT());
        String epsilonZ =  getValue(result.getEpsilonZ());
        String letterEpsilonZ= getLetter(result.getEpsilonZ());
        String deflection = getDeflection(result.getDeflection());
        String radius = getRadius(result.getRadius());
        return String.format(getFormat(mode), epsilonT, letterEpsilonT, epsilonZ, letterEpsilonZ, deflection, radius);
    }

    public void setMode(Mode mode) {
        this.mode = mode;
    }

    private static String getFormat(Mode mode) {
        char c = mode.getCharacter();
        return  STRING_PLACEHOLDER + c +
                STRING_PLACEHOLDER + c +
                STRING_PLACEHOLDER + c +
                STRING_PLACEHOLDER + c +
                STRING_PLACEHOLDER + c +
                STRING_PLACEHOLDER;
    }

    private static String getValue(String value) {
        return value.substring(0, value.length() - 1);
    }

    private static String getLetter(String value) {
        return value.substring(value.length() - 1);
    }

    private static String getDeflection(String deflection) {
        return deflection.substring(0, deflection.length() - 6);
    }

    private static String getRadius(String radius) {
        return radius.substring(0, radius.length() - 1);
    }

}


text:
package org.heigit.ors.api.requests.matrix;

import com.vividsolutions.jts.geom.Coordinate;
import org.heigit.ors.api.requests.common.APIEnums;
import org.heigit.ors.api.requests.common.APIRequest;
import org.heigit.ors.common.DistanceUnit;
import org.heigit.ors.exceptions.ParameterValueException;
import org.heigit.ors.exceptions.ServerLimitExceededException;
import org.heigit.ors.exceptions.StatusCodeException;
import org.heigit.ors.matrix.MatrixMetricsType;
import org.heigit.ors.matrix.MatrixRequest;
import org.heigit.ors.routing.RoutingProfileType;
import org.heigit.ors.routing.WeightingMethod;
import org.heigit.ors.services.matrix.MatrixServiceSettings;
import org.heigit.ors.util.HelperFunctions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

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

public class MatrixRequestHandlerTest {
    private MatrixRequest bareMatrixRequest = new MatrixRequest();
    private MatrixRequest matrixRequest = new MatrixRequest();
    private Coordinate[] coordinates = new Coordinate[3];
    private Double[][] bareCoordinates = new Double[3][];
    private Double[] bareCoordinate1 = new Double[2];
    private Double[] bareCoordinate2 = new Double[2];
    private Double[] bareCoordinate3 = new Double[2];
    private List<List<Double>> listOfBareCoordinatesList = new ArrayList<>();

    private Coordinate coordinate1 = new Coordinate();
    private Coordinate coordinate2 = new Coordinate();
    private Coordinate coordinate3 = new Coordinate();

    private List<List<Double>> minimalLocations;
    private int maximumRoutes;

    @Before
    public void setUp() {
        System.setProperty("ors_config", "target/test-classes/ors-config-test.json");

        List<Double> bareCoordinatesList = new ArrayList<>();
        bareCoordinatesList.add(8.681495);
        bareCoordinatesList.add(49.41461);
        listOfBareCoordinatesList.add(bareCoordinatesList);
        bareCoordinatesList = new ArrayList<>();
        bareCoordinatesList.add(8.686507);
        bareCoordinatesList.add(49.41943);
        listOfBareCoordinatesList.add(bareCoordinatesList);
        bareCoordinatesList = new ArrayList<>();
        bareCoordinatesList.add(8.687872);
        bareCoordinatesList.add(49.420318);
        listOfBareCoordinatesList.add(bareCoordinatesList);

        bareCoordinate1[0] = 8.681495;
        bareCoordinate1[1] = 49.41461;
        bareCoordinate2[0] = 8.686507;
        bareCoordinate2[1] = 49.41943;
        bareCoordinate3[0] = 8.687872;
        bareCoordinate3[1] = 49.420318;
        bareCoordinates[0] = bareCoordinate1;
        bareCoordinates[1] = bareCoordinate2;
        bareCoordinates[2] = bareCoordinate3;
        coordinate1.x = 8.681495;
        coordinate1.y = 49.41461;
        coordinate2.x = 8.686507;
        coordinate2.y = 49.41943;
        coordinate3.x = 8.687872;
        coordinate3.y = 49.420318;
        coordinates[0] = coordinate1;
        coordinates[1] = coordinate2;
        coordinates[2] = coordinate3;
        matrixRequest.setResolveLocations(true);
        matrixRequest.setMetrics(MatrixMetricsType.DURATION);
        matrixRequest.setSources(coordinates);
        matrixRequest.setDestinations(coordinates);
        matrixRequest.setProfileType(RoutingProfileType.CYCLING_REGULAR);
        matrixRequest.setUnits(DistanceUnit.METERS);
        bareMatrixRequest.setSources(coordinates);
        bareMatrixRequest.setDestinations(coordinates);

        // Fake locations to test maximum exceedings

        minimalLocations = HelperFunctions.fakeListLocations(1, 2);
        maximumRoutes = MatrixServiceSettings.getMaximumRoutes(false) + 1;
    }

    @Test
    public void convertMatrixRequestTest() throws StatusCodeException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(bareCoordinates);
        springMatrixRequest.setProfile(APIEnums.Profile.DRIVING_CAR);
        springMatrixRequest.setSources(new String[]{"all"});
        springMatrixRequest.setDestinations(new String[]{"all"});
        MatrixRequest matrixRequest = springMatrixRequest.convertMatrixRequest();
        Assert.assertEquals(1, matrixRequest.getProfileType());
        Assert.assertEquals(3, matrixRequest.getSources().length);
        Assert.assertEquals(3, matrixRequest.getDestinations().length);
        Assert.assertEquals(1, matrixRequest.getMetrics());
        Assert.assertEquals(WeightingMethod.UNKNOWN, matrixRequest.getWeightingMethod());
        Assert.assertEquals(DistanceUnit.METERS, matrixRequest.getUnits());
        Assert.assertFalse(matrixRequest.getResolveLocations());
        Assert.assertFalse(matrixRequest.getFlexibleMode());
        Assert.assertNull(matrixRequest.getId());

        springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(bareCoordinates);
        springMatrixRequest.setProfile(APIEnums.Profile.DRIVING_CAR);
        springMatrixRequest.setSources(new String[]{"all"});
        springMatrixRequest.setDestinations(new String[]{"all"});
        MatrixRequestEnums.Metrics[] metrics = new MatrixRequestEnums.Metrics[2];
        metrics[0] = MatrixRequestEnums.Metrics.DURATION;
        metrics[1] = MatrixRequestEnums.Metrics.DISTANCE;
        springMatrixRequest.setMetrics(metrics);
        matrixRequest = springMatrixRequest.convertMatrixRequest();

        Assert.assertEquals(3, matrixRequest.getMetrics());
    }

    @Test(expected = ParameterValueException.class)
    public void invalidLocationsTest() throws StatusCodeException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());
        springMatrixRequest.setProfile(APIEnums.Profile.DRIVING_CAR);
        springMatrixRequest.setSources(new String[]{"foo"});
        springMatrixRequest.setDestinations(new String[]{"bar"});
        springMatrixRequest.convertMatrixRequest();
    }

    @Test(expected = ParameterValueException.class)
    public void invalidMetricsTest() throws StatusCodeException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());
        springMatrixRequest.setProfile(APIEnums.Profile.DRIVING_CAR);
        springMatrixRequest.setLocations(listOfBareCoordinatesList);
        springMatrixRequest.setMetrics(new MatrixRequestEnums.Metrics[0]);
        springMatrixRequest.setSources(new String[]{"foo"});
        springMatrixRequest.setDestinations(new String[]{"bar"});
        springMatrixRequest.convertMatrixRequest();
    }

    @Test(expected = ParameterValueException.class)
    public void invalidSourceIndexTest() throws StatusCodeException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());
        springMatrixRequest.setProfile(APIEnums.Profile.DRIVING_CAR);
        springMatrixRequest.setLocations(listOfBareCoordinatesList);
        springMatrixRequest.setSources(new String[]{"foo"});
        springMatrixRequest.setDestinations(new String[]{"bar"});
        springMatrixRequest.convertMatrixRequest();
    }

    @Test(expected = ParameterValueException.class)
    public void invalidDestinationIndexTest() throws StatusCodeException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());
        springMatrixRequest.setProfile(APIEnums.Profile.DRIVING_CAR);
        springMatrixRequest.setLocations(listOfBareCoordinatesList);
        springMatrixRequest.setSources(new String[]{"all"});
        springMatrixRequest.setDestinations(new String[]{"foo"});
        springMatrixRequest.convertMatrixRequest();
    }

    @Test
    public void convertMetricsTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());
        Assert.assertEquals(1, springMatrixRequest.convertMetrics(new MatrixRequestEnums.Metrics[] {MatrixRequestEnums.Metrics.DURATION}));
        Assert.assertEquals(2, springMatrixRequest.convertMetrics(new MatrixRequestEnums.Metrics[] {MatrixRequestEnums.Metrics.DISTANCE}));
        Assert.assertEquals(3, springMatrixRequest.convertMetrics(new MatrixRequestEnums.Metrics[] {MatrixRequestEnums.Metrics.DURATION, MatrixRequestEnums.Metrics.DISTANCE}));
    }

    @Test(expected = ParameterValueException.class)
    public void notEnoughLocationsTest() throws ParameterValueException, ServerLimitExceededException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        springMatrixRequest.convertLocations(minimalLocations, 5);
    }

    @Test(expected = ServerLimitExceededException.class)
    public void maximumExceedingLocationsTest() throws ParameterValueException, ServerLimitExceededException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        springMatrixRequest.convertLocations(listOfBareCoordinatesList, maximumRoutes);
    }

    @Test
    public void convertLocationsTest() throws ParameterValueException, ServerLimitExceededException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        Coordinate[] coordinates = springMatrixRequest.convertLocations(listOfBareCoordinatesList, 3);
        Assert.assertEquals(8.681495, coordinates[0].x, 0);
        Assert.assertEquals(49.41461, coordinates[0].y, 0);
        Assert.assertEquals(Double.NaN, coordinates[0].z, 0);
        Assert.assertEquals(8.686507, coordinates[1].x, 0);
        Assert.assertEquals(49.41943, coordinates[1].y, 0);
        Assert.assertEquals(Double.NaN, coordinates[1].z, 0);
        Assert.assertEquals(8.687872, coordinates[2].x, 0);
        Assert.assertEquals(49.420318, coordinates[2].y, 0);
        Assert.assertEquals(Double.NaN, coordinates[2].z, 0);
    }

    @Test
    public void convertSingleLocationCoordinateTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        List<Double> locationsList = new ArrayList<>();
        locationsList.add(8.681495);
        locationsList.add(49.41461);
        Coordinate coordinates = springMatrixRequest.convertSingleLocationCoordinate(locationsList);
        Assert.assertEquals(8.681495, coordinates.x, 0);
        Assert.assertEquals(49.41461, coordinates.y, 0);
        Assert.assertEquals(Double.NaN, coordinates.z, 0);
    }

    @Test(expected = ParameterValueException.class)
    public void convertWrongSingleLocationCoordinateTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        List<Double> locationsList = new ArrayList<>();
        locationsList.add(8.681495);
        locationsList.add(49.41461);
        locationsList.add(123.0);
        springMatrixRequest.convertSingleLocationCoordinate(locationsList);

    }

    @Test
    public void convertSourcesTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        String[] emptySources = new String[0];
        Coordinate[] convertedSources = springMatrixRequest.convertSources(emptySources, this.coordinates);
        Assert.assertEquals(8.681495, convertedSources[0].x, 0);
        Assert.assertEquals(49.41461, convertedSources[0].y, 0);
        Assert.assertEquals(Double.NaN, convertedSources[0].z, 0);
        Assert.assertEquals(8.686507, convertedSources[1].x, 0);
        Assert.assertEquals(49.41943, convertedSources[1].y, 0);
        Assert.assertEquals(Double.NaN, convertedSources[1].z, 0);
        Assert.assertEquals(8.687872, convertedSources[2].x, 0);
        Assert.assertEquals(49.420318, convertedSources[2].y, 0);
        Assert.assertEquals(Double.NaN, convertedSources[2].z, 0);

        String[] allSources = new String[]{"all"};
        convertedSources = springMatrixRequest.convertSources(allSources, this.coordinates);
        Assert.assertEquals(8.681495, convertedSources[0].x, 0);
        Assert.assertEquals(49.41461, convertedSources[0].y, 0);
        Assert.assertEquals(Double.NaN, convertedSources[0].z, 0);
        Assert.assertEquals(8.686507, convertedSources[1].x, 0);
        Assert.assertEquals(49.41943, convertedSources[1].y, 0);
        Assert.assertEquals(Double.NaN, convertedSources[1].z, 0);
        Assert.assertEquals(8.687872, convertedSources[2].x, 0);
        Assert.assertEquals(49.420318, convertedSources[2].y, 0);
        Assert.assertEquals(Double.NaN, convertedSources[2].z, 0);

        String[] secondSource = new String[]{"1"};
        convertedSources = springMatrixRequest.convertSources(secondSource, this.coordinates);
        Assert.assertEquals(8.686507, convertedSources[0].x, 0);
        Assert.assertEquals(49.41943, convertedSources[0].y, 0);
        Assert.assertEquals(Double.NaN, convertedSources[0].z, 0);
    }

    @Test(expected = ParameterValueException.class)
    public void convertWrongSourcesTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        String[] wrongSource = new String[]{"foo"};
        springMatrixRequest.convertSources(wrongSource, this.coordinates);
    }

    @Test
    public void convertDestinationsTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        String[] emptyDestinations = new String[0];
        Coordinate[] convertedDestinations = springMatrixRequest.convertDestinations(emptyDestinations, this.coordinates);
        Assert.assertEquals(8.681495, convertedDestinations[0].x, 0);
        Assert.assertEquals(49.41461, convertedDestinations[0].y, 0);
        Assert.assertEquals(Double.NaN, convertedDestinations[0].z, 0);
        Assert.assertEquals(8.686507, convertedDestinations[1].x, 0);
        Assert.assertEquals(49.41943, convertedDestinations[1].y, 0);
        Assert.assertEquals(Double.NaN, convertedDestinations[1].z, 0);
        Assert.assertEquals(8.687872, convertedDestinations[2].x, 0);
        Assert.assertEquals(49.420318, convertedDestinations[2].y, 0);
        Assert.assertEquals(Double.NaN, convertedDestinations[2].z, 0);

        String[] allDestinations = new String[]{"all"};
        convertedDestinations = springMatrixRequest.convertDestinations(allDestinations, this.coordinates);
        Assert.assertEquals(8.681495, convertedDestinations[0].x, 0);
        Assert.assertEquals(49.41461, convertedDestinations[0].y, 0);
        Assert.assertEquals(Double.NaN, convertedDestinations[0].z, 0);
        Assert.assertEquals(8.686507, convertedDestinations[1].x, 0);
        Assert.assertEquals(49.41943, convertedDestinations[1].y, 0);
        Assert.assertEquals(Double.NaN, convertedDestinations[1].z, 0);
        Assert.assertEquals(8.687872, convertedDestinations[2].x, 0);
        Assert.assertEquals(49.420318, convertedDestinations[2].y, 0);
        Assert.assertEquals(Double.NaN, convertedDestinations[2].z, 0);

        String[] secondDestination = new String[]{"1"};
        convertedDestinations = springMatrixRequest.convertDestinations(secondDestination, this.coordinates);
        Assert.assertEquals(8.686507, convertedDestinations[0].x, 0);
        Assert.assertEquals(49.41943, convertedDestinations[0].y, 0);
        Assert.assertEquals(Double.NaN, convertedDestinations[0].z, 0);
    }

    @Test(expected = ParameterValueException.class)
    public void convertWrongDestinationsTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        String[] wrongDestinations = new String[]{"foo"};
        springMatrixRequest.convertDestinations(wrongDestinations, this.coordinates);
    }

    @Test
    public void convertIndexToLocationsTest() throws Exception {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        ArrayList<Coordinate> coordinate = springMatrixRequest.convertIndexToLocations(new String[]{"1"}, this.coordinates);
        Assert.assertEquals(8.686507, coordinate.get(0).x, 0);
        Assert.assertEquals(49.41943, coordinate.get(0).y, 0);
        Assert.assertEquals(Double.NaN, coordinate.get(0).z, 0);
    }

    @Test(expected = Exception.class)
    public void convertWrongIndexToLocationsTest() throws Exception {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        springMatrixRequest.convertIndexToLocations(new String[]{"foo"}, this.coordinates);
    }

    @Test
    public void convertUnitsTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        Assert.assertEquals(DistanceUnit.METERS, APIRequest.convertUnits(APIEnums.Units.METRES));
        Assert.assertEquals(DistanceUnit.KILOMETERS, APIRequest.convertUnits(APIEnums.Units.KILOMETRES));
        Assert.assertEquals(DistanceUnit.MILES, APIRequest.convertUnits(APIEnums.Units.MILES));
    }

    @Test
    public void convertToProfileTypeTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        Assert.assertEquals(1, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.DRIVING_CAR));
        Assert.assertEquals(2, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.DRIVING_HGV));
        Assert.assertEquals(10, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.CYCLING_REGULAR));
        Assert.assertEquals(12, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.CYCLING_ROAD));
        Assert.assertEquals(11, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.CYCLING_MOUNTAIN));
        Assert.assertEquals(17, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.CYCLING_ELECTRIC));
        Assert.assertEquals(20, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.FOOT_WALKING));
        Assert.assertEquals(21, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.FOOT_HIKING));
        Assert.assertEquals(30, springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.WHEELCHAIR));
    }

    @Test(expected = ParameterValueException.class)
    public void convertToWrongMatrixProfileTypeTest() throws ParameterValueException {
        org.heigit.ors.api.requests.matrix.MatrixRequest springMatrixRequest = new org.heigit.ors.api.requests.matrix.MatrixRequest(new ArrayList<>());

        springMatrixRequest.convertToMatrixProfileType(APIEnums.Profile.forValue("foo"));
    }

}


text:
ActiveRecord::Schema.define(:version => 20121105221805) do

  create_table "downtime_checks", :force => true do |t|
    t.string   "name"
    t.integer  "downtime_id"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  create_table "downtime_clients", :force => true do |t|
    t.string   "name"
    t.integer  "downtime_id"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  create_table "downtimes", :force => true do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "start_time"
    t.datetime "stop_time"
    t.integer  "user_id"
    t.boolean  "processed",   :default => false
    t.boolean  "completed",   :default => false
    t.datetime "created_at",                     :null => false
    t.datetime "updated_at",                     :null => false
  end

  create_table "logs", :force => true do |t|
    t.string   "client"
    t.string   "check"
    t.string   "silence_type"
    t.string   "action_type"
    t.string   "environment"
    t.text     "output"
    t.text     "reason"
    t.string   "status"
    t.integer  "user_id"
    t.datetime "created_at",   :null => false
    t.datetime "updated_at",   :null => false
  end

  create_table "roles", :force => true do |t|
    t.string   "name"
    t.integer  "resource_id"
    t.string   "resource_type"
    t.datetime "created_at",    :null => false
    t.datetime "updated_at",    :null => false
  end

  add_index "roles", ["name", "resource_type", "resource_id"], :name => "index_roles_on_name_and_resource_type_and_resource_id"
  add_index "roles", ["name"], :name => "index_roles_on_name"

  create_table "settings", :force => true do |t|
    t.string   "name"
    t.string   "value"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "users", :force => true do |t|
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "deleted_at"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

  create_table "users_roles", :id => false, :force => true do |t|
    t.integer "user_id"
    t.integer "role_id"
  end

  add_index "users_roles", ["user_id", "role_id"], :name => "index_users_roles_on_user_id_and_role_id"

end


text:
{-# LANGUAGE BangPatterns #-}

module Main where

import Control.Exception (finally)
import System.IO.MMap (
    Mode(..)
  , mmapFilePtr
  , munmapFilePtr
  )
import Foreign.Ptr (plusPtr)
import Foreign.Storable (sizeOf)
import System.Environment (getArgs)
import System.FilePath (addExtension)
import Foreign.C.Types (CDouble)

import OskarFFI

writeOSKAR
    :: OVisData
    -> FilePath
    -> FilePath
    -> IO Status
writeOSKAR (OVD hdl ts_x_bl chans write_and_fin) path_amp path_uvw = do
    (ptru, rawsizeu, offsetu, _sizeu) <- mmapFilePtr path_uvw ReadWriteEx (Just (0, 3 * ts_x_bl_bytes))
    (ptra, rawsizea, offseta, _sizea) <- mmapFilePtr path_amp ReadWriteEx (Just (0, 8 * ts_x_bl_bytes * chans))
    finally
      (write_and_fin hdl (ptra `plusPtr` offseta) (ptru `plusPtr` offsetu))
      (munmapFilePtr ptru rawsizeu >> munmapFilePtr ptra rawsizea)
  where
    ts_x_bl_bytes = ts_x_bl * sizeOf (undefined :: CDouble)

main :: IO ()
main = do
  fname <- fmap head getArgs
  evd <- vis_allocate_and_read fname
  let fadd_ex = addExtension fname
  case evd of
    Left status -> putStrLn $ "Error: " ++ show status
    Right ovd -> writeOSKAR ovd (fadd_ex "amp") (fadd_ex "uvw") >>= putStrLn . ("Done with: " ++) . show


text:
package edu.rutgers.css.Rutgers.interfaces;

/**
 * Interface for Bus fragments with 'dummy' search field to send focus events to main Bus fragment
 */
public interface FilterFocusBroadcaster {
    public void setFocusListener(FilterFocusListener listener);
}


text:
package com.tom.workflow.form;

import com.tom.workflow.entity.Panel;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Created by tom on 16/4/18.
 */
public class FreeOfChargeOrder extends WorkflowBase{
    private static final Logger logger = LoggerFactory.getLogger(FreeOfChargeOrder.class);

    public static final String WORKFLOW_NAME = "免费发货单";
    public static final String WORKFLOW_TYPE = "FreeOfChargeOrder";

    public FreeOfChargeOrder(String username, String password, String busId, String checkType, String id) {
        super(username, password, busId, checkType, id);
    }

    public String getType() {
        return WORKFLOW_TYPE;
    }

    public String getName() {
        return WORKFLOW_NAME;
    }

}


text:
/**
 * Contains web configuration classes.
 */
package org.springframework.cloud.dataflow.server.config.web;