text:
<?php
/*
 * php-proauth (c) Ingmar "KiNgMaR" Runge 2009-2010
 * You are free to use this code under the terms of The MIT License.
 * You should have received a copy of The MIT License in LICENSE.txt with this file.
 */

if(!defined('_OAUTH_LIB_DIR'))
{
	define('_OAUTH_LIB_DIR', dirname(__FILE__) . '/');
}

require_once _OAUTH_LIB_DIR . 'OAuthUtil.php';
require_once _OAUTH_LIB_DIR . 'OAuthRequest.php';
require_once _OAUTH_LIB_DIR . 'OAuthSignature.php';
require_once _OAUTH_LIB_DIR . 'OAuthServerBackend.php';

class OAuthServer
{
	protected $backend;
	protected $user_data = NULL;
	protected $signature_methods = array();
	protected $superglobals_auto_export;

	/**
	 * @param OAuthServerBackend backend The backend. Yeah.
	 * @param bool superglobals_auto_export If true, OAuthServerRequest parameters validated against \
	 *   this class will be exported as $_GET, $_POST and $_REQUEST automatically.
	 **/
	public function __construct(OAuthServerBackend $backend, $superglobals_auto_export = false)
	{
		$this->backend = $backend;
		$this->superglobals_auto_export = $superglobals_auto_export;
	}

	/**
	 * Registers a supported signature method.
	 **/
	public function addSignatureMethod(OAuthSignatureMethod $method)
	{
		$this->signature_methods[strtoupper($method->getName())] = $method;
	}

	/**
	 * For internal use, checks if the OAuth version of $req is okay.
	 **/
	protected function checkOAuthVersion(OAuthServerRequest $req)
	{
		$version = $req->getOAuthVersion();

		if(!version_compare($version, '1.0', '=='))
		{
			throw new OAuthException('OAuth version "' . $version . '" is not supported!',
				400, 'version_rejected', array('oauth_acceptable_versions' => '1.0-1.0'));
		}

		return $version;
	}

	/**
	 * For internal use, returns an OAuthConsumer instance.
	 **/
	protected function getConsumer(OAuthServerRequest $req)
	{
		$consumer_key = $req->getConsumerKey();

		if(!$consumer_key)
		{
			throw new OAuthException('Invalid consumer key.', 401, 'consumer_key_unknown');
		}

		$consumer = $this->backend->getConsumerByKey($consumer_key);

		if($consumer === OAuthServerBackend::RESULT_RATE_LIMITED)
		{
			throw new OAuthException('Too many requests have been made. Throttling.', 401, 'consumer_key_refused');
		}
		elseif($consumer === OAuthServerBackend::RESULT_DISABLED)
		{
			throw new OAuthException('This consumer key has been disabled permanently.', 401, 'consumer_key_rejected');
		}
		elseif($consumer === OAuthServerBackend::RESULT_NOT_FOUND)
		{
			throw new OAuthException('Consumer not found.', 500);
		}
		elseif(!$consumer instanceof OAuthConsumer)
		{
			throw new OAuthException('Backend returned an incorrect value from getConsumerByKey');
		}

		return $consumer;
	}

	/**
	 * For internal use, returns the appropriate OAuthSignatureMethod instance.
	 **/
	protected function getSignatureMethod(OAuthServerRequest $req)
	{
		$method = strtoupper($req->getSignatureMethod());

		if(!isset($this->signature_methods[$method]))
		{
			throw new OAuthException('Signature method "' . $method . '" not supported.', 400, 'signature_method_rejected');
		}

		return $this->signature_methods[$method];
	}

	/**
	 * For internal use, checks nonce, timestamp and token!
	 **/
	protected function checkSignature(OAuthServerRequest $req, OAuthConsumer $consumer, OAuthToken $token = NULL)
	{
		$req->getNonceAndTimeStamp($nonce, $timestamp);

		$result = $this->backend->checkNonceAndTimeStamp($nonce, (int)$timestamp, $consumer, $token);

		if($result == OAuthServerBackend::RESULT_OK)
		{
			$sig_method = $this->getSignatureMethod($req);

			if(!$sig_method->checkSignature($req, $consumer, $token))
			{
				throw new OAuthException('Invalid signature.', 401, 'signature_invalid');
			}

			if($this->superglobals_auto_export)
			{
				$req->exportAsSuperglobals();
			}
		}
		elseif($result == OAuthServerBackend::RESULT_DUPE_NONCE)
		{
			throw new OAuthException('A previously used nonce has been used again.', 401, 'nonce_used');
		}
		elseif($result == OAuthServerBackend::RESULT_BAD_TIMESTAMP)
		{
			throw new OAuthException('The request timestamp is invalid.', 401, 'timestamp_refused');
		}
		elseif($result == OAuthServerBackend::RESULT_BAD_TOKEN)
		{
			throw new OAuthException('The token is invalid, or has expired.', 401, 'token_rejected');
		}
		else
		{
			throw new OAuthException('Backend returned an incorrect value from checkNonceAndTimeStamp');
		}
	}

	/**
	 * Auth Flow Server API: Implements section 2.1. "Temporary Credentials" of the OAuth Core specs.
	 **/
	public function requestToken()
	{
		$req = new OAuthServerRequest();

		// check basic premises...
		$this->checkOAuthVersion($req);

		$consumer = $this->getConsumer($req);

		// this request does not require a token.
		$this->checkSignature($req, $consumer, NULL);

		// store a callback_url, if we have one:
		$callback_url = $req->getCallbackParameter();

		// generate a temp secret:
		$temp_secret = OAuthShared::randomString(40);

		do
		{
			// and a temp token:
			$new_token = new OAuthToken(OAuthShared::randomString(20), $temp_secret);
			// and validate it with the backend to make sure it's unique:
			$result = $this->backend->addTempToken($consumer, $new_token, $callback_url);
		} while($result == OAuthServerBackend::RESULT_DUPE);

		if($result != OAuthServerBackend::RESULT_OK)
		{
			throw new OAuthException('Creating a temporary token failed.');
		}

		// The specs say "oauth_callback_confirmed: MUST be present and set to true.
		// The parameter is used to differentiate from previous versions of the protocol."
		// But we feel free to also use "false", if no callback was given.
		$new_token->setAdditionalParam('oauth_callback_confirmed', (empty($callback_url) ? 'false' : 'true'));

		return $new_token;
	}

	/**
	 * Auth Flow Server API: Implements the first part of section
	 * 2.2. "Resource Owner Authorization" of the OAuth Core specs.
	 * @param user_idf string
	 **/
	public function authorize_checkToken($token_str, $user_idf, $callback_url)
	{
		$consumer = NULL;

		if($this->backend->checkTempToken($token_str, $user_idf, $callback_url, $consumer) != OAuthServerBackend::RESULT_OK)
		{
			throw new OAuthException('The token is invalid, or has expired.', 401, 'token_rejected');
		}

		// ok, nice, the request seems to be okay. Cool.
		// The server frontend can now render the "Hello user, plz authorize this app!" page.
		return $consumer;
	}

	/**
	 * Auth Flow Server API: Implements the second part of section 2.2.
	 **/
	public function authorize_result($token_str, $user_idf, $authorized)
	{
		// We do not need to check for an OAuthRequest, since this won't be one.
		if($authorized)
		{
			$callback_url = $this->backend->getTempTokenCallback($token_str, $user_idf);

			if($this->backend->validateCallbackURL($token_str, $callback_url) != OAuthServerBackend::RESULT_OK ||
				($callback_url != 'oob' && !filter_var($callback_url, FILTER_VALIDATE_URL)))
			{
				throw new OAuthException('The backend failed to deliver a valid callback for this temporary token!');
			}

			$verifier = $this->backend->generateVerifier($callback_url);
			$redirect = false;

			if($this->backend->authorizeTempToken($token_str, $user_idf, $verifier, $redirect) != OAuthServerBackend::RESULT_OK)
			{
				throw new OAuthException('Backend was unable to authorize the temporary token!');
			}

			if($redirect)
			{
				if(filter_var($callback_url, FILTER_VALIDATE_URL))
				{
					$oauth_params = array('oauth_token' => $token_str, 'oauth_verifier' => $verifier);

					// merge the oauth_token and oauth_verifier parameters and possible
					// parameters from a query string in $callback_url. Pretty gross.
					$url = OAuthUtil::normalizeRequestURL($callback_url) . '?';

					$params = array();
					parse_str(parse_url($callback_url, PHP_URL_QUERY), $params);

					$params = array_merge($params, $oauth_params);

					header('HTTP/1.0 301 Permanently Moved'); // :TODO: send a more appropriate status code.
					header('Location: ' . $url . http_build_query($params, '', '&'));
				}
				else
				{
					throw new OAuthException('The client failed to provide a valid oauth_callback!');
				}
			}

			return true;
		}
		else
		{
			if($this->backend->deleteTempToken($token_str, $user_idf) != OAuthServerBackend::RESULT_OK)
			{
				throw new OAuthException('Backend was unable to revoke the temporary token!');
			}
		}

		return true;
	}

	/**
	 * Auth Flow Server API: Implements section 2.3. "Token Credentials".
	 **/
	public function accessToken()
	{
		$req = new OAuthServerRequest();

		$this->checkOAuthVersion($req);

		$consumer = $this->getConsumer($req);

		$token_str = $req->getTokenParameter();
		$token_secret = '';

		// this request has to be signed using the temporary credentials.

		if($this->backend->checkAuthedTempToken($consumer, $token_str, $token_secret) != OAuthServerBackend::RESULT_OK)
		{
			throw new OAuthException('The token is invalid, or has expired.', 401, 'token_rejected');
		}

		if(empty($token_secret))
		{
			throw new OAuthException('Empty token secret in OAuthServer::accessToken.');
		}

		$token = new OAuthToken($token_str, $token_secret);

		$this->checkSignature($req, $consumer, $token);

		$access_secret = OAuthShared::randomString(40);

		if($this->backend->checkVerifier($token_str, $req->getVerifierParameter()) != OAuthServerBackend::RESULT_OK)
		{
			throw new OAuthException('The provided oauth_verifier did not match the token.', 401, 'verifier_invalid');
		}

		do
		{
			$new_token = new OAuthToken(OAuthShared::randomString(20), $access_secret);
			$result = $this->backend->exchangeTempToken($consumer, $token, $new_token);
		} while($result == OAuthServerBackend::RESULT_DUPE);

		if($result != OAuthServerBackend::RESULT_OK)
		{
			throw new OAuthException('Creating an authorized token failed.');
		}

		return $new_token;
	}

