text:
package semver

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
	"sort"
)

var inequalityTuples = []*semverInequalityTuple{
	// Absolute comparison greater-thans
	version("1.2.3").isGreaterThanVersion("1.2.2"),
	version("2.3.4").isGreaterThanVersion("1.3.4"),
	version("2.3.4").isGreaterThanVersion("2.2.4"),
	version("2.3.4").isGreaterThanVersion("2.3.4-alpha"),
	version("1.2.3").isGreaterThanVersion("1.2.2"),
	version("2.3.4").isGreaterThanVersion("1.3.4"),
	version("2.3.4").isGreaterThanVersion("2.2.4"),
	version("2.3.4").isGreaterThanVersion("2.3.4-alpha"),
	version("1.2.3").isGreaterThanVersion("1.2.2"),
	version("2.3.4").isGreaterThanVersion("2.3.3"),
	version("2.3.4-alpha.2").isGreaterThanVersion("2.3.4-alpha.1"),
	// Absolute comparison less-thans
	version("1.2.3").isLessThanVersion("2.2.3"),
	version("1.2.3").isLessThanVersion("1.3.3"),
	version("1.2.3").isLessThanVersion("1.2.4"),
	version("1.2.3-alpha").isLessThanVersion("1.2.3"),
	version("1.2.3-alpha").isLessThanVersion("1.2.3-beta"),
	version("1.2.3-beta.1").isLessThanVersion("1.2.3-beta.3"),
	version("1.2.3").isLessThanVersion("2.2.3"),
	version("1.2.3").isLessThanVersion("1.3.3"),
	version("1.2.3").isLessThanVersion("1.2.4"),
	version("1.2.3-alpha").isLessThanVersion("1.2.3"),
	version("1.2.3-alpha").isLessThanVersion("1.2.3-beta"),
	version("1.2.3-beta.1").isLessThanVersion("1.2.3-beta.3"),
	version("1.2.2").isLessThanVersion("1.2.3"),
	version("2.3.3").isLessThanVersion("2.3.4"),
	version("2.3.4-alpha.1").isLessThanVersion("2.3.4-alpha.2"),
	// Absolute comparison equal-tos
	version("1.2.2").isEqualToVersion("1.2.2"),
	version("1.2.3-beta").isEqualToVersion("1.2.3-beta"),
	version("1.2.3-beta.1").isEqualToVersion("1.2.3-beta.1"),
}

type semverInequalityTuple struct {
	expected                        int
	subject, object                 string
	compiledSubject, compiledObject SemverCandidate
}

func version(subject string) *semverInequalityTuple {
	return &semverInequalityTuple{subject: subject}
}

func (tuple *semverInequalityTuple) isGreaterThanVersion(object string) *semverInequalityTuple {
	tuple.object = object
	tuple.expected = 1
	return tuple
}

func (tuple *semverInequalityTuple) isEqualToVersion(object string) *semverInequalityTuple {
	tuple.object = object
	tuple.expected = 0
	return tuple
}

func (tuple *semverInequalityTuple) isLessThanVersion(object string) *semverInequalityTuple {
	tuple.object = object
	tuple.expected = -1
	return tuple
}

func (tuple *semverInequalityTuple) compile() {
	matches := candidateRegex.FindStringSubmatch(tuple.subject)
	if matches != nil {
		compiledSubject, err := NewSemverCandidate(
			"fakeHash",
			"fakeName",
			"fakeLabel",
			matches[1],
			matches[2],
			matches[3],
			matches[4],
			matches[5],
		)

		if err == nil {
			tuple.compiledSubject = compiledSubject
		} else {
			panic(fmt.Sprint("A test subject could not be initialized:", tuple.subject, "(", err, ")"))
		}
	} else {
		panic(fmt.Sprint("A test subject was invalid:", tuple.subject))
	}

	matches = candidateRegex.FindStringSubmatch(tuple.object)
	if matches != nil {
		compiledObject, err := NewSemverCandidate(
			"fakeHash",
			"fakeName",
			"fakeLabel",
			matches[1],
			matches[2],
			matches[3],
			matches[4],
			matches[5],
		)

		if err == nil {
			tuple.compiledObject = compiledObject
		} else {
			panic(fmt.Sprint("A test object could not be initialized:", tuple.object, "(", err, ")"))
		}
	} else {
		panic(fmt.Sprint("A test object was invalid:", tuple.object))
	}
}

func TestNewSemverCandidate(t *testing.T) {
	var (
		err       error
		candidate SemverCandidate
	)

	candidate, err = NewSemverCandidate("", "b", "", "", "", "", "", "")
	assert.NotNil(t, err, "should fail for invalid ref hash")

	candidate, err = NewSemverCandidate("a", "", "", "", "", "", "", "")
	assert.NotNil(t, err, "should fail for invalid ref name")

	candidate, err = NewSemverCandidate("a", "b", "", "1asdlkj", "", "", "", "")
	assert.NotNil(t, err, "should fail for invalid major")

	candidate, err = NewSemverCandidate("a", "b", "", "", "2", "", "", "")
	assert.NotNil(t, err, "should fail for invalid major")

	candidate, err = NewSemverCandidate("a", "b", "", "1", "uds", "", "", "")
	assert.NotNil(t, err, "should fail for invalid minor")

	candidate, err = NewSemverCandidate("a", "b", "", "1", "2", "asdjhak", "", "")
	assert.NotNil(t, err, "should fail for invalid patch")

	candidate, err = NewSemverCandidate("a", "b", "", "1", "2", "3", "whatever", "kjdahkdjsh")
	assert.NotNil(t, err, "should fail for invalid prerelease")

	candidate, err = NewSemverCandidate("a", "b", "", "1", "", "", "", "")
	assert.Nil(t, err, "should not return an error in simple cases")
	assert.Equal(t, "a", candidate.GitRefHash, "hash should match")
	assert.Equal(t, "b", candidate.GitRefName, "name should match")
	assert.Equal(t, 1, candidate.MajorVersion, "major should match")
	assert.Equal(t, 0, candidate.MinorVersion, "minor should match")
	assert.Equal(t, 0, candidate.PatchVersion, "patch should match")
	assert.Equal(t, "", candidate.PrereleaseLabel, "prerelease label should match")
	assert.Equal(t, 0, candidate.PrereleaseVersion, "prerelease version should match")
	assert.Equal(t, false, candidate.PrereleaseVersionExists, "prerelease version should not exist")

	candidate, err = NewSemverCandidate("a", "b", "", "1", "2", "3", "alpha", "4")
	assert.Nil(t, err, "should not return an error in simple cases")
	assert.Equal(t, "a", candidate.GitRefHash, "hash should match")
	assert.Equal(t, "b", candidate.GitRefName, "name should match")
	assert.Equal(t, 1, candidate.MajorVersion, "major should match")
	assert.Equal(t, 2, candidate.MinorVersion, "minor should match")
	assert.Equal(t, 3, candidate.PatchVersion, "patch should match")
	assert.Equal(t, "alpha", candidate.PrereleaseLabel, "prerelease label should match")
	assert.Equal(t, 4, candidate.PrereleaseVersion, "prerelease version should match")
	assert.Equal(t, true, candidate.PrereleaseVersionExists, "prerelease version should exist")
}

func TestSemverCandidateCompareTo(t *testing.T) {
	// Compile all the things first
	for _, tuple := range inequalityTuples {
		tuple.compile()
	}

	// Run all the tests fam
	for _, tuple := range inequalityTuples {
		assert.Equal(
			t,
			tuple.expected,
			tuple.compiledSubject.CompareTo(tuple.compiledObject),
			fmt.Sprintf(
				`"%s" compared to "%s" should be %d`,
				tuple.subject,
				tuple.object,
				tuple.expected,
			),
		)
	}
}

func TestSemverCandidateString(t *testing.T) {
	c1, _ := NewSemverCandidate(
		"someHash",
		"someRef",
		"someLabel",
		"1",
		"2",
		"3",
		"",
		"",
	)

	c2, _ := NewSemverCandidate(
		"someHash",
		"someRef",
		"someLabel",
		"1",
		"2",
		"3",
		"alpha",
		"",
	)

	c3, _ := NewSemverCandidate(
		"someHash",
		"someRef",
		"someLabel",
		"1",
		"2",
		"3",
		"beta",
		"4",
	)

	assert.Equal(t, "1.2.3", c1.String(), "Candidates without pre-release data should just be 3 numbers")
	assert.Equal(t, "1.2.3-alpha", c2.String(), "Candidates with a pre-release label and without a pre-release version should omit the pre-release version entirely")
	assert.Equal(t, "1.2.3-beta.4", c3.String(), "Candidates with a pre-release label and a pre-release version should show in full")
}

func TestSemverCandidateList(t *testing.T) {
	var (
		list                               SemverCandidateList
		c, expectedLowest, expectedHighest SemverCandidate
	)

	c, _ = NewSemverCandidate("a", "b", "c", "1", "2", "3", "", "")
	list = append(list, c)
	c, _ = NewSemverCandidate("a", "b", "c", "2", "3", "4", "", "")
	list = append(list, c)
	expectedLowest, _ = NewSemverCandidate("a", "b", "c", "1", "2", "3", "alpha", "2")
	list = append(list, expectedLowest)
	c, _ = NewSemverCandidate("a", "b", "c", "2", "1", "1", "", "")
	list = append(list, c)
	expectedHighest, _ = NewSemverCandidate("a", "b", "c", "3", "5", "6", "", "")
	list = append(list, expectedHighest)

	sort.Sort(list)

	lowest := list.Lowest()
	highest := list.Highest()

	assert.Equal(t, 0, lowest.CompareTo(expectedLowest), "The lowest candidate should be correct")
	assert.Equal(t, 0, highest.CompareTo(expectedHighest), "The highest candidate should be correct")

	selector, err := NewSemverSelector("", "1", "x", "", "", "", "")
	matchedList := list.Match(selector)
	assert.Nil(t, err, "Match should always work for normal candidate lists")
	assert.Equal(t, 2, len(matchedList), "Match should return the correct number of elements")

	list = []SemverCandidate{}
	assert.Nil(t, list.Lowest(), "Lowset should return nil when there are no elements to sort")
	assert.Nil(t, list.Highest(), "Highest should return nil when there are no elements to sort")
}


text:
<?php

