text:
logic-tree
===============

[![Build Status](https://travis-ci.org/jadekler/git-go-logictree.svg?branch=master)](https://travis-ci.org/jadekler/git-go-logictree)

### Installation

1. `go get github.com/jadekler/git-go-logictree`
1. Navigate to the project directory
1. `go test ./...` (make sure mysql is running and root/no pwd is enabled)
1. `go run $GOPATH/src/github.com/jadekler/git-go-logictree/main.go`
1. Navigate to `localhost:8080` in your browser

### Testing

To test locally, simply run `go test -v ./...` from the project root.

Note: Useful testing command: `printf "$(go test $GOPATH/src/github.com/jadekler/git-go-logictree/app/home | sed 's/::/\\n/g')" && echo;`

### What's it about?

This program is a pretty simple [lexical analyzer](http://en.wikipedia.org/wiki/Lexical_analysis) that accepts human-readable conditions, such as 'age greater than 5', and translates it to mysql-queryable language. The basic case is fairly simple, but the more advanced cases, such as '(age is greater than 5 or number of pets is less than 2) and age is less than 9', require a bit more work. The intermediary step between human-readable conditions and mysql conditions is implemented as a tree. Additionally, the human-readable conditions are stored in mysql as a left-right hierarchy tree (which represents nested sets). See more detail on the tree and nested sets below.

### Three-stage representation

The setup for this app is: human-readable on the front, golang tree in the middle, mysql nested sets in the back. Here is a basic overview of how the stages interact:

![](https://raw.github.com/jadekler/git-go-logictree/master/logictree-static/images/flowchart.png)

Below are the explanation for each stage.

#### Frontend representation of conditions - Human-readable language

The front end is represented as a set of parenthesis, equality conditions, and logical conditions. Combined, they look like this:

![](https://raw.github.com/jadekler/git-go-logictree/master/logictree-static/images/conditions.png)

Each block is draggable - by clicking the 'Save Re-ordering' button on the page, the re-ordered conditions are saved in mysql. The conditions will also be converted to a mysql query and executed against a dummy users table, with results displayed at the bottom of the page.

#### Server representation of conditions - Tree

We use a tree as an intermediary between the human-readable conditions on the front and interactions with mysql, including saving the conditions, executing the conditions, and converting the conditions (via tree) into human-readable conditions for the front. The tree is a simple n-child tree that is generally traversed post-order. The branches are logical conditions, and the leaves are equality conditions. For instance, (A OR B) would be represented as OR being the branch and A and B being two children of OR, and so on. See below a larger example (taken from the app):

![](https://raw.github.com/jadekler/git-go-logictree/master/logictree-static/images/tree.png)

#### Database representation of conditions - Nested sets

The general idea behind storing a tree in mysql as nested sets is well explained [here](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/). The basic idea, however, is that each condition is a set, and each child (in the aforementioned tree) is a set within the set that is its parent condition. Once we have so ordered our sets, we can assign lefts and rights to them as below:

![](https://raw.github.com/jadekler/git-go-logictree/master/logictree-static/images/nested_sets.png)

In mysql, this becomes:

```
condition, left, right
----------------------
AND, 1, 24
OR, 2, 17
AND, 3, 14
age = 4, 4, 5
age = 5, 6, 7
age = 6, 8, 9
age = 7, 10, 11
age = 8, 12, 13
age = 1, 15, 16
OR, 18, 23
age = 2, 19, 20
age = 3, 21, 22
```

### Time and Space Complexity

The space complexity is O(n) in both the server language and mysql - that is, we store each node and no additional information both in mysql and in our tree (we use pointers in the tree for parents and children).

The time complexity is as follows:

##### Unserialize From Mysql To Go

The function that deals with this is called [unserializeRawTree](https://github.com/jadekler/git-go-logictree/blob/master/app/home/unserialize.go#L71). This function assumes a set of conditions pulled from mysql ordered by the LEFT column ascending. It iterates through the conditions, popping conditions off and creating the tree until the conditions are empty.

The two sides to the equation:

- Pop each condition from the array - `O(n)`
- Insert each condition into a *non-binary, unbalanced* tree. In the worst case, we assume a left-leaning tree. Each item must traverse over each item previously inserted. Therefore, the traversal operations per condition are `1+2+...+(n-1)+n`. This series converges to `(1/2)n(n+1)`, which gives us `O(n^2)`.

Finally, we see that the time complexity is `O(n)+O(n^2) = O(n^2)`.

##### Unserialize From Frontend * To Go

The function that deals with this is called [unserializeFormattedTree](https://github.com/jadekler/git-go-logictree/blob/master/app/home/unserialize.go#L11). I realize my naming scheme is awful. Anyways, this function iterates over leaves and recurses through branches, building the tree as it goes and relying on the recursive call to glue it all together. So once again, we touch each condition only once - this function runs in `O(n)`.

##### Serialize From Go To Frontend *

The function that deals with this is called [serializeTree](https://github.com/jadekler/git-go-logictree/blob/master/app/home/serialize.go#L8). It traverses the tree post-order, building a linear array of conditions as it goes. Again, we traverse the tree touching each condition once - this function runs in `O(n)`.

##### Serialize From Go To Mysql

The function that deals with this is called [toJSON](https://github.com/jadekler/git-go-logictree/blob/master/app/home/helpers.go#L30) (actually, the helper function toJSONRecursively does the real work) and once again simply traverses the tree post-order in `O(n)` time.

\* By frontend, I mean a linear array of conditions, including parenthesis that surround children.

### Questions and feedback

Please shoot any questions or feedback over to jadekler@gmail.com.


text:
import ParseError from '../errors/parse_error';
import { Node, TypedNode } from '../trees/expression';
import getParser from './get_parser';
const expressionParser = getParser('expression');

export function walkNode(node: Node, callback: (node: Node) => void): void {
	callback(node);
	switch (node.exprNodeType) {
		case 'function_invocation':
			for (const param of node.parameters) {
				walkNode(param, callback);
			}
			break;
		case 'unary_minus':
			walkNode(node.op, callback);
			break;
		case 'binary_op':
			walkNode(node.lhs, callback);
			walkNode(node.rhs, callback);
			break;
		default: // Not needed, no child nodes of other types
	}
}

export function walkTypedNode(node: TypedNode, callback: (node: TypedNode) => void): void {
	callback(node);
	switch (node.exprNodeType) {
		case 'function_invocation':
			for (const param of node.parameters) {
				walkTypedNode(param, callback);
			}
			break;
		case 'unary_minus':
			walkTypedNode(node.op, callback);
			break;
		case 'binary_op':
			walkTypedNode(node.lhs, callback);
			walkTypedNode(node.rhs, callback);
			break;
		default: // Not needed, no child nodes of other types
	}
}

function substituteStringLiterals(node: Node, originalText: string): Node {
	walkNode(
		node,
		(expr): void => {
			if (expr.exprNodeType === 'string_literal') {
				try {
					const v = JSON.parse(expr.value);
					expr.value = v;
				} catch (e) {
					throw new ParseError(`Error parsing '${originalText}'. Invalid string literal ${expr.value}`);
				}
			}
		},
	);

	return node;
}

export default function parse(input: string): Node {
	const parsed: Node = expressionParser.parse(input);
	return substituteStringLiterals(parsed, input);
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * This adapter  is used when you do not have a database installed.
 *
 * @author     Hans Lellelid <hans@xmpl.org> (Propel)
 * @author     Jon S. Stevens <jon@clearink.com> (Torque)
 * @author     Brett McLaughlin <bmclaugh@algx.net> (Torque)
 * @version    $Revision: 1262 $
 * @package    propel.adapter
 */
class DBNone extends DBAdapter {

	/**
	 * @see        DBAdapter::initConnection()
	 */
	public function initConnection(PDO $con, array $settings)
	{
	}

	/**
	 * This method is used to ignore case.
	 *
	 * @param      in The string to transform to upper case.
	 * @return     The upper case string.
	 */
	public function toUpperCase($in)
	{
		return $in;
	}

	/**
	 * This method is used to ignore case.
	 *
	 * @param      in The string whose case to ignore.
	 * @return     The string in a case that can be ignored.
	 */
	public function ignoreCase($in)
	{
		return $in;
	}

	/**
	 * Returns SQL which concatenates the second string to the first.
	 *
	 * @param      string String to concatenate.
	 * @param      string String to append.
	 * @return     string
	 */
	public function concatString($s1, $s2)
	{
		return ($s1 . $s2);
	}

	/**
	 * Returns SQL which extracts a substring.
	 *
	 * @param      string String to extract from.
	 * @param      int Offset to start from.
	 * @param      int Number of characters to extract.
	 * @return     string
	 */
	public function subString($s, $pos, $len)
	{
		return substr($s, $pos, $len);
	}

	/**
	 * Returns SQL which calculates the length (in chars) of a string.
	 *
	 * @param      string String to calculate length of.
	 * @return     string
	 */
	public function strLength($s)
	{
		return strlen($s);
	}

	/**
	 * Modifies the passed-in SQL to add LIMIT and/or OFFSET.
	 */
	public function applyLimit(&$sql, $offset, $limit)
	{
	}

	/**
	 * Gets the SQL string that this adapter uses for getting a random number.
	 *
	 * @param      mixed $seed (optional) seed value for databases that support this
	 */
	public function random($seed = null)
	{
	}

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using System.Xml.XPath;
using Autofac.Core;
using Autofac.Core.Activators.Reflection;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Container = Autofac.Core.Container;
using System.Diagnostics;

namespace Autofac.Integration.SharePoint
{
    public class SPContainerBuilder : ContainerBuilder
    {
        /// <summary>
        /// Registers the module at farm scope. (farm properties)
        /// Intended only for SPFarm feature receiver
        /// </summary>
        /// <typeparam name="T">the type of the module</typeparam>
        /// <param name="properties">The properties.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="replaceIfExists">if set to <c>true</c> [replace if exists].</param>
        public static void RegisterModule<T>(IDictionary<string, string> properties = null,
                                             IDictionary<string, string> parameters = null, bool replaceIfExists = true)
            where T : IModule
        {
            IPropertyProvider propertyProvider = new FarmPropertyProvider();
            RegisterModule<T>(parameters, properties, propertyProvider, replaceIfExists);
        }

        /// <summary>
        /// Registers the module at web application scope. (web application properties)
        /// Intended only for SPWebApplication feature receiver
        /// </summary>
        /// <typeparam name="T">the type of the module</typeparam>
        /// <param name="webApplication">The web application.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="replaceIfExists">if set to <c>true</c> [replace if exists].</param>
        public static void RegisterModule<T>(SPWebApplication webApplication, IDictionary<string, string> properties = null,
                                             IDictionary<string, string> parameters = null, bool replaceIfExists = true)
            where T : IModule

        {
            IPropertyProvider propertyProvider = new WebApplicationPropertyProvider(webApplication);
            RegisterModule<T>(parameters, properties, propertyProvider, replaceIfExists);
        }

        /// <summary>
        /// Registers the module at site scope. (site rootweb properties)
        /// Intended only for SPSite feature receiver
        /// </summary>
        /// <typeparam name="T">the type of the module</typeparam>
        /// <param name="site">The site.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="replaceIfExists">if set to <c>true</c> [replace if exists].</param>
        public static void RegisterModule<T>(SPSite site, IDictionary<string, string> properties = null,
                                             IDictionary<string, string> parameters = null, bool replaceIfExists = true)
            where T : IModule
        {
            IPropertyProvider propertyProvider = new SitePropertyProvider(site);
            RegisterModule<T>(parameters, properties, propertyProvider, replaceIfExists);
        }

        private static void RegisterModule<T>(IDictionary<string, string> parameters, IDictionary<string, string> properties, IPropertyProvider propertyProvider, bool replaceIfExists)
        {
            string assenblyQualifiedName = typeof(T).AssemblyQualifiedName;
            // create the module
            var moduleConfigEntry = new XElement(XName.Get("module", ""));
            moduleConfigEntry.SetAttributeValue(XName.Get("type", ""), assenblyQualifiedName);
            if (parameters != null && parameters.Any())
            {
                var xepc = new XElement(XName.Get("parameters", ""));
                foreach (string parameter in parameters.Keys)
                {
                    var xep = new XElement(XName.Get("parameter", ""));
                    xep.SetAttributeValue(XName.Get("name", ""), parameter);
                    xep.SetAttributeValue(XName.Get("value", ""), parameters[parameter]);
                    xepc.Add(xep);
                }
                moduleConfigEntry.Add(xepc);
            }
            if (properties != null && properties.Any())
            {
                var xepc = new XElement(XName.Get("properties", ""));
                foreach (string property in properties.Keys)
                {
                    var xep = new XElement(XName.Get("property", ""));
                    xep.SetAttributeValue(XName.Get("name", ""), property);
                    xep.SetAttributeValue(XName.Get("value", ""), properties[property]);
                    xepc.Add(xep);
                }
                moduleConfigEntry.Add(xepc);
            }

            ModuleConfiguration modConfig = Configuration.ReadModuleConfiguration(propertyProvider);

            if (modConfig == null)
                modConfig = new ModuleConfiguration("<modules/>", propertyProvider.Scope, DateTime.Now,
                                                    propertyProvider.ID);

            XElement xm = modConfig.Configuration;
            bool exists = xm.XPathSelectElements("module[@type='" + assenblyQualifiedName + "']").Any();
            if (exists && !replaceIfExists)
            {
                Trace.WriteLine(string.Format("module {0} already defined at {1} and replaceIfExists set to {2} --> skipping replacement", assenblyQualifiedName, propertyProvider.ToString(), replaceIfExists));
                return;
            }
            if (exists)
            {
                RemoveModule<T>(propertyProvider, false);
                // refresh xm
                xm = Configuration.ReadModuleConfiguration(propertyProvider).Configuration;
            }
            xm.Add(moduleConfigEntry);
            Configuration.UpdatePersistedModules(xm, propertyProvider);

        }

        /// <summary>
        /// Removes the module from the farm properties.
        /// Intended only for SPFarm feature receiver
        /// </summary>
        /// <typeparam name="T">type of the module</typeparam>
        /// <param name="recursive">if set to <c>true</c> [recursive].</param>
        public static void RemoveModule<T>(bool recursive = false)
            where T : IModule
        {
            IPropertyProvider propertyProvider = new FarmPropertyProvider();
            RemoveModule<T>(propertyProvider, recursive);
        }

        /// <summary>
        /// Removes the module from web application properties.
        /// Intended only for SPWebApplication feature receiver.
        /// </summary>
        /// <typeparam name="T">type of the module</typeparam>
        /// <param name="webApplication">The web application.</param>
        /// <param name="recursive">if set to <c>true</c> [recursive].</param>
        public static void RemoveModule<T>(SPWebApplication webApplication, bool recursive = false)
            where T : IModule
        {
            if(webApplication == null)
                throw new ArgumentNullException("webApplication");
            IPropertyProvider propertyProvider = new WebApplicationPropertyProvider(webApplication);
            RemoveModule<T>(propertyProvider, recursive);
        }

        /// <summary>
        /// Removes the module from the site properties.
        /// Intended only for SPSite feature receiver
        /// </summary>
        /// <typeparam name="T">type of the module</typeparam>
        /// <param name="site">The site.</param>
        /// <param name="recursive">if set to <c>true</c> [recursive].</param>
        public static void RemoveModule<T>(SPSite site, bool recursive = false)
            where T : IModule
        {
            if (site == null)
                throw new ArgumentNullException("site");
            IPropertyProvider propertyProvider = new SitePropertyProvider(site);
            RemoveModule<T>(propertyProvider, recursive);
        }

        private static void RemoveModule<T>(IPropertyProvider propertyProvider, bool recursive = false)
        {
            string assemblyQualifiedName = typeof(T).AssemblyQualifiedName;
            IList<ModuleConfiguration> moduleConfigurations = Configuration.ReadAllModuleConfigurations(propertyProvider);

            if(moduleConfigurations.Count == 0)
            {
                Trace.WriteLine(string.Format("Could not remove module {0} from {1} as no moduleconfigurations could be found", assemblyQualifiedName, propertyProvider));
                return;
            }
            if(!moduleConfigurations.Any(mc => mc.Scope == propertyProvider.Scope))
            {
                Trace.WriteLine(string.Format("Could not remove module {0} from {1} as no moduleconfigurations could be found for that specific scope ({2})", assemblyQualifiedName, propertyProvider, Enum.GetName(typeof(SPScope), propertyProvider.Scope)));
                return;
            }

            // if recursive flag is not set, we only remove that module from the specified scope (Site, App, Farm)
            // and do not recursively remove it from all other scopes)
            if (!recursive)
                moduleConfigurations = moduleConfigurations.Take(1).ToList();

            foreach (ModuleConfiguration moduleConfiguration in moduleConfigurations)
            {
                var moduleConfigXml = moduleConfiguration.Configuration;
                if (moduleConfigXml.HasElements)
                {
                    XElement[] matchingModules = moduleConfigXml.XPathSelectElements("module[@type='" + assemblyQualifiedName + "']").ToArray();
                    if (matchingModules.Any())
                    {
                        Trace.WriteLine(string.Format("Module {0} removed from {1}", assemblyQualifiedName, propertyProvider.ToString()));
                        matchingModules.Remove();

                        Configuration.UpdatePersistedModules(moduleConfigXml, propertyProvider);
                    }
                }
            }
        }
    }
}


text:
==================

Bookmarklet to add number key shortcuts to urls on a page

I had seen a Vimium feature of hightlighting links and wanted to make a simple js to see if I could just throw something together -  but I do not try to match any or all of the Vimium features specifically.  This is a personal tool/project and is not as robust as the other great tools already out there.

####Installation
One option is to create a bookmark and place the code from the file: highlightLinks.min.js as the url.
You just click the bookmark when you want links numbered and highlighted for quick navigation.

However, the suggested setup would be to add it as a Custom Search Engine in Chrome.  Define your keyword and the url would be the code from the file: highlightLinks.min.js.
So for the below example, 'hl' is the keyword.  On any page, you would get to the omnibox (shortcut Command-L (Mac) or Alt-D on Windows), enter in 'hl' and enter.  This should run the bookmark code without needing to leave the keyboard.

**Note: Make sure that if you copy and paste the contents of the file that 'javascript:' is at the beginning.  Some tools might strip it out, but it is needed atm.**

#####Screen Shot - Setting up bookmarklet for Chrome
![Setting up bookmarklet for Chrome] (imgs/bookmarkletshortcut.png)

####Usage
Trigger the script to start with either your shortcut to the bookmark or clicking the bookmark.  You should see links with numbers to the left of the link text.  To navigate (click) a link: just type the highlighted number with the focus being the page you are on (no popup or textbox will be presented for entry - just type).  If it was just a navigation to a different spot on the same page (like a menu), you will still see the highlighted numbers and be able to enter in a new value (of course until you have navigated off of the page).

You can use the 'ESC' key to remove the added highlighting and navigation of the bookmark.

#####Screen Shot - Links numbered for quick navigation by highlightLinks.js
![highlightLinks.js in use] (imgs/hlExample.png)

####Credits
Vimium plugin for the idea

Google Closure complier for creating min.js and pretty-print versions.


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>org.apache.lucene.search.suggest.fst (Lucene 6.0.1 API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.lucene.search.suggest.fst

Finite-state based autosuggest.

See: Description

Interface Summary

Interface
Description

BytesRefSorter

Collects BytesRef and then allows one to iterate over their sorted order.

Class Summary

Class
Description

ExternalRefSorter

Builds and iterates over sequences stored on disk.

FSTCompletion

Finite state automata based implementation of "autocomplete" functionality.

FSTCompletion.Completion

A single completion for a given key.

FSTCompletionBuilder

Finite state automata based implementation of "autocomplete" functionality.

FSTCompletionLookup

An adapter from Lookup API to FSTCompletion.

WFSTCompletionLookup

Suggester based on a weighted FST: it first traverses the prefix,
 then walks the n shortest paths to retrieve top-ranked
 suggestions.

Package org.apache.lucene.search.suggest.fst Description

Finite-state based autosuggest.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Package

Next Package

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
package play.libs.concurrent;

import akka.actor.ActorSystem;
import scala.concurrent.ExecutionContext;
import scala.concurrent.ExecutionContextExecutor;

/**
 * Provides a custom execution context from an Akka dispatcher.
 *
 * Subclass this to create your own custom execution context, using
 * the full path to the Akka dispatcher.
 *
 *

 * {@code
 * class MyCustomExecutionContext extends CustomExecutionContext {
 *   // Dependency inject the actorsystem from elsewhere
 *   public MyCustomExecutionContext(ActorSystem actorSystem) {
 *     super(actorSystem, "full.path.to.my-custom-executor");
 *   }
 * }
 * }
 *

 *
 * Then use your custom execution context where you have blocking
 * operations that require processing outside of Play's main rendering
 * thread.
 *
 * @see Dispatchers
 * @see Thread Pools
 */
public abstract class CustomExecutionContext implements ExecutionContextExecutor {
    private final ExecutionContext executionContext;

    public CustomExecutionContext(ActorSystem actorSystem, String name) {
        this.executionContext = actorSystem.dispatchers().lookup(name);
    }

    @Override
    public ExecutionContext prepare() {
        return executionContext.prepare();
    }

    @Override
    public void execute(Runnable command) {
        executionContext.execute(command);
    }

    @Override
    public void reportFailure(Throwable cause) {
        executionContext.reportFailure(cause);
    }
}


text:
#pragma once

#include <vector>

#include "envoy/api/api.h"
#include "envoy/event/dispatcher.h"
#include "envoy/stats/store.h"
#include "envoy/thread_local/thread_local.h"
#include "envoy/upstream/cluster_manager.h"

#include "nighthawk/client/benchmark_client.h"
#include "nighthawk/client/client_worker.h"
#include "nighthawk/client/factories.h"
#include "nighthawk/common/factories.h"
#include "nighthawk/common/phase.h"
#include "nighthawk/common/request_source.h"
#include "nighthawk/common/sequencer.h"
#include "nighthawk/common/termination_predicate.h"
#include "nighthawk/user_defined_output/user_defined_output_plugin.h"

#include "source/common/worker_impl.h"

namespace Nighthawk {
namespace Client {

class ClientWorkerImpl : public WorkerImpl, virtual public ClientWorker {
public:
  enum class HardCodedWarmupStyle { OFF, ON };

  ClientWorkerImpl(Envoy::Api::Api& api, Envoy::ThreadLocal::Instance& tls,
                   Envoy::Upstream::ClusterManagerPtr& cluster_manager,
                   const BenchmarkClientFactory& benchmark_client_factory,
                   const TerminationPredicateFactory& termination_predicate_factory,
                   const SequencerFactory& sequencer_factory,
                   const RequestSourceFactory& request_generator_factory,
                   Envoy::Stats::Store& store, const int worker_number,
                   const Envoy::MonotonicTime starting_time,
                   Envoy::Tracing::HttpTracerSharedPtr& http_tracer,
                   const HardCodedWarmupStyle hardcoded_warmup_style,
                   std::vector<UserDefinedOutputNamePluginPair> user_defined_output_plugins);
  StatisticPtrMap statistics() const override;

  const std::map<std::string, uint64_t>& threadLocalCounterValues() override {
    return threadLocalCounterValues_;
  }

  const Phase& phase() const override { return *phase_; }

  void shutdownThread() override;

  void requestExecutionCancellation() override;

  /**
   * Returns additional output from any specified User Defined Output plugins.
   */
  std::vector<nighthawk::client::UserDefinedOutput> getUserDefinedOutputResults() const override;

protected:
  void work() override;

private:
  void simpleWarmup();

  std::unique_ptr<Envoy::TimeSource> time_source_;
  const TerminationPredicateFactory& termination_predicate_factory_;
  const SequencerFactory& sequencer_factory_;
  Envoy::Stats::ScopeSharedPtr worker_scope_;
  Envoy::Stats::ScopeSharedPtr worker_number_scope_;
  const int worker_number_;
  Envoy::Tracing::HttpTracerSharedPtr& http_tracer_;
  RequestSourcePtr request_generator_;
  BenchmarkClientPtr benchmark_client_;
  PhasePtr phase_;
  Envoy::LocalInfo::LocalInfoPtr local_info_;
  std::map<std::string, uint64_t> threadLocalCounterValues_;
  const HardCodedWarmupStyle hardcoded_warmup_style_;
};

using ClientWorkerImplPtr = std::unique_ptr<ClientWorkerImpl>;

} // namespace Client
} // namespace Nighthawk


text:
//#define BOOST_CHRONO_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0
#include <boost/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>
#include <atomic>

void test()
{
  std::atomic<boost::chrono::milliseconds> ms; // error C2338: atomic<T> requires T to be trivially copyable.
}

int main() {
  test();
  return 1;
}


text:
define(["require", "exports", "aurelia-framework"], function(require, exports, au) {
    var NavBar = (function () {
        function NavBar() {
        }
        NavBar.annotations = [new au.Property("router")];
        return NavBar;
    })();
    exports.NavBar = NavBar;
});


text:
//
// BinaryProtocol.hh for BinaryProtocol in /home/alexmog/projets/LibNet/src
//
// Made by Moghrabi Alexandre
// Login   <alexandre.moghrabi@epitech.eu>
//
// Started on  Fri Apr 17 15:34:03 2015 Moghrabi Alexandre
// Last update Tue May  5 13:37:40 2015 Moghrabi Alexandre
//

/*!
 * \file TextProtocol
 * \brief Text Protocol of the library
 * \author AlexMog
 * \version 0.2
 */

#ifndef MOGNETWORK_TEXTPROTOCOL_HH
# define MOGNETWORK_TEXTPROTOCOL_HH

# include <iostream>
# include "AProtocolListener.hh"

namespace mognetwork
{
  namespace protocol
  {
    /*!
     * \class TextProtocol
     * \brief Defines and execute the Binary protocol
     */
    class TextProtocol : public AProtocolListener
    {
    public:
      TextProtocol(TcpSocket* socket, char* separator);
      virtual ~TextProtocol();

    public:
      virtual Socket::Status onReadTrigger();
      virtual bool datasFullyReceived();
      virtual void onSendDatas(const char* data, uint32_t size, TcpSocket::Data& dataToSend);
      virtual Socket::Status onReadAllTrigger(TcpSocket::Data& data);
      virtual TcpSocket::ReadedDatas& getReadedDatas();
      virtual void flushReader();

    private:
      TcpSocket::ReadedDatas* m_fullDatas;
      char* m_separator;
    };
  }
}

#endif /* !MOGNETWORK_TEXTPROTOCOL_HH */


text:
var _ = require('lodash');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var Q = require('q');
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost/mydb", { native_parser: true });
db.bind('groups');

var service = {};

service.getAll = getAll;
service.getById = getById;
service.getMyGroups = getMyGroups;
service.create = create;
service.update = update;
service.delete = _delete;

module.exports = service;

function getAll() {
    var deferred = Q.defer();

    db.groups.find().toArray(function (err, groups) {
        if (err) deferred.reject(err.name + ': ' + err.message);

        // return groups (without hashed passwords)
        groups = _.map(groups, function (group) {
            return _.omit(group, 'hash');
        });

        deferred.resolve(groups);
    });

    return deferred.promise;
}

function getMyGroups(_id) {
    var deferred = Q.defer();

    db.groups.find({ "users": _id }).toArray(function (err, groups) {
        if (err) deferred.reject(err.name + ': ' + err.message);

        // return groups (without hashed passwords)
        groups = _.map(groups, function (group) {
            return _.omit(group, 'hash');
        });
        // console.log(groups);

        deferred.resolve(groups);
    });

    return deferred.promise;
}

function getById(_id) {
    var deferred = Q.defer();
    db.groups.findById(_id, function (err, group) {

        if (err) deferred.reject(err.name + ': ' + err.message);

        if (group) {
            // return group(without hashed password)
            deferred.resolve(_.omit(group, 'hash'));
        } else {
            // groupnot found
            deferred.resolve();
        }
    });

    return deferred.promise;
}

function create(groupParam) {
    var deferred = Q.defer();
     console.log(groupParam);

    // validation
    db.groups.findOne(
        { title: groupParam.title },
        function (err, group) {
            if (err) deferred.reject(err.name + ': ' + err.message);

            if (group) {
                // email already exists
                deferred.reject('Title "' + groupParam.title + '" is already taken');
            } else {
                createGroup();
            }
        });

    function createGroup() {
        // set groupobject to groupParam without the cleartext password
        var group = _.omit(groupParam);

        // add hashed password to groupobject
        // group.hash = bcrypt.hashSync(groupParam.password, 10);

        db.groups.insert(
            group,
            function (err, doc) {
                if (err) deferred.reject(err.name + ': ' + err.message);

                deferred.resolve();
            });
    }

    return deferred.promise;
}

function update(_id, groupParam) {
    var deferred = Q.defer();
    // console.log(groupParam);

    // validation
    db.groups.findById(_id, function (err, group) {
        if (err) deferred.reject(err.name + ': ' + err.message);

        if (group.title !== groupParam.title) {
            // email has changed so check if the new email is already taken
            db.groups.findOne(
                {
                    title: groupParam.title,
                },
                function (err, user) {
                    if (err) deferred.reject(err.name + ': ' + err.message);

                    if (group) {
                        // email already exists
                        deferred.reject('title "' + req.body.title + '" is already taken')
                    } else {
                        updateGroup();
                    }
                });
        } else {
            updateGroup();
        }
    });

    function updateGroup() {
        // fields to update
        var set = {
            title: groupParam.title,
            type: groupParam.type,
            description: groupParam.description,
            users: groupParam.users,
            likes: groupParam.likes
        };

        // update password if it was entered
        // if (userParam.password) {
        //     set.hash = bcrypt.hashSync(userParam.password, 10);
        // }

        db.groups.update(
            { _id: mongo.helper.toObjectID(_id) },
            { $set: set },
            function (err, doc) {
                if (err) deferred.reject(err.name + ': ' + err.message);

                deferred.resolve();
            });
    }

    return deferred.promise;
}

function _delete(_id) {
    console.log("iiiin");
    var deferred = Q.defer();

    db.groups.remove(
        { _id: mongo.helper.toObjectID(_id) },
        function (err) {
            if (err) deferred.reject(err.name + ': ' + err.message);

            deferred.resolve();
        });

    return deferred.promise;
}


text:
//using UnityEngine;
//using System.Collections;
//using UnityEditor.Callbacks;
//using UnityEditor;
//using System.IO;
//using System;

//public class BuildProcessor {

//	[PostProcessBuildAttribute(1)]
//	public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
//	{
//		CopyModsFilesToBuild (target, pathToBuiltProject);
//	}

//	private static void CopyModsFilesToBuild(BuildTarget target, string pathToBuiltProject)
//	{
//		Debug.Log("BuildProcessor.OnPostprocessBuild");

//        switch(target)
//        {
//            case BuildTarget.StandaloneWindows:
//            case BuildTarget.StandaloneWindows64:
//			case BuildTarget.StandaloneLinux:
//			case BuildTarget.StandaloneLinux64:
//			case BuildTarget.StandaloneLinuxUniversal:
//                pathToBuiltProject = Path.GetDirectoryName(pathToBuiltProject);
//                break;
//        }

//		Debug.LogFormat("pathToBuiltProject: {0}", pathToBuiltProject);
//		Debug.LogFormat("current directory: {0}", Application.dataPath);

//		var srcModsPath = Application.dataPath.Replace ("/Assets", "/mods");
//		Debug.LogFormat("srcModsPath: {0}", srcModsPath);

//		var destModsPath = pathToBuiltProject + "/mods";
//		Debug.LogFormat("destModsPath: {0}", destModsPath);

//		Directory.CreateDirectory(destModsPath);
//		var files = Directory.GetFiles (srcModsPath, "*.*", SearchOption.AllDirectories);

//		foreach (var file in files) {
//			var destFileName = destModsPath + file.Replace(srcModsPath, "");
//			Debug.LogFormat("Copying file: {0}", destFileName);

//			var destDir = Path.GetDirectoryName (destFileName);

//			if (!Directory.Exists (destDir)) {
//				Directory.CreateDirectory (destDir);
//			}

//			File.Copy (file, destFileName, true);
//		}
//	}
//}


text:
<!DOCTYPE html>

    <title>Bootstrap Tree View</title>
    <link href="./libs/bootstrap/css/bootstrap.css" rel="stylesheet">
    <link href="./css/bootstrap-treeview.css" rel="stylesheet">

Bootstrap Tree View

Default

Collapsed

Expanded

Blue Theme

Custom Icons

Tags as Badges

No Border

Colourful

Node Overrides

Searchable Tree

Input

              Search Tree:
              <input type="input" class="form-control" id="input-search" placeholder="Type to search..." value="">

                <input type="checkbox" class="checkbox" id="chk-ignore-case" value="false">
                Ignore Case

                <input type="checkbox" class="checkbox" id="chk-exact-match" value="false">
                Exact Match

                <input type="checkbox" class="checkbox" id="chk-reveal-results" value="false">
                Reveal Results

            <button type="button" class="btn btn-success" id="btn-search">Search</button>
            <button type="button" class="btn btn-default" id="btn-clear-search">Clear</button>

Tree

Results

Selectable Tree

Input

            Search Tree:
            <input type="input" class="form-control" id="input-select-node" placeholder="Identify node..." value="Parent 1">

              <input type="checkbox" class="checkbox" id="chk-select-multi" value="false">
              Multi Select

              <input type="checkbox" class="checkbox" id="chk-select-silent" value="false">
              Silent (No events)

              <button type="button" class="btn btn-success select-node" id="btn-select-node">Select Node</button>

            <button type="button" class="btn btn-danger select-node" id="btn-unselect-node">Unselect Node</button>

            <button type="button" class="btn btn-primary select-node" id="btn-toggle-selected">Toggle Node</button>

Tree

Events

Expandible Tree

Input

            Search Tree:
            <input type="input" class="form-control" id="input-expand-node" placeholder="Identify node..." value="Parent 1">

              <input type="checkbox" class="checkbox" id="chk-expand-silent" value="false">
              Silent (No events)

              <button type="button" class="btn btn-success expand-node" id="btn-expand-node">Expand Node</button>

              <select class="form-control" id="select-expand-node-levels">
                <option>1</option>
                <option>2</option>
              </select>

            <button type="button" class="btn btn-danger expand-node" id="btn-collapse-node">Collapse Node</button>

            <button type="button" class="btn btn-primary expand-node" id="btn-toggle-expanded">Toggle Node</button>

              <button type="button" class="btn btn-success" id="btn-expand-all">Expand All</button>

              <select class="form-control" id="select-expand-all-levels">
                <option>1</option>
                <option>2</option>
              </select>

          <button type="button" class="btn btn-danger" id="btn-collapse-all">Collapse All</button>

Tree

Events

Checkable Tree

Input

            Search Tree:
            <input type="input" class="form-control" id="input-check-node" placeholder="Identify node..." value="Parent 1">

              <input type="checkbox" class="checkbox" id="chk-check-silent" value="false">
              Silent (No events)

              <button type="button" class="btn btn-success check-node" id="btn-check-node">Check Node</button>

            <button type="button" class="btn btn-danger check-node" id="btn-uncheck-node">Uncheck Node</button>

            <button type="button" class="btn btn-primary check-node" id="btn-toggle-checked">Toggle Node</button>

              <button type="button" class="btn btn-success" id="btn-check-all">Check All</button>

          <button type="button" class="btn btn-danger" id="btn-uncheck-all">Uncheck All</button>

Tree

Events

Disabled Tree

Input

            Search Tree:
            <input type="input" class="form-control" id="input-disable-node" placeholder="Identify node..." value="Parent 1">

              <input type="checkbox" class="checkbox" id="chk-disable-silent" value="false">
              Silent (No events)

              <button type="button" class="btn btn-success disable-node" id="btn-disable-node">Disable Node</button>

            <button type="button" class="btn btn-danger disable-node" id="btn-enable-node">Enable Node</button>

            <button type="button" class="btn btn-primary disable-node" id="btn-toggle-disabled">Toggle Node</button>

              <button type="button" class="btn btn-success" id="btn-disable-all">Disable All</button>

          <button type="button" class="btn btn-danger" id="btn-enable-all">Enable All</button>

Tree

Events

Lifecycle Events

Input

            <button type="button" class="btn btn-success lifecycle-events" id="btn-init" disabled>New Tree</button>

            <button type="button" class="btn btn-danger lifecycle-events" id="btn-remove">Destroy</button>

Tree

Events

Data Options

Local JSON

Remote JSON


text:
#ifndef MPU_H_
#define MPU_H_

#include "types_def.h"

extern VOID MPU_init(VOID);

/* Masks for MPU Memory Region Sizes */
#define REGION_32B      0x08
#define REGION_64B      0x0A
#define REGION_128B     0x0C
#define REGION_256B     0x0E
#define REGION_512B     0x10
#define REGION_1K       0x12
#define REGION_2K       0x14
#define REGION_4K       0x16
#define REGION_8K       0x18
#define REGION_16K      0x1A
#define REGION_32K      0x1C
#define REGION_64K      0x1E
#define REGION_128K     0x20
#define REGION_256K     0x22
#define REGION_512K     0x24
#define REGION_1M       0x26
#define REGION_2M       0x28
#define REGION_4M       0x2A
#define REGION_8M       0x2C
#define REGION_16M      0x2E
#define REGION_32M      0x30
#define REGION_64M      0x32
#define REGION_128M     0x34
#define REGION_256M     0x36
#define REGION_512M     0x38
#define REGION_1G       0x3A
#define REGION_2G       0x3C
#define REGION_4G       0x3E

/* General MPU Masks */
#define REGION_Enabled  0x1
#define REGION_Valid    0x10

#define SHAREABLE       0x40000
#define CACHEABLE       0x20000
#define BUFFERABLE      0x10000

/* Region Permissions */

#define NOT_EXEC        0x10000000 /* All Instruction fetches abort */

#define NO_ACCESS       0x00000000 /* Privileged No Access, Unprivileged No Access */
#define P_NA_U_NA       0x00000000 /* Privileged No Access, Unprivileged No Access */
#define P_RW_U_NA       0x01000000 /* Privileged Read Write, Unprivileged No Access */
#define P_RW_U_RO       0x02000000 /* Privileged Read Write, Unprivileged Read Only */
#define P_RW_U_RW       0x03000000 /* Privileged Read Write, Unprivileged Read Write */
#define FULL_ACCESS     0x03000000 /* Privileged Read Write, Unprivileged Read Write */
#define P_RO_U_NA       0x05000000 /* Privileged Read Only, Unprivileged No Access */
#define P_RO_U_RO       0x06000000 /* Privileged Read Only, Unprivileged Read Only */
#define RO              0x07000000 /* Privileged Read Only, Unprivileged Read Only */

typedef struct
{
    VUINT32 Type;
    VUINT32 Ctrl;
    VUINT32 RegionNumber;
    VUINT32 RegionBaseAddr;
    VUINT32 RegionAttrSize;
} MPU_TypeDef;

#define MPU_BASE    ((UINT32)0xE000ED90)

#ifndef  DEBUG
#define NST_MPU            ((MPU_TypeDef *) MPU_BASE)
#else
/*------------------------ Debug Mode ----------------------------------------*/
extern MPU_TypeDef  *NST_MPU;
#endif

VOID MPU_Init(void);

#endif /* MPU_H_*/


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/CommonHttpLibrary.iml" filepath="$PROJECT_DIR$/CommonHttpLibrary.iml" />
    </modules>
  </component>
</project>


text:
$:.unshift File.dirname(__FILE__)

module Rewrite

  module ByExample

    # Base class fo all classes that match one or more entities within a list.
    #
    # Includes some backtracking magic to handle cases isomorphic to /.*foo/
    class Sequence

      # unfolders takes a length and answers a (possible empty) Enumerable of lambdas,
      # each of which has the method #call(array) and returning an unfold.
      #
      # Now obviously this means that there are three different ways to represent alternation.
      # First, if a sequence matches two things of different lengths, like A | AA, it returns
      # A for unfolders_by_length(1) and AA for unfolders_by_length(2). However, if a sequence
      # matches two things of the same length, tehre are two different ways to represent that.
      #
      # For example, if a sequence matches A | B, it can do either of:
      #
      # unfolders_by_length(1) =>
      #   [ lambda { |arr| A =~ arr.first }, lambda { |arr| B =~ arr.first } ]
      #
      # or:
      #
      # unfolders_by_length(1) =>
      #   [ lambda { |arr| A =~ arr.first || B =~ arr.first } ]
      #
      # Note the difference: The first example returns two lambdas, one matching A and the
      # other matching B. the second example returns a single lambda matching A or B.
      #
      # When would you use one over the other? The first example is to be used when you wish
      # to support backtracking. The second example is to be used when you do not wish to
      # support backtracking.
      #
      def unfolders_by_length(length)
        raise 'implemented by subclass'
      end
      remove_method :unfolders_by_length

      # Answer a range of possible lengths
      def length_range
        raise 'implemented by subclass'
      end
      remove_method :length_range

      def fold(enum_of_bindings)
        raise "Subclass #{self.class} should implement fold"
      end
      remove_method :fold

    end

  end

end


text:
(function (definition) {
    // CommonJS
    if (typeof exports === 'object') {
        module.exports = definition(
            require('underscore'),
            require('q'),
            require('chai'),
            require('superagent'),
            require('../lib/typson'),
            require('../lib/typson-schema'));
        // RequireJS
    } else if (typeof define === 'function' && define.amd) {
        return define([
            'vendor/underscore',
            'vendor/q',
            'vendor/chai',
            'vendor/superagent',
            'lib/typson',
            'lib/typson-schema'
        ], definition);
    }
})(function (underscore, Q, chai, request, typson, schema) {

    var fs;
    var mkdirp;
    var path;
    var baseDir = '';

    var isNode = (typeof process === 'object' && typeof process.execPath !== 'undefined');
    if (isNode) {
        fs = require('fs');
        mkdirp = require('mkdirp');
        path = require('path');
    }
    else {
        baseDir = '../';
    }

    Q.longStackSupport = true;
    chai.Assertion.includeStack = true;

    // For some odd readom every test file needs to call this
    function init(describe, it) {
        if (it && !it.eventually) {
            // For safety
            var promiseDoneMistake = function () {
                throw new Error('don\'t use a done() callback when using it.eventually()');
            };
            // Monkey promise support
            it.eventually = function eventually(expectation, assertion) {
                it(expectation, function (done) {
                    /*jshint -W064*/
                    Q(assertion(promiseDoneMistake)).done(function () {
                        done();
                    }, function (err) {
                        done(err);
                    });
                });
            };
        }
    }

    // IO helpers
    function readFile(target) {
        if (isNode) {
            // Node
            return Q.nfcall(fs.readFile, target, 'utf8').fail(function () {
                // sileny fail for Node (for easy update of new tests)
                return null;
            });
        }
        var defer = Q.defer();
        request(target).set('Content-Type', 'text/plain').end(function (res) {
            if (res.ok) {
                defer.resolve(res.body);
            } else {
                defer.reject(new Error('bad request: ' + target));

            }
        });
        return defer.promise;
    }

    function readJSON(target) {
        return readFile(target).then(function (str) {
            if (!str) {
                return null;
            }
            if (str && typeof str === 'object') {
                return str;
            }
            return Q.fcall(JSON.parse, str);
        });
    }

    function writeFile(target, content) {
        if (isNode) {
            return Q.nfcall(mkdirp, path.dirname(target), '744').then(function () {
                return Q.nfcall(fs.writeFile, target, content, 'utf8');
            });
        }
        // ignore
        return Q.resolve();
    }

    function writeJSON(target, object) {
        return this.writeFile(target, JSON.stringify(object, null, '    '));
    }

    // Export bundle for easy access in tests
    return {
        baseDir: baseDir,
        isNode: isNode,
        init: init,
        underscore: underscore,
        request: request,
        typson: typson,
        schema: schema,
        chai: chai,
        assert: chai.assert,
        readFile: readFile,
        readJSON: readJSON,
        writeFile: writeFile,
        writeJSON: writeJSON,
        Q: Q
    };
});


text:
"""Implements (a subset of) Sun XDR -- eXternal Data Representation.

See: RFC 1014

"""

import struct
from io import BytesIO

__all__ = ["Error", "Packer", "Unpacker", "ConversionError"]

# exceptions
class Error(Exception):
    """Exception class for this module. Use:

    except xdrlib.Error, var:
        # var has the Error instance for the exception

    Public ivars:
        msg -- contains the message

    """
    def __init__(self, msg):
        self.msg = msg
    def __repr__(self):
        return repr(self.msg)
    def __str__(self):
        return str(self.msg)

class ConversionError(Error):
    pass

class Packer:
    """Pack various data representations into a buffer."""

    def __init__(self):
        self.reset()

    def reset(self):
        self.__buf = BytesIO()

    def get_buffer(self):
        return self.__buf.getvalue()
    # backwards compatibility
    get_buf = get_buffer

    def pack_uint(self, x):
        self.__buf.write(struct.pack('>L', x))

    pack_int = pack_uint
    pack_enum = pack_int

    def pack_bool(self, x):
        if x: self.__buf.write(b'\0\0\0\1')
        else: self.__buf.write(b'\0\0\0\0')

    def pack_uhyper(self, x):
        self.pack_uint(x>>32 & 0xffffffff)
        self.pack_uint(x & 0xffffffff)

    pack_hyper = pack_uhyper

    def pack_float(self, x):
        try: self.__buf.write(struct.pack('>f', x))
        except struct.error as msg:
            raise ConversionError(msg)

    def pack_double(self, x):
        try: self.__buf.write(struct.pack('>d', x))
        except struct.error as msg:
            raise ConversionError(msg)

    def pack_fstring(self, n, s):
        if n < 0:
            raise ValueError('fstring size must be nonnegative')
        data = s[:n]
        n = ((n+3)//4)*4
        data = data + (n - len(data)) * b'\0'
        self.__buf.write(data)

    pack_fopaque = pack_fstring

    def pack_string(self, s):
        n = len(s)
        self.pack_uint(n)
        self.pack_fstring(n, s)

    pack_opaque = pack_string
    pack_bytes = pack_string

    def pack_list(self, list, pack_item):
        for item in list:
            self.pack_uint(1)
            pack_item(item)
        self.pack_uint(0)

    def pack_farray(self, n, list, pack_item):
        if len(list) != n:
            raise ValueError('wrong array size')
        for item in list:
            pack_item(item)

    def pack_array(self, list, pack_item):
        n = len(list)
        self.pack_uint(n)
        self.pack_farray(n, list, pack_item)

class Unpacker:
    """Unpacks various data representations from the given buffer."""

    def __init__(self, data):
        self.reset(data)

    def reset(self, data):
        self.__buf = data
        self.__pos = 0

    def get_position(self):
        return self.__pos

    def set_position(self, position):
        self.__pos = position

    def get_buffer(self):
        return self.__buf

    def done(self):
        if self.__pos < len(self.__buf):
            raise Error('unextracted data remains')

    def unpack_uint(self):
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        x = struct.unpack('>L', data)[0]
        try:
            return int(x)
        except OverflowError:
            return x

    def unpack_int(self):
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        return struct.unpack('>l', data)[0]

    unpack_enum = unpack_int

    def unpack_bool(self):
        return bool(self.unpack_int())

    def unpack_uhyper(self):
        hi = self.unpack_uint()
        lo = self.unpack_uint()
        return int(hi)<<32 | lo

    def unpack_hyper(self):
        x = self.unpack_uhyper()
        if x >= 0x8000000000000000:
            x = x - 0x10000000000000000
        return x

    def unpack_float(self):
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        return struct.unpack('>f', data)[0]

    def unpack_double(self):
        i = self.__pos
        self.__pos = j = i+8
        data = self.__buf[i:j]
        if len(data) < 8:
            raise EOFError
        return struct.unpack('>d', data)[0]

    def unpack_fstring(self, n):
        if n < 0:
            raise ValueError('fstring size must be nonnegative')
        i = self.__pos
        j = i + (n+3)//4*4
        if j > len(self.__buf):
            raise EOFError
        self.__pos = j
        return self.__buf[i:i+n]

    unpack_fopaque = unpack_fstring

    def unpack_string(self):
        n = self.unpack_uint()
        return self.unpack_fstring(n)

    unpack_opaque = unpack_string
    unpack_bytes = unpack_string

    def unpack_list(self, unpack_item):
        list = []
        while 1:
            x = self.unpack_uint()
            if x == 0: break
            if x != 1:
                raise ConversionError('0 or 1 expected, got %r' % (x,))
            item = unpack_item()
            list.append(item)
        return list

    def unpack_farray(self, n, unpack_item):
        list = []
        for i in range(n):
            list.append(unpack_item())
        return list

    def unpack_array(self, unpack_item):
        n = self.unpack_uint()
        return self.unpack_farray(n, unpack_item)


text:
namespace tgui
{
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// @brief Class to load widgets from a text file
    ///
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    class TGUI_API WidgetLoader
    {
    public:
        using LoadFunction = std::function<Widget::Ptr(std::shared_ptr<DataIO::Node>)>;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Load a container and its child widgets from a stream containing a widget file
        ///
        /// @param parent  The parent container for the child widget
        /// @param stream  Stream containing the widget file
        ///
        /// @note You should use the loadWidgetsFromFile or loadWidgetsFromSteam functions in Gui and Container
        ///       instead of calling this function directly.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        static void load(Container::Ptr parent, std::stringstream& stream);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Change the load function for a certain widget type
        ///
        /// @param type         Type of the widget
        /// @param loadFunction New load function
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        static void setLoadFunction(const std::string& type, const LoadFunction& loadFunction);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Retrieve the load function of a certain widget type
        ///
        /// @param type  Type of the widget
        ///
        /// @return Function called to load the widget
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        static const LoadFunction& getLoadFunction(const std::string& type);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private:
        static std::map<std::string, LoadFunction> m_loadFunctions;
    };

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#endif // TGUI_WIDGET_LOADER_HPP


text:
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";
    var page = WinJS.UI.Pages.define("/html/retrieveWithAppContent.html", {
        ready: function (element, options) {
            document.getElementById("addToIndex").addEventListener("click", IndexerHelpers.addAppContentFilesToIndexedFolder, false);
            document.getElementById("retrieveAllItems").addEventListener("click", retrieveAllItems, false);
            document.getElementById("retrieveMatchedItems").addEventListener("click", retrieveMatchedItems, false);
        }
    });

    // This function retrieves all items added to the index through the app's appcontent-ms files
    function retrieveAllItems() {
        var applicationData = Windows.Storage.ApplicationData.current,
            localFolder = applicationData.localFolder;
        var output;
        localFolder.createFolderAsync("Indexed", Windows.Storage.CreationCollisionOption.openIfExists).then(function (indexedFolder) {
            var queryAll = indexedFolder.createFileQuery(Windows.Storage.Search.CommonFileQuery.orderByName); // Queries for all files in the "LocalState\Indexed" folder and sorts the results by name
            return queryAll.getFilesAsync();
        }).then(function (indexedItems) {
            var promiseArray = [];
            output = "";
            for (var i = 0, len = indexedItems.length; i < len; i++) {
                promiseArray[i] = indexedItems[i].properties.retrievePropertiesAsync([Windows.Storage.SystemProperties.itemNameDisplay, Windows.Storage.SystemProperties.comment, Windows.Storage.SystemProperties.keywords, Windows.Storage.SystemProperties.title]).then(function (map) { // Retrieves the ItemNameDisplay, Comment, Keywords, and Title properties for the item
                    output += "Name: " + map[Windows.Storage.SystemProperties.itemNameDisplay];
                    output += "\nKeywords: " + IndexerHelpers.createKeywordString(map[Windows.Storage.SystemProperties.keywords]);
                    output += "\nComment: " + map[Windows.Storage.SystemProperties.comment];
                    output += "\nTitle: " + map[Windows.Storage.SystemProperties.title] + "\n\n";
                });
            }
            return WinJS.Promise.join(promiseArray);
        }).done(function () {
            WinJS.log && WinJS.log(output, "sample", "status");
        });
    }

    // This function retrieves all items added to the index through the app's appcontent-ms files which
    // have an ItemNameDisplay property containing "Sample 1".
    function retrieveMatchedItems() {
        var applicationData = Windows.Storage.ApplicationData.current,
            localFolder = applicationData.localFolder,
            queryOptions = new Windows.Storage.Search.QueryOptions();
        queryOptions.indexerOption = Windows.Storage.Search.IndexerOption.onlyUseIndexer; // Include only items returned via the index in the search results
        queryOptions.applicationSearchFilter = Windows.Storage.SystemProperties.itemNameDisplay + ":\"Sample 1\""; // Create an AQS (Advanced Query Syntax) query which will look for ItemNameDisplay properties which contain "Sample 1"
        var output;
        localFolder.createFolderAsync("Indexed", Windows.Storage.CreationCollisionOption.openIfExists).then(function (indexedFolder) {
            var query = indexedFolder.createFileQueryWithOptions(queryOptions); // Query for files using the options specified above
            return query.getFilesAsync();
        }).then(function (indexedItems) {
            var promiseArray = [];
            output = "";
            for (var i = 0, len = indexedItems.length; i < len; i++) {
                promiseArray[i] = indexedItems[i].properties.retrievePropertiesAsync([Windows.Storage.SystemProperties.itemNameDisplay, Windows.Storage.SystemProperties.comment, Windows.Storage.SystemProperties.keywords, Windows.Storage.SystemProperties.title]).then(function (map) {
                    output += "Name: " + map[Windows.Storage.SystemProperties.itemNameDisplay];
                    output += "\nKeywords: " + IndexerHelpers.createKeywordString(map[Windows.Storage.SystemProperties.keywords]);
                    output += "\nComment: " + map[Windows.Storage.SystemProperties.comment];
                    output += "\nTitle: " + map[Windows.Storage.SystemProperties.title] + "\n\n";
                });
            }
            return WinJS.Promise.join(promiseArray);
        }).done(function () {
            WinJS.log && WinJS.log(output, "sample", "status");
        });
    }
})();


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Online.API;
using osu.Game.Users;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Overlays.Toolbar
{
    public class ToolbarUserButton : ToolbarButton, IOnlineComponent
    {
        private readonly UpdateableAvatar avatar;

        public ToolbarUserButton()
        {
            AutoSizeAxes = Axes.X;

            DrawableText.Font = OsuFont.GetFont(italics: true);

            Add(new OpaqueBackground { Depth = 1 });

            Flow.Add(avatar = new UpdateableAvatar
            {
                Masking = true,
                Size = new Vector2(32),
                Anchor = Anchor.CentreLeft,
                Origin = Anchor.CentreLeft,
                CornerRadius = 4,
                OpenOnClick = { Value = false },
                EdgeEffect = new EdgeEffectParameters
                {
                    Type = EdgeEffectType.Shadow,
                    Radius = 4,
                    Colour = Color4.Black.Opacity(0.1f),
                }
            });
        }

        [BackgroundDependencyLoader]
        private void load(APIAccess api)
        {
            api.Register(this);
        }

        public void APIStateChanged(APIAccess api, APIState state)
        {
            switch (state)
            {
                default:
                    Text = @"Guest";
                    avatar.User = new User();
                    break;
                case APIState.Online:
                    Text = api.LocalUser.Value.Username;
                    avatar.User = api.LocalUser.Value;
                    break;
            }
        }
    }
}


text:
(function () {
    'use strict';

    angular
        .module('qrbweb')
        .factory('EstoqueFactory', ['$http', '$q', 'ResourcesFactory', EstoqueFactory]);

    function EstoqueFactory($http, $q, ResourcesFactory) {

        var estoque = [];

        function list() {
            var d = $q.defer();
            $http.get(ResourcesFactory.ESTOQUE_API).then(function (response, $q) {
                    d.resolve(response);
                    estoque = response.data;
                },
                function (data) {
                    d.reject(data);
                });
            return d.promise;
        }

        function remove(id) {
            var d = $q.defer();
            $http.delete(ResourcesFactory.ESTOQUE_API + id).then(function (response, $q) {
                    d.resolve(response);
                    list();
                },
                function (data) {
                    d.reject(data);
                });
            return d.promise;
        }

        function create(estoque) {
            var d = $q.defer();
            $http.post(ResourcesFactory.ESTOQUE_API, estoque).then(function (response, $q) {
                    d.resolve(response);
                },
                function (data) {
                    d.reject(data);
                });
            return d.promise;
        }

        function update(estoque) {
            var d = $q.defer();
            $http.put(ResourcesFactory.ESTOQUE_API + estoque.id, estoque).then(function (response, $q) {
                    d.resolve(response);
                },
                function (data) {
                    d.reject(data);
                });
            return d.promise;
        }

        function getById(id) {
            var d = $q.defer();
            $http.get(ResourcesFactory.ESTOQUE_API + id).then(function (response, $q) {
                    d.resolve(response);
                },
                function (data) {
                    d.reject(data);
                });
            return d.promise;
        }

        function get() {
            return estoque;
        }

        return {
            list: list,
            remove: remove,
            create: create,
            get: get,
            getById: getById,
            update: update
        };
    }
})();


text:
__author__ = 'tribhu'

import json
import ssl

from flask import Flask, jsonify, abort, make_response, url_for, request
from flask.ext.cors import CORS, cross_origin

import requests

import sqlite3

from persistent_helpers import get_recipe_info, get_recipe_short_descriptions
from parse_helper import route_command
from hardware_helpers import get_latest_temperatures, get_oven_temperature

context = None
try:
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.load_cert_chain('server.crt', 'server.key')
except:
    pass
app = Flask(__name__, static_url_path='')
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route('/recipes/api/v1.0/recipes', methods=['GET'])
@cross_origin()
def get_recipes():
    """
    @return: a JSON RecipeList object
    """
    return get_recipe_short_descriptions()

@app.route('/temp', methods=['GET'])
def store_temperature():
    query_template = """INSERT INTO TEMPERATURE(TEMPERATURE) VALUES(%f);"""
    temp_value = float(request.args.get('t'))

    query = query_template % temp_value
    conn = sqlite3.connect('temperature.db')
    c = conn.cursor()
    c.execute(query)
    conn.commit()
    c.close()
    conn.close()

    return 'OK'

@app.route('/get_temp_list', methods=['GET'])
def get_temperature_list():
    response = get_latest_temperatures()
    return json.dumps({'response': response})

@app.route('/get_temp', methods=['GET'])
def get_temperature():
    temperature = get_oven_temperature()
    response = {'response' : temperature}
    return json.dumps(response)

@app.route('/recipes/api/v1.0/recipe_info', methods=['GET'])
@cross_origin()
def get_recipes_info():
    """
    @return: a JSON RecipeList object
    """
    recipe_id =  int(request.args.get('recipe_id'))
    return get_recipe_info(recipe_id)

@app.route('/recipes/api/v1.0/ask', methods=['GET'])
@cross_origin()
def get_recipe():
    """get_recipe requires two GET parameters:
    a. recipe_id - the recipe ID number
    b. text - the (sepeech-converted) textual command

    @return: a JSON Recipe object
    """
    recipe_id =  int(request.args.get('recipe_id'))
    text = request.args.get('text')
    response_json = route_command(text, recipe_id)

    if response_json == None:
        abort(404)
    return response_json

@app.route('/tokens/api/v1.0/watson_token', methods=['GET'])
@cross_origin()
def get_watson_token():
    """
    @return: a JSON RecipeList object
    """
    from creds import watson_username, watson_password
    service_url = 'https://stream.watsonplatform.net/text-to-speech/api'
    r = requests.get('https://stream.watsonplatform.net/authorization/api/v1/token?url=%s' % service_url,
                     auth=(watson_username, watson_password))
    return json.dumps({'response': r.text})

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

def make_public_task(recipe):
    new_recipe = {}
    for field in recipe:
        if field == 'id':
            new_recipe['uri'] = url_for('get_recipe', recipe_id=recipe['id'], _external=True)
        else:
            new_recipe[field] = recipe[field]
    return new_recipe

if __name__ == '__main__':
    app.run(debug=True, ssl_context=context)


text:
.. title:: clang-tidy - openmp-use-default-none

openmp-use-default-none
=======================

Finds OpenMP directives that are allowed to contain a ``default`` clause,
but either don't specify it or the clause is specified but with the kind
other than ``none``, and suggests to use the ``default(none)`` clause.

Using ``default(none)`` clause forces developers to explicitly specify data
sharing attributes for the variables referenced in the construct,
thus making it obvious which variables are referenced, and what is their
data sharing attribute, thus increasing readability and possibly making errors
easier to spot.

Example
-------

.. code-block:: c++

  // ``for`` directive can not have ``default`` clause, no diagnostics.
  void n0(const int a) {
  #pragma omp for
    for (int b = 0; b < a; b++)
      ;
  }

  // ``parallel`` directive.

  // ``parallel`` directive can have ``default`` clause, but said clause is not
  // specified, diagnosed.
  void p0_0() {
  #pragma omp parallel
    ;
    // WARNING: OpenMP directive ``parallel`` does not specify ``default``
    //          clause. Consider specifying ``default(none)`` clause.
  }

  // ``parallel`` directive can have ``default`` clause, and said clause is
  // specified, with ``none`` kind, all good.
  void p0_1() {
  #pragma omp parallel default(none)
    ;
  }

  // ``parallel`` directive can have ``default`` clause, and said clause is
  // specified, but with ``shared`` kind, which is not ``none``, diagnose.
  void p0_2() {
  #pragma omp parallel default(shared)
    ;
    // WARNING: OpenMP directive ``parallel`` specifies ``default(shared)``
    //          clause. Consider using ``default(none)`` clause instead.
  }


text:
ES5Harness.registerTest({
    id: "15.2.3.6-4-73",

    path: "TestCases/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-73.js",

    description: "Object.defineProperty - both desc.writable and name.writable are boolean values with the same value (8.12.9 step 6)",

    test: function testcase() {

        var obj = {};

        Object.defineProperty(obj, "foo", { writable: false});

        Object.defineProperty(obj, "foo", { writable: false });
        return dataPropertyAttributesAreCorrect(obj, "foo", undefined, false, false, false);
    },

    precondition: function prereq() {
        return fnExists(Object.defineProperty);
    }
});


text:
package com.yahoo.ycsb;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

import java.util.Arrays;

import org.testng.annotations.Test;

public class TestUtils {

  @Test
  public void bytesToFromLong() throws Exception {
    byte[] bytes = new byte[8];
    assertEquals(Utils.bytesToLong(bytes), 0L);
    assertArrayEquals(Utils.longToBytes(0), bytes);

    bytes[7] = 1;
    assertEquals(Utils.bytesToLong(bytes), 1L);
    assertArrayEquals(Utils.longToBytes(1L), bytes);

    bytes = new byte[] { 127, -1, -1, -1, -1, -1, -1, -1 };
    assertEquals(Utils.bytesToLong(bytes), Long.MAX_VALUE);
    assertArrayEquals(Utils.longToBytes(Long.MAX_VALUE), bytes);

    bytes = new byte[] { -128, 0, 0, 0, 0, 0, 0, 0 };
    assertEquals(Utils.bytesToLong(bytes), Long.MIN_VALUE);
    assertArrayEquals(Utils.longToBytes(Long.MIN_VALUE), bytes);

    bytes = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
        (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF  };
    assertEquals(Utils.bytesToLong(bytes), -1L);
    assertArrayEquals(Utils.longToBytes(-1L), bytes);

    // if the array is too long we just skip the remainder
    bytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 42, 42, 42 };
    assertEquals(Utils.bytesToLong(bytes), 1L);
  }

  @Test
  public void bytesToFromDouble() throws Exception {
    byte[] bytes = new byte[8];
    assertEquals(Utils.bytesToDouble(bytes), 0, 0.0001);
    assertArrayEquals(Utils.doubleToBytes(0), bytes);

    bytes = new byte[] { 63, -16, 0, 0, 0, 0, 0, 0 };
    assertEquals(Utils.bytesToDouble(bytes), 1, 0.0001);
    assertArrayEquals(Utils.doubleToBytes(1), bytes);

    bytes = new byte[] { -65, -16, 0, 0, 0, 0, 0, 0 };
    assertEquals(Utils.bytesToDouble(bytes), -1, 0.0001);
    assertArrayEquals(Utils.doubleToBytes(-1), bytes);

    bytes = new byte[] { 127, -17, -1, -1, -1, -1, -1, -1 };
    assertEquals(Utils.bytesToDouble(bytes), Double.MAX_VALUE, 0.0001);
    assertArrayEquals(Utils.doubleToBytes(Double.MAX_VALUE), bytes);

    bytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 };
    assertEquals(Utils.bytesToDouble(bytes), Double.MIN_VALUE, 0.0001);
    assertArrayEquals(Utils.doubleToBytes(Double.MIN_VALUE), bytes);

    bytes = new byte[] { 127, -8, 0, 0, 0, 0, 0, 0 };
    assertTrue(Double.isNaN(Utils.bytesToDouble(bytes)));
    assertArrayEquals(Utils.doubleToBytes(Double.NaN), bytes);

    bytes = new byte[] { 63, -16, 0, 0, 0, 0, 0, 0, 42, 42, 42 };
    assertEquals(Utils.bytesToDouble(bytes), 1, 0.0001);
  }

  @Test (expectedExceptions = NullPointerException.class)
  public void bytesToLongNull() throws Exception {
    Utils.bytesToLong(null);
  }

  @Test (expectedExceptions = IndexOutOfBoundsException.class)
  public void bytesToLongTooShort() throws Exception {
    Utils.bytesToLong(new byte[] { 0, 0, 0, 0, 0, 0, 0 });
  }

  @Test (expectedExceptions = IllegalArgumentException.class)
  public void bytesToDoubleTooShort() throws Exception {
    Utils.bytesToDouble(new byte[] { 0, 0, 0, 0, 0, 0, 0 });
  }

  @Test
  public void jvmUtils() throws Exception {
    // This should ALWAYS return at least one thread.
    assertTrue(Utils.getActiveThreadCount() > 0);
    // This should always be greater than 0 or something is goofed up in the JVM.
    assertTrue(Utils.getUsedMemoryBytes() > 0);
    // Some operating systems may not implement this so we don't have a good
    // test. Just make sure it doesn't throw an exception.
    Utils.getSystemLoadAverage();
    // This will probably be zero but should never be negative.
    assertTrue(Utils.getGCTotalCollectionCount() >= 0);
    // Could be zero similar to GC total collection count
    assertTrue(Utils.getGCTotalTime() >= 0);
    // Could be empty
    assertTrue(Utils.getGCStatst().size() >= 0);
  }

  /**
   * Since this version of TestNG doesn't appear to have an assertArrayEquals,
   * this will compare the two to make sure they're the same.
   * @param actual Actual array to validate
   * @param expected What the array should contain
   * @throws AssertionError if the test fails.
   */
  public void assertArrayEquals(final byte[] actual, final byte[] expected) {
    if (actual == null && expected != null) {
      throw new AssertionError("Expected " + Arrays.toString(expected) +
          " but found [null]");
    }
    if (actual != null && expected == null) {
      throw new AssertionError("Expected [null] but found " +
          Arrays.toString(actual));
    }
    if (actual.length != expected.length) {
      throw new AssertionError("Expected length " + expected.length +
          " but found " + actual.length);
    }
    for (int i = 0; i < expected.length; i++) {
      if (actual[i] != expected[i]) {
        throw new AssertionError("Expected byte [" + expected[i] +
            "] at index " + i + " but found [" + actual[i] + "]");
      }
    }
  }
}


text:
package edu.swau.matthew.dao.impl;

import edu.swau.matthew.dao.BaseDao;
import edu.swau.matthew.dao.CompanyDao;
import edu.swau.matthew.model.Company;
import edu.swau.matthew.model.XCompany;
import edu.swau.matthew.utils.Constants;
import java.util.Date;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author J. David Mendoza <jdmendoza@swau.edu>
 */
@Repository
@Transactional
public class CompanyDaoHibernate extends BaseDao implements CompanyDao {

    @Override
    public Company create(Company company) {
        Date date = new Date();
        company.setDateCreated(date);
        company.setLastUpdated(date);
        currentSession().save(company);

        audit(company, Constants.CREATE);

        return company;
    }

    private void audit(Company company, String action) {
        XCompany xcompany = new XCompany();
        BeanUtils.copyProperties(company, xcompany, new String[] {"id", "version"});
        xcompany.setOrganizationId(company.getOrganization().getId());
        xcompany.setCompanyId(company.getId());
        xcompany.setAction(action);
        currentSession().save(xcompany);
    }

}


text:
package org.apache.logging.log4j.core.async;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.categories.AsyncLoggers;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static org.junit.Assert.*;

/**
 * Tests the DiscardingAsyncQueueFullPolicy class..
 */
@Category(AsyncLoggers.class)
public class DiscardingAsyncQueueFullPolicyTest {

    private static long currentThreadId() {
        return Thread.currentThread().getId();
    }

    private static long otherThreadId() {
        return -1;
    }

    @Test(expected = NullPointerException.class)
    public void testConstructorDisallowsNullThresholdLevel() {
        new DiscardingAsyncQueueFullPolicy(null);
    }

    @Test
    public void testThresholdLevelIsConstructorValue() {
        assertSame(Level.ALL, new DiscardingAsyncQueueFullPolicy(Level.ALL).getThresholdLevel());
        assertSame(Level.OFF, new DiscardingAsyncQueueFullPolicy(Level.OFF).getThresholdLevel());
        assertSame(Level.INFO, new DiscardingAsyncQueueFullPolicy(Level.INFO).getThresholdLevel());
    }

    @Test
    public void testGetRouteDiscardsIfThresholdCapacityReachedAndLevelEqualOrLessSpecificThanThreshold()
            throws Exception {
        final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN);

        for (final Level level : new Level[] {Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE, Level.ALL}) {
            assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level));
            assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level));
            assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level));
            assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level));
        }
    }

    @Test
    public void testGetRouteDiscardsIfQueueFullAndLevelEqualOrLessSpecificThanThreshold() throws Exception {
        final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN);

        for (final Level level : new Level[] {Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE, Level.ALL}) {
            assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level));
            assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level));
        }
    }

    @Test
    public void testGetRouteEnqueuesIfThresholdCapacityReachedButLevelMoreSpecificThanThreshold()
            throws Exception {
        final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN);

        for (final Level level : new Level[] {Level.ERROR, Level.FATAL, Level.OFF}) {
            assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level));
            assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(otherThreadId(), level));
            assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level));
            assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(otherThreadId(), level));
        }
    }

    @Test
    public void testGetRouteSynchronousIfOtherThreadQueueFullAndLevelMoreSpecificThanThreshold() throws Exception {
        final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN);

        for (final Level level : new Level[] {Level.ERROR, Level.FATAL, Level.OFF}) {
            assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(otherThreadId(), level));
        }
    }

    @Test
    public void testGetRouteSynchronousIfCurrentThreadQueueFullAndLevelMoreSpecificThanThreshold() throws Exception {
        final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN);

        for (final Level level : new Level[] {Level.ERROR, Level.FATAL, Level.OFF}) {
            assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level));
        }
    }

    @Test
    public void testGetDiscardCount() throws Exception {
        final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.INFO);
        assertEquals("initially", 0, DiscardingAsyncQueueFullPolicy.getDiscardCount(router));

        assertEquals(EventRoute.DISCARD, router.getRoute(-1L, Level.INFO));
        assertEquals("increase", 1, DiscardingAsyncQueueFullPolicy.getDiscardCount(router));

        assertEquals(EventRoute.DISCARD, router.getRoute(-1L, Level.INFO));
        assertEquals("increase", 2, DiscardingAsyncQueueFullPolicy.getDiscardCount(router));

        assertEquals(EventRoute.DISCARD, router.getRoute(-1L, Level.INFO));
        assertEquals("increase", 3, DiscardingAsyncQueueFullPolicy.getDiscardCount(router));
    }
}