	/**
	 * Use this method to verify an API call and its parameters.
	 * If the verification succeeds, you can use the parameters from $_GET and $_POST.
	 * @param bool requires_user Defines whether the call needs a user or if a valid consumer and signature are enough. \
	 *  If this is false, but the request still has a non-empty oauth_token, the user data will be checked and returned as usual.
	 * @return mixed Returns the user data that the backend associated with the access_token session.
	 **/
	public function verifyApiCall($requires_user = true)
	{
		$req = new OAuthServerRequest();

		$this->checkOAuthVersion($req);

		$consumer = $this->getConsumer($req);

		$token = NULL;
		$user_data = true;
		$token_str = $req->getTokenParameter();

		if($requires_user || !empty($token_str))
		{
			$token_secret = '';
			$user_data = NULL;

			$result = $this->backend->getAccessTokenInfo($consumer, $token_str, $token_secret, $user_data);
			if($consumer === OAuthServerBackend::RESULT_RATE_LIMITED)
			{
				throw new OAuthException('Too many requests have been made. Throttling.', 401, 'user_refused');
			}
			elseif($result == OAuthServerBackend::RESULT_OPERATION_NOT_PERMITTED)
			{
				throw new OAuthException('Operation not permitted.', 401, 'permission_denied');
			}
			elseif($result != OAuthServerBackend::RESULT_OK)
			{
				throw new OAuthException('The token is invalid, or has expired.', 401, 'token_rejected');
			}

			$token = new OAuthToken($token_str, $token_secret);
		}
		// If no user is required (and the token is empty), we only check the signature
		// with the consumer credentials, oauth version and signature.
		// If it's nice, we return true, and throw otherwise.

		$this->checkSignature($req, $consumer, $token);

		return $user_data;
	}
}

class OAuthServerRequest extends OAuthRequest
{
	public function __construct()
	{
		parent::__construct();

		// Determine HTTP method...
		$this->http_method = OAuthShared::getIfSet($_SERVER, 'REQUEST_METHOD');

		if(empty($this->http_method))
		{
			// :TODO: find out if this actually happens and how bad the fallback is.
			$this->http_method = (count($_POST) > 0 ? 'POST' : 'GET');
		}

		// Determine request URL:
		$host = OAuthShared::getIfSet($_SERVER, 'HTTP_HOST');

		if(empty($host))
		{
			throw new OAuthException('The requesting client did not send the HTTP Host header which is required by this implementation.', 400);
		}

		$scheme = (OAuthShared::getIfSet($_SERVER, 'HTTPS', 'off') === 'on' ? 'https' : 'http');

		$port = (int)$_SERVER['SERVER_PORT'];

		if(preg_match('~^(.+):(\d+)$~', $host, $match))
		{
			if(false)
			{
				// this check breaks with NAT and mod_proxy and stuff. :TODO: figure it out.
				if((int)$match[2] != $port)
				{
					throw new OAuthException('Bad port in the HTTP Host header.', 400);
				}
			}
			else
			{
				$port = (int)$match[2];
			}

			$host = $match[1];
		}

		// courtesy: http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address
		if(!preg_match('~^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$~', $host)
			&& !filter_var($host, FILTER_VALIDATE_IP))
		{
			throw new OAuthException('Invalid HTTP Host header.', 400);
		}

		$this->request_url = $scheme . '://' . $host .
			($port == ($scheme == 'https' ? 443 : 80) ? '' : ':' . $port) .
			$_SERVER['REQUEST_URI'];

		if(!filter_var($this->request_url, FILTER_VALIDATE_URL))
		{
			throw new OAuthException('Unable to form a valid URL from the request.');
		}

		$page_request_headers = OAuthUtil::getPageRequestHeaders();

		// extract oauth parameters from the Authorization
		// HTTP header. If present, these take precedence over
		// GET and POST parameters.
		$header_parameters = OAuthShared::getIfSet($page_request_headers, 'authorization');

		if(!empty($header_parameters))
		{
			$header_parameters = OAuthUtil::parseHttpAuthorizationHeader($header_parameters);
			$realm = '';

			if(is_array($header_parameters) && count($header_parameters) > 0)
			{
				$realm = OAuthShared::getIfSet($header_parameters, 'realm');
				unset($header_parameters['realm']);

				$this->params_oauth = $header_parameters;
			}

			$this->setRealm($realm);
		}

		// The next paragraphs refers to sections 3.4.1.3.1. and 3.5. of the OAuth Core specs.

		// We rely on PHP to parse the $_POST and $_GET parameters for us.
		// This *could* break in some weird cases, but I am not aware of any
		// situation out in the wild where that would happen. PHP uses
		// urldecode() to decode the parameters, which works in accordance to
		// section 3.4.1.3.1. of the Core specs.
		// C.f. OAuthShared::urlDecode()

		$this->params_post = array();
		$this->params_get = array();

		$content_type = trim(OAuthShared::getIfSet($page_request_headers, 'content-type'));

		if(preg_match('~^application/x-www-form-urlencoded~i', $content_type))
		{
			// extract POST parameters...
			foreach($_POST as $key => $value)
			{
				if(OAuthUtil::isKnownOAuthParameter($key))
				{
					if(!isset($this->params_oauth[$key]))
					{
						$this->params_oauth[$key] = $value;
					}
					else
					{
						throw new OAuthException('You cannot specify the "' . $key . '" parameter multiple times.', 400);
					}
				}
				else
				{
					$this->params_post[$key] = $value;
				}
			}
		}

		// extract GET parameters...
		foreach($_GET as $key => $value)
		{
			if(OAuthUtil::isKnownOAuthParameter($key))
			{
				if(!isset($this->params_oauth[$key]))
				{
					$this->params_oauth[$key] = $value;
				}
				else
				{
					throw new OAuthException('You cannot specify the "' . $key . '" parameter multiple times.', 400);
				}
			}
			else
			{
				if(isset($this->params_post[$key]))
				{
					throw new OAuthException('We do not support GET and POST parameters with the same name.', 400);
				}

				$this->params_get[$key] = $value;
			}
		}

		// whew, done with the parameter extraction.

		if(count($this->params_oauth) == 0)
		{
			// the Service Provider can now send
			// header('WWW-Authenticate: OAuth realm="http://sp.example.com/"');
			// if he deems it necessary.
			throw new NonOAuthRequestException();
		}
	}

	/**
	 * Overwrites the $_GET, $_POST and $_REQUEST superglobals with the data from this
	 * request. They won't contain any known oauth_ parameters and $_REQUEST will
	 * be cookie-parameter free.
	 **/
	public function exportAsSuperglobals()
	{
		// POST parameters would take precedence here, but we do not
		// support POST and GET parameters of the same name, so
		// yeah. Just writing this down here so we know later.
		$_REQUEST = array_merge($this->params_get, $this->params_post);

		$_GET = $this->params_get;
		$_POST = $this->params_post;

		// we cannot validate file uploads right now,
		// if there were any files, $_POST will be empty too
		// (because Content-Type isn't application/x-www-form-urlencoded)
		$_FILES = array();
	}

	/**
	 * Returns the oauth_callback parameter's value or an empty string.
	 **/
	public function getCallbackParameter()
	{
		return OAuthShared::getIfSet($this->params_oauth, 'oauth_callback', '');
	}

	/**
	 * Returns the oauth_token parameter's value or an empty string.
	 **/
	public function getTokenParameter()
	{
		return OAuthShared::getIfSet($this->params_oauth, 'oauth_token', '');
	}

	/**
	 * Returns the oauth_verifier parameter's value or an empty string.
	 **/
	public function getVerifierParameter()
	{
		return OAuthShared::getIfSet($this->params_oauth, 'oauth_verifier', '');
	}
}

class NonOAuthRequestException extends Exception {}


text:
/* eslint-disable @typescript-eslint/no-require-imports */
process.on('unhandledRejection', (error: any) => {
  // Won't execute
  console.log('unhandledRejection', error.test);
});

const cwd = process.cwd();
// eslint-disable-next-line
const resolve = require('path').resolve;
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('glob')('./spec/**/*-spec.ts', (err: Error, files: string[]) => {
  if (err) {
    throw err;
  }
  files.forEach((file) => require(resolve(cwd, file)));
});

redpajama_set_name: RedPajamaGithub


text:
// Copyright NVIDIA Corporation 2002-2005
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <dp/util/Config.h>

#if defined(DP_OS_WINDOWS)
  #include <Windows.h>
#elif defined(DP_OS_LINUX)
  #include <sys/time.h>
#else
  #error Unknown OS
#endif

namespace dp
{
  namespace util
  {
    /*! \brief A simple timer class.
     * This timer class can be used on Windows and Linux systems to
     * measure time intervals in seconds.
     * The timer can be started and stopped several times and accumulates
     * time elapsed between the start() and stop() calls. */
    class Timer
    {
    public:
      //! Default constructor. Constructs a Timer, but does not start it yet.
      DP_UTIL_API Timer();

      //! Default destructor.
      DP_UTIL_API ~Timer();

      //! Starts the timer.
      DP_UTIL_API void start();

      //! Stops the timer.
      DP_UTIL_API void stop();

      //! Resets the timer.
      DP_UTIL_API void reset();

      //! Resets the timer and starts it.
      DP_UTIL_API void restart();

      //! Returns the current time in seconds.
      DP_UTIL_API double getTime() const;

      //! Return whether the timer is still running.
      bool isRunning() const { return m_running; }

    private:
#if defined(DP_OS_WINDOWS)
      typedef LARGE_INTEGER Time;
#elif defined(DP_OS_LINUX)
      typedef timeval Time;
#else
  #error Unknown OS
#endif

    private:
      double calcDuration(Time begin, Time end) const;

    private:
#if defined(DP_OS_WINDOWS)
      LARGE_INTEGER m_freq;
#endif
      Time m_begin;
      bool m_running;
      double m_seconds;
    };

  } // namespace util
} // namespace dp


text:
/*
Package mailbox implements mailbox queues and dispatching
*/
package mailbox


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("rxjs-compat/operators/debounce"));
//# sourceMappingURL=debounce.js.map


text:
using System;
using System.Linq;

namespace UnityEditor.PackageManager.UI.Tests
{
    internal class MockAddOperation : MockOperation, IAddOperation
    {
        public new event Action<Error> OnOperationError = delegate { };
        public new event Action OnOperationFinalized = delegate { };
        public event Action<PackageInfo> OnOperationSuccess = delegate { };

        public PackageInfo PackageInfo { get; set; }

        public MockAddOperation(MockOperationFactory factory, PackageInfo packageInfo = null) : base(factory)
        {
            PackageInfo = packageInfo;
        }