namespace Bupy7\Queue;

use Laminas\ModuleManager\Feature\ConfigProviderInterface;
use Laminas\ModuleManager\Feature\InitProviderInterface;
use Laminas\ModuleManager\ModuleManagerInterface;

/**
 * @author Vasily Belosludcev <https://github.com/bupy7>
 */
class Module implements ConfigProviderInterface, InitProviderInterface
{
    public function getConfig(): array
    {
        return require __DIR__ . '/../config/module.config.php';
    }

    public function init(ModuleManagerInterface $manager)
    {
        $event = $manager->getEvent();
        $container = $event->getParam('ServiceManager');
        /** @var \Laminas\ModuleManager\Listener\ServiceListener $serviceListener */
        $serviceListener = $container->get('ServiceListener');
        $serviceListener->addServiceManager(
            'Bupy7\Queue\Manager\QueueManager',
            'queue_manager',
            'Bupy7\Queue\Manager\Provider\QueueManagerProviderInterface',
            'getQueueManagerConfig'
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import Radium from 'radium';

import variables from './styles/variables';

import { Span } from '../index';

@Radium
export default class Badge extends React.Component {
  static propTypes = {
    type: React.PropTypes.oneOf(['success', 'warning', 'danger']),
    notification: React.PropTypes.bool
  };

  static defaultProps = {
    notification: false
  };

  getStyles() {
    return {
      base: {
        display: 'inline-block',
        padding: `0 ${variables.badgePaddingHorizontal}px`,
        background: variables.badgeBackground,
        fontSize: variables.badgeFontSize,
        fontWeight: variables.badgeFontWeight,
        lineHeight: `${variables.badgeLineHeight}px`,
        color: variables.badgeColor,
        textAlign: 'center',
        verticalAlign: 'middle',
        textTransform: variables.badgeTextTransform,
        ':hover': {
          color: variables.badgeHoverColor
        }
      },
      notification: {
        boxSizing: 'border-box',
        minWidth: variables.badgeNotificationLineHeight,
        borderRadius: 500,
        fontSize: variables.badgeNotificationFontSize,
        lineHeight: variables.badgeNotificationLineHeight
      },
      types: {
        success: { background: variables.badgeSuccessBackground },
        warning: { background: variables.badgeWarningBackground },
        danger: { background: variables.badgeDangerBackground }
      }
    };
  }

  render() {
    const styles = this.getStyles();
    const props = this.props;

    return (
      <Span style={[
        styles.base,
        props.notification && styles.notification,
        props.type && styles.types[props.type]
      ]}>
        {props.children}
      </Span>
    );
  }
}


text:
package com.amazonaws.services.costexplorer.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum GroupDefinitionType {

    DIMENSION("DIMENSION"),
    TAG("TAG");

    private String value;

    private GroupDefinitionType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return GroupDefinitionType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static GroupDefinitionType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (GroupDefinitionType enumEntry : GroupDefinitionType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
.. _qibuild-host-tools:

Using host tools for cross compilation
=======================================

Say you have to generate sources during the build.
You do so using an executable called ``footool``.

In the tutorial we assume you have two configs:

* ``linux64``, associated to a toolchain containing for instance pre-compiled
  dependencies of ``footool``
* ``arm``, associated to a cross-toolchain targeting arm

The code looks like this:

.. code-block:: console

    worktree
      footool
        qiproject.xml
        CMakeLists.txt
        foo-config.cmake
        footool.cpp

.. code-block:: cpp

    // In footool.cpp

    int main(int argc, char* argv)
    {
      char* input = argv[1];
      char* output = argv[2];

      // Generate output from input

    }

.. code-block:: cmake

    # in CMakeLists.txt

    qi_create_bin(footool footool.cpp)
    qi_stage_bin(footool)

    qi_stage_cmake(foo-config.cmake)

    # in foo-config.cmake

    find_package(footool REQUIRED)

    function(generate_foo output input)

      qi_generate_src(${output}
        COMMAND ${FOOTOOL_EXECUTABLE} ${input} ${output}
      )

    endfunction()

You then have an other project which uses ``footool`` to generate some sources:

.. code-block:: console

    worktree
      footool
      usefootool
        qiproject.xml
        CMakeLists.txt

.. code-block:: cmake

    # In CMakeLists.txt

    find_package(foo REQUIRED)

    generate_foo(out src.cpp)

    # ...

So what you need is to configure and build the ``footool`` project so the binary
``footool`` exists, and find the ``footool`` executable in the build directory
of the ``footool`` project even when you are for instance cross-compiling.

To do so, you should:

* Patch the ``qiproject.xml`` to add a host dependency to ``footool``

.. code-block:: xml

    <!-- in usefootool/qiproject.xml -->
    <project version="3">
      <qibuild name="usefootool">
        <depends host="true" names="footool" />
      </qibuild>
    </project>

* Tell qibuild to use a ``host`` config.

  .. code-block:: console

    qibuild set-host-config linux64

* Configure and build the ``footool`` project:

  .. code-block:: console

      qibuild configure footool -c linux64
      qibuild make footool -c linux64

* Then you can cross-compile for arm:

  .. code-block:: console

      qibuild configure usefootool -c arm
      qibuild make usefootool -c arm

If you are not using any toolchain, you can of course just configure and build ``usefootool`` normally:

.. code-block:: console

    qibuild configure footool
    qibuild make footool

    qibuild configure usefootool -c arm
    qibuild make usefootool -c arm

* Alternatively, you can use ``qibuild make-host-tools`` from
  the ``usefootool`` directory. It will parse the host dependencies
  of the current build project and build them.

  .. code-block:: console

      cd usefootool
      qibuild make-host-tools


text:
package org.planx.xmlstore.routing.operation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import org.planx.xmlstore.routing.Configuration;
import org.planx.xmlstore.routing.Identifier;
import org.planx.xmlstore.routing.Node;
import org.planx.xmlstore.routing.RoutingException;
import org.planx.xmlstore.routing.Space;
import org.planx.xmlstore.routing.messaging.*;

/**
 * Finds the K closest nodes to a specified identifier.
 * The algorithm terminates when the operation has gotten responses from the
 * K closest nodes it has seen. Nodes that fail to respond are
 * removed from consideration.
 **/
public class NodeLookupOperation extends Operation implements Receiver {
    private static final Byte UNASKED  = new Byte((byte) 0x00);
    private static final Byte AWAITING = new Byte((byte) 0x01);
    private static final Byte ASKED    = new Byte((byte) 0x02);
    private static final Byte FAILED   = new Byte((byte) 0x03);

    protected Configuration conf;
    protected MessageServer server;
    protected Space space;
    protected Node local;
    protected Identifier id;
    protected boolean error;

    /**
     * Message sent to each peer. Subclasses could change this field to send
     * other kinds of lookup messages.
     **/
    protected LookupMessage lookupMessage;

    /**
     * Comparator used to select CONCURRENCY nodes among the K closest nodes.
     **/
    private Comparator cmp;

    /**
     * Keeps track of which nodes have been asked and gotten reply from.
     * Nodes are keys mapped to a Byte indicating the status.
     * The map is kept sorted according to closeness to the sought after identifier.
     **/
    private SortedMap nodes;

    /**
     * Keeps track of messages in transit and awaiting reply. No more than
     * CONCURRENCY message may be in transit and unreplied at
     * the same time. Communication ids as Integers are keys and Nodes are
     * values.
     **/
    private Map transit;

    /**
     * Create a NodeLookupOperation for the specified id.
     **/
    public NodeLookupOperation(Configuration conf, MessageServer server,
                               Space space, Node local, Identifier id) {
        this.conf = conf;
        this.server = server;
        this.space = space;
        this.local = local;
        this.id = id;
        lookupMessage = new NodeLookupMessage(local, id);
        Comparator distCmp = new Node.DistanceComparator(id);
        nodes = new TreeMap(distCmp);
        transit = new HashMap();
        cmp = distCmp;
    }

    /**
     * @return A List containing the K closest nodes to the id provided
     *         in the constructor.
     * @throws RoutingException If the lookup operation timed out
     * @throws IOException      If a network error occurred
     **/
    public synchronized Object execute() throws IOException, RoutingException {
        try {
            error = true;
            nodes.put(local, ASKED);
            addNodes(space.getAll());
            if (!askNodesOrFinish()) {
                // Nodes were asked, wait for termination
                wait(conf.OPERATION_TIMEOUT);
                if (error) throw new RoutingException("Lookup timeout");
            }
            return closestNodes(ASKED);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Receives an incoming NodeReplyMessage.
     **/
    public synchronized void receive(Message incoming, int comm) throws IOException {
        NodeReplyMessage mess = (NodeReplyMessage) incoming;
        Node origin = mess.getOrigin();

        // Insert origin node or refresh time last seen, update status
        space.insertNode(origin);
        nodes.put(origin, ASKED);
        transit.remove(new Integer(comm));

        addNodes(mess.getNodes());
        askNodesOrFinish();
    }

    /**
     * A node does not respond or a packet was lost.
     **/
    public synchronized void timeout(int comm) throws IOException {
        Integer c = new Integer(comm);
        Node node = (Node) transit.get(c);
        if (node == null)
            throw new UnknownMessageException("Incoming comm "+comm+" unknown");

        // Mark as unresponsive
        nodes.put(node, FAILED);
        space.removeNode(node);
        transit.remove(c);

        askNodesOrFinish();
    }

    /**
     * Asks some of the K closest nodes seen but not yet queried. Assures that no
     * more than CONCURRENCY messages are in transit at a time. If this limit is
     * reached, no nodes are queried. Instead, this method should be called again
     * when a reply is received or a timeout occurs. If all K closest nodes have
     * been asked and there are no messages in transit the algorithm is finished
     * and a thread waiting on this object is woken up.
     * Returns true if finished and false otherwise.
     **/
    private boolean askNodesOrFinish() throws IOException {
        if (transit.size() >= conf.CONCURRENCY) return false;

        // Find nodes not yet queried among the K closest seen
        List ask = filterClosestNodes(UNASKED);

        // Are none of the K nodes unasked and no messages in transit?
        if ((ask.size() == 0) && (transit.size() == 0)) {
            // At this point all the K closest nodes seen are marked ASKED
            // none can be AWAITING or UNASKED (FAILED are ignored).
            error = false;
            notify();
            return true;
        }

        // Sort nodes according to criteria
        Collections.sort(ask, cmp);

        // Send messages to the first nodes in the list and ensure that no more
        // than CONCURRENCY messages are in transit
        for (int i=0; (transit.size()<conf.CONCURRENCY) && (i<ask.size()); i++) {
            Node node = (Node) ask.get(i);
            int comm = server.send(lookupMessage, node.getInetAddress(),
                                   node.getPort(), this);
            nodes.put(node, AWAITING);
            transit.put(new Integer(comm), node);
        }
        return false;
    }

    /**
     * Returns the K nodes encountered closest to the target that have the
     * specified status.
     **/
    private List closestNodes(Byte status) {
        int remaining = conf.K;
        List matches = new ArrayList(conf.K);

        // Note that "nodes" are kept sorted according to closeness to target
        Iterator it = nodes.entrySet().iterator();
        while (it.hasNext() && (remaining > 0)) {
            Map.Entry entry = (Map.Entry) it.next();
            if (status.equals(entry.getValue())) {
                matches.add(entry.getKey());
                remaining--;
            }
        }
        return matches;
    }

    /**
     * Returns the subset of nodes with the specified status among the K
     * nodes encountered closest to the target that have status not FAILED.
     **/
    private List filterClosestNodes(Byte status) {
        int remaining = conf.K;
        List matches = new ArrayList(conf.K);

        // Note that "nodes" are kept sorted according to closeness to target
        Iterator it = nodes.entrySet().iterator();
        while (it.hasNext() && (remaining > 0)) {
            Map.Entry entry = (Map.Entry) it.next();
            Object value = entry.getValue();
            if (!FAILED.equals(value)) {
                remaining--;
                if (status.equals(value)) {
                    matches.add(entry.getKey());
                }
            }
        }
        return matches;
    }

    private void addNodes(List list) {
        for (int i = 0, max = list.size(); i < max; i++) {
            Object o = list.get(i);
            if (!nodes.containsKey(o)) nodes.put(o, UNASKED);
        }
    }
}


text:
var Avrgirl = require('../../');
var avrgirl = new Avrgirl({
  board: 'qduino',
  debug: true
});

var hex = __dirname + '/../../junk/hex/qduino/rainbow.cpp.hex';

avrgirl.flash(hex, function(error) {
  if (error) {
    console.error(error);
  } else {
    console.info('done.');
  }
});


text:
package org.books.application.amazon.soap;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java-Klasse für anonymous complex type.
 *
 *
Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="MarketplaceDomain" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="AWSAccessKeyId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="AssociateTag" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="XMLEscaping" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="Validate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="Shared" type="{http://webservices.amazon.com/AWSECommerceService/2011-08-01}ItemSearchRequest" minOccurs="0"/>
 *         <element name="Request" type="{http://webservices.amazon.com/AWSECommerceService/2011-08-01}ItemSearchRequest" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "marketplaceDomain",
    "awsAccessKeyId",
    "associateTag",
    "xmlEscaping",
    "validate",
    "shared",
    "request"
})
@XmlRootElement(name = "ItemSearch")
public class ItemSearch {

    @XmlElement(name = "MarketplaceDomain")
    protected String marketplaceDomain;
    @XmlElement(name = "AWSAccessKeyId")
    protected String awsAccessKeyId;
    @XmlElement(name = "AssociateTag")
    protected String associateTag;
    @XmlElement(name = "XMLEscaping")
    protected String xmlEscaping;
    @XmlElement(name = "Validate")
    protected String validate;
    @XmlElement(name = "Shared")
    protected ItemSearchRequest shared;
    @XmlElement(name = "Request")
    protected List<ItemSearchRequest> request;

    /**
     * Ruft den Wert der marketplaceDomain-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getMarketplaceDomain() {
        return marketplaceDomain;
    }

    /**
     * Legt den Wert der marketplaceDomain-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setMarketplaceDomain(String value) {
        this.marketplaceDomain = value;
    }

    /**
     * Ruft den Wert der awsAccessKeyId-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAWSAccessKeyId() {
        return awsAccessKeyId;
    }

    /**
     * Legt den Wert der awsAccessKeyId-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAWSAccessKeyId(String value) {
        this.awsAccessKeyId = value;
    }

    /**
     * Ruft den Wert der associateTag-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAssociateTag() {
        return associateTag;
    }

    /**
     * Legt den Wert der associateTag-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAssociateTag(String value) {
        this.associateTag = value;
    }

    /**
     * Ruft den Wert der xmlEscaping-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getXMLEscaping() {
        return xmlEscaping;
    }

    /**
     * Legt den Wert der xmlEscaping-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setXMLEscaping(String value) {
        this.xmlEscaping = value;
    }

    /**
     * Ruft den Wert der validate-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValidate() {
        return validate;
    }

    /**
     * Legt den Wert der validate-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValidate(String value) {
        this.validate = value;
    }

    /**
     * Ruft den Wert der shared-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link ItemSearchRequest }
     *
     */
    public ItemSearchRequest getShared() {
        return shared;
    }

    /**
     * Legt den Wert der shared-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link ItemSearchRequest }
     *
     */
    public void setShared(ItemSearchRequest value) {
        this.shared = value;
    }

    /**
     * Gets the value of the request property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the request property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getRequest().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ItemSearchRequest }
     *
     *
     */
    public List<ItemSearchRequest> getRequest() {
        if (request == null) {
            request = new ArrayList<ItemSearchRequest>();
        }
        return this.request;
    }

}


text:
export {EmailComponent} from './email.component';
export {HiddenComponent} from './hidden.component';
export {TextComponent} from './text.component';
export {SelectComponent} from './select.component';
export {TinyMceComponent} from './tinymce.component';
export {ChbxListComponent} from './chbxlist.component';
export { NumberComponent } from './number.component';
export { TextAreaComponent} from './textarea.component';
export { SearchFieldComponent } from './search.component';
export { TableFieldComponent }  from './tblfield.component';
export { DateComponent} from './date.component';
export { FileFieldComponent } from './filefield.component';
export { UploadFileComponent } from './uploadfile.component';
export { CodeMirrorComponent } from './codemirror.component';
export { MediaComponent } from './media.component';
export { MediaSearchComponent } from './media-search.component';


text:
<?php //-->
namespace Journal\Repositories\Tag;

use Illuminate\Support\Str;
use Journal\Post;
use Journal\Tag;

class DbTagRepository implements TagRepositoryInterface {
    /**
     * @param $tag
     * @return \Journal\Tag
     */
    public function create($tag)
    {
        return Tag::firstOrCreate([
            'name' => $tag,
            'slug' => Str::slug(strtolower($tag))]);
    }

    /**
     * @return \Journal\Tag
     */
    public function all()
    {
        return Tag::where('active', '=', 1)
            ->orderBy('name', 'ASC')
            ->get();
    }

    /**
     * @param $id
     * @return \Journal\Tag
     */
    public function findById($id)
    {
        return Tag::where('id', '=', $id)->first();
    }

    /**
     * @param $slug
     * @return \Journal\Tag
     */
    public function findBySlug($slug)
    {
        return Tag::where('slug', '=', $slug)->first();
    }

    /**
     * @param $id
     * @param $numberOfPosts
     * @return \Journal\Post
     */
    public function getPosts($id, $numberOfPosts)
    {
        return Post::with(['author', 'tags'])
            ->whereHas('tags', function($query) use ($id) {
                // set a query to fetch posts according to the tag ID to which
                // a tag is related to
                $query->where('id', '=', $id);
            })
            // get the active posts
            ->where('active', '=', 1)
            // published post only
            ->where('status', '=', 1)
            // order by timestamp of publish
            ->orderBy('published_at', 'DESC')
            ->paginate($numberOfPosts);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Pl. Scand. fasc. 2:49. 1852

#### Original name
Poa fulva Trin.

### Remarks
null


text:
extern std::string delsp(std::string input);

// split
// devide a string by space and make it into list
extern std::list<std::string> split(std::string input);


text:
/**
 * A module used for collision detection
 * @module Physics/Collisions
 */

/**
Finds any collisions between the terrain elements and the entity and calls the respective methods.
After finding a collision if the entity returns true and the terrain element returns true
the position of the entity will not be corrected, if both return false then the entity will be.
@param {Terrain} terrain the terrain who's elements to check collisiosn against.
@param {Entity} entity the entity to use for collision detection
*/
function terrainAndEntity(terrain, entity, booleanReturn){
  for(let terrainElement of terrain.elements){
    if(terrainElement.ghost){
      continue;
    }
    let xOff = terrainElement.pos.x-entity.pos.x;
    let yOff = terrainElement.pos.y- entity.pos.y;
    let side = 0;
    if((side = terrainElement.box.intersects(entity.box, xOff, yOff)) !== 0){
      let overlap = terrainElement.box.getOverlap(entity.box, xOff, yOff);
      let oldX = entity.pos.x;
      let oldY = entity.pos.y;
      let oldVelX = entity.vel.x;
      let oldVelY = entity.vel.y;
      if(overlap[0] > overlap[1]){
        side = 2;
        side += correctY(entity, terrainElement, yOff);
      } else {
        side = 1;
        side += correctX(entity, terrainElement, xOff);
      }
      //console.log(entity.vel.x +" before");
      let bool = terrainElement.collision(entity, side, oldX, oldY) || terrainElement.dontMoveOnCollision || booleanReturn;
      if(bool || entity.collision(terrainElement, side)){
        entity.pos.x = oldX;
        entity.pos.y = oldY;
        entity.vel.x = oldVelX;
        entity.vel.y = oldVelY;
      }
      if(booleanReturn){
        return true;
      }
    }
  }
  return false;
}

/**
Finds any collisions between the terrain elements and the element and calls the respective methods.
After finding a collision if the element returns true and the terrain element returns true
the position of the element will not be corrected, if both return false then the element will be.
@param {Terrain} terrain the terrain who's elements to check collisiosn against.
@param {Entity} element the entity to use for collision detection
*/
function terrainAndElement(terrain, element, booleanReturn){
  for(let terrainElement of terrain.elements){
    if(terrainElement.ghost){
      continue;
    }
    let xOff = terrainElement.pos.x-element.pos.x;
    let yOff = terrainElement.pos.y- element.pos.y;
    let side = 0;
    if((side = terrainElement.box.intersects(element.box, xOff, yOff)) !== 0){
      let overlap = terrainElement.box.getOverlap(element.box, xOff, yOff);
      let oldX = element.pos.x;
      let oldY = element.pos.y;
      if(overlap[0] > overlap[1]){
        side = 2;
        side += correctY(element, terrainElement, yOff);
      } else {
        side = 1;
        side += correctX(element, terrainElement, xOff);
      }
      //console.log(element.vel.x +" before");
      let bool = terrainElement.dontMoveOnCollision || booleanReturn;
      if(bool){
        element.pos.x = oldX;
        element.pos.y = oldY;
      }
      if(booleanReturn){
        return overlap;
      }
    }
  }
  return false;
}

/**
Corrects the x direction of the entity returning which direction it was corrected, left = 2, right = 0
@param {Entity} toMove the entity to check and to move
@param {Entity} notToMove the entity to check and not to move
@param {number} xOff the offset in the x direction of the two elements, how far further left the notToMove is.
*/
function correctX(toMove, notToMove, xOff){
  let direction = 0;
  if(xOff !== 0)
    direction = -Math.abs(xOff)/xOff;
  else
    return 0;
  if(notToMove.dontMoveCollision){
    toMove.vel.x = 0;
  }
  toMove.pos.x = notToMove.pos.x + direction*(toMove.box.width/2 + notToMove.box.width/2);
  return (direction < 0) ? 2 : 0;
}

/**
Corrects the y direction of the entity returning which direction it was corrected, down = 2, up = 0
@param {Entity} toMove the entity to check and to move
@param {Entity} notToMove the entity to check and not to move
@param {number} yOff the offset in the y direction of the two elements, how far further up the notToMove is.
*/
function correctY(toMove, notToMove, yOff){
  let direction = 0;
  if(yOff !== 0)
    direction = -Math.abs(yOff)/yOff;
  else {
    return 0;
  }
  if(toMove.vel){
    toMove.vel.y = 0;
  }
  toMove.pos.y = notToMove.pos.y + direction*(toMove.box.height/2 + notToMove.box.height/2);
  return (direction < 0) ? 2 : 0;
}

/**
* finds all of the entities which collide with the box
* @param {Box} box the box to check against
* @param {Entity[]} entities the entities to check against
* @return {Entity[]} a list of entities that collided
*/
function boxAndEntities(box, entities, x, y){
  let collided = [];
  for(let entity of entities){
    let dx = entity.pos.x - x;
    let dy = entity.pos.y - y;
    if(box.intersects(entity.box, dx, dy) && !entity.hidden && !entity.ghost){
      collided.push(entity);
    }
  }
  return collided;
}

export default {terrainAndEntity: terrainAndEntity, correctX: correctX, correctY: correctY, terrainAndElement : terrainAndElement, boxAndEntities: boxAndEntities};


text:
package cyclops.typeclasses.taglessfinal;

import com.oath.cyclops.hkt.DataWitness;
import com.oath.cyclops.hkt.DataWitness.io;
import com.oath.cyclops.hkt.Higher;
import cyclops.data.tuple.Tuple2;
import cyclops.instances.reactive.IOInstances;
import cyclops.reactive.IO;
import cyclops.reactive.IOMonad;
import org.junit.Before;
import org.junit.Test;
import static cyclops.typeclasses.taglessfinal.Cases.*;

public class TaglessFinalTest {

    private Account acc1;
    private Account acc2;
    Program<io> prog;
    @Before
    public void setup(){
        acc1 = new Account(10000d,10);
        acc2 = new Account(0d,11);
        prog = new Program<>(IOInstances.monad(),new AccountIO(),acc1,acc2);
    }

    @Test
    public void programA(){

        IO<Tuple2<Account, Account>> res = prog.transfer(100)
                                                .convert(IO::narrowK);
        res.run().peek(System.out::println);
    }
    @Test
    public void programB(){

        IO<Tuple2<Account, Account>> res = prog.transfer(100,IO::narrowK);
        res.run().peek(System.out::println);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://jboss.org/schema/arquillian"
    xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

    <container qualifier="proxy" default="true">
        <configuration>
            <property name="target">wildfly:8.1.0.Final:remote</property>
        </configuration>
    </container>

    <extension qualifier="reporter">
        <property name="report">html5</property>
    </extension>
</arquillian>


text:
<?php

// guard to ensure basic configuration is loaded
defined('APPLICATION_PATH') || exit("APPLICATION_PATH not found.");

class ClassNotFoundException extends \Exception {}

/**
 * the auto-loading function, which will be called every time a file "is missing"
 * NOTE: don't get confused, this is not "__autoload", the now deprecated function
 * The PHP Framework Interoperability Group (@see https://github.com/php-fig/fig-standards) recommends using a
 * standardized auto-loader https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md, so we do:
 */
class Autoloader
{
    static public function loader($className)
    {
    	$className = ltrim($className, '\\');
		$parts = explode('\\', $className);
		if ( count($parts) == 1 || in_array(strtolower($parts[0]), array('controller', 'model', 'processor')) == false ) {
			array_unshift($parts, 'libs');
		}
		else if ( in_array(strtolower($parts[0]), array('controller', 'model', 'processor')) == true ) {
			$parts[0] = strtolower($parts[0]);
		}

		array_unshift($parts, APPLICATION_PATH);
		$filename = implode(DIRECTORY_SEPARATOR, $parts) . ".php";
        if (file_exists($filename)) {
            include($filename);
            if (class_exists($className) || interface_exists($className)) {
                return TRUE;
            }
        }

// 		Logger::logError( 'Failed to load ' . $filename . "|" . backtraceString() );

        return FALSE;
    }
}
spl_autoload_register('Autoloader::loader');


text:
class MemCacheExceptionBase(Exception):
    pass

class MemCacheUnknownException(MemCacheExceptionBase):

    def __init__(self, code, message = ''):
        '''
        Initialize an Unknown error exception
        '''
        self.code = code
        self.message = 'Unknown error. Code [{0}] Message [{1}]'.format(code, message)
        super(MemCacheUnknownException, self).__init__(self.message)

class MemCacheInvalidResponseException(MemCacheExceptionBase):

    RESPONSE_CODE = 0x81

    def __init__(self, magic=None):
        '''
        Initialize an Invalid response exception
        '''
        self.magic = magic
        if magic:
            self.message = 'Invalid response header. Expected magic [{0}] got [{1}]'.format(self.RESPONSE_CODE, magic)
        else:
            self.message = 'Invalid response header'
        super(MemCacheInvalidResponseException, self).__init__(self.message)

class MemCacheKeyNotFoundException(MemCacheExceptionBase, KeyError):

    STATUS_CODE = 0x01

    def __init__(self, key, server, bodylen=None):
        '''
        Initialize a Key not found exception
        '''
        self.key = key
        self.server = server
        self.bodylen = bodylen
        self.message = 'Key [{0}] not found in MemCache server [{1}]'.format(key, server)
        super(MemCacheKeyNotFoundException, self).__init__(self.message)

class MemCacheCASException(MemCacheExceptionBase, KeyError):

    STATUS_CODE = 0x02

    def __init__(self, key, server, bodylen=None):
        '''
        Initialize a CAS set exception.
        This is actually a Key already exists exception, but in the CAS command context it means
        that the operation could not complete due to CAS unique value mismatch.
        '''
        self.key = key
        self.server = server
        self.bodylen = bodylen
        self.message = 'Unable to store value for [{0}] in MemCache server [{1}]. CAS mismatch.'.format(key, server)
        super(MemCacheCASException, self).__init__(self.message)

class MemCacheServerDisconnectionException(MemCacheExceptionBase):

    STATUS_CODE = 0xFFFFFFFF

    def __init__(self, server):
        '''
        Initialize a server disconnected exception
        '''
        self.server = server
        self.message = 'Server [{0}] is not connected'.format(server)
        super(MemCacheServerDisconnectionException, self).__init__(self.message)

class MemCacheConnectionErrorException(MemCacheExceptionBase):

    def __init__(self, server, e):
        '''
        Initialize a connection error exception
        '''
        self.server = server
        self.exception = e
        self.message = 'Unable to connect to [{0}]: {1}'.format(str(server), e)
        super(MemCacheConnectionErrorException, self).__init__(self.message)

class MemCacheTimeoutException(MemCacheExceptionBase):

    def __init__(self, server, message=None):
        '''
        Initialize a connection error exception
        '''
        self.server = server
        self.message = 'Timeout while waiting for [{0}]'.format(server) if message is None else message
        super(MemCacheTimeoutException, self).__init__(self.message)


text:
from typing import Union, List, Tuple, Callable, Generator, TypeVar, cast
import tempfile
import contextlib
import csv
from pathlib import Path
import logging
import matplotlib.pyplot as plt
import numpy as np
import dask.bag
import edgar_code.cli.config as config
from edgar_code.gs_path import copy
from edgar_code.util import time_code
from edgar_code.retrieve import get_rfs, get_indexes
from edgar_code.types import PathLike, Bag

# TODO: combine with retrieve.py

logger = logging.getLogger(__name__)

def rf_mapper(rf: Union[List[str], Exception]) -> Tuple[int, int, str]:
    if isinstance(rf, list):
        return (
            sum(map(len, rf)),
            len(rf),
            rf[0][:50] + ' ... ' + rf[1][-50:],
        )
    else:
        return (-1, -1, repr(rf))

T = TypeVar('T')
def time_code_getter(val: T) -> T:
    print(time_code.format_stats())
    return val

@time_code.decor(print_start=True, print_time=True, print_args=True)
def get_bag(year: int, qtr: int) -> Bag[Tuple[str, int, int, str]]:
    return dask.bag.map(
        lambda index, rf_count: (index.url, rf_count[0], rf_count[1], rf_count[2]),
        get_indexes('10-K', year, qtr),
        get_rfs(year, qtr).map(rf_mapper),
    )

@contextlib.contextmanager
def get_styled_ax(path: PathLike) -> Generator[plt.Axes, None, None]:
    with tempfile.TemporaryDirectory() as temp_dir_:
        temp_dir = Path(temp_dir_)
        chars_file = temp_dir / 'plot.png'
        fig = plt.figure()
        ax = fig.gca()
        yield ax
        fig.savefig(chars_file)
        plt.close(fig)
        copy(chars_file, path)

def main() -> None:
    client = config.get_client()
    logger.debug('using client: %r', client)

    # This comment is commented out
    # # submiting all bags for computation at once loads the cluster
    # # more efficiently. Workers don't have to idle in between bags
    # # being submitted; there is always more work available.
    # before uncommenting generator->list

    get_bag(1995, 1).compute()
    logger.debug('here')
    get_bag(1995, 2).compute()

    future_bags = [
        ((year, qtr), get_bag(year, qtr).compute())
        for year in range(1993, 2019)
        for qtr in range(1, 5)
    ]

    all_chars: List[int] = []
    all_paragraphs: List[int] = []
    alltime_path = config.results_path / 'get_all_rfs/good_stats.txt'
    with alltime_path.open('w') as alltime_file:
        for (year, qtr), future_bag in future_bags:
            quarter_dir = config.results_path / 'get_all_rfs/{year}_{qtr}/'

            # This is also commented out
            # # I am calling .result instead of gather because the whole
            # # thing might not fit in RAM on the workers.  When I consume
            # # one result, it frees up that memory, so they can compute the
            # # next one. It also is less memory intensive on this pod.
            with time_code.ctx(
                    f'fetching get_rfs({year}, {qtr})', print_start=True, print_time=True
            ):
                # bag = future_bag.result(timeout=None)
                bag = future_bag

            with time_code.ctx(f'write for {year} {qtr}', print_start=True, print_time=True):
                urls, chars, paragraphs, texts = (
                    [''] * len(bag),
                    np.zeros(len(bag), dtype=int),
                    np.zeros(len(bag), dtype=int),
                    [''] * len(bag),
                )
                for i, row in enumerate(bag):
                    urls[i] = row[0]
                    chars[i] = row[1]
                    paragraphs[i] = row[2]
                    texts[i] = row[3]

                all_chars.extend(chars)
                all_paragraphs.extend(paragraphs)

                with (quarter_dir / 'results.txt').open('w') as results_file:
                    csvw = csv.writer(results_file)
                    csvw.writerow(zip(urls, texts))

                total = len(bag)
                good = sum(map(
                    # cannot type lambdas; must use cast :(
                    cast(Callable[[int], int], lambda x: x != -1),
                    paragraphs
                ))
                print(f'For: {year} {qtr}', file=alltime_file)
                print(f'Good: {good / total * 100:.0f}%', file=alltime_file)
                print('', file=alltime_file)

    with get_styled_ax(config.results_path / 'get_all_rfs/chars.png') as ax:
        ax.plot(range(len(chars)), sorted(chars))
        ax.set_xlabel('# of chars')
        ax.set_ylabel('# of docs')

    with get_styled_ax(config.results_path / 'get_all_rfs/paragraphs.png') as ax:
        ax.plot(range(len(paragraphs)), sorted(paragraphs))
        ax.set_xlabel('# of chars')
        ax.set_ylabel('# of docs')

if __name__ == '__main__':
    main()


text:
#pragma once

void rd_hexdump (FILE *fp, const char *name, const void *ptr, size_t len);

void rd_iov_print (const char *what, int iov_idx, const struct iovec *iov,
                   int hexdump);
struct msghdr;
void rd_msghdr_print (const char *what, const struct msghdr *msg,
                      int hexdump);


text:
<?php
namespace Navy;

require dirname(__DIR__) . '/vendor/autoload.php';

$kernel = new Kernel(__DIR__);
$kernel->bootstrap();

return $kernel;


text:
/*
 * This file was semi-automatically converted from the public-domain USGS PROJ source.
 */
package com.jhlabs.map.proj;

import java.awt.geom.*;
import com.jhlabs.map.*;

public class Eckert5Projection extends Projection {

	private final static double XF = 0.44101277172455148219;
	private final static double RXF = 2.26750802723822639137;
	private final static double YF = 0.88202554344910296438;
	private final static double RYF = 1.13375401361911319568;

	public Point2D.Double project(double lplam, double lpphi, Point2D.Double out) {
		out.x = XF * (1. + Math.cos(lpphi)) * lplam;
		out.y = YF * lpphi;
		return out;
	}

	public Point2D.Double projectInverse(double xyx, double xyy, Point2D.Double out) {
		out.x = RXF * xyx / (1. + Math.cos( out.y = RYF * xyy));
		return out;
	}

	public boolean hasInverse() {
		return true;
	}

	public String toString() {
		return "Eckert V";
	}

}


text:
import { RestServiceBuilder } from "../RestServiceBuilder";
import { ServiceStackOptions } from "./ServiceStackOptions";
export declare class ServiceStackBuilder extends RestServiceBuilder {
    constructor(options: ServiceStackOptions);
    build(url: string): Promise<any>;
    private buildMetadata(url);
    private buildService(url, name);
    private buildServiceRoutes(name, path, methods, request);
    private parseVerbs(verbs);
}


text:
/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-07 The eXist Project
 *  http://exist-db.org
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *  $Id: ValidationContentHandler.java 6639 2007-09-27 19:49:04Z dizzzz $
 */

package org.exist.validation;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *  Simple contenthandler to determine the NamespaceUri of
 * the document root node.
 *
 * @author Dannes Wessels
 */
public class ValidationContentHandler extends DefaultHandler {

    private boolean isFirstElement = true;
    private String namespaceUri = null;

    /**
     * @see org.xml.sax.helpers.DefaultHandler#startElement(String,String,String,Attributes)
     */
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException {

        if(isFirstElement){
            namespaceUri=uri;
            isFirstElement=false;
        }
    }

    public String getNamespaceUri(){
        return namespaceUri;
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Lich. univ. 483 (1810)

#### Original name
Lichen pityreus Ach.

### Remarks
null


text:
<?php

namespace Nfq\WeatherBundle\Controller;

use Nfq\WeatherBundle\Location\Location;
use Nfq\WeatherBundle\Provider\WeatherProviderInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("weather/{city}")
     * @Template("NfqWeatherBundle:Default:index.html.twig")
     */
    public function indexAction($city)
    {
        $location = new Location($city);
        /** @var WeatherProviderInterface $provider */
        $provider = $this->get('nfq_weather');
        $weather = $provider->fetch($location);

        $parameters = [
            'temp' => $weather->getTemperature(),
            'provider' => $weather->getProviderName()
        ];

        return $parameters;
    }
}


text:
<einit prefix="configuration-services">

 <!-- your in.tftpd Daemon options go here -->

 <tftpd options="-R 4096:32767 -s /tftpboot/" />
</einit>


text:
<?php

namespace App\TiendaOnlineBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Lista
 */
class Lista
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $nombre;

    /**
     * @var string
     */
    private $descripcion;

    /**
     * @var integer
     */
    private $borrado;

    /**
     * @var \DateTime
     */
    private $created_at;

    /**
     * @var \DateTime
     */
    private $updated_at;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $detalles;

    /**
     * @var \App\TiendaOnlineBundle\Entity\Institucion
     */
    private $institucion;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->detalles = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return Lista
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return Lista
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set borrado
     *
     * @param integer $borrado
     * @return Lista
     */
    public function setBorrado($borrado)
    {
        $this->borrado = $borrado;

        return $this;
    }

    /**
     * Get borrado
     *
     * @return integer
     */
    public function getBorrado()
    {
        return $this->borrado;
    }

    /**
     * Set created_at
     *
     * @param \DateTime $createdAt
     * @return Lista
     */
    public function setCreatedAt($createdAt)
    {
        $this->created_at = $createdAt;

        return $this;
    }

    /**
     * Get created_at
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->created_at;
    }

    /**
     * Set updated_at
     *
     * @param \DateTime $updatedAt
     * @return Lista
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updated_at = $updatedAt;

        return $this;
    }

    /**
     * Get updated_at
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updated_at;
    }

    /**
     * Add detalles
     *
     * @param \App\TiendaOnlineBundle\Entity\DetalleLista $detalles
     * @return Lista
     */
    public function addDetalle(\App\TiendaOnlineBundle\Entity\DetalleLista $detalles)
    {
        $this->detalles[] = $detalles;

        return $this;
    }

    /**
     * Remove detalles
     *
     * @param \App\TiendaOnlineBundle\Entity\DetalleLista $detalles
     */
    public function removeDetalle(\App\TiendaOnlineBundle\Entity\DetalleLista $detalles)
    {
        $this->detalles->removeElement($detalles);
    }

    /**
     * Get detalles
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getDetalles()
    {
        return $this->detalles;
    }

    /**
     * Set institucion
     *
     * @param \App\TiendaOnlineBundle\Entity\Institucion $institucion
     * @return Lista
     */
    public function setInstitucion(\App\TiendaOnlineBundle\Entity\Institucion $institucion = null)
    {
        $this->institucion = $institucion;

        return $this;
    }

    /**
     * Get institucion
     *
     * @return \App\TiendaOnlineBundle\Entity\Institucion
     */
    public function getInstitucion()
    {
        return $this->institucion;
    }
    /**
     * @ORM\PrePersist
     */
    public function preInsert()
    {
        // Add your code here
    }

    /**
     * @ORM\PreUpdate
     */
    public function preUpdate()
    {
        // Add your code here
    }
}


text:
package net.liftweb
package mocks

import common.Logger

import scala.collection.mutable.HashMap
import scala.collection.JavaConverters._

import java.io.PrintWriter
import java.io.StringReader
import java.io.BufferedReader
import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.io.StringBufferInputStream
import java.nio.file.{Files, Paths}
import java.util.Arrays
import java.util.Date
import java.util.Locale
import java.util.Vector
import javax.servlet._
import javax.servlet.http._

/**
 * An example of how to use these mock classes in your unit tests:
 *
 *   def testLiftCore = {
 *     val output = new ByteArrayOutputStream
 *     val outputStream = new MockServletOutputStream(output)
 *     val writer = new PrintWriter(outputStream)
 *
 *     val req = new MockHttpServletRequest
 *     req.method = "GET"
 *     req.path = "/"
 *     val res = new MockHttpServletResponse(writer, outputStream)
 *
 *     val filter = new LiftFilter
 *     filter.init(new MockFilterConfig(new MockServletContext("target/test1-1.0-SNAPSHOT")))
 *     filter.doFilter(req, res,new DoNothingFilterChain)
 *     assertTrue(output.toString.startsWith("<?xml"))
 *   }
 */

/**
 * A Mock ServletContext. LiftFilter expects a ServletContext inside a FilterConfig
 *
 * @param target the target directory where your template files live
 *
 * @author Steve Jenson (stevej@pobox.com)
 */
class MockServletContext(var target: String) extends ServletContext {
  def getInitParameter(f: String): String = null
  def getInitParameterNames(): java.util.Enumeration[String] = new Vector[String]().elements
  def getAttribute(f: String): Object = null
  def getAttributeNames(): java.util.Enumeration[String]  = new Vector[String]().elements
  def removeAttribute(name: String) {}
  def setAttribute(name: String, o: Object) {}
  def getContext(path: String): ServletContext  = this
  def getMajorVersion() = 2
  def getMimeType(file: String): String = null
  def getMinorVersion() = 3
  def getRealPath(path: String): String = null
  def getNamedDispatcher(name: String): RequestDispatcher = null
  def getRequestDispatcher(path: String): RequestDispatcher = null
  def getResource(path: String): java.net.URL = null
  def getResourceAsStream(path: String): java.io.InputStream = {
    val file = Paths.get(target + path)
    if (Files.exists(file)) {
      Files.newInputStream(file)
    } else {
      null
    }
  }

  def getResourcePaths(path: String): java.util.Set[String] = null
  def getServerInfo(): String = null
  def getServlet(name: String): Servlet = null
  def getServletContextName(): String = null
  def getServletNames(): java.util.Enumeration[String] = new Vector[String]().elements
  def getServlets(): java.util.Enumeration[Servlet] = new Vector[Servlet]().elements
  def log(msg: String, t: Throwable) {
    t.printStackTrace
    log(msg)
  }
  def log(e: Exception, msg: String) {
    e.printStackTrace
    log(msg)
  }
  def log(msg: String) = println("MockServletContext.log: " + msg)
  def getContextPath(): String = null

  def addFilter(x$1: String,x$2: Class[_ <: javax.servlet.Filter]): FilterRegistration.Dynamic = null
  def addFilter(x$1: String,x$2: javax.servlet.Filter): FilterRegistration.Dynamic = null
  def addFilter(x$1: String,x$2: String): FilterRegistration.Dynamic = null

  def addListener(listenerClass: Class[_ <: java.util.EventListener]): Unit = ()
  def addListener[T <: java.util.EventListener](listener: T): Unit = ()
  def addListener(listenerClass: String): Unit = ()

  def addServlet(servletNAme: String, servletClass: Class[_ <: javax.servlet.Servlet]): ServletRegistration.Dynamic = null
  def addServlet(servletName: String, servlet: javax.servlet.Servlet): ServletRegistration.Dynamic = null
  def addServlet(servletName: String, servletClass: String): ServletRegistration.Dynamic = null

  // This remains unimplemented since we can't provide a Null here due to type restrictions.
  def createFilter[T <: javax.servlet.Filter](filter: Class[T]): T = ???
  def createListener[T <: java.util.EventListener](listener: Class[T]): T = ???
  def createServlet[T <: javax.servlet.Servlet](servletClass: Class[T]): T = ???

  def getDefaultSessionTrackingModes(): java.util.Set[SessionTrackingMode] = Set.empty[SessionTrackingMode].asJava

  def declareRoles(roles: String*): Unit = ()
  def getClassLoader(): ClassLoader = getClass.getClassLoader
  def getEffectiveMajorVersion(): Int = 0
  def getEffectiveMinorVersion(): Int = 0
  def getEffectiveSessionTrackingModes(): java.util.Set[javax.servlet.SessionTrackingMode] = null
  def getFilterRegistration(x$1: String): javax.servlet.FilterRegistration = null
  def getFilterRegistrations(): java.util.Map[String, _ <: javax.servlet.FilterRegistration] = null
  def getJspConfigDescriptor(): javax.servlet.descriptor.JspConfigDescriptor = null
  def getServletRegistration(x$1: String): javax.servlet.ServletRegistration = null
  def getServletRegistrations(): java.util.Map[String, _ <: javax.servlet.ServletRegistration] = null
  def getSessionCookieConfig(): javax.servlet.SessionCookieConfig = null
  def setInitParameter(key: String,value: String): Boolean = true
  def setSessionTrackingModes(trackingModes: java.util.Set[javax.servlet.SessionTrackingMode]): Unit = ()
  def getVirtualServerName(): String = null
}

/**
 * A Mock FilterConfig. Construct with a MockServletContext and pass into
 * LiftFilter.init
 */
class MockFilterConfig(servletContext: ServletContext) extends FilterConfig {
  def getFilterName(): String = "LiftFilter" // as in lift's default web.xml
  def getInitParameter(key: String): String = null
  def getInitParameterNames(): java.util.Enumeration[String]  = new Vector[String]().elements
  def getServletContext(): ServletContext = servletContext
}

/**
 * A FilterChain that does nothing.
 *
 * @author Steve Jenson (stevej@pobox.com)
 */
class DoNothingFilterChain extends FilterChain with Logger {
  def doFilter(req: ServletRequest, res: ServletResponse) { debug("Doing nothing on filter chain") }
}

/**
 * A Mock ServletInputStream. Pass in any ol InputStream like a ByteArrayInputStream.
 *
 * @author Steve Jenson (stevej@pobox.com)
 */
class MockServletInputStream(is: InputStream) extends ServletInputStream {
  def read() = is.read()
  def isFinished(): Boolean = is.available() > 0
  def isReady(): Boolean = true
  def setReadListener(x$1: javax.servlet.ReadListener): Unit = ()
}

/**
 * A Mock ServletOutputStream. Pass in any ol' OutputStream like a ByteArrayOuputStream.
 *
 * @author Steve Jenson (stevej@pobox.com)
 */
class MockServletOutputStream(os: ByteArrayOutputStream) extends ServletOutputStream {
  def write(b: Int) {
    os.write(b)
  }

  def isReady(): Boolean = true
  def setWriteListener(x$1: javax.servlet.WriteListener): Unit = ()
}

/**
 * A Mock HttpSession implementation.
 *
 * @author Steve Jenson (stevej@pobox.com)
 */
class MockHttpSession extends HttpSession {
  @volatile protected var values: Map[String, Object] = Map()
  @volatile protected var attr: Map[String, Object] = Map()

  protected var maxii: Int = 0
  protected var creationTime: Long = System.currentTimeMillis
  def isNew = false
  def invalidate {}
  def getValue(key: String): Object = values.get(key) match {
    case Some(v) => v
    case None => null
  }
  def removeValue(key: String): Unit = values -= key
  def putValue(key: String, value: Object): Unit = values += (key -> value)
  def getAttribute(key: String): Object = attr.get(key) match {
      case Some(v) => v
      case None => null
    }
  def removeAttribute(key: String): Unit = attr -= key
  def setAttribute(key: String, value: Object): Unit = attr += (key -> value)
  def getValueNames(): Array[String] = values.keys.toList.toArray
  def getAttributeNames(): java.util.Enumeration[String] = new java.util.Enumeration[String] {
    private val keys = attr.keys.iterator
    def hasMoreElements() = keys.hasNext
    def nextElement(): String = keys.next
  }
  def getSessionContext(): HttpSessionContext = null
  def getMaxInactiveInterval(): Int = maxii
  def setMaxInactiveInterval(i: Int): Unit = maxii = i
  def getServletContext(): ServletContext = null
  def getLastAccessedTime(): Long = 0L
  def getId(): String = null
  def getCreationTime(): Long = creationTime
}


text:
import {
  cyan700,
  grey600,
  pinkA100, pinkA200, pinkA400,
  fullWhite,
} from '../colors';
import {fade} from '../../colorManipulator';
import spacing from '../spacing';

export default {
  spacing: spacing,
  fontFamily: 'Roboto, sans-serif',
  palette: {
    primary1Color: cyan700,
    primary2Color: cyan700,
    primary3Color: grey600,
    accent1Color: pinkA200,
    accent2Color: pinkA400,
    accent3Color: pinkA100,
    textColor: fullWhite,
    secondaryTextColor: fade(fullWhite, 0.7),
    alternateTextColor: '#303030',
    canvasColor: '#303030',
    borderColor: fade(fullWhite, 0.3),
    disabledColor: fade(fullWhite, 0.3),
    pickerHeaderColor: fade(fullWhite, 0.12),
    clockCircleColor: fade(fullWhite, 0.12),
  },
};


text:
module Chapter1Exercise2 where
import System.Environment

-- Exercise 2:
-- Change the program so it performs a simple arithmetic operation on the two
-- arguments and prints out the result. You can use read to convert a string to
-- a number, and show to convert a number back into a string. Play around with
-- different operations.

main :: IO ()
main = do
  -- Doing this prefix notation style, like Lisp!
  -- Could use readMaybe, some let bindings, and other stuff too, but I'm trying
  -- not to overengineer this *too* much. :)
  args <- getArgs
  (putStrLn . show) $ case args !! 0 of
    "+"   -> ((read (args !! 1)) :: Double) + ((read (args !! 2)) :: Double)
    "-"   -> ((read (args !! 1)) :: Double) - ((read (args !! 2)) :: Double)
    "*"   -> ((read (args !! 1)) :: Double) * ((read (args !! 2)) :: Double)
    "/"   -> ((read (args !! 1)) :: Double) / ((read (args !! 2)) :: Double)
    _     -> 0 -- default error...


text:
/*  Example of a code-generator for a DEC Alpha                     */

#include "dt.h"

/*  This struct can be used to implement machine-specific           */
/*  addressing-modes.                                               */
/*  Not used in this code-generrator.                               */
struct AddressingMode{
  int flags;
  int base;
  int align;
  long offset;
};

/*  The number of registers of the target machine.                  */
#define MAXR 64

/*  Number of commandline-options the code-generator accepts.       */
#define MAXGF 10

/*  If this is set to zero vbcc will not generate ICs where the     */
/*  target operand is the same as the 2nd source operand.           */
/*  This can sometimes simplify the code-generator, but usually     */
/*  the code is better if the code-generator allows it.             */
#define USEQ2ASZ 1

/*  This specifies the smallest integer type that can be added to a */
/*  pointer.                                                        */
#define MINADDI2P LONG

/*  If the bytes of an integer are ordered most significant byte    */
/*  byte first and then decreasing set BIGENDIAN to 1.              */
#define BIGENDIAN 0

/*  If the bytes of an integer are ordered lest significant byte    */
/*  byte first and then increasing set LITTLEENDIAN to 1.           */
#define LITTLEENDIAN 1

/*  Note that BIGENDIAN and LITTLEENDIAN are mutually exclusive.    */

/*  If switch-statements should be generated as a sequence of       */
/*  SUB,TST,BEQ ICs rather than COMPARE,BEQ ICs set this to 1.      */
/*  This can yield better code on some machines.                    */
#define SWITCHSUBS 1

/*  In optimizing compilation certain library memcpy/strcpy-calls   */
/*  with length known at compile-time will be inlined using an      */
/*  ASSIGN-IC if the size is less or equal to INLINEMEMCPY.         */
/*  The type used for the ASSIGN-IC will be UNSIGNED|CHAR.          */
#define INLINEMEMCPY 1024

/*  Parameters are sometimes passed in registers without __reg.     */
#define HAVE_REGPARMS 1

/*  Parameters on the stack should be pushed in order rather than   */
/*  in reverse order.                                               */
#define ORDERED_PUSH 1

/*  Structure for reg_parm().                                       */
struct reg_handle{
    int nextr;
};

/* size of buffer for asm-output */
#define EMIT_BUF_LEN 1024 /* should be enough */
/* number of asm-output lines buffered */
#define EMIT_BUF_DEPTH 4

/*  We have no asm_peephole to optimize assembly-output */
#define HAVE_TARGET_PEEPHOLE 0


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: >
    Returns a boolean value (not a Boolean object) computed by
    ToBoolean(value)
es5id: 15.6.1.1_A1_T4
description: Used various undefined values and null as argument
---*/

//CHECK#1
if( typeof Boolean(undefined) !== "boolean" ) {
  $ERROR('#1.1: typeof Boolean(undefined) should be "boolean", actual is "'+typeof Boolean(undefined)+'"');
}
if( Boolean(undefined) !== false ) {
  $ERROR('#1.2: Boolean(undefined) should be false');
}

//CHECK#2
if( typeof Boolean(void 0) !== "boolean" ) {
  $ERROR('#2.1: typeof Boolean(void 0) should be "boolean", actual is "'+typeof Boolean(void 0)+'"');
}
if( Boolean(void 0) !== false ) {
  $ERROR('#2.2: Boolean(void 0) should be false');
}

//CHECK#3
if( typeof Boolean(function(){}()) !== "boolean" ) {
  $ERROR('#3.1: typeof Boolean(function(){}()) should be "boolean", actual is "'+typeof Boolean(function(){}())+'"');
}
if( Boolean(function(){}()) !== false ) {
  $ERROR('#3.2: Boolean(function(){}()) should be false');
}

//CHECK#4
if( typeof Boolean(null) !== "boolean" ) {
  $ERROR('#4.1: typeof Boolean(null) should be "boolean", actual is "'+typeof Boolean(null)+'"');
}
if( Boolean(null) !== false ) {
  $ERROR('#4.2: Boolean(null) should be false');
}

//CHECK#5
if( typeof Boolean(x) !== "boolean" ) {
  $ERROR('#5.1: var x; typeof Boolean(x) should be "boolean", actual is "'+typeof Boolean(x)+'"');
}
if( Boolean(x) !== false ) {
  $ERROR('#5.2: var x; Boolean(x) should be false');
}
var x;


text:
import os
import json
from.error import DependencyError
class OnPassiveLoadPathResolver(object):
	def __init__(self,dependency,resolve_config_path):
		self.dependency=dependency
		self.resolve_config_path=resolve_config_path
	def resolve(self):
		config=self.__read_config()
		if self.dependency.sha1!=config['sha1']:
			raise DependencyError('Failed sha1 check',self.dependency)
		if config['is_symlink']:
			self.dependency.is_symlink=config['is_symlink']
			self.dependency.real_path=str(config['real_path'])
		path=str(config['path'])
		if not os.path.isdir(path):
			raise DependencyError('Invalid path: "{}"'.format(path),self.dependency)
		return path
	def __read_config(self):
		config_path=os.path.join(self.resolve_config_path,self.dependency.name+'.resolve.json')
		if not os.path.isfile(config_path):
			raise DependencyError('No config - re-run configure',self.dependency)
		with open(config_path,'r')as config_file:
			return json.load(config_file)


text:
package cashier.resource;

import java.util.ArrayList;
import cashier.exceptions.connection.ConnectionDisabledException;
import cashier.net.*;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Cashier data access object containing getters/accessors and mutators/setters and a toString method that formats add class data members in a string
 * for easy output.  The object contains Google Gson annotations and structure for JSON serialization and deserialization of the data.  Class resource
 * constants are provided for easy Cashier Query object formation.
 *
 * @author  Andrew Koerner
 * @version 1.0
 *
 */
public class Till extends Resource {

	@Expose(serialize = false, deserialize = false) public static final String TABLE = "tills";
	@Expose(serialize = false, deserialize = false) public static final String RESOURCE = "till";
	@SerializedName(Till.RESOURCE)
	@Expose(serialize = true, deserialize = true) private Data data;

	/*-Resource Constants-*/
	@Expose(serialize = false, deserialize = false) public static final String ID = "id";
	@Expose(serialize = false, deserialize = false) public static final String STORE_ID = "store_id";
	@Expose(serialize = false, deserialize = false) public static final String TITLE = "title";
	@Expose(serialize = false, deserialize = false) public static final String DESCRIPTION = "description";
	@Expose(serialize = false, deserialize = false) public static final String MINIMUM_TRANSFER = "minimum_transfer";
	@Expose(serialize = false, deserialize = false) public static final String MINIMUM_BALANCE = "minimum_balance";
	@Expose(serialize = false, deserialize = false) public static final String RETAINABLE = "retainable";
	@Expose(serialize = false, deserialize = false) public static final String ACTIVE = "active";

	private class Data {
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.ID) public int id;
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.STORE_ID) public int storeId;
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.TITLE) public String title;
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.DESCRIPTION) public String description;
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.MINIMUM_TRANSFER) public int minimumTransfer;
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.MINIMUM_BALANCE) public int minimumBalance;
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.RETAINABLE) public boolean retainable;
		@Expose(serialize = true, deserialize = true)
		@SerializedName(Till.ACTIVE) public boolean active;
	}

	public static ArrayList<Resource> find(int id) throws ConnectionDisabledException {
		return Resource.find(id, Till.RESOURCE, Till.TABLE);
	}

	public static ArrayList<Resource> all() throws ConnectionDisabledException {
		return Resource.all(Till.RESOURCE, Till.TABLE);
	}

	public static ArrayList<Resource> all(int limit, int offset) throws ConnectionDisabledException {
		return Resource.all(limit, offset, Till.RESOURCE, Till.TABLE);
	}

	public static Response destroy(int id) throws ConnectionDisabledException {
		return Resource.destroy(id, Till.RESOURCE, Till.TABLE);
	}

	public static ArrayList<Resource> query(Query query) throws ConnectionDisabledException {
		return Resource.query(query, Till.RESOURCE, Till.TABLE);
	}
	public Till() {
		super();
		this.data = new Data();
		this.setTable(Till.TABLE);
		this.setResource(Till.RESOURCE);
	}

	@Override
	public String toString() {
		return "Till [id=" + this.data.id + ", storeId=" + this.data.storeId
				+ ", title=" + this.data.title + ", description="
				+ this.data.description + ", minimumTransfer="
				+ this.data.minimumTransfer + ", minimumBalance="
				+ this.data.minimumBalance + ", retainable="
				+ this.data.retainable + ", active=" + this.data.active + "]";
	}

    ///////////////////////
	//Getters and Setters//
	///////////////////////
	public int getId() {
		return this.data.id;
	}

	public int getStoreId() {
		return this.data.storeId;
	}

	public String getTitle() {
		return this.data.title;
	}

	public String getDescription() {
		return this.data.description;
	}

	public int getMinimumTransfer() {
		return this.data.minimumTransfer;
	}

	public int getMinimumBalance() {
		return this.data.minimumBalance;
	}

	public boolean isRetainable() {
		return this.data.retainable;
	}

	public boolean isActive() {
		return this.data.active;
	}

	public void setId(int id) {
		this.data.id = id;
	}

	public void setStoreId(int storeId) {
		this.data.storeId = storeId;
	}

	public void setTitle(String title) {
		this.data.title = title;
	}

	public void setDescription(String description) {
		this.data.description = description;
	}

	public void setMinimumTransfer(int minimumTransfer) {
		this.data.minimumTransfer = minimumTransfer;
	}

	public void setMinimumBalance(int minimumBalance) {
		this.data.minimumBalance = minimumBalance;
	}

	public void setRetainable(boolean retainable) {
		this.data.retainable = retainable;
	}

	public void setActive(boolean active) {
		this.data.active = active;
	}

}


text:
import { connect } from 'amqp-connection-manager';
import { logger } from './local-logging';

const rabbitmqHost = process.env.RABBITMQ_HOST || 'broker';
const rabbitmqUsername = process.env.RABBITMQ_USERNAME || 'guest';
const rabbitmqPassword = process.env.RABBITMQ_PASSWORD || 'guest';

let channelWrapperLogs;

export function initSendToLagoonLogs() {
  const connection = connect(
    [`amqp://${rabbitmqUsername}:${rabbitmqPassword}@${rabbitmqHost}`],
    // @ts-ignore
    { json: true }
  );

  connection.on('connect', ({ url }) =>
    logger.verbose('lagoon-logs: Connected to %s', url, {
      action: 'connected',
      url
    })
  );
  connection.on('disconnect', params =>
    // @ts-ignore
    logger.error('lagoon-logs: Not connected, error: %s', params.err.code, {
      action: 'disconnected',
      reason: params
    })
  );

  // Cast any to ChannelWrapper to get type-safetiness through our own code
  channelWrapperLogs = connection.createChannel({
    setup: channel =>
      Promise.all([
        channel.assertExchange('lagoon-logs', 'direct', { durable: true })
      ])
  });
}

export async function sendToLagoonLogs(
  severity: string,
  project: string,
  uuid: string,
  event: string,
  meta: any,
  message: string
): Promise<void> {
  const payload = {
    severity,
    project,
    uuid,
    event,
    meta,
    message
  };

  try {
    const buffer = Buffer.from(JSON.stringify(payload));
    const packageName = process.env.npm_package_name || '';
    const options = {
      persistent: true,
      appId: packageName
    };
    await channelWrapperLogs.publish('lagoon-logs', '', buffer, options);

    logger.log(severity, `lagoon-logs: Send to lagoon-logs: ${message}`);
  } catch (error) {
    logger.error(
      `lagoon-logs: Error send to rabbitmq lagoon-logs exchange, error: ${error}`
    );
  }
}


text:
"""Controllers for custom landing pages."""

from __future__ import annotations

from core.controllers import acl_decorators
from core.controllers import base

class FractionLandingRedirectPage(base.BaseHandler):
    """The handler redirecting to the Fractions landing page."""

