text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.provisioning;

import com.yahoo.config.provision.CloudAccount;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provision.NodeFlavors;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.vespa.hosted.provision.Node;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * A specification of a set of nodes.
 * This reflects that nodes can be requested either by count and flavor or by type,
 * and encapsulates the differences in logic between these two cases.
 *
 * @author bratseth
 */
public interface NodeSpec {

    /** The node type this requests */
    NodeType type();

    /** Returns whether the hosts running the nodes of this application can also run nodes of other applications. */
    boolean isExclusive();

    /** Returns whether the given node resources is compatible with this spec */
    boolean isCompatible(NodeResources resources);

    /** Returns whether the given node count is sufficient to consider this spec fulfilled to the maximum amount */
    boolean saturatedBy(int count);

    /** Returns whether the given node count is sufficient to fulfill this spec */
    default boolean fulfilledBy(int count) {
        return fulfilledDeficitCount(count) == 0;
    }

    /** Returns whether this should throw an exception if the requested nodes are not fully available */
    boolean canFail();

    /** Returns whether we should retire nodes at all when fulfilling this spec */
    boolean considerRetiring();

    /** Returns the ideal number of nodes that should be retired to fulfill this spec */
    int idealRetiredCount(int acceptedCount, int wantToRetireCount, int currentRetiredCount);

    /** Returns number of additional nodes needed for this spec to be fulfilled given the current node count */
    int fulfilledDeficitCount(int count);

    /** Returns a specification of a fraction of all the nodes of this. It is assumed the argument is a valid divisor. */
    NodeSpec fraction(int divisor);

    /** Returns the resources requested by this or empty if none are explicitly requested */
    Optional<NodeResources> resources();

    /** Returns whether the given node must be resized to match this spec */
    boolean needsResize(Node node);

    /** Returns true if there exist some circumstance where we may accept to have this node allocated */
    boolean acceptable(NodeCandidate node);

    /** Returns true if nodes with non-active parent hosts should be rejected */
    boolean rejectNonActiveParent();

    /** Returns the cloud account to use when fulfilling this spec */
    CloudAccount cloudAccount();

    /**
     * Returns true if a node with given current resources and current spare host resources can be resized
     * in-place to resources in this spec.
     */
    default boolean canResize(NodeResources currentNodeResources, NodeResources currentSpareHostResources,
                              ClusterSpec.Type type, boolean hasTopologyChange, int currentClusterSize) {
        return false;
    }

    static NodeSpec from(int nodeCount, NodeResources resources, boolean exclusive, boolean canFail, CloudAccount cloudAccount) {
        return new CountNodeSpec(nodeCount, resources, exclusive, canFail, cloudAccount);
    }

    static NodeSpec from(NodeType type, CloudAccount cloudAccount) {
        return new TypeNodeSpec(type, cloudAccount);
    }

    /** A node spec specifying a node count and a flavor */
    class CountNodeSpec implements NodeSpec {

        private final int count;
        private final NodeResources requestedNodeResources;
        private final boolean exclusive;
        private final boolean canFail;
        private final CloudAccount cloudAccount;

        private CountNodeSpec(int count, NodeResources resources, boolean exclusive, boolean canFail, CloudAccount cloudAccount) {
            this.count = count;
            this.requestedNodeResources = Objects.requireNonNull(resources, "Resources must be specified");
            this.exclusive = exclusive;
            this.canFail = canFail;
            this.cloudAccount = Objects.requireNonNull(cloudAccount);
        }

        @Override
        public Optional<NodeResources> resources() {
            return Optional.of(requestedNodeResources);
        }

        @Override
        public boolean isExclusive() { return exclusive; }

        @Override
        public NodeType type() { return NodeType.tenant; }

        @Override
        public boolean isCompatible(NodeResources resources) {
            return resources.equalsWhereSpecified(requestedNodeResources);
        }

        @Override
        public boolean saturatedBy(int count) { return fulfilledBy(count); } // min=max for count specs

        @Override
        public boolean canFail() { return canFail; }

        @Override
        public boolean considerRetiring() {
            // If we cannot fail we cannot retire as we may end up without sufficient replacement capacity
            return canFail();
        }

        @Override
        public int idealRetiredCount(int acceptedCount, int wantToRetireCount, int currentRetiredCount) {
            return acceptedCount - this.count - currentRetiredCount;
        }

        @Override
        public int fulfilledDeficitCount(int count) {
            return Math.max(this.count - count, 0);
        }

        @Override
        public NodeSpec fraction(int divisor) {
            return new CountNodeSpec(count/divisor, requestedNodeResources, exclusive, canFail, cloudAccount);
        }

        @Override
        public boolean needsResize(Node node) {
            return ! node.resources().equalsWhereSpecified(requestedNodeResources);
        }

        @Override
        public boolean canResize(NodeResources currentNodeResources, NodeResources currentSpareHostResources,
                                 ClusterSpec.Type type, boolean hasTopologyChange, int currentClusterSize) {
            // Never allow in-place resize when also changing topology or decreasing cluster size
            if (hasTopologyChange || count < currentClusterSize) return false;

            // Do not allow increasing cluster size and decreasing node resources at the same time for content nodes
            if (type.isContent() && count > currentClusterSize && !requestedNodeResources.satisfies(currentNodeResources.justNumbers()))
                return false;

            // Otherwise, allowed as long as the host can satisfy the new requested resources
            return currentSpareHostResources.add(currentNodeResources.justNumbers()).satisfies(requestedNodeResources);
        }

        @Override
        public boolean acceptable(NodeCandidate node) { return true; }

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

        @Override
        public CloudAccount cloudAccount() {
            return cloudAccount;
        }

        @Override
        public String toString() { return "request for " + count + " nodes with " + requestedNodeResources; }

    }

    /** A node spec specifying a node type. This will accept all nodes of this type. */
    class TypeNodeSpec implements NodeSpec {

        private static final Map<NodeType, Integer> WANTED_NODE_COUNT = Map.of(NodeType.config, 3,
                                                                               NodeType.controller, 3);

        private final NodeType type;
        private final CloudAccount cloudAccount;

        public TypeNodeSpec(NodeType type, CloudAccount cloudAccount) {
            this.type = type;
            this.cloudAccount = cloudAccount;
        }

        @Override
        public NodeType type() { return type; }

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

        @Override
        public boolean isCompatible(NodeResources resources) { return true; }

        @Override
        public boolean saturatedBy(int count) { return false; }

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

        @Override
        public boolean considerRetiring() { return true; }

        @Override
        public int idealRetiredCount(int acceptedCount, int wantToRetireCount, int currentRetiredCount) {
            return wantToRetireCount - currentRetiredCount;
        }

        @Override
        public int fulfilledDeficitCount(int count) {
            // If no wanted count is specified for this node type, then any count fulfills the deficit
            return Math.max(0, WANTED_NODE_COUNT.getOrDefault(type, 0) - count);
        }

        @Override
        public NodeSpec fraction(int divisor) { return this; }

        @Override
        public Optional<NodeResources> resources() {
            return Optional.empty();
        }

        @Override
        public boolean needsResize(Node node) { return false; }

        @Override
        public boolean acceptable(NodeCandidate node) {
            // Since we consume all offered nodes we should not accept previously deactivated nodes
            return node.state() != Node.State.inactive;
        }

        @Override
        public boolean rejectNonActiveParent() {
            return true;
        }

        @Override
        public CloudAccount cloudAccount() {
            return cloudAccount;
        }

        @Override
        public String toString() { return "request for all nodes of type '" + type + "'"; }

    }

}


text:
package org.trustedanalytics.cfbroker.catalog.utils;

import org.cloudfoundry.community.servicebroker.model.Plan;