        public void AddPackageAsync(PackageInfo packageInfo, Action<PackageInfo> doneCallbackAction = null,
                                    Action<Error> errorCallbackAction = null)
        {
            if (ForceError != null)
            {
                if (errorCallbackAction != null)
                    errorCallbackAction(ForceError);

                IsCompleted = true;
                OnOperationError(ForceError);
            }
            else
            {
                // on add package success, add the package to the list and set it to current
                var list = Factory.Packages.ToList();
                list.RemoveAll(p => p.PackageId.ToLower() == packageInfo.PackageId.ToLower());
                list.Add(packageInfo);
                Factory.Packages = list;

                Factory.Packages.ByName(packageInfo.Name).SetCurrent(false);
                packageInfo.IsCurrent = true;

                if (doneCallbackAction != null)
                    doneCallbackAction(PackageInfo);

                IsCompleted = true;
                OnOperationSuccess(PackageInfo);
            }

            OnOperationFinalized();
        }

        internal void ResetEvents()
        {
            OnOperationError = delegate { };
            OnOperationFinalized = delegate { };
            OnOperationSuccess = delegate { };
        }
    }
}


text:
<?xml version="1.0"?>
<tool_dependency>
    <package name="python" version="2.7">
        <repository name="package_python_2_7" owner="iuc" prior_installation_required="True" />
    </package>

    <package name="htseq" version="0.6.1">
        <repository name="package_htseq_0_6" owner="iuc" prior_installation_required="True" />
    </package>

    <package name="fuma" version="2.11.0">
        <install version="1.0">
            <actions>
                <action type="download_by_url">https://github.com/yhoogstrate/fuma/archive/4b3432078949523f93e523c501f6ed813ee23d35.tar.gz</action>

                <action type="set_environment_for_install">
                     <repository name="package_python_2_7" owner="iuc">
                        <package name="python" version="2.7" />
                    </repository>

                   <repository name="package_htseq_0_6" owner="iuc">
                        <package name="htseq" version="0.6.1" />
                    </repository>
                </action>

                <action type="make_directory">$INSTALL_DIR/lib/python</action>
                <action type="make_directory">$INSTALL_DIR/lib64/python</action>

                <action type="shell_command"><![CDATA[
                    export PYTHONPATH=$PYTHONPATH:$INSTALL_DIR/lib/python:$INSTALL_DIR/lib64/python &&
                    python setup.py build                                                           &&
                    python setup.py install --home $INSTALL_DIR --install-scripts $INSTALL_DIR/bin

                    ## Tests fails because the import of unittest goes wrong:
                    ## http://stackoverflow.com/questions/26893504/attributeerror-module-object-has-no-attribute-testcase
                    ## python setup.py test
                ]]></action>

                <action type="set_environment">
                    <environment_variable action="append_to" name="PYTHONPATH">$INSTALL_DIR/lib/python:$INSTALL_DIR/lib64/python</environment_variable>
                    <environment_variable action="prepend_to" name="PATH">$INSTALL_DIR/bin</environment_variable>
                </action>
            </actions>
        </install>
        <readme>
            Downloads and installs FuMa.

            Prerequisites:
                - git
        </readme>
    </package>
</tool_dependency>


text:
package org.gwtbootstrap3.client.ui.constants;

import com.google.gwt.dom.client.Style;
import org.gwtbootstrap3.client.ui.base.helper.EnumHelper;

/**
 * @author Joshua Godi
 */
public enum ProgressBarType implements Type, Style.HasCssName {
    DEFAULT(""),
    SUCCESS("progress-bar-success"),
    INFO("progress-bar-info"),
    WARNING("progress-bar-warning"),
    DANGER("progress-bar-danger");

    private final String cssClass;

    private ProgressBarType(final String cssClass) {
        this.cssClass = cssClass;
    }

    @Override
    public String getCssName() {
        return cssClass;
    }

    public static ProgressBarType fromStyleName(final String styleName) {
        return EnumHelper.fromStyleName(styleName, ProgressBarType.class, DEFAULT);
    }
}


text:
class SkBitmap;

namespace history {

/////////////////////////////////////////////////////////////////////////////
//
// PageUsageData
//
// A per domain usage data structure to compute and manage most visited
// pages.
//
// See QueryPageUsageSince()
//
/////////////////////////////////////////////////////////////////////////////
class PageUsageData {
 public:
  explicit PageUsageData(SegmentID id);

  virtual ~PageUsageData();

  // Return the url ID
  SegmentID GetID() const { return id_; }

  void SetURL(const GURL& url) {
    url_ = url;
  }

  const GURL& GetURL() const {
    return url_;
  }

  void SetTitle(const base::string16& s) {
    title_ = s;
  }

  const base::string16& GetTitle() const {
    return title_;
  }

  void SetScore(double v) {
    score_ = v;
  }

  double GetScore() const {
    return score_;
  }

  // Sort predicate to sort instances by score (high to low)
  static bool Predicate(const PageUsageData* dud1, const PageUsageData* dud2);

 private:
  SegmentID id_;
  GURL url_;
  base::string16 title_;

  double score_;
};

}  // namespace history

#endif  // COMPONENTS_HISTORY_CORE_BROWSER_PAGE_USAGE_DATA_H__


text:
package org.apache.lucene.analysis.shingle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.miscellaneous.EmptyTokenStream;
import org.apache.lucene.analysis.payloads.PayloadHelper;
import org.apache.lucene.analysis.shingle.ShingleMatrixFilter.Matrix.Column.Row;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.FlagsAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.index.Payload;

/**
 *
A ShingleMatrixFilter constructs shingles (token n-grams) from a token stream.
 * In other words, it creates combinations of tokens as a single token.
 *
 *
For example, the sentence "please divide this sentence into shingles"
 * might be tokenized into shingles "please divide", "divide this",
 * "this sentence", "sentence into", and "into shingles".
 *
 *
Using a shingle filter at index and query time can in some instances
 * be used to replace phrase queries, especially them with 0 slop.
 *
 *
Without a spacer character
 * it can be used to handle composition and decomposition of words
 * such as searching for "multi dimensional" instead of "multidimensional".
 * It is a rather common human problem at query time
 * in several languages, notably the northern Germanic branch.
 *
 *
Shingles are amongst many things also known to solve problems
 * in spell checking, language detection and document clustering.
 *
 *
This filter is backed by a three dimensional column oriented matrix
 * used to create permutations of the second dimension, the rows,
 * and leaves the third, the z-axis, for for multi token synonyms.
 *
 *
In order to use this filter you need to define a way of positioning
 * the input stream tokens in the matrix. This is done using a
 * {@link org.apache.lucene.analysis.shingle.ShingleMatrixFilter.TokenSettingsCodec}.
 * There are three simple implementations for demonstrational purposes,
 * see {@link org.apache.lucene.analysis.shingle.ShingleMatrixFilter.OneDimensionalNonWeightedTokenSettingsCodec},
 * {@link org.apache.lucene.analysis.shingle.ShingleMatrixFilter.TwoDimensionalNonWeightedSynonymTokenSettingsCodec}
 * and {@link org.apache.lucene.analysis.shingle.ShingleMatrixFilter.SimpleThreeDimensionalTokenSettingsCodec}.
 *
 *
Consider this token matrix:
 *

 *  Token[column][row][z-axis]{
 *    {{hello}, {greetings, and, salutations}},
 *    {{world}, {earth}, {tellus}}
 *  };
 *

 *
 * It would produce the following 2-3 gram sized shingles:
 *
 *

 * "hello_world"
 * "greetings_and"
 * "greetings_and_salutations"
 * "and_salutations"
 * "and_salutations_world"
 * "salutations_world"
 * "hello_earth"
 * "and_salutations_earth"
 * "salutations_earth"
 * "hello_tellus"
 * "and_salutations_tellus"
 * "salutations_tellus"
 *

 *
 *
This implementation can be rather heap demanding
 * if (maximum shingle size - minimum shingle size) is a great number and the stream contains many columns,
 * or if each column contains a great number of rows.
 *
 *
The problem is that in order avoid producing duplicates
 * the filter needs to keep track of any shingle already produced and returned to the consumer.
 *
 * There is a bit of resource management to handle this
 * but it would of course be much better if the filter was written
 * so it never created the same shingle more than once in the first place.
 *
 *
The filter also has basic support for calculating weights for the shingles
 * based on the weights of the tokens from the input stream, output shingle size, etc.
 * See {@link #calculateShingleWeight(org.apache.lucene.analysis.Token, java.util.List, int, java.util.List, java.util.List)}.
 *

 * @deprecated Will be removed in Lucene 4.0. This filter is unmaintained and might not behave
 * correctly if used with custom Attributes, i.e. Attributes other than
 * the ones located in org.apache.lucene.analysis.tokenattributes. It also uses
 * hardcoded payload encoders which makes it not easily adaptable to other use-cases.
 */
@Deprecated
public final class ShingleMatrixFilter extends TokenStream {

  public static Character defaultSpacerCharacter = Character.valueOf('_');
  public static TokenSettingsCodec defaultSettingsCodec = new OneDimensionalNonWeightedTokenSettingsCodec();
  public static boolean ignoringSinglePrefixOrSuffixShingleByDefault = false;

  /**
   * Strategy used to code and decode meta data of the tokens from the input stream
   * regarding how to position the tokens in the matrix, set and retreive weight, et c.
   */
  public static abstract class TokenSettingsCodec {

    /**
     * Retrieves information on how a {@link org.apache.lucene.analysis.Token} is to be inserted to a {@link org.apache.lucene.analysis.shingle.ShingleMatrixFilter.Matrix}.
     * @param token
     * @return {@link ShingleMatrixFilter.TokenPositioner}
     * @throws IOException
     */
    public abstract TokenPositioner getTokenPositioner(Token token) throws IOException;

    /**
     * Sets information on how a {@link org.apache.lucene.analysis.Token} is to be inserted to a {@link org.apache.lucene.analysis.shingle.ShingleMatrixFilter.Matrix}.
     *
     * @param token
     * @param tokenPositioner
     */
    public abstract void setTokenPositioner(Token token, ShingleMatrixFilter.TokenPositioner tokenPositioner);

    /**
     * Have this method return 1f in order to 'disable' weights.
     * @param token
     * @return the weight of parameter token
     */
    public abstract float getWeight(Token token);

    /**
     * Have this method do nothing in order to 'disable' weights.
     * @param token
     * @param weight
     */
    public abstract void setWeight(Token token, float weight);
  }