    URL_PATH_ARGS_SCHEMAS = {}
    HANDLER_ARGS_SCHEMAS = {
        'GET': {}
    }

    @acl_decorators.open_access
    def get(self):
        """Handles GET requests."""
        self.redirect('/math/fractions')

class TopicLandingRedirectPage(base.BaseHandler):
    """The handler redirecting the old landing page URL to the new one."""

    URL_PATH_ARGS_SCHEMAS = {
        'topic': {
            'schema': {
                'type': 'basestring'
            }
        }
    }
    HANDLER_ARGS_SCHEMAS = {
        'GET': {}
    }

    @acl_decorators.open_access
    def get(self, topic):
        """Handles GET requests.

        Args:
            topic: str. Topic of page to be redirected to.
        """
        self.redirect('/math/%s' % topic)


text:
package com.nestpia.nest.plugins;

import android.content.Intent;
import android.net.Uri;

/**
 * Created by john on 4/2/15.
 */
public class mapgetdir extends AbstractPlugin {

	@Override
	public void execute(String[] data) {
		if (data != null && data.length >= 2) {
			String l = String.format("geo:%s,%s", data[0], data[1]);

			Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(l));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
			startActivity(intent);
		}

		callbackWithMessage(0, null);
	}

	@Override
	public boolean onActivityResult(int requestCode, int resultCode, Intent intent) {
		return false;
	}

}