import java.util.List;
import java.util.stream.IntStream;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class PlanCollectionAsserts {

    public static void assertThatPlanListsAreEqual(List<Plan> actualPlans, List<Plan> expectedPlans) {
        assertThat(actualPlans.size(), equalTo(expectedPlans.size()));

        IntStream.range(0, actualPlans.size())
            .mapToObj(i -> new Pair<>(actualPlans.get(i), expectedPlans.get(i)))
            .forEach(pair -> {
                Plan actual = pair.getLeft();
                Plan expected = pair.getRight();
                assertThat(actual.getDescription(), equalTo(expected.getDescription()));
                assertThat(actual.getId(), equalTo(expected.getId()));
                assertThat(actual.getMetadata(), equalTo(expected.getMetadata()));
                assertThat(actual.getName(), equalTo(expected.getName()));
                assertThat(actual.isFree(), equalTo(expected.isFree()));
            });
    }

    private static class Pair<T> {

        private final T left;
        private final T right;

        private Pair(T left, T right) {
            this.left = left;
            this.right = right;
        }

        public T getLeft() {
            return left;
        }

        public T getRight() {
            return right;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Routing\Matcher\Dumper;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class PhpMatcherDumper extends MatcherDumper
{
    /**
     * Dumps a set of routes to a PHP class.
     *
     * Available options:
     *
     *  * class:      The class name
     *  * base_class: The base class name
     *
     * @param  array  $options An array of options
     *
     * @return string A PHP class representing the matcher class
     */
    public function dump(array $options = array())
    {
        $options = array_merge(array(
            'class'      => 'ProjectUrlMatcher',
            'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
        ), $options);

        // trailing slash support is only enabled if we know how to redirect the user
        $interfaces = class_implements($options['base_class']);
        $supportsRedirections = isset($interfaces['Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface']);

        return
            $this->startClass($options['class'], $options['base_class']).
            $this->addConstructor().
            $this->addMatcher($supportsRedirections).
            $this->endClass()
        ;
    }

    private function addMatcher($supportsRedirections)
    {
        // we need to deep clone the routes as we will modify the structure to optimize the dump
        $code = rtrim($this->compileRoutes(clone $this->getRoutes(), $supportsRedirections), "\n");

        return <<<EOF

    public function match(\$pathinfo)
    {
        \$allow = array();
        \$pathinfo = rawurldecode(\$pathinfo);

$code

        throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
    }

EOF;
    }

    private function compileRoutes(RouteCollection $routes, $supportsRedirections, $parentPrefix = null)
    {
        $code = '';

        $routeIterator = $routes->getIterator();
        $keys = array_keys($routeIterator->getArrayCopy());
        $keysCount = count($keys);

        $i = 0;
        foreach ($routeIterator as $name => $route) {
            $i++;

            if ($route instanceof RouteCollection) {
                $prefix = $route->getPrefix();
                $optimizable = $prefix && count($route->all()) > 1 && false === strpos($route->getPrefix(), '{');
                $optimized = false;

                if ($optimizable) {
                    for ($j = $i; $j < $keysCount; $j++) {
                        if (null === $keys[$j]) {
                            continue;
                        }

                        $testRoute = $routeIterator->offsetGet($keys[$j]);
                        $isCollection = ($testRoute instanceof RouteCollection);

                        $testPrefix = $isCollection ? $testRoute->getPrefix() : $testRoute->getPattern();

                        if (0 === strpos($testPrefix, $prefix)) {
                            $routeIterator->offsetUnset($keys[$j]);

                            if ($isCollection) {
                                $route->addCollection($testRoute);
                            } else {
                                $route->add($keys[$j], $testRoute);
                            }

                            $i++;
                            $keys[$j] = null;
                        }
                    }

                    if ($prefix !== $parentPrefix) {
                        $code .= sprintf("        if (0 === strpos(\$pathinfo, %s)) {\n", var_export($prefix, true));
                        $optimized = true;
                    }
                }

                if ($optimized) {
                    foreach (explode("\n", $this->compileRoutes($route, $supportsRedirections, $prefix)) as $line) {
                        if ('' !== $line) {
                            $code .= '    '; // apply extra indention
                        }
                        $code .= $line."\n";
                    }
                    $code = substr($code, 0, -2); // remove redundant last two line breaks
                    $code .= "        }\n\n";
                } else {
                    $code .= $this->compileRoutes($route, $supportsRedirections, $prefix);
                }
            } else {
                $code .= $this->compileRoute($route, $name, $supportsRedirections, $parentPrefix)."\n";
            }
        }

        return $code;
    }

    private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
    {
        $code = '';
        $compiledRoute = $route->compile();
        $conditions = array();
        $hasTrailingSlash = false;
        $matches = false;
        $methods = array();

        if ($req = $route->getRequirement('_method')) {
            $methods = explode('|', strtoupper($req));
            // GET and HEAD are equivalent
            if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
                $methods[] = 'HEAD';
            }
        }

        $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));

        if (!count($compiledRoute->getVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
            if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
                $conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
                $hasTrailingSlash = true;
            } else {
                $conditions[] = sprintf("\$pathinfo === %s", var_export(str_replace('\\', '', $m['url']), true));
            }
        } else {
            if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() != $parentPrefix) {
                $conditions[] = sprintf("0 === strpos(\$pathinfo, %s)", var_export($compiledRoute->getStaticPrefix(), true));
            }

            $regex = $compiledRoute->getRegex();
            if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
                $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
                $hasTrailingSlash = true;
            }
            $conditions[] = sprintf("preg_match(%s, \$pathinfo, \$matches)", var_export($regex, true));

            $matches = true;
        }

        $conditions = implode(' && ', $conditions);

        $code .= <<<EOF
        // $name
        if ($conditions) {

EOF;

        if ($methods) {
            $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);

            if (1 === count($methods)) {
                $code .= <<<EOF
            if (\$this->context->getMethod() != '$methods[0]') {
                \$allow[] = '$methods[0]';
                goto $gotoname;
            }

EOF;
            } else {
                $methods = implode("', '", $methods);
                $code .= <<<EOF
            if (!in_array(\$this->context->getMethod(), array('$methods'))) {
                \$allow = array_merge(\$allow, array('$methods'));
                goto $gotoname;
            }

EOF;
            }
        }

        if ($hasTrailingSlash) {
            $code .= <<<EOF
            if (substr(\$pathinfo, -1) !== '/') {
                return \$this->redirect(\$pathinfo.'/', '$name');
            }

EOF;
        }

        if ($scheme = $route->getRequirement('_scheme')) {
            if (!$supportsRedirections) {
                throw new \LogicException('The "_scheme" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
            }

            $code .= <<<EOF
            if (\$this->context->getScheme() !== '$scheme') {
                return \$this->redirect(\$pathinfo, '$name', '$scheme');
            }

EOF;
        }

        // optimize parameters array
        if (true === $matches && $compiledRoute->getDefaults()) {
            $code .= sprintf("            return array_merge(\$this->mergeDefaults(\$matches, %s), array('_route' => '%s'));\n"
                , str_replace("\n", '', var_export($compiledRoute->getDefaults(), true)), $name);
        } elseif (true === $matches) {
            $code .= sprintf("            \$matches['_route'] = '%s';\n", $name);
            $code .= "            return \$matches;\n";
        } elseif ($compiledRoute->getDefaults()) {
            $code .= sprintf("            return %s;\n", str_replace("\n", '', var_export(array_merge($compiledRoute->getDefaults(), array('_route' => $name)), true)));
        } else {
            $code .= sprintf("            return array('_route' => '%s');\n", $name);
        }
        $code .= "        }\n";

        if ($methods) {
            $code .= "        $gotoname:\n";
        }

        return $code;
    }

    private function startClass($class, $baseClass)
    {
        return <<<EOF
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * $class
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class $class extends $baseClass
{

EOF;
    }

    private function addConstructor()
    {
        return <<<EOF
    /**
     * Constructor.
     */
    public function __construct(RequestContext \$context)
    {
        \$this->context = \$context;
    }

EOF;
    }

    private function endClass()
    {
        return <<<EOF
}

EOF;
    }
}


text:
class UserStore {
  constructor() {
    this.userName = undefined;
    this.userEmail = undefined;
  }
}

let userStore = new UserStore();

export default userStore;


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <ladspa.h>
#include "tap_utils.h"

/* The Unique ID of the plugin: */

#define ID_MONO         2145

/* The port numbers for the plugin: */

#define LIMIT_VOL       0
#define OUT_VOL         1
#define LATENCY         2
#define INPUT           3
#define OUTPUT          4

/* Total number of ports */

#define PORTCOUNT_MONO   5

/* Size of a ringbuffer that must be large enough to hold audio
 * between two zero-crosses in any case (or you'll hear
 * distortion). 40 Hz sound at 192kHz yields a half-period of 2400
 * samples, so this should be enough.
 */
#define RINGBUF_SIZE 2500

/* The structure used to hold port connection information and state */

typedef struct {
	LADSPA_Data * limit_vol;
	LADSPA_Data * out_vol;
	LADSPA_Data * latency;
	LADSPA_Data * input;
	LADSPA_Data * output;

	LADSPA_Data * ringbuffer;
	unsigned long buflen;
	unsigned long pos;
	unsigned long ready_num;

	unsigned long sample_rate;
	LADSPA_Data run_adding_gain;
} Limiter;

/* Construct a new plugin instance. */
LADSPA_Handle
instantiate_Limiter(const LADSPA_Descriptor * Descriptor,
		    unsigned long             sample_rate) {

	LADSPA_Handle * ptr;

	if ((ptr = malloc(sizeof(Limiter))) != NULL) {
		((Limiter *)ptr)->sample_rate = sample_rate;
		((Limiter *)ptr)->run_adding_gain = 1.0f;

		if ((((Limiter *)ptr)->ringbuffer =
		     calloc(RINGBUF_SIZE, sizeof(LADSPA_Data))) == NULL)
			return NULL;

		/* 80 Hz is the lowest frequency with which zero-crosses were
		 * observed to occur (this corresponds to 40 Hz signal frequency).
		 */
		((Limiter *)ptr)->buflen = ((Limiter *)ptr)->sample_rate / 80;

		((Limiter *)ptr)->pos = 0;
		((Limiter *)ptr)->ready_num = 0;

		return ptr;
	}
       	return NULL;
}

void
activate_Limiter(LADSPA_Handle Instance) {

	Limiter * ptr = (Limiter *)Instance;
	unsigned long i;

	for (i = 0; i < RINGBUF_SIZE; i++)
		ptr->ringbuffer[i] = 0.0f;
}

/* Connect a port to a data location. */
void
connect_port_Limiter(LADSPA_Handle Instance,
		     unsigned long Port,
		     LADSPA_Data * DataLocation) {

	Limiter * ptr = (Limiter *)Instance;

	switch (Port) {
	case LIMIT_VOL:
		ptr->limit_vol = DataLocation;
		break;
	case OUT_VOL:
		ptr->out_vol = DataLocation;
		break;
	case LATENCY:
		ptr->latency = DataLocation;
		*(ptr->latency) = ptr->buflen;  /* IS THIS LEGAL? */
		break;
	case INPUT:
		ptr->input = DataLocation;
		break;
	case OUTPUT:
		ptr->output = DataLocation;
		break;
	}
}