  /**
   * Used to describe how a {@link org.apache.lucene.analysis.Token} is to be inserted to a {@link org.apache.lucene.analysis.shingle.ShingleMatrixFilter.Matrix}.
   * @see org.apache.lucene.analysis.shingle.ShingleMatrixFilter.TokenSettingsCodec#getTokenPositioner(org.apache.lucene.analysis.Token)
   * @see org.apache.lucene.analysis.shingle.ShingleMatrixFilter.TokenSettingsCodec#setTokenPositioner(org.apache.lucene.analysis.Token,org.apache.lucene.analysis.shingle.ShingleMatrixFilter.TokenPositioner)
   */
  public static class TokenPositioner {
    public static final TokenPositioner newColumn = new TokenPositioner(0);
    public static final TokenPositioner newRow = new TokenPositioner(1);
    public static final TokenPositioner sameRow = new TokenPositioner(2);

    private final int index;

    private TokenPositioner(int index) {
      this.index = index;
    }

    public int getIndex() {
      return index;
    }
  }

  // filter instance settings variables

  private TokenSettingsCodec settingsCodec;

  private int minimumShingleSize;
  private int maximumShingleSize;

  private boolean ignoringSinglePrefixOrSuffixShingle = false;

  private Character spacerCharacter = defaultSpacerCharacter;

  private TokenStream input;

  private CharTermAttribute termAtt;
  private PositionIncrementAttribute posIncrAtt;
  private PayloadAttribute payloadAtt;
  private OffsetAttribute offsetAtt;
  private TypeAttribute typeAtt;
  private FlagsAttribute flagsAtt;

  private CharTermAttribute in_termAtt;
  private PositionIncrementAttribute in_posIncrAtt;
  private PayloadAttribute in_payloadAtt;
  private OffsetAttribute in_offsetAtt;
  private TypeAttribute in_typeAtt;
  private FlagsAttribute in_flagsAtt;

  /**
   * Creates a shingle filter based on a user defined matrix.
   *
   * The filter /will/ delete columns from the input matrix! You will not be able to reset the filter if you used this constructor.
   * todo: don't touch the matrix! use a boolean, set the input stream to null or something, and keep track of where in the matrix we are at.
   *
   * @param matrix the input based for creating shingles. Does not need to contain any information until {@link #incrementToken()} is called the first time.
   * @param minimumShingleSize minimum number of tokens in any shingle.
   * @param maximumShingleSize maximum number of tokens in any shingle.
   * @param spacerCharacter character to use between texts of the token parts in a shingle. null for none.
   * @param ignoringSinglePrefixOrSuffixShingle if true, shingles that only contains permutation of the first of the last column will not be produced as shingles. Useful when adding boundary marker tokens such as '^' and '$'.
   * @param settingsCodec codec used to read input token weight and matrix positioning.
   */
  public ShingleMatrixFilter(Matrix matrix, int minimumShingleSize, int maximumShingleSize, Character spacerCharacter, boolean ignoringSinglePrefixOrSuffixShingle, TokenSettingsCodec settingsCodec) {
    this.matrix = matrix;
    this.minimumShingleSize = minimumShingleSize;
    this.maximumShingleSize = maximumShingleSize;
    this.spacerCharacter = spacerCharacter;
    this.ignoringSinglePrefixOrSuffixShingle = ignoringSinglePrefixOrSuffixShingle;
    this.settingsCodec = settingsCodec;

    termAtt = addAttribute(CharTermAttribute.class);
    posIncrAtt = addAttribute(PositionIncrementAttribute.class);
    payloadAtt = addAttribute(PayloadAttribute.class);
    offsetAtt = addAttribute(OffsetAttribute.class);
    typeAtt = addAttribute(TypeAttribute.class);
    flagsAtt = addAttribute(FlagsAttribute.class);

    // set the input to be an empty token stream, we already have the data.
    this.input = new EmptyTokenStream();

    in_termAtt = input.addAttribute(CharTermAttribute.class);
    in_posIncrAtt = input.addAttribute(PositionIncrementAttribute.class);
    in_payloadAtt = input.addAttribute(PayloadAttribute.class);
    in_offsetAtt = input.addAttribute(OffsetAttribute.class);
    in_typeAtt = input.addAttribute(TypeAttribute.class);
    in_flagsAtt = input.addAttribute(FlagsAttribute.class);
  }

  /**
   * Creates a shingle filter using default settings.
   *
   * @see #defaultSpacerCharacter
   * @see #ignoringSinglePrefixOrSuffixShingleByDefault
   * @see #defaultSettingsCodec
   *
   * @param input stream from which to construct the matrix
   * @param minimumShingleSize minimum number of tokens in any shingle.
   * @param maximumShingleSize maximum number of tokens in any shingle.
   */
  public ShingleMatrixFilter(TokenStream input, int minimumShingleSize, int maximumShingleSize) {
    this(input, minimumShingleSize, maximumShingleSize, defaultSpacerCharacter);
  }

  /**
   * Creates a shingle filter using default settings.
   *
   * @see #ignoringSinglePrefixOrSuffixShingleByDefault
   * @see #defaultSettingsCodec
   *
   * @param input stream from which to construct the matrix
   * @param minimumShingleSize minimum number of tokens in any shingle.
   * @param maximumShingleSize maximum number of tokens in any shingle.
   * @param spacerCharacter character to use between texts of the token parts in a shingle. null for none.
   */
  public ShingleMatrixFilter(TokenStream input, int minimumShingleSize, int maximumShingleSize, Character spacerCharacter) {
    this(input, minimumShingleSize, maximumShingleSize, spacerCharacter, ignoringSinglePrefixOrSuffixShingleByDefault);
  }

  /**
   * Creates a shingle filter using the default {@link TokenSettingsCodec}.
   *
   * @see #defaultSettingsCodec
   *
   * @param input stream from which to construct the matrix
   * @param minimumShingleSize minimum number of tokens in any shingle.
   * @param maximumShingleSize maximum number of tokens in any shingle.
   * @param spacerCharacter character to use between texts of the token parts in a shingle. null for none.
   * @param ignoringSinglePrefixOrSuffixShingle if true, shingles that only contains permutation of the first of the last column will not be produced as shingles. Useful when adding boundary marker tokens such as '^' and '$'.
   */
  public ShingleMatrixFilter(TokenStream input, int minimumShingleSize, int maximumShingleSize, Character spacerCharacter, boolean ignoringSinglePrefixOrSuffixShingle) {
    this(input, minimumShingleSize, maximumShingleSize, spacerCharacter, ignoringSinglePrefixOrSuffixShingle, defaultSettingsCodec);
  }

  /**
   * Creates a shingle filter with ad hoc parameter settings.
   *
   * @param input stream from which to construct the matrix
   * @param minimumShingleSize minimum number of tokens in any shingle.
   * @param maximumShingleSize maximum number of tokens in any shingle.
   * @param spacerCharacter character to use between texts of the token parts in a shingle. null for none.
   * @param ignoringSinglePrefixOrSuffixShingle if true, shingles that only contains permutation of the first of the last column will not be produced as shingles. Useful when adding boundary marker tokens such as '^' and '$'.
   * @param settingsCodec codec used to read input token weight and matrix positioning.
   */
  public ShingleMatrixFilter(TokenStream input, int minimumShingleSize, int maximumShingleSize, Character spacerCharacter, boolean ignoringSinglePrefixOrSuffixShingle, TokenSettingsCodec settingsCodec) {
    this.input = input;
    this.minimumShingleSize = minimumShingleSize;
    this.maximumShingleSize = maximumShingleSize;
    this.spacerCharacter = spacerCharacter;
    this.ignoringSinglePrefixOrSuffixShingle = ignoringSinglePrefixOrSuffixShingle;
    this.settingsCodec = settingsCodec;
    termAtt = addAttribute(CharTermAttribute.class);
    posIncrAtt = addAttribute(PositionIncrementAttribute.class);
    payloadAtt = addAttribute(PayloadAttribute.class);
    offsetAtt = addAttribute(OffsetAttribute.class);
    typeAtt = addAttribute(TypeAttribute.class);
    flagsAtt = addAttribute(FlagsAttribute.class);

    in_termAtt = input.addAttribute(CharTermAttribute.class);
    in_posIncrAtt = input.addAttribute(PositionIncrementAttribute.class);
    in_payloadAtt = input.addAttribute(PayloadAttribute.class);
    in_offsetAtt = input.addAttribute(OffsetAttribute.class);
    in_typeAtt = input.addAttribute(TypeAttribute.class);
    in_flagsAtt = input.addAttribute(FlagsAttribute.class);
  }

  // internal filter instance variables

  /** iterator over the current matrix row permutations */
  private Iterator<Matrix.Column.Row[]> permutations;

  /** the current permutation of tokens used to produce shingles */
  private List<Token> currentPermuationTokens;
  /** index to what row a token in currentShingleTokens represents*/
  private List<Matrix.Column.Row> currentPermutationRows;

  private int currentPermutationTokensStartOffset;
  private int currentShingleLength;

  /**
   * a set containing shingles that has been the result of a call to {@link #incrementToken()},
   * used to avoid producing the same shingle more than once.
   */
  private Set<List<Token>> shinglesSeen = new HashSet<List<Token>>();

  @Override
  public void reset() throws IOException {
    permutations = null;
    shinglesSeen.clear();
    input.reset();
  }

  private Matrix matrix;

  private Token reusableToken = new Token();

  @Override
  public final boolean incrementToken() throws IOException {
    if (matrix == null) {
      matrix = new Matrix();
      // fill matrix with maximumShingleSize columns
      while (matrix.columns.size() < maximumShingleSize && readColumn()) {
        // this loop looks ugly
      }
    }

    // this loop exists in order to avoid recursive calls to the next method
    // as the complexity of a large matrix
    // then would require a multi gigabyte sized stack.
    Token token;
    do {
      token = produceNextToken(reusableToken);
    } while (token == request_next_token);
    if (token == null) return false;

    clearAttributes();
    termAtt.copyBuffer(token.buffer(), 0, token.length());
    posIncrAtt.setPositionIncrement(token.getPositionIncrement());
    flagsAtt.setFlags(token.getFlags());
    offsetAtt.setOffset(token.startOffset(), token.endOffset());
    typeAtt.setType(token.type());
    payloadAtt.setPayload(token.getPayload());
    return true;
  }

  private Token getNextInputToken(Token token) throws IOException {
    if (!input.incrementToken()) return null;
    token.copyBuffer(in_termAtt.buffer(), 0, in_termAtt.length());
    token.setPositionIncrement(in_posIncrAtt.getPositionIncrement());
    token.setFlags(in_flagsAtt.getFlags());
    token.setOffset(in_offsetAtt.startOffset(), in_offsetAtt.endOffset());
    token.setType(in_typeAtt.type());
    token.setPayload(in_payloadAtt.getPayload());
    return token;
  }