text:
title: BSD operating system
---
## BSD operating system

![BSD operating system, most notably freeBSD: the power to serve](https://www.freebsd.org/layout/images/logo-red.png)

### Overview

Berkeley Software Distribution (BSD) is a group of related open source Unix-like operating systems (OS) with origins in early versions of Research Unix at Bell Labs.
FreeBSD is the most popular member.

BSD is configured for internet hosting, web hosting, and hosting many servers on one system.
It is the first OS to have added an internet protocol.
BSD OSes have a very strongly enforced time-sharing system, which makes them most useful where resources are shared between processes.
As a comparision, the Linux OS is known to be preferred for single-task processes such as supercomputers and desktops.
The effective BSD multi-tasking forced-interrupt part of timesharing gets in the way of dedicated single processes.

BSD includes a 'Jails' system which is somewhat analogous to Linux Containers --except with additional security and flexibility in implementation.

### More Information:

[FreeBSD (Wikipedia.org)](https://en.wikipedia.org/wiki/FreeBSD)

[OpenBSD (Wikipedia.org)](https://en.wikipedia.org/wiki/OpenBSD)

[NetBSD (Wikipedia.org)](https://en.wikipedia.org/wiki/NetBSD)

[Comparison of BSD operating systems (Wikipedia.org)](https://en.wikipedia.org/wiki/Comparison_of_BSD_operating_systems)


text:
package com.thomashaertel.regattatimer;

import android.os.Bundle;

import preference.WearPreferenceActivity;

public class SettingsActivity extends WearPreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.layout.preferences);
    }

}


text:
import { render } from '@testing-library/react';
import { mocked } from 'jest-mock';
import { IServerVersions, MatrixClient } from 'matrix-js-sdk/src/matrix';
import React from 'react';

import LoginWithQRSection from '../../../../../src/components/views/settings/devices/LoginWithQRSection';
import { MatrixClientPeg } from '../../../../../src/MatrixClientPeg';
import { SettingLevel } from '../../../../../src/settings/SettingLevel';
import SettingsStore from '../../../../../src/settings/SettingsStore';

function makeClient() {
    return mocked({
        getUser: jest.fn(),
        isGuest: jest.fn().mockReturnValue(false),
        isUserIgnored: jest.fn(),
        isCryptoEnabled: jest.fn(),
        getUserId: jest.fn(),
        on: jest.fn(),
        isSynapseAdministrator: jest.fn().mockResolvedValue(false),
        isRoomEncrypted: jest.fn().mockReturnValue(false),
        mxcUrlToHttp: jest.fn().mockReturnValue('mock-mxcUrlToHttp'),
        removeListener: jest.fn(),
        currentState: {
            on: jest.fn(),
        },
    } as unknown as MatrixClient);
}

function makeVersions(unstableFeatures: Record<string, boolean>): IServerVersions {
    return {
        versions: [],
        unstable_features: unstableFeatures,
    };
}

describe('<LoginWithQRSection />', () => {
    beforeAll(() => {
        jest.spyOn(MatrixClientPeg, 'get').mockReturnValue(makeClient());
    });

    const defaultProps = {
        onShowQr: () => {},
        versions: makeVersions({}),
    };

    const getComponent = (props = {}) =>
        (<LoginWithQRSection {...defaultProps} {...props} />);

    describe('should not render', () => {
        it('no support at all', () => {
            const { container } = render(getComponent());
            expect(container).toMatchSnapshot();
        });

        it('feature enabled', async () => {
            await SettingsStore.setValue('feature_qr_signin_reciprocate_show', null, SettingLevel.DEVICE, true);
            const { container } = render(getComponent());
            expect(container).toMatchSnapshot();
        });

        it('only feature + MSC3882 enabled', async () => {
            await SettingsStore.setValue('feature_qr_signin_reciprocate_show', null, SettingLevel.DEVICE, true);
            const { container } = render(getComponent({ versions: makeVersions({ 'org.matrix.msc3882': true }) }));
            expect(container).toMatchSnapshot();
        });
    });

    describe('should render panel', () => {
        it('enabled by feature + MSC3882 + MSC3886', async () => {
            await SettingsStore.setValue('feature_qr_signin_reciprocate_show', null, SettingLevel.DEVICE, true);
            const { container } = render(getComponent({ versions: makeVersions({
                'org.matrix.msc3882': true,
                'org.matrix.msc3886': true,
            }) }));
            expect(container).toMatchSnapshot();
        });
    });
});


text:
layout: post
title: International Domain Names
header: International Domain Names
category: Features
author: mike
---
It's been a busy few weeks here at CloudCannon. We've just pushed a whole heap of changes you're going to love.

###International Domain Names###
First up is International Domain name support. We've had hundreds of designers making some amazing websites on CloudCannon using their own custom domains. Unfortunately, there have been a few designers who couldn't use CloudCannon because we didn't support domain names in their language. Well, fear not, those days are over. We now have full support of [IDN](http://en.wikipedia.org/wiki/Internationalized_domain_name).

###Tweaks/Bug fixes###
We're making CloudCannon better everyday, the past few weeks we've had a massive focus on improving the usability of the application. Now you'll see a lot more help text and useful gestures to help you when you get stuck. If you ever get completely stuck or just want a chat, click on the question icon and the top right of the screen and send us a message. We'll reply as soon as we can.


text:
<?php

namespace Robo;

use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;

class Application extends SymfonyApplication
{
    /**
     * @param string $name
     * @param string $version
     */
    public function __construct($name, $version)
    {
        parent::__construct($name, $version);

        $this->getDefinition()
            ->addOption(
                new InputOption('--simulate', null, InputOption::VALUE_NONE, 'Run in simulated mode (show what would have happened).')
            );
        $this->getDefinition()
            ->addOption(
                new InputOption('--progress-delay', null, InputOption::VALUE_REQUIRED, 'Number of seconds before progress bar is displayed in long-running task collections. Default: 2s.', Config::DEFAULT_PROGRESS_DELAY)
            );

        $this->getDefinition()
            ->addOption(
                new InputOption('--define', '-D', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Define a configuration item value.', [])
            );
    }

    /**
     * @param string $roboFile
     * @param string $roboClass
     */
    public function addInitRoboFileCommand($roboFile, $roboClass)
    {
        $createRoboFile = new Command('init');
        $createRoboFile->setDescription("Intitalizes basic RoboFile in current dir");
        $createRoboFile->setCode(function () use ($roboClass, $roboFile) {
            $output = Robo::output();
            $output->writeln("<comment>  ~~~ Welcome to Robo! ~~~~ </comment>");
            $output->writeln("<comment>  " . basename($roboFile) . " will be created in the current directory </comment>");
            file_put_contents(
                $roboFile,
                '<?php'
                . "\n/**"
                . "\n * This is project's console commands configuration for Robo task runner."
                . "\n *"
                . "\n * @see http://robo.li/ and http://www.github.com/imi-digital/irobo"
                . "\n */"
                . "\n"
                . "\ndefine('IROBO_MIN_VERSION', '" . Robo::VERSION . "'); // define minium irobo version here"
                . "\n"
                . "\nif (\\Robo\\Robo::APPLICATION_NAME != 'iRobo'"
                . "\n   || \\Composer\\Semver\\Comparator::lessThan(\\Robo\\Robo::VERSION, IROBO_MIN_VERSION)) {"
                . "\n   echo 'ERROR: This script needs iRobo (not only robo) version ' . IROBO_MIN_VERSION"
                . "\n   . ' or later - download at http://irobo.imi.de/irobo.phar '. PHP_EOL;"
                . "\n   die(1);"
                . "\n}"
                . "\n"
                . "\nclass " . $roboClass . " extends \\Robo\\Tasks"
                . "\n{"
                . "\n   use \\iMi\\RoboPack\\LoadTasks;"
                . "\n"
                . "\n   // define public methods as commands"
                . "\n}"
                . "\n"
            );
            $output->writeln("<comment>  Edit this file to add your commands! </comment>");
        });
        $this->add($createRoboFile);
    }
}