void
run_Limiter(LADSPA_Handle Instance,
	    unsigned long SampleCount) {

	Limiter * ptr = (Limiter *)Instance;

	LADSPA_Data * input = ptr->input;
	LADSPA_Data * output = ptr->output;
	LADSPA_Data limit_vol = db2lin(LIMIT(*(ptr->limit_vol),-30.0f,20.0f));
	LADSPA_Data out_vol = db2lin(LIMIT(*(ptr->out_vol),-30.0f,20.0f));
	unsigned long sample_index;
	unsigned long sample_count = SampleCount;
	unsigned long index_offs = 0;
	unsigned long i;
	LADSPA_Data max_value = 0;
	LADSPA_Data section_gain = 0;
	unsigned long run_length;
	unsigned long total_length = 0;

	while (total_length < sample_count) {

		run_length = ptr->buflen;
		if (total_length + run_length > sample_count)
			run_length = sample_count - total_length;

		while (ptr->ready_num < run_length) {
			if (read_buffer(ptr->ringbuffer, ptr->buflen,
					ptr->pos, ptr->ready_num) >= 0.0f) {
				index_offs = 0;
				while ((read_buffer(ptr->ringbuffer, ptr->buflen, ptr->pos,
						    ptr->ready_num + index_offs) >= 0.0f) &&
				       (ptr->ready_num + index_offs < run_length)) {
					index_offs++;
				}
			} else {
				index_offs = 0;
				while ((read_buffer(ptr->ringbuffer, ptr->buflen, ptr->pos,
						    ptr->ready_num + index_offs) <= 0.0f) &&
				       (ptr->ready_num + index_offs < run_length)) {
					index_offs++;
				}
			}

			/* search for max value in scanned halfcycle */
			max_value = 0;
			for (i = ptr->ready_num; i < ptr->ready_num + index_offs; i++) {
				if (fabs(read_buffer(ptr->ringbuffer, ptr->buflen,
						     ptr->pos, i)) > max_value)
					max_value = fabs(read_buffer(ptr->ringbuffer,
								     ptr->buflen, ptr->pos, i));
			}
			section_gain = limit_vol / max_value;
			if (max_value > limit_vol)
				for (i = ptr->ready_num; i < ptr->ready_num + index_offs; i++) {
					write_buffer(read_buffer(ptr->ringbuffer, ptr->buflen,
								 ptr->pos, i) * section_gain,
						     ptr->ringbuffer, ptr->buflen, ptr->pos, i);
				}
			ptr->ready_num += index_offs;
		}

		/* push run_length values out of ringbuffer, feed with input */
		for (sample_index = 0; sample_index < run_length; sample_index++) {
			*(output++) = out_vol *
				push_buffer(*(input++), ptr->ringbuffer,
					    ptr->buflen, &(ptr->pos));
		}
		ptr->ready_num -= run_length;
		total_length += run_length;
	}
	*(ptr->latency) = ptr->buflen;
}

void
set_run_adding_gain_Limiter(LADSPA_Handle Instance, LADSPA_Data gain) {

	Limiter * ptr = (Limiter *)Instance;

	ptr->run_adding_gain = gain;
}

void
run_adding_Limiter(LADSPA_Handle Instance,
		   unsigned long SampleCount) {

	Limiter * ptr = (Limiter *)Instance;

	LADSPA_Data * input = ptr->input;
	LADSPA_Data * output = ptr->output;
	LADSPA_Data limit_vol = db2lin(LIMIT(*(ptr->limit_vol),-30.0f,20.0f));
	LADSPA_Data out_vol = db2lin(LIMIT(*(ptr->out_vol),-30.0f,20.0f));
	unsigned long sample_index;
	unsigned long sample_count = SampleCount;
	unsigned long index_offs = 0;
	unsigned long i;
	LADSPA_Data max_value = 0;
	LADSPA_Data section_gain = 0;
	unsigned long run_length;
	unsigned long total_length = 0;

	while (total_length < sample_count) {

		run_length = ptr->buflen;
		if (total_length + run_length > sample_count)
			run_length = sample_count - total_length;

		while (ptr->ready_num < run_length) {
			if (read_buffer(ptr->ringbuffer, ptr->buflen,
					ptr->pos, ptr->ready_num) >= 0.0f) {
				index_offs = 0;
				while ((read_buffer(ptr->ringbuffer, ptr->buflen, ptr->pos,
						    ptr->ready_num + index_offs) >= 0.0f) &&
				       (ptr->ready_num + index_offs < run_length)) {
					index_offs++;
				}
			} else {
				index_offs = 0;
				while ((read_buffer(ptr->ringbuffer, ptr->buflen, ptr->pos,
						    ptr->ready_num + index_offs) <= 0.0f) &&
				       (ptr->ready_num + index_offs < run_length)) {
					index_offs++;
				}
			}

			/* search for max value in scanned halfcycle */
			max_value = 0;
			for (i = ptr->ready_num; i < ptr->ready_num + index_offs; i++) {
				if (fabs(read_buffer(ptr->ringbuffer, ptr->buflen,
						     ptr->pos, i)) > max_value)
					max_value = fabs(read_buffer(ptr->ringbuffer,
								     ptr->buflen, ptr->pos, i));
			}
			section_gain = limit_vol / max_value;
			if (max_value > limit_vol)
				for (i = ptr->ready_num; i < ptr->ready_num + index_offs; i++) {
					write_buffer(read_buffer(ptr->ringbuffer, ptr->buflen,
								 ptr->pos, i) * section_gain,
						     ptr->ringbuffer, ptr->buflen, ptr->pos, i);
				}
			ptr->ready_num += index_offs;
		}

		/* push run_length values out of ringbuffer, feed with input */
		for (sample_index = 0; sample_index < run_length; sample_index++) {
			*(output++) += ptr->run_adding_gain * out_vol *
				push_buffer(*(input++), ptr->ringbuffer,
					    ptr->buflen, &(ptr->pos));
		}
		ptr->ready_num -= run_length;
		total_length += run_length;
	}
	*(ptr->latency) = ptr->buflen;
}

/* Throw away a Limiter effect instance. */
void
cleanup_Limiter(LADSPA_Handle Instance) {

	Limiter * ptr = (Limiter *)Instance;
	free(ptr->ringbuffer);
	free(Instance);
}

LADSPA_Descriptor * mono_descriptor = NULL;

/* __attribute__((constructor)) tap_init() is called automatically when the plugin library is first
   loaded. */
void
__attribute__((constructor)) tap_init() {

	char ** port_names;
	LADSPA_PortDescriptor * port_descriptors;
	LADSPA_PortRangeHint * port_range_hints;

	if ((mono_descriptor =
	     (LADSPA_Descriptor *)malloc(sizeof(LADSPA_Descriptor))) == NULL)
		exit(1);

	mono_descriptor->UniqueID = ID_MONO;
	mono_descriptor->Label = strdup("tap_limiter");
	mono_descriptor->Properties = 0;
	mono_descriptor->Name = strdup("TAP Scaling Limiter");
	mono_descriptor->Maker = strdup("Tom Szilagyi");
	mono_descriptor->Copyright = strdup("GPL");
	mono_descriptor->PortCount = PORTCOUNT_MONO;

	if ((port_descriptors =
	     (LADSPA_PortDescriptor *)calloc(PORTCOUNT_MONO, sizeof(LADSPA_PortDescriptor))) == NULL)
		exit(1);

	mono_descriptor->PortDescriptors = (const LADSPA_PortDescriptor *)port_descriptors;
	port_descriptors[LIMIT_VOL] = LADSPA_PORT_INPUT | LADSPA_PORT_CONTROL;
	port_descriptors[OUT_VOL] = LADSPA_PORT_INPUT | LADSPA_PORT_CONTROL;
	port_descriptors[LATENCY] = LADSPA_PORT_OUTPUT | LADSPA_PORT_CONTROL;
	port_descriptors[INPUT] = LADSPA_PORT_INPUT | LADSPA_PORT_AUDIO;
	port_descriptors[OUTPUT] = LADSPA_PORT_OUTPUT | LADSPA_PORT_AUDIO;

	if ((port_names =
	     (char **)calloc(PORTCOUNT_MONO, sizeof(char *))) == NULL)
		exit(1);

	mono_descriptor->PortNames = (const char **)port_names;
	port_names[LIMIT_VOL] = strdup("Limit Level [dB]");
	port_names[OUT_VOL] = strdup("Output Volume [dB]");
	port_names[LATENCY] = strdup("latency");
	port_names[INPUT] = strdup("Input");
	port_names[OUTPUT] = strdup("Output");

	if ((port_range_hints =
	     ((LADSPA_PortRangeHint *)calloc(PORTCOUNT_MONO, sizeof(LADSPA_PortRangeHint)))) == NULL)
		exit(1);

	mono_descriptor->PortRangeHints	= (const LADSPA_PortRangeHint *)port_range_hints;
	port_range_hints[LIMIT_VOL].HintDescriptor =
		(LADSPA_HINT_BOUNDED_BELOW |
		 LADSPA_HINT_BOUNDED_ABOVE |
		 LADSPA_HINT_DEFAULT_0);
	port_range_hints[OUT_VOL].HintDescriptor =
		(LADSPA_HINT_BOUNDED_BELOW |
		 LADSPA_HINT_BOUNDED_ABOVE |
		 LADSPA_HINT_DEFAULT_0);
	port_range_hints[LATENCY].HintDescriptor =
		(LADSPA_HINT_BOUNDED_BELOW |
		 LADSPA_HINT_BOUNDED_ABOVE |
		 LADSPA_HINT_DEFAULT_MAXIMUM);
	port_range_hints[LIMIT_VOL].LowerBound = -30;
	port_range_hints[LIMIT_VOL].UpperBound = +20;
	port_range_hints[OUT_VOL].LowerBound = -30;
	port_range_hints[OUT_VOL].UpperBound = +20;
	port_range_hints[LATENCY].LowerBound = 0;
	port_range_hints[LATENCY].UpperBound = RINGBUF_SIZE + 0.1f;
	port_range_hints[INPUT].HintDescriptor = 0;
	port_range_hints[OUTPUT].HintDescriptor = 0;
	mono_descriptor->instantiate = instantiate_Limiter;
	mono_descriptor->connect_port = connect_port_Limiter;
	mono_descriptor->activate = activate_Limiter;
	mono_descriptor->run = run_Limiter;
	mono_descriptor->run_adding = run_adding_Limiter;
	mono_descriptor->set_run_adding_gain = set_run_adding_gain_Limiter;
	mono_descriptor->deactivate = NULL;
	mono_descriptor->cleanup = cleanup_Limiter;
}

void
delete_descriptor(LADSPA_Descriptor * descriptor) {
	unsigned long index;
	if (descriptor) {
		free((char *)descriptor->Label);
		free((char *)descriptor->Name);
		free((char *)descriptor->Maker);
		free((char *)descriptor->Copyright);
		free((LADSPA_PortDescriptor *)descriptor->PortDescriptors);
		for (index = 0; index < descriptor->PortCount; index++)
			free((char *)(descriptor->PortNames[index]));
		free((char **)descriptor->PortNames);
		free((LADSPA_PortRangeHint *)descriptor->PortRangeHints);
		free(descriptor);
	}
}

/* __attribute__((destructor)) tap_fini() is called automatically when the library is unloaded. */
void
__attribute__((destructor)) tap_fini() {
	delete_descriptor(mono_descriptor);
}

/* Return a descriptor of the requested plugin type. */
const LADSPA_Descriptor *
ladspa_descriptor(unsigned long Index) {

	switch (Index) {
	case 0:
		return mono_descriptor;
	default:
		return NULL;
	}
}