  private Token getNextToken(Token token) throws IOException {
    if (!this.incrementToken()) return null;
    token.copyBuffer(termAtt.buffer(), 0, termAtt.length());
    token.setPositionIncrement(posIncrAtt.getPositionIncrement());
    token.setFlags(flagsAtt.getFlags());
    token.setOffset(offsetAtt.startOffset(), offsetAtt.endOffset());
    token.setType(typeAtt.type());
    token.setPayload(payloadAtt.getPayload());
    return token;
  }

  private static final Token request_next_token = new Token();

  /**
   * This method exists in order to avoid recursive calls to the method
   * as the complexity of a fairly small matrix then easily would require
   * a gigabyte sized stack per thread.
   *
   * @param reusableToken
   * @return null if exhausted, instance request_next_token if one more call is required for an answer, or instance parameter resuableToken.
   * @throws IOException
   */
  private Token produceNextToken(final Token reusableToken) throws IOException {

    if (currentPermuationTokens != null) {
      currentShingleLength++;

      if (currentShingleLength + currentPermutationTokensStartOffset <= currentPermuationTokens.size()
          && currentShingleLength <= maximumShingleSize) {

        // it is possible to create at least one more shingle of the current matrix permutation

        if (ignoringSinglePrefixOrSuffixShingle
            && currentShingleLength == 1
            && ((currentPermutationRows.get(currentPermutationTokensStartOffset)).getColumn().isFirst() || (currentPermutationRows.get(currentPermutationTokensStartOffset)).getColumn().isLast())) {
          return getNextToken(reusableToken);
        }

        int termLength = 0;

        List<Token> shingle = new ArrayList<Token>(currentShingleLength);

        for (int i = 0; i < currentShingleLength; i++) {
          Token shingleToken = currentPermuationTokens.get(i + currentPermutationTokensStartOffset);
          termLength += shingleToken.length();
          shingle.add(shingleToken);
        }
        if (spacerCharacter != null) {
          termLength += currentShingleLength - 1;
        }

        // only produce shingles that not already has been created
        if (!shinglesSeen.add(shingle)) {
          return request_next_token;
        }

        // shingle token factory
        StringBuilder sb = new StringBuilder(termLength + 10); // paranormal ability to foresee the future.
        for (Token shingleToken : shingle) {
          if (spacerCharacter != null && sb.length() > 0) {
            sb.append(spacerCharacter);
          }
          sb.append(shingleToken.buffer(), 0, shingleToken.length());
        }
        reusableToken.setEmpty().append(sb);
        updateToken(reusableToken, shingle, currentPermutationTokensStartOffset, currentPermutationRows, currentPermuationTokens);

        return reusableToken;

      } else {

        // it is NOT possible to create one more shingles of the current matrix permutation

        if (currentPermutationTokensStartOffset < currentPermuationTokens.size() - 1) {
          // reset shingle size and move one step to the right in the current tokens permutation
          currentPermutationTokensStartOffset++;
          currentShingleLength = minimumShingleSize - 1;
          return request_next_token;
        }

        if (permutations == null) {
          // todo does this ever occur?
          return null;
        }

        if (!permutations.hasNext()) {

          // load more data (if available) to the matrix

          if (input != null && readColumn()) {
            // don't really care, we just read it.
          }

          // get rid of resources

          // delete the first column in the matrix
          Matrix.Column deletedColumn = matrix.columns.remove(0);

          // remove all shingles seen that include any of the tokens from the deleted column.
          List<Token> deletedColumnTokens = new ArrayList<Token>();
          for (Matrix.Column.Row row : deletedColumn.getRows()) {
            for (Token token : row.getTokens()) {
              deletedColumnTokens.add(token);
            }

          }
          for (Iterator<List<Token>> shinglesSeenIterator = shinglesSeen.iterator(); shinglesSeenIterator.hasNext();) {
            List<Token> shingle = shinglesSeenIterator.next();
            for (Token deletedColumnToken : deletedColumnTokens) {
              if (shingle.contains(deletedColumnToken)) {
                shinglesSeenIterator.remove();
                break;
              }
            }
          }

          if (matrix.columns.size() < minimumShingleSize) {
            // exhausted
            return null;
          }

          // create permutations of the matrix it now looks
          permutations = matrix.permutationIterator();
        }

        nextTokensPermutation();
        return request_next_token;

      }
    }

    if (permutations == null) {
      permutations = matrix.permutationIterator();
    }

    if (!permutations.hasNext()) {
      return null;
    }

    nextTokensPermutation();

    return request_next_token;
  }

  /**
   * get next permutation of row combinations,
   * creates list of all tokens in the row and
   * an index from each such token to what row they exist in.
   * finally resets the current (next) shingle size and offset.
   */
  private void nextTokensPermutation() {
    Matrix.Column.Row[] rowsPermutation = permutations.next();
    List<Matrix.Column.Row> currentPermutationRows = new ArrayList<Matrix.Column.Row>();
    List<Token> currentPermuationTokens = new ArrayList<Token>();
    for (Matrix.Column.Row row : rowsPermutation) {
      for (Token token : row.getTokens()) {
        currentPermuationTokens.add(token);
        currentPermutationRows.add(row);
      }
    }
    this.currentPermuationTokens = currentPermuationTokens;
    this.currentPermutationRows = currentPermutationRows;

    currentPermutationTokensStartOffset = 0;
    currentShingleLength = minimumShingleSize - 1;

  }

  /**
   * Final touch of a shingle token before it is passed on to the consumer from method {@link #incrementToken()}.
   *
   * Calculates and sets type, flags, position increment, start/end offsets and weight.
   *
   * @param token Shingle token
   * @param shingle Tokens used to produce the shingle token.
   * @param currentPermutationStartOffset Start offset in parameter currentPermutationTokens
   * @param currentPermutationRows index to Matrix.Column.Row from the position of tokens in parameter currentPermutationTokens
   * @param currentPermuationTokens tokens of the current permutation of rows in the matrix.
   */
  public void updateToken(Token token, List<Token> shingle, int currentPermutationStartOffset, List<Row> currentPermutationRows, List<Token> currentPermuationTokens) {
    token.setType(ShingleMatrixFilter.class.getName());
    token.setFlags(0);
    token.setPositionIncrement(1);
    token.setStartOffset(shingle.get(0).startOffset());
    token.setEndOffset(shingle.get(shingle.size() - 1).endOffset());
    settingsCodec.setWeight(token, calculateShingleWeight(token, shingle, currentPermutationStartOffset, currentPermutationRows, currentPermuationTokens));
  }

  /**
   * Evaluates the new shingle token weight.
   *
   * for (shingle part token in shingle)
   * weight +=  shingle part token weight * (1 / sqrt(all shingle part token weights summed))
   *
   * This algorithm gives a slightly greater score for longer shingles
   * and is rather penalising to great shingle token part weights.
   *
   * @param shingleToken token returned to consumer
   * @param shingle tokens the tokens used to produce the shingle token.
   * @param currentPermutationStartOffset start offset in parameter currentPermutationRows and currentPermutationTokens.
   * @param currentPermutationRows an index to what matrix row a token in parameter currentPermutationTokens exist.
   * @param currentPermuationTokens all tokens in the current row permutation of the matrix. A sub list (parameter offset, parameter shingle.size) equals parameter shingle.
   * @return weight to be set for parameter shingleToken
   */
  public float calculateShingleWeight(Token shingleToken, List<Token> shingle, int currentPermutationStartOffset, List<Row> currentPermutationRows, List<Token> currentPermuationTokens) {
    double[] weights = new double[shingle.size()];

    double total = 0f;
    double top = 0d;

    for (int i=0; i<weights.length; i++) {
      weights[i] = settingsCodec.getWeight(shingle.get(i));

      double tmp = weights[i];
      if (tmp > top) {
        top = tmp;
      }
      total += tmp;
    }

    double factor = 1d / Math.sqrt(total);

    double weight = 0d;
    for (double partWeight : weights) {
      weight += partWeight * factor;
    }

    return (float) weight;
  }

  private Token readColumnBuf;

  /**
   * Loads one column from the token stream.
   *
   * When the last token is read from the token stream it will column.setLast(true);
   *
   * @return true if it manage to read one more column from the input token stream
   * @throws IOException if the matrix source input stream throws an exception
   */
  private boolean readColumn() throws IOException {

    Token token;
    if (readColumnBuf != null) {
      token = readColumnBuf;
      readColumnBuf = null;
    } else {
      token = getNextInputToken(new Token());
    }

    if (token == null) {
      return false;
    }

    Matrix.Column currentReaderColumn = matrix.new Column();
    Matrix.Column.Row currentReaderRow = currentReaderColumn.new Row();

    currentReaderRow.getTokens().add(token);
    TokenPositioner tokenPositioner;
    while ((readColumnBuf = getNextInputToken(new Token())) != null
        && (tokenPositioner = settingsCodec.getTokenPositioner(readColumnBuf)) != TokenPositioner.newColumn) {

      if (tokenPositioner == TokenPositioner.sameRow) {
        currentReaderRow.getTokens().add(readColumnBuf);
      } else /*if (tokenPositioner == TokenPositioner.newRow)*/ {
        currentReaderRow = currentReaderColumn.new Row();
        currentReaderRow.getTokens().add(readColumnBuf);
      }
      readColumnBuf = null;

    }

    if (readColumnBuf == null) {
      readColumnBuf = getNextInputToken(new Token());
      if (readColumnBuf == null) {
        currentReaderColumn.setLast(true);
      }
    }

    return true;

  }

  /**
   * A column focused matrix in three dimensions:
   *
   *

   * Token[column][row][z-axis] {
   *     {{hello}, {greetings, and, salutations}},
   *     {{world}, {earth}, {tellus}}
   * };
   *

   *
   * todo consider row groups
   * to indicate that shingles is only to contain permutations with texts in that same row group.
   *
   */
  public static class Matrix {

    private boolean columnsHasBeenCreated = false;

    private List<Column> columns = new ArrayList<Column>();

    public List<Column> getColumns() {
      return columns;
    }

    public class Column {

      private boolean last;
      private boolean first;

      public Matrix getMatrix() {
        return Matrix.this;
      }

      public Column(Token token) {
        this();
        Row row = new Row();
        row.getTokens().add(token);
      }

      public Column() {
        synchronized (Matrix.this) {
          if (!columnsHasBeenCreated) {
            this.setFirst(true);
            columnsHasBeenCreated = true;
          }
        }
        Matrix.this.columns.add(this);
      }

      private List<Row> rows = new ArrayList<Row>();

      public List<Row> getRows() {
        return rows;
      }

      public int getIndex() {
        return Matrix.this.columns.indexOf(this);
      }

      @Override
      public String toString() {
        return "Column{" +
            "first=" + first +
            ", last=" + last +
            ", rows=" + rows +
            '}';
      }