text:
To setup your local environment to run this, ensure you have Ruby 2+ installed,
then install dependencies by running:

```
$ bundle
```

To launch the app locally run:

```
$ rackup
```


text:
namespace PregiLiga.Api
{
    public class ConfigureAutomapper : IBootstrapperTask
    {
        #region IBootstrapperTask Members

        public void Run()
        {
            //automappings go here
            //Ex: Mapper.CreateMap<SomeType, SomeOtherType>().ReverseMap();

        }

        #endregion
    }
}


text:
require 'spec_helper'

module LAME
  module Decoding
    describe StreamDecoder do

      subject(:decoder) { StreamDecoder.new(decode_flags, mp3_data, stream) }

      let(:decode_flags) { double("decode flags") }
      let(:mp3_data) { double("mp3 data") }

      let(:stream) { StringIO.new(stream_string) }
      let(:stream_string) { "a" * 1024 + "b" * 1024}

      it "creates a single frame decoder" do
        expect(SingleFrameDecoder).to receive(:new).with(decode_flags, mp3_data)
        decoder
      end

      it "it passes chunks of stream into the single frame decoder" do
        single_frame_decoder = double("single_frame_decoder")
        allow(SingleFrameDecoder).to receive(:new).and_return(single_frame_decoder)

        expect(single_frame_decoder).to receive(:decode).exactly(:twice)

        decoder.each_decoded_frame
      end

      it "yields the decoded frame" do
        single_frame_decoder = double("single frame decoder")
        allow(SingleFrameDecoder).to receive(:new).and_return(single_frame_decoder)

        allow(single_frame_decoder).to receive(:decode).with("a"*1024).and_yield(:one)
        allow(single_frame_decoder).to receive(:decode).with("b"*1024).and_yield(:two).and_yield(:three)

        expect { |block|
          decoder.each_decoded_frame(&block)
        }.to yield_successive_args(:one, :two, :three)
      end

    end
  end
end