text:
<?php

namespace Google\Service\Contentwarehouse;

class VideoYoutubeCommentsClassificationProtoYouTubeCommentSmartReply extends \Google\Collection
{
  protected $collection_key = 'smartSuggestions';
  protected $smartSuggestionsType = VideoYoutubeCommentsClassificationProtoSmartSuggestion::class;
  protected $smartSuggestionsDataType = 'array';
  /**
   * @var string
   */
  public $suggestionListIdentifier;

  /**
   * @param VideoYoutubeCommentsClassificationProtoSmartSuggestion[]
   */
  public function setSmartSuggestions($smartSuggestions)
  {
    $this->smartSuggestions = $smartSuggestions;
  }
  /**
   * @return VideoYoutubeCommentsClassificationProtoSmartSuggestion[]
   */
  public function getSmartSuggestions()
  {
    return $this->smartSuggestions;
  }
  /**
   * @param string
   */
  public function setSuggestionListIdentifier($suggestionListIdentifier)
  {
    $this->suggestionListIdentifier = $suggestionListIdentifier;
  }
  /**
   * @return string
   */
  public function getSuggestionListIdentifier()
  {
    return $this->suggestionListIdentifier;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(VideoYoutubeCommentsClassificationProtoYouTubeCommentSmartReply::class, 'Google_Service_Contentwarehouse_VideoYoutubeCommentsClassificationProtoYouTubeCommentSmartReply');


text:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}

body {
  box-sizing: border-box;
  font-family: sans-serif;
  overflow: hidden;
  height: 100vh;
}

ol, ul {
  list-style: none;
}

blockquote, q {
  quotes: none;
}

blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

button {
  background: transparent;
  border: none;
}

.Bottom {
  position: fixed;
  bottom: 0;
  height: 80px;
  width: 100%;
  font-size: 0;
  z-index: 30;
}

.Bottom-context {
  display: inline-block;
  width: 50%;
  background-color: black;
  height: 100%;
}

.Bottom-context.active {
  background-color: rgba(0, 0, 0, 0.7);
}

.Bottom-context--tag {
  background-image: url("/static/img/tag.png");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 50px;
}

.Bottom-context--tag.active {
  background-image: url("/static/img/tag_selected.png");
}

.Bottom-context--play {
  background-image: url("/static/img/play.png");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 50px;
}

.Bottom-context--play.active {
  background-image: url("/img/play_selected.png");
}

.Map {
  height: 100vh;
  position: relative;
}

.Map-poi {
  position: absolute;
}

.Map-poi img {
  width: 50px;
}

.Map-poi--play {
  left: 130px;
  top: 200px;
  display: none;
}

.Map-poi--tag {
  left: 160px;
  top: 250px;
}

.Map-actions {
  position: fixed;
  top: 80px;
  right: 15px;
  z-index: 12;
}

.Map-action {
  display: block;
  background: transparent;
  border: none;
  margin-bottom: 10px;
}

.Map-action--roaming {
  width: 57px;
  height: 50px;
  background-image: url("/static/img/roaming.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 50px;
}

.Map-action--roaming.active {
  background-image: url("/static/img/roaming_selected.png");
}

.Menu {
  position: fixed;
  width: 100%;
  z-index: 30;
}

.Menu-logo {
  background-color: black;
  padding: 15px 0;
  text-align: center;
}

.Menu-logo svg {
  width: 80px;
  height: 22px;
}

.Menu-gradient {
  height: 3px;
  background-image: -moz-linear-gradient(0deg, cyan 0%, yellow 100%);
  background-image: -webkit-linear-gradient(0deg, cyan 0%, yellow 100%);
  background-image: -ms-linear-gradient(0deg, cyan 0%, yellow 100%);
}

.Overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  bottom: 80px;
  z-index: 5;
  background-color: rgba(0, 0, 0, 0.7);
}

.Player {
  position: fixed;
  bottom: 80px;
  width: 100%;
  background: rgba(0, 0, 0, 0.7);
  z-index: 10;
  color: white;
  font-size: 16px;
  text-align: center;
  display: none;
}

.Player-informations {
  padding: 10px;
}

.Player-controls {
  position: relative;
}

.Player-bar {
  background-image: url("/static/img/bar.jpg");
  background-repeat: repeat-x;
  background-position: center center;
  padding: 10px 0;
  width: 60%;
  margin: 0 auto 10px auto;
  position: relative;
}

.Player-position {
  width: 20px;
}

.Player-pause {
  position: absolute;
  left: 30px;
  bottom: 15px;
  background-image: url("/static/img/pause.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 10px;
  height: 15px;
  width: 15px;
}

.Player-play {
  position: absolute;
  left: 30px;
  bottom: 15px;
  background-image: url("/static/img/unpause.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 10px;
  height: 15px;
  width: 15px;
}

.Player-time {
  position: absolute;
  right: 20px;
  bottom: 15px;
}

.Player.active {
  display: block;
}

.Search {
  z-index: 15;
  overflow-y: scroll;
  height: 100%;
  position: absolute;
  width: 100%;
  display: none;
}

.Search-first {
  position: relative;
  top: 40%;
  z-index: 15;
  text-align: center;
  display: none;
}

.Search-input {
  border: none;
  height: 40px;
  border-bottom: 2px solid white;
  display: block;
  width: 70%;
  margin: 0 auto;
  background: transparent;
  font-size: 16px;
  color: white;
}

.Search-submit {
  background-image: url("/static/img/submit.png");
  background-repeat: no-repeat;
  background-size: 70px;
  background-position: center;
  height: 70px;
  width: 70px;
  margin-top: 80px;
}

.Search-submit.active {
  background-image: url("/static/img/submit_ok.png");
}

.Search-results {
  display: none;
  position: relative;
  z-index: 15;
  padding: 20px;
  top: 120px;
}

.Search-results a {
  color: white;
  text-decoration: none;
}

.Search-item {
  border-top: 1px solid white;
  margin-bottom: 10px;
  padding-top: 10px;
  position: relative;
  color: white;
}

.Search-item a {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.Search-artist {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 2px;
}

.Search-track {
  font-size: 14px;
}

.Search-choice {
  position: relative;
  z-index: 15;
  padding: 20px;
  top: 80px;
  color: white;
  text-align: center;
  display: none;
}

.Search-cover {
  width: 130px;
  height: 130px;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  margin: 0 auto 30px auto;
}

.Search-artistChoice {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.Search-trackChoice {
  font-size: 16px;
  margin-bottom: 10px;
}

.Search-time {
  font-size: 14px;
}

.Search-choose {
  background-image: url("/static/img/choose.png");
  background-repeat: no-repeat;
  background-size: 70px;
  background-position: center;
  height: 70px;
  width: 70px;
  margin-top: 30px;
}

.Search-overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 58px;
  bottom: 80px;
  z-index: 5;
  background-color: rgba(0, 0, 0, 0.9);
  display: none;
}

.Search-close {
  position: absolute;
  z-index: 30;
  top: 20px;
  right: 20px;
}

.Search-close img {
  width: 40px;
}

.Search.visible, .Search-overlay.visible, .Search-first.visible, .Search-results.visible, .Search-choice.visible {
  display: block;
}

.Splash {
  height: 100vh;
  background-color: black;
  background-image: url("/static/img/bg.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 250px;
  position: relative;
}

.Splash-logo {
  margin: 0 auto 0 auto;
  padding: 40px 0 0 0;
  width: 270px;
  text-align: center;
}

.Splash-logo img {
  width: 100%;
}

.Splash-informations {
  position: absolute;
  bottom: 30px;
  color: white;
  padding: 0 20px;
  font-size: 12px;
  width: 100%;
  text-transform: uppercase;
  letter-spacing: 3px;
}

.Splash-bottom {
  display: inline-block;
  width: 44%;
}

.Splash-bottom--credits {
  text-align: right;
}

.Loading-Infos {
  color: #fff;
  text-align: center;
  padding-top: 5%;
  text-transform: uppercase;
  font-size: 100%;
  font: inherit;
}


text:
[redhat]
#krb5 settings
krbprefix=/usr/kerberos
klistpath:%(krbprefix)s/bin/klist
kinitpath:%(krbprefix)s/bin/kinit
kdestroypath:%(krbprefix)s/bin/kdestroy
kadminPath:%(krbprefix)s/sbin/kadmin
plugin_authen:krb5_apache
ldapservers:ldap.example.com
cachedir=/tmp/


text:
#ifndef _LLC_H
#define _LLC_H

#pragma warning(push)
#pragma warning(disable:4214) // nonstandard extension used : bit field types other than int
#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union

#pragma pack(push, 1)

// LLC data structures
//
// NOTE: Fields are in network byte order

typedef struct _LLC_U_HEADER {
    UCHAR   DestinationSAP;
    UCHAR   SourceSAP;
    UCHAR   Control;
} LLC_U_HEADER, *PLLC_U_HEADER;

#define LLC_SAP_MASK (~(UCHAR)1)
#define LLC_U_FRAME 0x03

typedef struct _LLC_SNAP_HEADER {
    UCHAR   DestinationSAP;
    UCHAR   SourceSAP;
    UCHAR   Control;
    UCHAR   OUI[3];
    USHORT  Type;
} LLC_SNAP_HEADER, *PLLC_SNAP_HEADER;

#define SNAPTYPE_IPX    0x8137
#define SNAPTYPE_IPV4   ETHERTYPE_IPV4
#define SNAPTYPE_IPV6   ETHERTYPE_IPV6

#pragma pack(pop)

#pragma warning(pop)

#endif  //_LLC_H


text:
import os, sys, struct, glob

def peek(f, size = 1):
    pos = f.tell()
    data = f.read(size)
    f.seek(pos)
    return data

class CompressionMode:
    RLE = 'RLE'
    XYV = 'XYV'
    NoCompression = 'No Compression'
    Unknown = 'Unknown'

class LUCIDFile:
    def __init__(self):
        self.clear()

    def clear(self):
        self.chipActive = [False, False, False, False, False]
        self.startTime = 0
        self.fileID = ''
        self.shutterRate = 0
        self.isCompressed = False
        self.isLinearLUT = False
        self.compressionMode = CompressionMode.Unknown

    def getIsChipActive(self, chipNumber):
        return self.chipActive[chipNumber]

    def setIsChipActive(self, chipNumber, value):
        self.chipActive[chipNumber] = value

    def getStartTime(self):
        return self.startTime

    def setStartTime(self, value):
        self.startTime = value

    def getFileID(self):
        return self.fileID

    def setFileID(self, value):
        self.fileID = value

    def getShutterRate(self):
        return self.shutterRate

    def setShutterRate(self, value):
        self.shutterRate = value

    def getIsCompressed(self):
        return self.isCompressed

    def setIsCompressed(self, value):
        self.isCompressed = value

    def getIsLinearLUT(self):
        return self.isLinearLUT

    def setIsLinearLUT(self, value):
        self.isLinearLUT = value

    def getCompressionMode(self):
        return self.compressionMode

    def setCompressionMode(self, value):
        self.compressionMode = value

    def convert(self, fileName, outputPath):
        # -Header Format:-
        # First 2 bytes are header magic - 0xDC 0xCC
        # 1 byte - Matrix table bits [1:0] and a bit field of the active
        # channel
        # 1 byte - Matrix table bits [9:2]
        # 2 bytes - Shutter mode
        # 1 byte - compression bitfield
        # 1 byte - shutter rate
        # 4 bytes - start time
        # 4 bytes - file ID

        # -Frame Format:-
        # Start of Frame demarker
        # Control data word w/ timestamp
        # and multiple of the following until the next time stamp:
        # Control data word w/ channel marker, 5 bit bitfield indexing from 0 at 2nd
        # byte
        # Data payload
        # Pixels are stored in 256 word rows from bottom left pixel to top right

        # -Word Format:-
        # 16-bit words, first 1/2 bits are flag bits, options are:
        # 0  - Number of zeroes
        # 10 - Payload data
        # 11 - Control data - Start of frame data characters etc.
        self.clear()

        input = open(fileName, 'rb')
        fileSize = os.path.getsize(fileName)

        output = open(outputPath + os.path.splitext(os.path.basename(fileName))[0] + '.lane', 'wb')

        # Check for valid header
        current = input.read(2)
        if (ord(current[0]) == 0xDC and ord(current[1]) == 0xCC):
            # Channel
            # The active detectors are flagged using a bit field.
            # This is only the last 5 bits of the byte.
            # 1F would translate to 00011111
            # This would mean all 5 detectors are taking data for this run.
            # I do not know which way round the bit field is
            # so whether TPX0 is bit 3 or bit 7 is unknown as of yet
            current = input.read(1)
            for i in range(0, 5):
                self.chipActive[i] = True if ((ord(current) >> i) & 0x01) == 0x01 else False;

            current = input.read(3) # skip 3 bytes

            # Compression
            # Type of compression
            # 0 - RLE
            # 1 - XYV
            current = input.read(1)
            temp = ((ord(current) >> 2) & 0x01)
            if temp == 0x00:
                self.compressionMode = CompressionMode.RLE
            elif temp == 0x01:
                self.compressionMode = CompressionMode.XYV
            else:
                self.compressionMode = CompressionMode.Unknown
            # Type of LUT used
            # 0 - PRN
            # 1 - Linear
            self.isLinearLUT = True if ((ord(current) >> 1) & 0x01) == 0x01 else False;
            # Data compression enabled?
            # 0 - Off
            # 1 - On
            self.isCompressed = True if (ord(current) & 0x01) == 0x01 else False;
            if not self.isCompressed:
                self.compressionMode = CompressionMode.NoCompression

            # Shutter Rate
            current = input.read(1)
            self.shutterRate = current

            # Start Time
            current = input.read(4)
            self.startTime = struct.unpack('>I', current[0:4])[0]

            # File ID
            current = input.read(4)
            for i in range(0, 4):
                self.fileID += chr(ord(current[i]))
                self.fileID = self.fileID[::-1]

            print 'Found valid header!'

        else:
            print 'Unable to find a valid header, assuming defaults...'
            self.compressionMode = CompressionMode.Unknown
            self.isCompressed = False
            self.isLinearLUT = False
            self.startTime = 0
            self.fileID = '????'
            for i in range(0, 5):
                self.chipActive[i] = True # Assume all chips are active

            # Scan forward for first valid frame denotation
            input.seek(0)
            headerFound = False
            while not headerFound:
                if ord(peek(input, 2)[0]) == 0xDC and ord(peek(input, 2)[1]) == 0xDF:
                    headerFound = True
                else:
                    input.read(1)

        print 'Compression mode: ', self.compressionMode
        print 'Compressed? ', 'True' if (self.isCompressed) else 'False'
        print 'Linear LUT? ', 'True' if (self.isLinearLUT) else 'False'
        print 'Start Time: ', self.startTime
        print 'Config ID: ', self.fileID
        print 'Active Chips: '
        for i in range(0, 5):
            print 'Chip ', i, ' is ', 'active' if (self.chipActive[i]) else 'inactive'

        output.write(self.fileID + ',' + str(self.startTime) + '\n')

        # Parse main body
        # Read in frames
        isFindingFrames = True
        while isFindingFrames:
            # Check for frames demarkers
            current = input.read(2)
            if not (ord(current[0]) == 0xDC and ord(current[1]) == 0xDF):
                raise Exception('Expected frame header, Position = ' + str(input.tell()))

            # Get timestamp - 4 byte UNIX time, 1 byte sub second time
            current = input.read(4)
            frameTime = int(struct.unpack('>I', current)[0])
            current = input.read(1)
            frameTimeSub = int(ord(current))

            isFindingChannelData = True
            while isFindingChannelData:
                # Get channel
                current = input.read(1)
                channel = 5
                if (ord(current) >> 6) == 0x03:
                    if (ord(current) & 0x01) == 0x01:
                        channel = 0
                    elif ((ord(current) & 0x02) >> 1) == 0x01:
                        channel = 1
                    elif ((ord(current) & 0x04) >> 2) == 0x01:
                        channel = 2
                    elif ((ord(current) & 0x08) >> 3) == 0x01:
                        channel = 3
                    elif ((ord(current) & 0x16) >> 4) == 0x01:
                        channel = 4
                else:
                    raise Exception("Expected channel control word, Position = " + str(input.tell()))

                output.write(str(channel) + '\n')
                output.write(str(frameTime) + '.' + str(frameTimeSub) + '\n')

                # Xs and Ys starting from the bottom left of the pixel grid
                x = 0
                y = 0
                # Get data until next control word (channel marker or frame demarking)
                isFindingData = True
                while isFindingData:
                    # Check if this is the last word, and stop reading after this iteration if so
                    currentPos = input.tell()
                    current = peek(input, 2)
                    if currentPos + 2 >= fileSize:
                        isFindingData = False;
                        isFindingChannelData = False;
                        isFindingFrames = False;
                    # Check the next word for a new frame demarker
                    elif ord(current[0]) == 0xDC and ord(current[1]) == 0xDF:
                        isFindingData = False
                        isFindingChannelData = False
                    # Check for a channel marker
                    elif (ord(current[0]) >> 6) == 0x03:
                        isFindingData = False

                    # Get actual data
                    current = peek(input, 1)
                    if (ord(current) >> 6) == 0x02:
                        # Payload data (10-)
                        current = input.read(2)
                        payload = int(struct.unpack('>H', current[0:2])[0])
                        payload = payload & 32767;

                        if payload > 0:
                            output.write(str(x) + ',' + str(y) + ',' + str(payload) + '\n')

                        if x == 255:
                            x = 0
                            y += 1
                        else:
                            x += 1

                    elif (ord(current) >> 7) == 0x00:
                        # Number of zeroes (0-)
                        current = input.read(2)
                        numberOfZeroes = ord(struct.unpack('>H', current[0:2])[0])
                        for i in range(0, numberOfZeroes):
                            currentFrame.setPixel(pixel)
                            output.write(str(x) + ',' + str(y) + ',' + str(payload) + '\n')
                            if x == 255:
                                x = 0
                                y += 1
                            else:
                                x += 1

                output.write('EOF\n')
            output.write('EOC\n')

def lucidFileToLane(input, outputPath):
    lf = LUCIDFile()
    lf.convert(input, outputPath)
    return

def listFiles(directory, extension = ''):
    """Gets a list of files from a given directory of a given extension

    :directory: The directory to search
    :extension: The extension of the files to find. If extension is left empty,
    grabs every file in a directory
    :returns: A list of absolute file path strings

    """
    absDirectory = os.path.abspath(directory)
    if extension == '':
        globString = os.path.join(absDirectory, '*')
    else:
        globString = os.path.join(absDirectory, '*.' + extension)
    fileList = []

    for f in glob.glob(globString):
        fileList.append(f)

    return fileList

if __name__ == '__main__':
    if len(sys.argv) != 6:
        print "USAGE: %s input-dir output-dir masks-dir calibrations-dir configurations-dir" % (str(sys.argv[0]))
        sys.exit(1)

    fileTypes = {'ldat':lucidFileToLane}

    for ext, converter in fileTypes.iteritems():
        print 'Converting', ext, 'files...'
        for p in listFiles(sys.argv[1], ext):
            isConverted = False
            for q in listFiles(sys.argv[2], 'lane'):
                if os.path.splitext(os.path.basename(p))[0] == os.path.splitext(os.path.basename(q))[0]:
                    isConverted = True
            if not isConverted:
                print p
                print "Converting ", p
                converter(p, sys.argv[2])


text:
Minikube uses Docker Machine to manage the Kubernetes VM so it benefits from the
driver plugin architecture that Docker Machine uses to provide a consistent way to
manage various VM providers. Minikube embeds VirtualBox and VMware Fusion drivers
so there are no additional steps to use them. However, other drivers require an
extra binary to be present in the host PATH.

The following drivers currently require driver plugin binaries to be present in
the host PATH:

* [KVM](#kvm-driver)
* [xhyve](#xhyve-driver)
* [HyperV](#HyperV-driver)

#### KVM driver

Minikube is currently tested against [`docker-machine-driver-kvm` v0.10.0](https://github.com/dhiltgen/docker-machine-kvm/releases).

After following the instructions on the KVM driver releases page, you need to make sure that have the necessary packages and permissions by following these instructions:
```

# Install libvirt and qemu-kvm on your system, e.g.
# Debian/Ubuntu
$ sudo apt install libvirt-bin qemu-kvm
# Fedora/CentOS/RHEL
$ sudo yum install libvirt-daemon-kvm kvm

# Add yourself to the libvirtd group (use libvirt group for rpm based distros) so you don't need to sudo
# Debian/Ubuntu
$ sudo usermod -a -G libvirtd $(whoami)
# Fedora/CentOS/RHEL
$ sudo usermod -a -G libvirt $(whoami)

# Update your current session for the group change to take effect
# Debian/Ubuntu
$ newgrp libvirtd
# Fedora/CentOS/RHEL
$ newgrp libvirt
```

#### xhyve driver

From https://github.com/zchee/docker-machine-driver-xhyve#install:

```
$ brew install docker-machine-driver-xhyve

# docker-machine-driver-xhyve need root owner and uid
$ sudo chown root:wheel $(brew --prefix)/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
$ sudo chmod u+s $(brew --prefix)/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
```

#### HyperV driver

Hyper-v users may need to create a new external network switch as described [here](https://docs.docker.com/machine/drivers/hyper-v/). This step may prevent a problem in which `minikube start` hangs indefinitely, unable to ssh into the minikube virtual machine. In this add, add the `--hyperv-virtual-switch=switch-name` argument to the `minikube start` command.


text:
require 'beaker-rspec/spec_helper'
require 'beaker-rspec/helpers/serverspec'

unless ENV['RS_PROVISION'] == 'no' || ENV['BEAKER_provision'] == 'no'
  hosts.each do |host|
    foss_opts = { default_action: 'gem_install' }
    install_puppet(foss_opts)
    on host, "mkdir -p #{host['distmoduledir']}"
    on host, "sed -i '/templatedir/d' #{host['puppetpath']}/puppet.conf"
  end
end

UNSUPPORTED_PLATFORMS = %w[AIX windows Solaris].freeze

RSpec.configure do |c|
  # Project root
  proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))

  # Readable test descriptions
  c.formatter = :documentation

  # Configure all nodes in nodeset
  c.before :suite do
    # Install module
    puppet_module_install(
      source: proj_root,
      module_name: 'confluence',
      ignore_list: %w[spec/fixtures/* .git/* .vagrant/*]
    )
    hosts.each do |host|
      on host, "/bin/touch #{default['puppetpath']}/hiera.yaml"
      on host, 'chmod 755 /root'
      if fact('osfamily') == 'Debian'
        on host, "echo \"en_US ISO-8859-1\nen_NG.UTF-8 UTF-8\nen_US.UTF-8 UTF-8\n\" > /etc/locale.gen"
        on host, '/usr/sbin/locale-gen'
        on host, '/usr/sbin/update-locale'
      end
      on host, puppet('module', 'install', 'puppet-archive'), acceptable_exit_codes: [0, 1]
      on host, puppet('module', 'install', 'puppetlabs-java'), acceptable_exit_codes: [0, 1]
      on host, puppet('module', 'install', 'puppetlabs-postgresql'), acceptable_exit_codes: [0, 1]
      on host, puppet('module', 'install', 'puppet-staging'), acceptable_exit_codes: [0, 1]
      on host, puppet('module', 'install', 'puppetlabs-stdlib'), acceptable_exit_codes: [0, 1]
    end
  end
end


text:
package com.yoghurt.crypto.transactions.client.widget;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.yoghurt.crypto.transactions.client.place.BlockPlaceRouter;

/**
 * TODO Needs some attention. Because meh.
 */
public class BlockViewer extends ValueViewer {
  private final ClickHandler mouseClickHandler = new ClickHandler() {
    @Override
    public void onClick(final ClickEvent event) {
      if (blockHash != null) {
        router.goToBlock(blockHash);
      } else {
        router.goToBlock(blockHeight);
      }
    }
  };

  private final BlockPlaceRouter router;

  private int blockHeight;
  private String blockHash;

  public BlockViewer(final BlockPlaceRouter router) {
    super("View this block.");

    this.router = router;

    setMouseClickHandler(mouseClickHandler);
  }

  public void setValue(final int blockHeight) {
    this.blockHeight = blockHeight;

    super.setValue(blockHeight);
  }

  @Override
  public void setValue(final String blockHash) {
    this.blockHash = blockHash;

    super.setValue(blockHash);
  }
}


text:
package net.i2p.itoopie.i2pcontrol;

public class InvalidI2PControlAPI extends Exception {

	private static final long serialVersionUID = -8120904521634957457L;

	public InvalidI2PControlAPI(String msg){
		super(msg);
	}

}


text:
package com.cvent.dropwizard.mybatis.typehandlers;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.function.Function;

import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * URI type handler
 */
@MappedTypes(URI.class)
public class URITypeHandler extends AbstractTypeHandler<URI> {

    private static final Logger LOG = LoggerFactory.getLogger(URITypeHandler.class);

    public URITypeHandler() {
        this(URITypeHandler::toURI, null);
    }

    protected URITypeHandler(Function<String, URI> format, URI nullValue) {
        super(format, nullValue);
    }

    private static URI toURI(String value) {
        try {
            return new URI(value);
        } catch (URISyntaxException e) {
            LOG.error("URI transformation fail for: " + value, e);
        }
        return null;
    }

}


text:
namespace
{

template< typename ValueType >
Gaffer::ConstValuePlugPtr createNumericPlug(
	const std::string& name, const Gaffer::Plug::Direction direction, const ValueType& value, const unsigned flags )
{
	const Gaffer::ConstValuePlugPtr plug( new Gaffer::NumericPlug< ValueType >( name, direction, value,
		ValueType( Imath::limits< ValueType >::min() ),
		ValueType( Imath::limits< ValueType >::max() ), flags ) );
	return plug;
}

template< typename ValueType >
Gaffer::ConstValuePlugPtr createCompoundNumericPlug(
	const std::string& name, const Gaffer::Plug::Direction direction, const ValueType& value, const unsigned flags )
{
	const Gaffer::ConstValuePlugPtr plug( new Gaffer::CompoundNumericPlug< ValueType >( name, direction, value,
		ValueType( Imath::limits< typename ValueType::BaseType >::min() ),
		ValueType( Imath::limits< typename ValueType::BaseType >::max() ), flags ) );
	return plug;
}

template< typename ValueType >
Gaffer::ConstValuePlugPtr createBoxPlug(
	const std::string& name, const Gaffer::Plug::Direction direction, const Imath::Box< ValueType >& value, const unsigned flags )
{
	const Gaffer::ConstValuePlugPtr plug( new Gaffer::BoxPlug< Imath::Box< ValueType > >( name, direction, value,
		ValueType( Imath::limits< typename ValueType::BaseType >::min() ),
		ValueType( Imath::limits< typename ValueType::BaseType >::max() ), flags ) );
	return plug;
}

template< typename ValueType >
Gaffer::ConstValuePlugPtr createVectorDataPlug(
	const std::string& name, const Gaffer::Plug::Direction direction, const IECore::TypedData< std::vector< ValueType > >* value, const unsigned flags )
{
	const Gaffer::ConstValuePlugPtr plug( new Gaffer::TypedObjectPlug< IECore::TypedData< std::vector< ValueType > > >( name, direction, value, flags ) );
	return plug;
}

struct MenuItem
{
	explicit
	MenuItem( const std::string& name, Gaffer::ConstValuePlugPtr plug = Gaffer::ConstValuePlugPtr() )
	: m_name( name )
	, m_plug( plug )
	{}

	const std::string& getName() const
	{
		return m_name;
	}

	const Gaffer::ValuePlug* getPlug() const
	{
		return m_plug.get();
	}

private:

	std::string m_name;
	Gaffer::ConstValuePlugPtr m_plug;
};

using MenuItemContainer = boost::multi_index_container<
	MenuItem,
	boost::multi_index::indexed_by<
		boost::multi_index::random_access<>,
		boost::multi_index::ordered_non_unique<
			boost::multi_index::const_mem_fun<MenuItem, const std::string&, & MenuItem::getName>
		>
	>
>;

struct PlugAdder : GafferUI::PlugAdder
{
	explicit PlugAdder( GafferScene::AttributeQuery& query )
	: GafferUI::PlugAdder()
	, m_query( & query )
	{
		m_query->childAddedSignal().connect( boost::bind( & PlugAdder::updateVisibility, this ) );
		m_query->childRemovedSignal().connect( boost::bind( & PlugAdder::updateVisibility, this ) );

		buttonReleaseSignal().connect( boost::bind( & PlugAdder::buttonRelease, this, ::_2 ) );

		updateVisibility();
	}

	~PlugAdder() override
	{}

protected:

	bool canCreateConnection( const Gaffer::Plug* plug ) const override
	{
		assert( m_query );

		return (
			( GafferUI::PlugAdder::canCreateConnection( plug ) ) &&
			( plug->direction() == Gaffer::Plug::In ) &&
			( plug->node() != m_query ) &&
			( m_query->canSetup( IECore::runTimeCast< const Gaffer::ValuePlug >( plug ) ) ) );
	}

	void createConnection( Gaffer::Plug* plug ) override
	{
		assert( plug->direction() == Gaffer::Plug::In );

		m_query->setup( IECore::assertedStaticCast< const Gaffer::ValuePlug >( plug ) );

		plug->setInput( m_query->valuePlug() );
	}

private:

	bool buttonRelease( const GafferUI::ButtonEvent& event )
	{
		return GafferSceneUI::AttributeQueryUI::showSetupMenu( *m_query );
	}

	void updateVisibility()
	{
		setVisible( !( m_query->isSetup() ) );
	}

	GafferScene::AttributeQueryPtr m_query;
};

struct Registration
{
	Registration()
	{
		GafferUI::NoduleLayout::registerCustomGadget( "GafferSceneUI.AttributeQueryUI.PlugAdder", & Registration::create );
	}

	static GafferUI::GadgetPtr create( Gaffer::GraphComponentPtr parent )
	{
		const GafferScene::AttributeQueryPtr query = IECore::runTimeCast< GafferScene::AttributeQuery >( parent );

		if( ! query )
		{
			throw IECore::Exception( "AttributeQueryUI.PlugAdder requires an AttributeQuery" );
		}

		const GafferUI::GadgetPtr gadget( new PlugAdder( *query ) );
		return gadget;
	}
};

Registration m_registration;

} // namespace

namespace GafferSceneUI
{
namespace AttributeQueryUI
{

bool showSetupMenu( GafferScene::AttributeQuery& query )
{
	static MenuItemContainer items;
	static std::vector< std::string > names;
	static const std::string title( "Plug type" );

	if( items.empty() )
	{
		const std::string name( "value" );
		const Gaffer::Plug::Direction direction = Gaffer::Plug::In;
		const unsigned flags = Gaffer::Plug::Flags::Default | Gaffer::Plug::Flags::Dynamic;

		items.push_back( MenuItem( "Bool", new Gaffer::BoolPlug( name, direction, false, flags ) ) );
		items.push_back( MenuItem( "Float", createNumericPlug( name, direction, 0.f, flags ) ) );
		items.push_back( MenuItem( "Int", createNumericPlug( name, direction, 0, flags ) ) );
		items.push_back( MenuItem( "" ) );
		items.push_back( MenuItem( "String", new Gaffer::StringPlug( name, direction, "", flags ) ) );
		items.push_back( MenuItem( "" ) );
		items.push_back( MenuItem( "V2i", createCompoundNumericPlug( name, direction, Imath::V2i( 0 ), flags ) ) );
		items.push_back( MenuItem( "V2f", createCompoundNumericPlug( name, direction, Imath::V2f( 0 ), flags ) ) );
		items.push_back( MenuItem( "V3i", createCompoundNumericPlug( name, direction, Imath::V3i( 0 ), flags ) ) );
		items.push_back( MenuItem( "V3f", createCompoundNumericPlug( name, direction, Imath::V3f( 0 ), flags ) ) );
		items.push_back( MenuItem( "" ) );
		items.push_back( MenuItem( "Color3f", createCompoundNumericPlug( name, direction, Imath::Color3f( 0 ), flags ) ) );
		items.push_back( MenuItem( "Color4f", createCompoundNumericPlug( name, direction, Imath::Color4f( 0 ), flags ) ) );
		items.push_back( MenuItem( "" ) );
		items.push_back( MenuItem( "Box2i", createBoxPlug( name, direction, Imath::Box2i( Imath::V2i( 0 ) ), flags ) ) );
		items.push_back( MenuItem( "Box2f", createBoxPlug( name, direction, Imath::Box2f( Imath::V2f( 0.f ) ), flags ) ) );
		items.push_back( MenuItem( "Box3i", createBoxPlug( name, direction, Imath::Box3i( Imath::V3i( 0 ) ), flags ) ) );
		items.push_back( MenuItem( "Box3f", createBoxPlug( name, direction, Imath::Box3f( Imath::V3f( 0.f ) ), flags ) ) );
		items.push_back( MenuItem( "" ) );
		items.push_back( MenuItem( "Object", new Gaffer::ObjectPlug( name, direction, IECore::NullObject::defaultNullObject(), flags ) ) );
		items.push_back( MenuItem( "" ) );
		items.push_back( MenuItem( "Array/Bool", createVectorDataPlug( name, direction, new IECore::BoolVectorData(), flags ) ) );
		items.push_back( MenuItem( "Array/Float", createVectorDataPlug( name, direction, new IECore::FloatVectorData(), flags ) ) );
		items.push_back( MenuItem( "Array/Int", createVectorDataPlug( name, direction, new IECore::IntVectorData(), flags ) ) );
		items.push_back( MenuItem( "Array/" ) );
		items.push_back( MenuItem( "Array/String", createVectorDataPlug( name, direction, new IECore::StringVectorData(), flags ) ) );
	}

	if( names.empty() )
	{
		const MenuItemContainer::nth_index< 0 >::type& index = items.get< 0 >();
		std::transform( index.begin(), index.end(), std::back_inserter( names ), std::mem_fn( & MenuItem::getName ) );
	}

	if( query.isSetup() )
	{
		return false;
	}

	const std::string name = GafferUI::PlugAdder::menuSignal()( title, names );

	if( name.empty() )
	{
		return false;
	}

	const MenuItemContainer::nth_index< 1 >::type& index = items.get< 1 >();
	const MenuItemContainer::nth_index< 1 >::type::iterator it = index.find( name );

	if( it == index.end() )
	{
		return false;
	}

	{
		Gaffer::UndoScope undoScope( query.ancestor< Gaffer::ScriptNode >() );
		query.setup( ( *it ).getPlug() );
	}

	return true;
}

} // AttributeQueryUI
} // GafferSceneUI


text:
module Sinatra
  module EasyBreadcrumbs
    Breadcrumbs = ::EasyBreadcrumbs::Breadcrumbs

    def easy_breadcrumbs
      Breadcrumbs.new(config).to_html
    end

    private

    EXCLUDED_VARS = [:@default_layout, :@preferred_extension,
                     :@app, :@template_cache, :@template_cache,
                     :@env, :@request, :@response, :@params]

    Configuration = Struct.new(:request_path, :route_matchers, :view_variables)

    def config
      # The name of the current Sinatra Application
      app = self.class

      # The Rack::Request object
      request_path = request.path

      # All defined GET request routes
      route_matchers = app.routes['GET'].map { |route| route[0] }

      Configuration.new(request_path, route_matchers, view_variables)
    end

    # All user defined instance variables for current request.
    def view_variables
      instance_variables
        .select { |var| additional_var?(var) }
        .map { |var| fetch_ivar_value(var) }
    end

    def fetch_ivar_value(var)
      name = var.to_s.delete('@').to_sym
      value = instance_eval(var.to_s)

      { name: name, value: value }
    end

    def additional_var?(var)
      !EXCLUDED_VARS.include?(var)
    end
  end

  # Register helper with Sinatra::Application
  helpers EasyBreadcrumbs
end


text:
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NokiaMMSLibraryNet.Tests
{
    [TestFixture]
    public class Decoding_tests
    {
        [Test]
        public void Deserializes_data_correctly()
        {
            var decoder = new MultimediaMessageDecoder();
            decoder.setMessage(File.ReadAllBytes(@".\TestData\expected"));

            decoder.decodeMessage();

            var message = decoder.getMessage();

            Console.WriteLine(string.Join(Environment.NewLine, message.Date.ToString("R")));

            Assert.AreEqual("2077.1427358451410", message.TransactionId);
            Assert.AreEqual(MultimediaMessageConstants.CT_APPLICATION_MULTIPART_RELATED, message.ContentType);
            Assert.AreEqual(MultimediaMessageConstants.MESSAGE_TYPE_M_SEND_REQ, message.MessageType);
            Assert.AreEqual(new DateTime(2015, 3, 26, 9, 27, 31), message.Date);
            Assert.AreEqual(false, message.DeliveryReport);
            Assert.AreEqual("+4798682185", message.To.First().Address);
            Assert.AreEqual(MultimediaMessageConstants.ADDRESS_TYPE_PLMN, message.To.First().Type);
            Assert.AreEqual("2077", message.From.Address);
            Assert.AreEqual(MultimediaMessageConstants.ADDRESS_TYPE_PLMN, message.From.Type);
            Assert.AreEqual("Test mms", message.Subject);
            Assert.AreEqual(true, message.IncludeEncodingInSubject);
            Assert.AreEqual(MultimediaMessageConstants.SENDER_VISIBILITY_SHOW, message.SenderVisibility);
            Assert.AreEqual(MultimediaMessageConstants.MESSAGE_CLASS_PERSONAL, message.MessageClass);
            Assert.AreEqual(MultimediaMessageConstants.PRIORITY_NORMAL, message.Priority);
            Assert.AreEqual(false, message.ReadReply);

            Assert.AreEqual(4, message.NumContents);
        }
    }
}


text:
go-libapns
==========

APNS library for go

The idea here is to be a simple low level library that will handle establishing a connection and sending push notifications via Apple's apns service with thought towards throughput and performance.

Handles the latest Apple push notification guidelines at https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html

Specifically will implement the binary framed format by batching push notifications. Each batch will be flushed either every 10ms or when a frame is full. A frame is full when the framed format cannot fit anymore data into a tcp packet (65535 bytes). Due to this framing, when finished with the apns connection, one should call Disconnect() to flush any remaining messages out the door.

##Godoc
Located here [![GoDoc](https://godoc.org/github.com/joekarl/go-libapns?status.svg)](https://godoc.org/github.com/joekarl/go-libapns)

##Installation

```bash
> go get github.com/joekarl/go-libapns
```

##Basic Usage
```go
package main

import (
    apns "github.com/joekarl/go-libapns"
    "io/ioutil"
)

func main() {
  certPem, err := ioutil.ReadFile("../certs/PushTestCert.pem")
  if err != nil {
    panic(err)
  }
  keyPem, err := ioutil.ReadFile("../certs/PushTestKey-noenc.pem")
  if err != nil {
    panic(err)
  }

  apnsConnection, _ := apns.NewAPNSConnection(&APNSConfig{
      CertificateBytes: certPem,
      KeyBytes: keyPem,
  })

  payload := &apns.Payload {
      Token: "2ed202ac08ea9...cf8d55910df290567037dcc4",
      AlertText: "This is a push notification!",
  }

  apnsConnection.SendChannel <- payload
  apnsConnection.Disconnect()
}
```
**Note** This example doesn't take into account essential error handling. See below for error handling details

**Payload.Badge Need to Know** Apple specifies that one should set the badge key to 0 to clear the badge number. This unfortunately has the side effect of causing the go JSON serializer to omit the badge field. Luckily Apple uses negative badge numbers to clear the badge as well. So for our purposes, a badge > 0 will set the badge number, a badge < 0 will clear the badge number, and a badge == 0 will leave the badge number as is.

##Creating an APNS connection
Creating a connection consists of a couple of steps. They are:

* Creating a tcp socket to Apple's servers
* Initiating a TLS session using your Pem certs

There are two ways to do this using go-libapns. They are:

* NewConnection(*APNSConfig)
* SocketAPNSConnection(net.Conn, *APNSConfig)

The `NewConnection` method will validate your config, create the tcp connection, initiate a TLS session, and return a new APNSConnection. You probably will always use this way of creating a connection.

If you are on a platform that needs to create a custom socket (like Google App Engine), you can use the `SocketAPNSConnection` method. This takes a `net.Conn` (should be a tcpSocket), validates your config, initializes a TLS session, and returns a new APNSConnection.

##Pem Certs
You should provide your apns certificate as separated cert/key pem files. Currently go doesn't support password protected pem files (https://github.com/golang/go/issues/6722) so you'll need remove the password from your key pem.

####Separate pem files from p12
```sh
openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12

openssl pkcs12 -nocerts -out key.pem -in key.p12
```

####Remove password from pem file
```sh
openssl rsa -in key.pem -out key-noenc.pem
```

##Error Handling
As per Apple's guidelines, when a connection is closed due to error, the id of the message which caused the error will be transmitted back over the connection. In this case, multiple push notifications may have followed the bad message. These push notifications will be supplied on a channel **as well as any other unsent messages** and will be then available to re-process. Also when writing to the send channel, you should wrap the send with a select and case both the send and connection close channels. This will allow you to correctly handle the async nature of Apple's error handling scheme. See this gist (https://gist.github.com/joekarl/86d9bdb8f9af044710b7) for a full featured example of how to integrate go-libapns with proper shutdown handling and looped connection handling.

##Persistent Connection
go-libapns will use a persistant tcp connection (supplied by the user) to connect to Apple's APNS gateway. This allows for the greatest throughput to Apple's servers. On close or error, this connection will be killed and all unsent push notifications will be supplied for re-process. **Note** Unlike most other APNS libraries, go-libapns will NOT attempt to re-transmit your unsent payloads. Because it is trivial to write this retry logic, go-libapns leaves that to the user to implement as not everyone needs or wants this behavior (i.e. you may want to put the messages that need resent into a queue or store them for later).

##Feedback Service
Apple specifies that you should connect to the feedback service gateway regularly to keep track of devices that no longer have your application installed. go-libapns provides a simple interface to the feedback service. Simply create a `APNSFeedbackServiceConfig` object and then call `ConnectToFeedbackService`. This will return a list of device tokens that you should keep track of and not send push notifications to again (specifically this will return a List of `*FeedbackResponse`)

##Push Notification Length
Apple places a strict limit on push notification length (currently at 2048 bytes). go-libapns will attempt to fit your push notification into that size limit by first applying all of your supplied custom fields and applying as much of your alert text as possible. This truncation is not without cost as it takes almost twice the time to fix a message that is too long. So if possible, try to find a sweet spot that won't cause truncation to occur. If unable to truncate the message, go-libapns will close it's connection to the APNS gateway (you've been warned). This limit is configurable in the APNSConfig object.

_Note: Prior to iOS 8, the limit was 256 bytes. APNS will accept and deliver up to 2048 bytes to devices
running iOS 8 as well as those running on older versions of iOS._

##TCP Framing
Most APNS libraries rely on the OS Nagling to buffer data into the socket. go-libapns does not rely on Nagling but does do what it can to optimize the number of bytes sent per TCP frame. The two relevant config options that control this behavior are:

* MaxOutboundTCPFrameSize - (default TCP_FRAME_MAX) Max number of bytes to send per TCP frame
* FramingTimeout - (default 10ms) Max time between TCP flushes

TCP_NODELAY can be turned on with this setup by setting the FramingTimeout to anything less than 0 (like -1). In practice you want this buffering to occur, so best to leave defaults. If you're concerned about a (max) 10ms delay between your push notifications being sent onto the socket be aware that this is much much much shorter than the default linux Nagle timeout of 1 second.

##What's with using channels for writing to the connection?
Basically, this makes it easier to synchronize error handling and socket errors. Not sure if this is the best idea, but definitely works.

##APNSConfig
The only required fields are the CertificateBytes and KeyBytes.
The other fields all have sane defaults

```go
InFlightPayloadBufferSize       int                     //number of payloads to keep for error purposes, defaults to 10000
FramingTimeout                  int                     //number of milliseconds between frame flushes, defaults to 10ms
MaxPayloadSize                  int                     //max number of bytes allowed in payload, defaults to 2048
CertificateBytes                []byte                  //bytes for cert.pem : required
KeyBytes                        []byte                  //bytes for key.pem : required
GatewayHost                     string                  //apple gateway, defaults to "gateway.push.apple.com"
GatewayPort                     string                  //apple gateway port, defaults to "2195"
MaxOutboundTCPFrameSize         int                     //max number of bytes to frame data to, defaults to TCP_FRAME_MAX
                                                        //generally best to NOT set this and use the default
SocketTimeout                   int                     //number of seconds to wait before bailing on a socket connection, defaults to no timeout
TlsTimeout                      int                     //number of seconds to wait before bailing on a tls handshake, defaults to 5 sec
```

#License
The MIT License (MIT)

Copyright (c) 2014 Karl Kirch

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

'use strict';

var Projects = _react2['default'].createClass({
  displayName: 'Projects',

  render: function render() {
    var _this = this;

    var projectNames = Object.keys(this.props.projects).sort();

    return _react2['default'].createElement(
      'div',
      null,
      _react2['default'].createElement(
        'h1',
        null,
        'Projects'
      ),
      _react2['default'].createElement(
        'ul',
        { className: 'list-group' },
        projectNames.map(function (projectName) {
          return _react2['default'].createElement(
            'li',
            { className: _this.getProjectClasses(projectName),
              onClick: _this.onClick.bind(_this, projectName) },
            _react2['default'].createElement(
              'span',
              null,
              _this.props.projects[projectName].title
            )
          );
        })
      )
    );
  },

  getProjectClasses: function getProjectClasses(projectName) {
    var classes = 'list-item';
    if (this.props.activeProjects.indexOf(projectName) !== -1) {
      classes += ' ' + 'selected';
    }
    return classes;
  },

  onClick: function onClick(projectName) {
    var project = this.props.projects[projectName];
    this.props.onSelect(project);
  }
});

exports['default'] = Projects;
module.exports = exports['default'];


text:
namespace Boo.Lang.Compiler.Ast
{
	using System.Collections;
	using System.Runtime.Serialization;

	[System.Serializable]
	public partial class StatementModifier : Node
	{
		protected StatementModifierType _type;

		protected Expression _condition;

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		new public StatementModifier CloneNode()
		{
			return (StatementModifier)Clone();
		}

		/// <summary>
		/// <see cref="Node.CleanClone"/>
		/// </summary>
		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		new public StatementModifier CleanClone()
		{
			return (StatementModifier)base.CleanClone();
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public NodeType NodeType
		{
			get { return NodeType.StatementModifier; }
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public void Accept(IAstVisitor visitor)
		{
			visitor.OnStatementModifier(this);
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public bool Matches(Node node)
		{
			if (node == null) return false;
			if (NodeType != node.NodeType) return false;
			var other = ( StatementModifier)node;
			if (_type != other._type) return NoMatch("StatementModifier._type");
			if (!Node.Matches(_condition, other._condition)) return NoMatch("StatementModifier._condition");
			return true;
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public bool Replace(Node existing, Node newNode)
		{
			if (base.Replace(existing, newNode))
			{
				return true;
			}
			if (_condition == existing)
			{
				this.Condition = (Expression)newNode;
				return true;
			}
			return false;
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public object Clone()
		{

			StatementModifier clone = new StatementModifier();
			clone._lexicalInfo = _lexicalInfo;
			clone._endSourceLocation = _endSourceLocation;
			clone._documentation = _documentation;
			clone._isSynthetic = _isSynthetic;
			clone._entity = _entity;
			if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
			clone._type = _type;
			if (null != _condition)
			{
				clone._condition = _condition.Clone() as Expression;
				clone._condition.InitializeParent(clone);
			}
			return clone;

		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override internal void ClearTypeSystemBindings()
		{
			_annotations = null;
			_entity = null;
			if (null != _condition)
			{
				_condition.ClearTypeSystemBindings();
			}

		}

		[System.Xml.Serialization.XmlElement]
		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		public StatementModifierType Type
		{

			get { return _type; }
			set { _type = value; }

		}

		[System.Xml.Serialization.XmlElement]
		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		public Expression Condition
		{

			get { return _condition; }
			set
			{
				if (_condition != value)
				{
					_condition = value;
					if (null != _condition)
					{
						_condition.InitializeParent(this);
					}
				}
			}

		}

	}
}


text:
package org.neo4art.importer.wikipedia.parser.settlement;

import java.net.MalformedURLException;

import org.junit.Assert;
import org.junit.Test;
import org.neo4art.domain.Settlement;
import org.neo4art.importer.wikipedia.parser.settlement.WikipediaSettlementFinnishFormerInfoboxParser;

public class WikipediaSettlementFrenchComuneParisInfoboxTest {

	private static String INFOBOX ="{{Infobox French communet\n"+
			"|name = Paris \n"+
			"|latitude = 48.856667\n"+
			"|longitude = 2.350833\n"+
			"|website = [http://www.paris.fr paris.fr]\n"+
			"}}";

	@Test
	public void shoudParseSettlement() throws MalformedURLException{
		Settlement frenchComune = WikipediaSettlementFinnishFormerInfoboxParser.parse(INFOBOX);

		Assert.assertEquals("Paris", frenchComune.getName());
		Assert.assertEquals("48.856667",""+frenchComune.getCoordinate().getLatD());
		Assert.assertEquals("2.350833", ""+frenchComune.getCoordinate().getLongD());
		Assert.assertEquals("http://www.paris.fr", frenchComune.getWebsite());
		Assert.assertEquals("French communet", frenchComune.getType());
	}

}


text:
package student;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Courses")
public class Course {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="ID")
	private long courseId;

	@Column(name="Name")
	private String courseName;

	public Course() {
	}

	public Course(String courseName) {
		this.courseName = courseName;
	}

	public long getCourseId() {
		return this.courseId;
	}

	public void setCourseId(long courseId) {
		this.courseId = courseId;
	}

	public String getCourseName() {
		return this.courseName;
	}

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

}