      public boolean isFirst() {
        return first;
      }

      public void setFirst(boolean first) {
        this.first = first;
      }

      public void setLast(boolean last) {
        this.last = last;
      }

      public boolean isLast() {
        return last;
      }

      public class Row {

        public Column getColumn() {
          return Column.this;
        }

        private List<Token> tokens = new LinkedList<Token>();

        public Row() {
          Column.this.rows.add(this);
        }

        public int getIndex() {
          return Column.this.rows.indexOf(this);
        }

        public List<Token> getTokens() {
          return tokens;
        }

        public void setTokens(List<Token> tokens) {
          this.tokens = tokens;
        }

//        public int getStartOffset() {
//          int ret = tokens[0].startOffset();
//          if (getIndex() > 0 && ret == 0) {
//            ret = Column.this.rows.get(0).getStartOffset();
//          }
//          return ret;
//        }
//
//        public int getEndOffset() {
//          int ret = tokens[tokens.length - 1].endOffset();
//          if (getIndex() > 0 && ret == 0) {
//            ret = Column.this.rows.get(0).getEndOffset();
//          }
//          return ret;
//        }

        @Override
        public String toString() {
          return "Row{" +
              "index=" + getIndex() +
              ", tokens=" + (tokens == null ? null : tokens) +
              '}';
        }
      }

    }

    public Iterator<Column.Row[]> permutationIterator() {

      return new Iterator<Column.Row[]>() {

        private int[] columnRowCounters = new int[columns.size()];

        public void remove() {
          throw new IllegalStateException("not implemented");
        }

        public boolean hasNext() {
          int s = columnRowCounters.length;
          int n = columns.size();
          return s != 0 && n >= s && columnRowCounters[s - 1] < (columns.get(s - 1)).getRows().size();
        }

        public Column.Row[] next() {
          if (!hasNext()) {
            throw new NoSuchElementException("no more elements");
          }

          Column.Row[] rows = new Column.Row[columnRowCounters.length];

          for (int i = 0; i < columnRowCounters.length; i++) {
            rows[i] = columns.get(i).rows.get(columnRowCounters[i]);
          }
          incrementColumnRowCounters();

          return rows;
        }

        private void incrementColumnRowCounters() {
          for (int i = 0; i < columnRowCounters.length; i++) {
            columnRowCounters[i]++;
            if (columnRowCounters[i] == columns.get(i).rows.size() &&
                i < columnRowCounters.length - 1) {
              columnRowCounters[i] = 0;
            } else {
              break;
            }
          }
        }
      };
    }

    @Override
    public String toString() {
      return "Matrix{" +
          "columns=" + columns +
          '}';
    }
  }

  public int getMinimumShingleSize() {
    return minimumShingleSize;
  }

  public void setMinimumShingleSize(int minimumShingleSize) {
    this.minimumShingleSize = minimumShingleSize;
  }

  public int getMaximumShingleSize() {
    return maximumShingleSize;
  }

  public void setMaximumShingleSize(int maximumShingleSize) {
    this.maximumShingleSize = maximumShingleSize;
  }

  public Matrix getMatrix() {
    return matrix;
  }

  public void setMatrix(Matrix matrix) {
    this.matrix = matrix;
  }

  public Character getSpacerCharacter() {
    return spacerCharacter;
  }

  public void setSpacerCharacter(Character spacerCharacter) {
    this.spacerCharacter = spacerCharacter;
  }

  public boolean isIgnoringSinglePrefixOrSuffixShingle() {
    return ignoringSinglePrefixOrSuffixShingle;
  }

  public void setIgnoringSinglePrefixOrSuffixShingle(boolean ignoringSinglePrefixOrSuffixShingle) {
    this.ignoringSinglePrefixOrSuffixShingle = ignoringSinglePrefixOrSuffixShingle;
  }

  /**
   * Using this codec makes a {@link ShingleMatrixFilter} act like {@link org.apache.lucene.analysis.shingle.ShingleFilter}.
   * It produces the most simple sort of shingles, ignoring token position increments, et c.
   *
   * It adds each token as a new column.
   */
  public static class OneDimensionalNonWeightedTokenSettingsCodec extends TokenSettingsCodec {

    @Override
    public TokenPositioner getTokenPositioner(Token token) throws IOException {
      return TokenPositioner.newColumn;
    }

    @Override
    public void setTokenPositioner(Token token, TokenPositioner tokenPositioner) {
    }

    @Override
    public float getWeight(Token token) {
      return 1f;
    }

    @Override
    public void setWeight(Token token, float weight) {
    }

  }

  /**
   * A codec that creates a two dimensional matrix
   * by treating tokens from the input stream with 0 position increment
   * as new rows to the current column.
   */
  public static class TwoDimensionalNonWeightedSynonymTokenSettingsCodec extends TokenSettingsCodec {

    @Override
    public TokenPositioner getTokenPositioner(Token token) throws IOException {
      if (token.getPositionIncrement() == 0) {
        return TokenPositioner.newRow;
      } else {
        return TokenPositioner.newColumn;
      }
    }

    @Override
    public void setTokenPositioner(Token token, TokenPositioner tokenPositioner) {
      throw new UnsupportedOperationException();
    }

    @Override
    public float getWeight(Token token) {
      return 1f;
    }

    @Override
    public void setWeight(Token token, float weight) {
    }

  }

  /**
   * A full featured codec not to be used for something serious.
   *
   * It takes complete control of
   * payload for weight
   * and the bit flags for positioning in the matrix.
   *
   * Mainly exist for demonstrational purposes.
   */
  public static class SimpleThreeDimensionalTokenSettingsCodec extends TokenSettingsCodec {

    /**
     * @param token
     * @return the token flags int value as TokenPosition
     * @throws IOException
     */
    @Override
    public TokenPositioner getTokenPositioner(Token token) throws IOException {
      switch (token.getFlags()) {
        case 0:
          return TokenPositioner.newColumn;
        case 1:
          return TokenPositioner.newRow;
        case 2:
          return TokenPositioner.sameRow;
      }
      throw new IOException("Unknown matrix positioning of token " + token);
    }

    /**
     * Sets the TokenPositioner as token flags int value.
     *
     * @param token
     * @param tokenPositioner
     */
    @Override
    public void setTokenPositioner(Token token, TokenPositioner tokenPositioner) {
      token.setFlags(tokenPositioner.getIndex());
    }

    /**
     * Returns a 32 bit float from the payload, or 1f it null.
     *
     * @param token
     * @return 32 bit float
     */
    @Override
    public float getWeight(Token token) {
      if (token.getPayload() == null || token.getPayload().getData() == null) {
        return 1f;
      } else {
        return PayloadHelper.decodeFloat(token.getPayload().getData());
      }
    }

    /**
     * Stores a 32 bit float in the payload, or set it to null if 1f;
     * @param token
     * @param weight
     */
    @Override
    public void setWeight(Token token, float weight) {
      if (weight == 1f) {
        token.setPayload(null);
      } else {
        token.setPayload(new Payload(PayloadHelper.encodeFloat(weight)));
      }
    }

  }

}


text:
#pragma once

#include <thrust/detail/pointer.h>

#include <thrust/detail/type_traits.h>
#include <thrust/system/cuda/detail/execution_policy.h>

namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{

// forward decl for iterator traits:
template <typename T>
class managed_memory_pointer;

} // end namespace detail
} // end namespace cuda
} // end namespace system

// Specialize iterator traits to define `pointer` to something meaningful.
template <typename Element, typename Tag, typename Reference>
struct iterator_traits<thrust::pointer<
  Element,
  Tag,
  Reference,
  thrust::system::cuda::detail::managed_memory_pointer<Element> > > {
private:
  typedef thrust::pointer<
    Element,
    Tag,
    Reference,
    thrust::system::cuda::detail::managed_memory_pointer<Element> >
    ptr;

public:
  typedef typename ptr::iterator_category iterator_category;
  typedef typename ptr::value_type value_type;
  typedef typename ptr::difference_type difference_type;
  typedef Element* pointer;
  typedef typename ptr::reference reference;
}; // end iterator_traits

namespace system
{
namespace cuda
{
namespace detail
{

/*! A version of thrust::cuda_cub::pointer that uses c++ references instead
 * of thrust::cuda::reference. This is to allow managed memory pointers to
 * be used with host-side code in standard libraries that are not compatible
 * with proxy references.
 */
template <typename T>
class managed_memory_pointer
    : public thrust::pointer<
        T,
        thrust::cuda_cub::tag,
        typename thrust::detail::add_reference<T>::type,
        thrust::system::cuda::detail::managed_memory_pointer<T> >
{
private:
  typedef thrust::pointer<
    T,
    thrust::cuda_cub::tag,
    typename thrust::detail::add_reference<T>::type,
    thrust::system::cuda::detail::managed_memory_pointer<T> >
    super_t;

public:
  typedef typename super_t::raw_pointer pointer;

  /*! \p managed_memory_pointer's no-argument constructor initializes its
   * encapsulated pointer to \c 0.
   */
  __host__ __device__ managed_memory_pointer()
      : super_t()
  {}

#if THRUST_CPP_DIALECT >= 2011
  // NOTE: This is needed so that Thrust smart pointers can be used in
  // `std::unique_ptr`.
  __host__ __device__ managed_memory_pointer(decltype(nullptr))
      : super_t(nullptr)
  {}
#endif

  /*! This constructor allows construction of a <tt><const T></tt> from a
   * <tt>T*</tt>.
   *
   *  \param ptr A raw pointer to copy from, presumed to point to a location
   * in memory accessible by the \p cuda system. \tparam OtherT \p OtherT
   * shall be convertible to \p T.
   */
  template <typename OtherT>
  __host__ __device__ explicit managed_memory_pointer(OtherT* ptr)
      : super_t(ptr)
  {}

  /*! This constructor allows construction from another pointer-like object
   * with related type.
   *
   *  \param other The \p OtherPointer to copy.
   *  \tparam OtherPointer The system tag associated with \p OtherPointer
   * shall be convertible to \p thrust::system::cuda::tag and its element
   * type shall be convertible to \p T.
   */
  template <typename OtherPointer>
  __host__ __device__ managed_memory_pointer(
    const OtherPointer& other,
    typename thrust::detail::enable_if_pointer_is_convertible<
      OtherPointer,
      managed_memory_pointer>::type* = 0)
      : super_t(other)
  {}

  /*! This constructor allows construction from another pointer-like object
   * with \p void type.
   *
   *  \param other The \p OtherPointer to copy.
   *  \tparam OtherPointer The system tag associated with \p OtherPointer
   * shall be convertible to \p thrust::system::cuda::tag and its element
   * type shall be \p void.
   */
  template <typename OtherPointer>
  __host__ __device__ explicit managed_memory_pointer(
    const OtherPointer& other,
    typename thrust::detail::enable_if_void_pointer_is_system_convertible<
      OtherPointer,
      managed_memory_pointer>::type* = 0)
      : super_t(other)
  {}

  /*! Assignment operator allows assigning from another pointer-like object
   * with related type.
   *
   *  \param other The other pointer-like object to assign from.
   *  \tparam OtherPointer The system tag associated with \p OtherPointer
   * shall be convertible to \p thrust::system::cuda::tag and its element
   * type shall be convertible to \p T.
   */
  template <typename OtherPointer>
  __host__ __device__ typename thrust::detail::enable_if_pointer_is_convertible<
    OtherPointer,
    managed_memory_pointer,
    managed_memory_pointer&>::type
  operator=(const OtherPointer& other)
  {
    return super_t::operator=(other);
  }

#if THRUST_CPP_DIALECT >= 2011
  // NOTE: This is needed so that Thrust smart pointers can be used in
  // `std::unique_ptr`.
  __host__ __device__ managed_memory_pointer& operator=(decltype(nullptr))
  {
    super_t::operator=(nullptr);
    return *this;
  }
#endif

  __host__ __device__
  pointer operator->() const
  {
    return this->get();
  }

}; // class managed_memory_pointer

} // namespace detail
} // namespace cuda
} // namespace system
} // namespace thrust


text:
@interface PodsDummy_Pods_ScaledVisibleCellsCollectionView_Example : NSObject
@end
@implementation PodsDummy_Pods_ScaledVisibleCellsCollectionView_Example
@end


text:
import React from 'react';
import { css, cx } from 'emotion';
import { GrafanaTheme } from '@savantly/sprout-api';
import { Icon } from '../Icon/Icon';
import { useTheme, stylesFactory } from '../../themes';

export interface FieldValidationMessageProps {
  children: string;
  /** Override component style */
  className?: string;
}

export const getFieldValidationMessageStyles = stylesFactory((theme: GrafanaTheme) => {
  return {
    fieldValidationMessage: css`
      font-size: ${theme.typography.size.sm};
      font-weight: ${theme.typography.weight.semibold};
      margin: ${theme.spacing.formValidationMessageMargin};
      padding: ${theme.spacing.formValidationMessagePadding};
      color: ${theme.colors.formValidationMessageText};
      background: ${theme.colors.formValidationMessageBg};
      border-radius: ${theme.border.radius.sm};
      position: relative;
      display: inline-block;

      &:before {
        content: '';
        position: absolute;
        left: 9px;
        top: -4px;
        width: 0;
        height: 0;
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-bottom: 4px solid ${theme.colors.formValidationMessageBg};
      }
    `,
    fieldValidationMessageIcon: css`
      margin-right: ${theme.spacing.formSpacingBase}px;
    `,
  };
});

export const FieldValidationMessage: React.FC<FieldValidationMessageProps> = ({ children, className }) => {
  const theme = useTheme();
  const styles = getFieldValidationMessageStyles(theme);

  return (
    <div role="alert" className={cx(styles.fieldValidationMessage, className)}>
      <Icon className={styles.fieldValidationMessageIcon} name="exclamation-triangle" />
      {children}
    </div>
  );
};


text:
Aho-Corasick string matching
============================

The [Aho-Corasick string matching algorithm](http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm) will find all instances of a set of terms that are substrings of a certain string in constant time with respect to the length of the string. It does this by pre-building a NFA-like structure which it uses to efficiently parse the string for all the terms in the set to be matched against.

Our implementation is written in pure Ruby, and is used like so:

```ruby
require 'aho_corasick'
matcher = AhoCorasick.new("woodchuck", "chuck", "could")
matcher.match("How much wood would a woodchuck chuck if a woodchuck could chuck wood.")
#=> ["woodchuck", "chuck", "woodchuck", "could", "chuck"]
```

You can insert additional terms into the matcher after instantiation, however each call to insert takes linear time with respect to the total number of terms to be matched against. You can call insert passing multiple terms to mitigate against this:

```ruby
matcher.insert("would", "wood")
matcher.match("How much wood would a woodchuck chuck if a woodchuck could chuck wood.")
#=> ["wood", "would", "wood", "woodchuck", "chuck", "wood", "woodchuck", "could", "chuck", "wood"]
```

To install: ``gem install aho_corasick`` or add ``gem "aho_corasick"`` to your Gemfile. We've tested it with Ruby 1.9.2, but there's nothing in there that should stop it working with any other Ruby. If you find any bugs, let us know - Feature requests and pull requests also welcome!


text:
FROM node:argon

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

COPY . /usr/src/app

ENV PORT 80
EXPOSE 80

CMD [ "npm", "start" ]


text:
module Quickpull.EqShow ((===)) where

import Test.QuickCheck

infix 4 ===

-- | Like '==', but prints a counterexample when it fails.
(===) :: (Eq a, Show a) => a -> a -> Property
x === y =
  printTestCase (show x ++ " /= " ++ show y) (x == y)


text:
<?php
namespace Jme\MediaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Xi\Filelib\Backend\Adapter\DoctrineOrm\Entity\File as BaseFile;

/**
 * @ORM\Entity(repositoryClass="Jme\MediaBundle\Repository\MediaRepository")
 */
class File extends BaseFile
{

}


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

<TITLE>
org.jivesoftware.openfire.spi Class Hierarchy (Openfire 3.9.3 Javadoc)
</TITLE>

<META NAME="date" CONTENT="2014-05-06">

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

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

Openfire 3.9.3 Javadoc

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.jivesoftware.openfire.spi

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.jivesoftware.openfire.container.BasicModule (implements org.jivesoftware.openfire.container.Module)

org.jivesoftware.openfire.spi.ConnectionManagerImpl (implements org.jivesoftware.util.CertificateEventListener, org.jivesoftware.openfire.ConnectionManager)

org.jivesoftware.openfire.spi.PacketDelivererImpl (implements org.jivesoftware.openfire.PacketDeliverer)

org.jivesoftware.openfire.spi.PacketRouterImpl (implements org.jivesoftware.openfire.PacketRouter)

org.jivesoftware.openfire.spi.PacketTransporterImpl
org.jivesoftware.openfire.spi.PresenceManagerImpl (implements org.jivesoftware.openfire.PresenceManager, org.jivesoftware.openfire.event.UserEventListener, org.jivesoftware.openfire.XMPPServerListener)

org.jivesoftware.openfire.spi.RoutingTableImpl (implements org.jivesoftware.openfire.cluster.ClusterEventListener, org.jivesoftware.openfire.RoutingTable)

org.jivesoftware.openfire.spi.BasicStreamIDFactory (implements org.jivesoftware.openfire.StreamIDFactory)

org.jivesoftware.openfire.spi.ClientRoute (implements org.jivesoftware.util.cache.Cacheable, java.io.Externalizable)

org.jivesoftware.openfire.spi.XMPPServerInfoImpl (implements org.jivesoftware.openfire.XMPPServerInfo)

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

Openfire 3.9.3 Javadoc

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2003-2008 Jive Software.


text:
import numpy as np
import wmf
import batched_inv
import batched_inv_precompute
import solve_mp
import solve_gpu

np.random.seed(123)

B = np.load("test_matrix.pkl")

S = wmf.log_surplus_confidence_matrix(B, alpha=2.0, epsilon=1e-6)

num_factors = 40 + 1
num_iterations = 1
batch_size = 10000

# solve = batched_inv.solve_sequential
# solve = solve_mp.solve_mp
solve = solve_gpu.solve_gpu

# U, V = wmf.factorize(S, num_factors=num_factors, lambda_reg=1e-5, num_iterations=num_iterations, init_std=0.01, verbose=True, dtype='float32',
#     recompute_factors=batched_inv.recompute_factors_bias_batched, batch_size=batch_size, solve=solve)

U, V = wmf.factorize(S, num_factors=num_factors, lambda_reg=1e-5, num_iterations=num_iterations, init_std=0.01, verbose=True, dtype='float32',
    recompute_factors=batched_inv_precompute.recompute_factors_bias_batched_precompute, batch_size=batch_size, solve=solve)


text:
<?php

namespace Elcodi\AdminCouponBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Elcodi\CouponBundle\ElcodiCouponTypes;
use Elcodi\CouponBundle\Entity\Interfaces\CouponInterface;
use Elcodi\CouponBundle\Factory\CouponFactory;
use Elcodi\CurrencyBundle\Entity\Money;
use Elcodi\CurrencyBundle\Factory\CurrencyFactory;

/**
 * Class CouponType
 */
class CouponType extends AbstractType
{
    /**
     * @var string
     *
     * Entity namespace
     */
    protected $entityNamespace;

    /**
     * @var CouponFactory
     *
     * productFactory
     */
    protected $couponFactory;

    /**
     * @var CurrencyFactory
     *
     * currencyFactory
     */
    protected $currencyFactory;

    /**
     * Construct method
     *
     * @param string          $entityNamespace Entity namespace
     * @param CouponFactory   $couponFactory   Coupon Factory
     * @param CurrencyFactory $currencyFactory Currency factory
     */
    public function __construct(
        $entityNamespace,
        CouponFactory $couponFactory,
        CurrencyFactory $currencyFactory
    )
    {
        $this->entityNamespace = $entityNamespace;
        $this->couponFactory = $couponFactory;
        $this->currencyFactory = $currencyFactory;
    }

    /**
     * Default form options
     *
     * @param OptionsResolverInterface $resolver
     *
     * @return array With the options
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $money = Money::create(1, $this->currencyFactory->create()->setIso('EUR'));

        /**
         * @var CouponInterface $coupon
         */
        $coupon = $this->couponFactory->create();
        $coupon->setPrice($money);
        $coupon->setMinimumPurchase($money);

        $resolver->setDefaults(array(
            'empty_data' => $coupon
        ));
    }

    /**
     * Buildform function
     *
     * @param FormBuilderInterface $builder the formBuilder
     * @param array                $options the options for this form
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('code', 'text', array(
                'required' => false,
                'label'    => 'code',
            ))
            ->add('name', 'text', array(
                'required' => false,
                'label'    => 'name',
            ))
            ->add('type', 'choice', array(
                'required' => true,
                'label'    => 'type',
                'choices'  => [
                    ElcodiCouponTypes::TYPE_AMOUNT  => 'Amount',
                    ElcodiCouponTypes::TYPE_PERCENT => 'Percent',
                ],
            ))
            ->add('enforcement', 'choice', array(
                'required' => true,
                'label'    => 'type',
                'choices'  => [
                    ElcodiCouponTypes::ENFORCEMENT_MANUAL    => 'Manual application',
                    ElcodiCouponTypes::ENFORCEMENT_AUTOMATIC => 'Automatic application',
                ],
            ))
            ->add('price', 'money_object', array(
                'required' => false,
                'label'    => 'priceAmount',
            ))
            ->add('discount', 'integer', array(
                'required' => false,
                'label'    => 'discount',
            ))
            ->add('count', 'integer', array(
                'required' => false,
                'label'    => 'count',
            ))
            ->add('used', 'integer', array(
                'required' => false,
                'label'    => 'used',
            ))
            ->add('priority', 'integer', array(
                'required' => false,
                'label'    => 'priority',
            ))
            ->add('minimumPurchase', 'money_object', array(
                'required' => false,
                'label'    => 'Minimum purchase',
            ))
            ->add('validFrom', 'datetime', array(
                'widget'   => 'single_text',
                'format'   => 'yyyy-MM-dd - HH:mm:ss',
                'required' => false,
                'label'    => 'validFrom',
            ))
            ->add('validTo', 'datetime', array(
                'widget'   => 'single_text',
                'format'   => 'yyyy-MM-dd - HH:mm:ss',
                'required' => false,
                'label'    => 'validTo',
            ))
            ->add('createdAt', 'datetime', array(
                'widget'   => 'single_text',
                'format'   => 'yyyy-MM-dd - HH:mm:ss',
                'required' => false,
                'label'    => 'createdAt',
            ))
            ->add('updatedAt', 'datetime', array(
                'widget'   => 'single_text',
                'format'   => 'yyyy-MM-dd - HH:mm:ss',
                'required' => false,
                'label'    => 'updatedAt',
            ))
            ->add('enabled', 'checkbox', array(
                'required' => false,
                'label'    => 'enabled',
            ));
    }

    /**
     * Return unique name for this form
     *
     * @return string
     */
    public function getName()
    {
        return 'elcodi_admin_coupon_form_type_coupon';
    }
}


text:
package org.pac4j.oauth.credentials.authenticator;

import com.github.scribejava.core.model.OAuth2AccessToken;
import org.pac4j.core.client.IndirectClient;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.exception.HttpCommunicationException;
import org.pac4j.oauth.config.OAuth20Configuration;
import org.pac4j.oauth.credentials.OAuth20Credentials;
import org.pac4j.oauth.credentials.OAuthCredentials;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * OAuth 2.0 authenticator.
 *
 * @author Jerome Leleu
 * @since 2.0.0
 */
public class OAuth20Authenticator extends OAuthAuthenticator<OAuth20Credentials, OAuth20Configuration> {

    public OAuth20Authenticator(final OAuth20Configuration configuration, final IndirectClient client) {
        super(configuration, client);
    }

    @Override
    protected void retrieveAccessToken(final WebContext context, final OAuthCredentials credentials) {
        OAuth20Credentials oAuth20Credentials = (OAuth20Credentials) credentials;
        // no request token saved in context and no token (OAuth v2.0)
        final String code = oAuth20Credentials.getCode();
        logger.debug("code: {}", code);
        final OAuth2AccessToken accessToken;
        try {
            accessToken = this.configuration.buildService(context, client, null).getAccessToken(code);
        } catch (final IOException | InterruptedException | ExecutionException e) {
            throw new HttpCommunicationException("Error getting token:" + e.getMessage());
        }
        logger.debug("accessToken: {}", accessToken);
        oAuth20Credentials.setAccessToken(accessToken);
    }
}


text:
Todo
----
* No way to check if input BAM is RNA-Seq/Ribo-Seq (plot will still be generated in either case).
* Check if BAM is sorted.


text:
To try and encourage more sales of different books from a popular 5 book
series, a bookshop has decided to offer discounts on multiple book purchases.

One copy of any of the five books costs $8.

If, however, you buy two different books, you get a 5%
discount on those two books.

If you buy 3 different books, you get a 10% discount.

If you buy 4 different books, you get a 20% discount.

If you buy all 5, you get a 25% discount.

Note: that if you buy four books, of which 3 are
different titles, you get a 10% discount on the 3 that
form part of a set, but the fourth book still costs $8.

Your mission is to write a piece of code to calculate the
price of any conceivable shopping basket (containing only
books of the same series), giving as big a discount as
possible.

For example, how much does this basket of books cost?

- 2 copies of the first book
- 2 copies of the second book
- 2 copies of the third book
- 1 copy of the fourth book
- 1 copy of the fifth book

One way of grouping these 8 books is:

- 1 group of 5 --> 25% discount (1st,2nd,3rd,4th,5th)
- +1 group of 3 --> 10% discount (1st,2nd,3rd)

This would give a total of:

- 5 books at a 25% discount
- +3 books at a 10% discount

Resulting in:

- 5 x (8 - 2.00) == 5 x 6.00 == $30.00
- +3 x (8 - 0.80) == 3 x 7.20 == $21.60

For a total of $51.60

However, a different way to group these 8 books is:

- 1 group of 4 books --> 20% discount  (1st,2nd,3rd,4th)
- +1 group of 4 books --> 20% discount  (1st,2nd,3rd,5th)

This would give a total of:

- 4 books at a 20% discount
- +4 books at a 20% discount

Resulting in:

- 4 x (8 - 1.60) == 4 x 6.40 == $25.60
- +4 x (8 - 1.60) == 4 x 6.40 == $25.60

For a total of $51.20

And $51.20 is the price with the biggest discount.

## Testing

In order to run the tests for this track, you will need to install
DUnitX. Please see the [installation](http://www.exercism.io/languages/delphi/installation) instructions for more information.

### Loading Exercises into Delphi

If Delphi is properly installed, and `*.dpr` file types have been associated with Delphi, then double clicking the supplied `*.dpr` file will start Delphi and load the exercise/project.  `control + F9` is the keyboard shortcut to compile the project or pressing `F9` will compile and run the project.

Alternatively you may opt to start Delphi and load your project via. the `File` drop down menu.

### When Questions Come Up
We monitor the [Pascal-Delphi](https://gitter.im/exercism/Pascal-Delphi) support room on [gitter.im](https://gitter.im) to help you with any questions that might arise.

### Submitting Exercises

Note that, when trying to submit an exercise, make sure the exercise file you're submitting is in the `exercism/delphi/<exerciseName>` directory.

For example, if you're submitting `ubob.pas` for the Bob exercise, the submit command would be something like `exercism submit <path_to_exercism_dir>/delphi/bob/ubob.pas`.

## Source

Inspired by the harry potter kata from Cyber-Dojo. [http://cyber-dojo.org](http://cyber-dojo.org)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you may receive assistance from a mentor.


text:
package com.flowy.core.services;

import com.flowy.core.models.Action;
import com.flowy.core.repos.IActionRepository;
import org.junit.Before;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
 * Created by ssinghal
 * Created on 30-May-2014
 * If you refactor this code, remember: Code so clean you could eat off it!
 */
public class ActionServiceSpecs {

    private Action action;
    private IActionService actionService;
    private IActionRepository mockRepository;

    @Before
    public void setUp() throws Exception {
        mockRepository = mock(IActionRepository.class);
        actionService = new ActionService(mockRepository);
        action = new Action("actionName", "actionDescription");
    }

    @Test
    public void itShouldSaveOrUpdateAnAction() {
        //When
        actionService.saveOrUpdate(action);

        //Then
        verify(mockRepository).saveOrUpdate(action);
    }
}


text:
package servingTea.Robots;

public class Robot_Milker extends Robot_Agent {

	public Robot_Milker() {
		super();
		serviceName = "bringing milk";
	}

	private static final long serialVersionUID = -1835060061893378826L;

}


text:
package libkb

import (
	"bytes"
	"crypto/sha256"
	"hash"
	"io"

	keybase1 "github.com/keybase/client/go/protocol/keybase1"
	"github.com/keybase/go-crypto/openpgp"
	"github.com/keybase/go-crypto/openpgp/armor"
	"github.com/keybase/go-crypto/openpgp/packet"
)

// SimpleSign signs the given data stream, outputs an armored string which is
// the attached signature of the input data
func SimpleSign(payload []byte, key PGPKeyBundle) (out string, id keybase1.SigID, err error) {
	var outb bytes.Buffer
	var in io.WriteCloser
	var h HashSummer
	if !key.HasSecretKey() {
		err = NoSecretKeyError{}
		return
	}
	if in, h, err = ArmoredAttachedSign(NopWriteCloser{&outb}, *key.Entity, nil, nil); err != nil {
		return
	}
	if _, err = in.Write(payload); err != nil {
		return
	}
	if err = in.Close(); err != nil {
		return
	}
	out = outb.String()
	if id, err = keybase1.SigIDFromSlice(h()); err != nil {
		return
	}
	return
}

type HashingWriteCloser struct {
	targ   io.WriteCloser
	hasher hash.Hash
}

func (h HashingWriteCloser) Write(buf []byte) (int, error) {
	n, err := h.targ.Write(buf)
	if err == nil {
		_, err = h.hasher.Write(buf)
	}
	return n, err
}

func (h HashingWriteCloser) Close() error {
	err := h.targ.Close()
	return err
}

type HashSummer func() []byte

func ArmoredAttachedSign(out io.WriteCloser, signed openpgp.Entity, hints *openpgp.FileHints, config *packet.Config) (in io.WriteCloser, h HashSummer, err error) {

	var aout io.WriteCloser

	aout, err = armor.Encode(out, "PGP MESSAGE", PGPArmorHeaders)
	if err != nil {
		return
	}

	hwc := HashingWriteCloser{aout, sha256.New()}
	in, err = openpgp.AttachedSign(hwc, signed, hints, config)
	h = func() []byte { return hwc.hasher.Sum(nil) }

	return
}

func AttachedSignWrapper(out io.WriteCloser, key PGPKeyBundle, armored bool) (
	in io.WriteCloser, err error) {

	if armored {
		in, _, err = ArmoredAttachedSign(out, *key.Entity, nil, nil)
	} else {
		in, err = openpgp.AttachedSign(out, *key.Entity, nil, nil)
	}
	return
}

// NopWriteCloser is like an ioutil.NopCloser, but for an io.Writer.
// TODO: we have two of these in OpenPGP packages alone. This probably needs
// to be promoted somewhere more common.
//
// From here:
//     https://code.google.com/p/go/source/browse/openpgp/write.go?repo=crypto&r=1e7a3e301825bf9cb32e0535f3761d62d2d369d1#364
//
type NopWriteCloser struct {
	W io.Writer
}

func (c NopWriteCloser) Write(data []byte) (n int, err error) {
	return c.W.Write(data)
}

func (c NopWriteCloser) Close() error {
	return nil
}