text:
"""Support for HomematicIP Cloud binary sensor."""
import logging

from homeassistant.components.binary_sensor import BinarySensorDevice

from . import DOMAIN as HMIPC_DOMAIN, HMIPC_HAPID, HomematicipGenericDevice
from .device import ATTR_GROUP_MEMBER_UNREACHABLE

_LOGGER = logging.getLogger(__name__)

ATTR_MOTIONDETECTED = 'motion detected'
ATTR_PRESENCEDETECTED = 'presence detected'
ATTR_POWERMAINSFAILURE = 'power mains failure'
ATTR_WINDOWSTATE = 'window state'
ATTR_MOISTUREDETECTED = 'moisture detected'
ATTR_WATERLEVELDETECTED = 'water level detected'
ATTR_SMOKEDETECTORALARM = 'smoke detector alarm'
ATTR_TODAY_SUNSHINE_DURATION = 'today_sunshine_duration_in_minutes'

async def async_setup_platform(
        hass, config, async_add_entities, discovery_info=None):
    """Set up the HomematicIP Cloud binary sensor devices."""
    pass

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the HomematicIP Cloud binary sensor from a config entry."""
    from homematicip.aio.device import (
        AsyncDevice, AsyncShutterContact, AsyncMotionDetectorIndoor,
        AsyncMotionDetectorOutdoor, AsyncSmokeDetector, AsyncWaterSensor,
        AsyncRotaryHandleSensor, AsyncMotionDetectorPushButton,
        AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)

    from homematicip.aio.group import (
        AsyncSecurityGroup, AsyncSecurityZoneGroup)

    home = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]].home
    devices = []
    for device in home.devices:
        if isinstance(device, (AsyncShutterContact, AsyncRotaryHandleSensor)):
            devices.append(HomematicipShutterContact(home, device))
        if isinstance(device, (AsyncMotionDetectorIndoor,
                               AsyncMotionDetectorOutdoor,
                               AsyncMotionDetectorPushButton)):
            devices.append(HomematicipMotionDetector(home, device))
        if isinstance(device, AsyncSmokeDetector):
            devices.append(HomematicipSmokeDetector(home, device))
        if isinstance(device, AsyncWaterSensor):
            devices.append(HomematicipWaterDetector(home, device))
        if isinstance(device, (AsyncWeatherSensorPlus,
                               AsyncWeatherSensorPro)):
            devices.append(HomematicipRainSensor(home, device))
        if isinstance(device, (AsyncWeatherSensor, AsyncWeatherSensorPlus,
                               AsyncWeatherSensorPro)):
            devices.append(HomematicipStormSensor(home, device))
            devices.append(HomematicipSunshineSensor(home, device))
        if isinstance(device, AsyncDevice) and device.lowBat is not None:
            devices.append(HomematicipBatterySensor(home, device))

    for group in home.groups:
        if isinstance(group, AsyncSecurityGroup):
            devices.append(HomematicipSecuritySensorGroup(home, group))
        elif isinstance(group, AsyncSecurityZoneGroup):
            devices.append(HomematicipSecurityZoneSensorGroup(home, group))

    if devices:
        async_add_entities(devices)

class HomematicipShutterContact(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud shutter contact."""

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'door'

    @property
    def is_on(self):
        """Return true if the shutter contact is on/open."""
        from homematicip.base.enums import WindowState

        if self._device.sabotage:
            return True
        if self._device.windowState is None:
            return None
        return self._device.windowState != WindowState.CLOSED

class HomematicipMotionDetector(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud motion detector."""

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'motion'

    @property
    def is_on(self):
        """Return true if motion is detected."""
        if self._device.sabotage:
            return True
        return self._device.motionDetected

class HomematicipSmokeDetector(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud smoke detector."""

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'smoke'

    @property
    def is_on(self):
        """Return true if smoke is detected."""
        from homematicip.base.enums import SmokeDetectorAlarmType
        return (self._device.smokeDetectorAlarmType
                != SmokeDetectorAlarmType.IDLE_OFF)

class HomematicipWaterDetector(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud water detector."""

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'moisture'

    @property
    def is_on(self):
        """Return true, if moisture or waterlevel is detected."""
        return self._device.moistureDetected or self._device.waterlevelDetected

class HomematicipStormSensor(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud storm sensor."""

    def __init__(self, home, device):
        """Initialize storm sensor."""
        super().__init__(home, device, "Storm")

    @property
    def icon(self):
        """Return the icon."""
        return 'mdi:weather-windy' if self.is_on else 'mdi:pinwheel-outline'

    @property
    def is_on(self):
        """Return true, if storm is detected."""
        return self._device.storm

class HomematicipRainSensor(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud rain sensor."""

    def __init__(self, home, device):
        """Initialize rain sensor."""
        super().__init__(home, device, "Raining")

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'moisture'

    @property
    def is_on(self):
        """Return true, if it is raining."""
        return self._device.raining

class HomematicipSunshineSensor(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud sunshine sensor."""

    def __init__(self, home, device):
        """Initialize sunshine sensor."""
        super().__init__(home, device, 'Sunshine')

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'light'

    @property
    def is_on(self):
        """Return true if sun is shining."""
        return self._device.sunshine

    @property
    def device_state_attributes(self):
        """Return the state attributes of the illuminance sensor."""
        attr = super().device_state_attributes
        if hasattr(self._device, 'todaySunshineDuration') and \
                self._device.todaySunshineDuration:
            attr[ATTR_TODAY_SUNSHINE_DURATION] = \
                self._device.todaySunshineDuration
        return attr

class HomematicipBatterySensor(HomematicipGenericDevice, BinarySensorDevice):
    """Representation of a HomematicIP Cloud low battery sensor."""

    def __init__(self, home, device):
        """Initialize battery sensor."""
        super().__init__(home, device, 'Battery')

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'battery'

    @property
    def is_on(self):
        """Return true if battery is low."""
        return self._device.lowBat

class HomematicipSecurityZoneSensorGroup(HomematicipGenericDevice,
                                         BinarySensorDevice):
    """Representation of a HomematicIP Cloud security zone group."""

    def __init__(self, home, device, post='SecurityZone'):
        """Initialize security zone group."""
        device.modelType = 'HmIP-{}'.format(post)
        super().__init__(home, device, post)

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return 'safety'

    @property
    def available(self):
        """Security-Group available."""
        # A security-group must be available, and should not be affected by
        # the individual availability of group members.
        return True

    @property
    def device_state_attributes(self):
        """Return the state attributes of the security zone group."""
        attr = super().device_state_attributes

        if self._device.motionDetected:
            attr[ATTR_MOTIONDETECTED] = True
        if self._device.presenceDetected:
            attr[ATTR_PRESENCEDETECTED] = True
        from homematicip.base.enums import WindowState
        if self._device.windowState is not None and \
                self._device.windowState != WindowState.CLOSED:
            attr[ATTR_WINDOWSTATE] = str(self._device.windowState)
        if self._device.unreach:
            attr[ATTR_GROUP_MEMBER_UNREACHABLE] = True
        return attr

    @property
    def is_on(self):
        """Return true if security issue detected."""
        if self._device.motionDetected or \
                self._device.presenceDetected or \
                self._device.unreach or \
                self._device.sabotage:
            return True
        from homematicip.base.enums import WindowState
        if self._device.windowState is not None and \
                self._device.windowState != WindowState.CLOSED:
            return True
        return False

class HomematicipSecuritySensorGroup(HomematicipSecurityZoneSensorGroup,
                                     BinarySensorDevice):
    """Representation of a HomematicIP security group."""

    def __init__(self, home, device):
        """Initialize security group."""
        super().__init__(home, device, 'Sensors')

    @property
    def device_state_attributes(self):
        """Return the state attributes of the security group."""
        attr = super().device_state_attributes

        if self._device.powerMainsFailure:
            attr[ATTR_POWERMAINSFAILURE] = True
        if self._device.moistureDetected:
            attr[ATTR_MOISTUREDETECTED] = True
        if self._device.waterlevelDetected:
            attr[ATTR_WATERLEVELDETECTED] = True
        from homematicip.base.enums import SmokeDetectorAlarmType
        if self._device.smokeDetectorAlarmType is not None and \
                self._device.smokeDetectorAlarmType != \
                SmokeDetectorAlarmType.IDLE_OFF:
            attr[ATTR_SMOKEDETECTORALARM] = \
                str(self._device.smokeDetectorAlarmType)

        return attr

    @property
    def is_on(self):
        """Return true if safety issue detected."""
        parent_is_on = super().is_on
        from homematicip.base.enums import SmokeDetectorAlarmType
        if parent_is_on or \
                self._device.powerMainsFailure or \
                self._device.moistureDetected or \
                self._device.waterlevelDetected or \
                self._device.lowBat:
            return True
        if self._device.smokeDetectorAlarmType is not None and \
                self._device.smokeDetectorAlarmType != \
                SmokeDetectorAlarmType.IDLE_OFF:
            return True
        return False


text:
package org.apache.causeway.core.metamodel.facets.members.disabled;

import org.springframework.lang.Nullable;

import org.apache.causeway.core.metamodel.facetapi.FacetHolder;
import org.apache.causeway.core.metamodel.facets.WhereValueFacet;
import org.apache.causeway.core.metamodel.interactions.DisablingInteractionAdvisor;
import org.apache.causeway.core.metamodel.object.ManagedObject;

import lombok.NonNull;

/**
 * Disable a property, collection or action.
 *
 * <p>
 * In the standard Apache Causeway Programming Model, corresponds to annotating the
 * member with <tt>@Disabled</tt>.
 */
public interface DisabledFacet
extends WhereValueFacet, DisablingInteractionAdvisor {

    public enum Semantics {

        /** regular semantics */
        DISABLED,

        /** inverted semantics */
        ENABLED;

        public boolean isDisabled() {
            return this == DISABLED;
        }

        public boolean isEnabled() {
            return this == ENABLED;
        }
    }

    /**
     * "Special" phrase returned for facets which are always disabled.
     */
    String ALWAYS_DISABLED_REASON = "Always disabled";

    /**
     * The reason why the (feature of the) target object is currently disabled,
     * or <tt>null</tt> if enabled.
     */
    @Nullable
    public String disabledReason(ManagedObject target);

    public Semantics getSemantics();

    // -- PREDICATES

    static boolean isAlwaysDisabled(final @NonNull FacetHolder facetHolder) {
        return WhereValueFacet.isAlways(facetHolder, DisabledFacet.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
CKEDITOR.plugins.setLang( 'find', 'de', {
	find: 'Suchen',
	findOptions: 'Suchoptionen',
	findWhat: 'Suche nach:',
	matchCase: 'Groß-/Kleinschreibung beachten',
	matchCyclic: 'Zyklische Suche',
	matchWord: 'Nur ganze Worte suchen',
	notFoundMsg: 'Der angegebene Text wurde nicht gefunden.',
	replace: 'Ersetzen',
	replaceAll: 'Alle ersetzen',
	replaceSuccessMsg: '%1 Vorkommen ersetzt.',
	replaceWith: 'Ersetze mit:',
	title: 'Suchen und Ersetzen'
} );


text:
<?php
/**
 * Template functions used for pages.
 *
 * @package storefront
 */

if ( ! function_exists( 'storefront_page_header' ) ) {
	/**
	 * Display the post header with a link to the single post
	 * @since 1.0.0
	 */
	function storefront_page_header() {
		?>

			<?php the_title( '
', '
' ); ?>

		<?php
	}
}

if ( ! function_exists( 'storefront_page_content' ) ) {
	/**
	 * Display the post content with a link to the single post
	 * @since 1.0.0
	 */
	function storefront_page_content() {
		?>

			<?php the_content(); ?>
			<?php
				wp_link_pages( array(
					'before' => '
' . __( 'Pages:', 'storefront' ),
					'after'  => '
',
				) );
			?>

		<?php
	}
}


text:
package com.aps;

import java.io.Serializable;

final class x
    implements Serializable
{

    protected byte a[];
    protected short b;
    protected byte c[];

    x()
    {
        a = new byte[16];
        b = 0;
        c = new byte[32];
    }
}


text:
<?xml version="1.0"  encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
	<Set name="contextPath">/identity</Set>
	<Set name="war">
		<Property name="jetty.webapps" default="." />/identity.war
	</Set>
	<Set name="extractWAR">true</Set>

	<!-- <Set name="extraClasspath"></Set> -->
</Configure>


text:
[![Build Status](https://travis-ci.org/marteinn/genres.svg?branch=master)](https://travis-ci.org/marteinn/genres)
[![PyPI version](https://badge.fury.io/py/genres.svg)](http://badge.fury.io/py/genres)

# Genres
Genres is a python library that analyzes text with musical context (such as reviews) in order to determine musical genres

## How it works
Genres is based on a list of genres and tags (database), those are then compared against supplied text using regexp and points for ranking are calculated. Found genres are compared agains its main category to avoid mismatches.

## Usage

The api is simple.

    >>> import genres
    >>> r = genres.find("Pink Floyd is a rock band)
    >>> r
    ['rock']

It detects multiple genres, as long as they are related to the same category

    >>> import genres
    >>> genres.find("Acid jazz, an electronic masterpiece.")
    ['acid jazz', 'jazz']

In this example the two occurences of electronic and techno triumps rock.

    >>> import genres
    >>> genres.find("Electronic music with a techno vibe. Different from rock")
    ['techno', 'electronic']

## Database

The database is a simple list of words, separated by newline and structured like this:

|Data|Description|
|-------------|:-------------:|
|Rock|Main category|
|Rock|Sub category|
|Metal,0.8|Sub category, Percentage of full rank (10*0.8=8)|
|-Pink Floyd|Tag associated to category rock|
|#Test|Comment|
||Categories are sparated with newline|
|Jazz|...|
|Post-bop|...|

Genres are distributed with a database that can be found under `genres/data.txt` and the genre structure is based on [Allmusic genre categorisation](http://en.wikipedia.org/wiki/List_of_popular_music_genres).

It is possible to supply your own database:

```python
import genres

db_obj = genres.db.Db("./example.txt")
finder_obj = genres.finder.Finder(db_obj)
```

## Installation

Genres can easily be installed through pip.

    $ pip install genres

## Tests

This library include tests, just run `python runtests.py.`

## Contributing

Want to contribute? Awesome. Just send a pull request.

## License

Genres is released under the [MIT License](http://www.opensource.org/licenses/MIT).


text:
<?php

namespace Ftven\Sdk\Api\Test;

use Ftven\Sdk\ApiInterface;
use Ftven\Sdk\SdkInterface;

/**
 * @author Olivier Hoareau <olivier@phppro.fr>
 */
class TestApi implements ApiInterface
{
    /**
     * @var SdkInterface
     */
    protected $sdk;
    /**
     * @return string
     */
    public function getName()
    {
        return 'test';
    }
    /**
     * @param SdkInterface $sdk
     *
     * @return $this|void
     */
    public function setSdk(SdkInterface $sdk)
    {
        $this->sdk = $sdk;

        return $this;
    }
    /**
     * @return SdkInterface
     */
    public function getSdk()
    {
        return $this->sdk;
    }
    /**
     * @param int $number
     *
     * @return int
     */
    public function computeDouble($number)
    {
        return 2 * $number;
    }
}


text:
/**
 * Faroe Islands subdivision code.
 *
 * ISO 3166-1 alpha-2: FO
 *
 * @link http://www.geonames.org/FO/administrative-division-faroe-islands.html
 */
export const FO: (string | null)[] = [null, ''];


text:
"""
Setup script for installing yellowbrick.
See http://bbengfort.github.io/programmer/2016/01/20/packaging-with-pypi.html
"""

##########################################################################
## Imports
##########################################################################

import os
import codecs

from setuptools import setup
from setuptools import find_packages

##########################################################################
## Package Information
##########################################################################

## Basic information
NAME         = "yellowbrick"
DESCRIPTION  = "A suite of visual analysis and diagnostic tools for machine learning."
AUTHOR       = "Rebecca Bilbro, Benjamin Bengfort"
EMAIL        = "yellowbrick@googlegroups.com"
MAINTAINER   = "Benjamin Bengfort"
LICENSE      = "Apache 2"
REPOSITORY   = "https://github.com/districtdatalabs/yellowbrick"
PACKAGE      = "yellowbrick"
URL          = "http://scikit-yb.org/"

## Define the keywords
KEYWORDS     = ('visualization', 'machine learning', 'scikit-learn', 'matplotlib', 'data science')

## Define the classifiers
## See https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS  = (
    'Development Status :: 4 - Beta',
    'Intended Audience :: Developers',
    'Intended Audience :: Science/Research',
    'License :: OSI Approved :: Apache Software License',
    'Natural Language :: English',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
    'Programming Language :: Python :: 3.7',
    'Topic :: Software Development',
    'Topic :: Software Development :: Libraries :: Python Modules',
    'Topic :: Scientific/Engineering :: Visualization',
)

## Important Paths
PROJECT      = os.path.abspath(os.path.dirname(__file__))
REQUIRE_PATH = "requirements.txt"
VERSION_PATH = os.path.join(PACKAGE, "version.py")
PKG_DESCRIBE = "DESCRIPTION.rst"

## Directories to ignore in find_packages
EXCLUDES     = (
    "tests", "bin", "docs", "fixtures", "register", "notebooks",
    "examples", "binder", "paper",
)

##########################################################################
## Helper Functions
##########################################################################

def read(*parts):
    """
    Assume UTF-8 encoding and return the contents of the file located at the
    absolute path from the REPOSITORY joined with *parts.
    """
    with codecs.open(os.path.join(PROJECT, *parts), 'rb', 'utf-8') as f:
        return f.read()

def get_version(path=VERSION_PATH):
    """
    Reads the python file defined in the VERSION_PATH to find the get_version
    function, and executes it to ensure that it is loaded correctly. Separating
    the version in this way ensures no additional code is executed.
    """
    namespace = {}
    exec(read(path), namespace)
    return namespace['get_version'](short=True)

def get_requires(path=REQUIRE_PATH):
    """
    Yields a generator of requirements as defined by the REQUIRE_PATH which
    should point to a requirements.txt output by `pip freeze`.
    """
    for line in read(path).splitlines():
        line = line.strip()
        if line and not line.startswith('#'):
            yield line

def get_description_type(path=PKG_DESCRIBE):
    """
    Returns the long_description_content_type based on the extension of the
    package describe path (e.g. .txt, .rst, or .md).
    """
    _, ext = os.path.splitext(path)
    return {
        ".rst": "text/x-rst",
        ".txt": "text/plain",
        ".md": "text/markdown",
    }[ext]

##########################################################################
## Define the configuration
##########################################################################

config = {
    "name": NAME,
    "version": get_version(),
    "description": DESCRIPTION,
    "long_description": read(PKG_DESCRIBE),
    "long_description_content_type": get_description_type(PKG_DESCRIBE),
    "classifiers": CLASSIFIERS,
    "keywords": KEYWORDS,
    "license": LICENSE,
    "author": AUTHOR,
    "author_email": EMAIL,
    "url": URL,
    "maintainer": MAINTAINER,
    "maintainer_email": EMAIL,
    "project_urls": {
        "Documentation": URL,
        "Download": "{}/tarball/v{}".format(REPOSITORY, get_version()),
        "Source": REPOSITORY,
        "Tracker": "{}/issues".format(REPOSITORY),
    },
    "download_url": "{}/tarball/v{}".format(REPOSITORY, get_version()),
    "packages": find_packages(where=PROJECT, exclude=EXCLUDES),
    "package_data": {
        "yellowbrick": ["datasets/manifest.json"],
    },
    "zip_safe": False,
    "entry_points": {
        "console_scripts": [],
    },
    "install_requires": list(get_requires()),
    "python_requires": ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4",
    "setup_requires":["pytest-runner"],
    "tests_require":["pytest"],
}

##########################################################################
## Run setup script
##########################################################################

if __name__ == '__main__':
    setup(**config)


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

namespace __Centuries_to_Nanoseconds
{
    class Program
    {
        static void Main(string[] args)
        {
            var centuries = int.Parse(Console.ReadLine());
            var years = centuries * 100;
            var days = (ulong)(years * 365.2422);
            decimal hours = days * 24;
            decimal min = hours * 60;
            decimal sec = min * 60;
            decimal milSec = sec * 1000;
            decimal micSec = milSec * 1000;
            decimal nanoSec = micSec * 1000;

            Console.WriteLine($"{centuries} centuries = {years} years = {days} days = {hours} hours = {min} minutes = {sec} seconds = {milSec} milliseconds = {micSec} microseconds = {nanoSec} nanoseconds");

        }
    }
}


text:
__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"

from androlyze.model.script.AndroScript import AndroScript

# TODO: RENAME THE SCRIPT AND MODULE NAME!!
from androlyze.model.script.dblyze.DBLyze import DBLyze
from pprint import pprint

class ScriptTemplate(AndroScript):
    ''' Template for writing a custom `AndroScript` '''

    VERSION = "0.1"

    def _analyze(self, apk, dalvik_vm_format, vm_analysis, gvm_analysis, *args, **kwargs):
        '''
        Overwrite this function in apk subclass to build your own script!
        Use the `ResultObject` for logging.

        Parameters
        ----------
        apk: EAndroApk
        dalvik_vm_format: DalvikVMFormat
            Parsed .dex file.
            Only available if `needs_dalvik_vm_format` returns True.
        vm_analysis: VMAnalysis
            Dex analyzer.
            Only available if `needs_vmanalysis` returns True.
        gvm_analysis : GVMAnalysis
        '''
        # TODO: CUSTOMIZE

        #categories
        CAT_FILES = "files"

        res = self.res

        res.register_keys([CAT_FILES])

        # files
        res.log(CAT_FILES, apk.get_files())

    def custom_result_object(self):
        '''
        Overwrite this method, if you want to use your own result logging framework/object,
        You can supply it here and access it via `self.cres`.

        E.g. you could return ("", "txt") for simply logging with a string to a .txt file.

        The str representation of it will be stored!

        The `ResultObject` in `self.res` is still existing and internally used to log some meta information.

        Returns
        -------
        tuple<object, str>
            First argument is the result object you want to use,
            the second is the file name extension used for storage (without a leading point)
        '''
        raise NotImplementedError

    def reset(self):
        '''
        Reset the `AndroScript` so that it can be used for a new analysis.
        If you do a custom initialization in your script,
        you probably want do put the init code inside this method.

        Don't forget to call the super `reset` !
        '''
        super(ScriptTemplate, self).reset()

    ############################################################
    #---Script requirements
    ############################################################

    def needs_dalvik_vm_format(self):
        ''' Gives access to the `DalvikVMFormat` object which is a parser for the classes.dex file '''
        return False

    def needs_vmanalysis(self):
        ''' Gives access to the `VMAnalysis` object which is a analyzer for the `DalvikVMFormat` object '''
        return False

    def needs_gvmanalysis(self):
        ''' Gives access to the `GVMAnalysis` object.
        Creates a graph which you can use for export (gexf etc) or do your custom stuff
        '''
        return False

    def needs_xref(self):
        ''' Create cross references '''
        return False

    def needs_dref(self):
        ''' Create data references '''
        return False

    ############################################################
    #---Options
    ############################################################

    def create_script_stats(self):
        ''' If true, create some script statistics and
        write them into the `ResultObject` '''
        return False

    def is_big_res(self):
        ''' Return true, if your result may exceed 16mb.
        This will store your data (str() of `self.cres`) in mongodb's gridfs.

        You don't need to return true, if you're using a different result object! (see :py:meth:`.custom_result_object`)
        This will be done automatically.
        '''
        return False

class Eval(DBLyze):

    # Evaluate ScripTemplate
    ON_SCRIPT = ScriptTemplate

    def _evaluate(self, storage):
        '''
        Evaluate the script results.

        Parameters
        ----------
        storage : RedundantStorage
        '''

        # Use either the AndroLyze query API:

        # iterate over the results (one result per APK = iteration)
        for ordered_dict in self.action_query_result_db():
            # do something else than just printing the dictionary
            #pprint(dict(ordered_dict))
            pass

        # Or perform a direct query on the mongodb API:

        # get the mongodb singleton
        mongodb = storage.result_db_storage
        for ordered_dict in mongodb.get_res_coll().find({"script meta.name" : "ScriptTemplate"}, {"apk meta" : 1}):
            pprint(dict(ordered_dict))

# testing code
if __name__ == '__main__':
    for res in AndroScript.test(ScriptTemplate, ["../../../../testenv/apks/a2dp.Vol.apk"]):
        print res
        print res.write_to_json()


text:
package org.plugface.core.internal;

import org.plugface.core.internal.di.Graph;
import org.plugface.core.internal.di.Node;

import java.util.Collection;

/**
 * Internal class used to create a dependency graph
 * for plugin dependency injection.
 */
public class DependencyResolver {
    private final AnnotationProcessor processor;

    public DependencyResolver(AnnotationProcessor processor) {
        this.processor = processor;
    }

    public Collection<Node<?>> resolve(Collection<Class<?>> pluginClasses) {

        final Graph graph = new Graph();
        for (Class<?> pluginClass : pluginClasses) {
            final Collection<Node<?>> deps = processor.getDependencies(pluginClass);
            final Node<?> node = new Node<>(pluginClass);
            if (deps.isEmpty()) {
                graph.addLeaf(node);
            } else {
                graph.addEdges(node, deps);
            }
        }

        return graph.resolve();
    }
}


text:
package org.apache.drill.exec.fn.hive;

import java.time.LocalDateTime;
import java.util.List;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.drill.categories.HiveStorageTest;
import org.apache.drill.categories.SlowTest;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.exec.compile.ClassTransformer;
import org.apache.drill.exec.hive.HiveTestBase;
import org.apache.drill.exec.server.options.OptionValue;
import org.apache.drill.test.QueryTestUtil;
import org.apache.drill.test.TestBuilder;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.google.common.collect.Lists;

@Category({SlowTest.class, HiveStorageTest.class})
public class TestInbuiltHiveUDFs extends HiveTestBase {

  @Test // DRILL-3273
  public void testConcatWS() throws Exception {
    testBuilder()
        .sqlQuery("SELECT concat_ws(string_field, string_part, '|') as rst from hive.readtest")
        .unOrdered()
        .baselineColumns("rst")
        .baselineValues("stringstringfield|")
        .baselineValues(new Object[] { null })
        .go();
  }

  @Test // DRILL-3273
  public void testEncode() throws Exception {
    testBuilder()
        .sqlQuery("SELECT encode(varchar_field, 'UTF-8') as rst from hive.readtest")
        .unOrdered()
        .baselineColumns("rst")
        .baselineValues("varcharfield".getBytes())
        .baselineValues(new Object[] { null })
        .go();
  }

  @Test
  public void testXpath_Double() throws Exception {
    final String query = "select xpath_double ('20<c>40</c>', 'a/b * a/c') as col \n" +
        "from hive.kv \n" +
        "limit 0";

    final TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
        .setMinorType(TypeProtos.MinorType.FLOAT8)
        .setMode(TypeProtos.DataMode.OPTIONAL)
        .build();

    final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
    expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));

    testBuilder()
        .sqlQuery(query)
        .schemaBaseLine(expectedSchema)
        .build()
        .run();
  }

  @Test // DRILL-4459
  public void testGetJsonObject() throws Exception {
    testBuilder()
        .sqlQuery("select convert_from(json, 'json') as json from hive.simple_json " +
            "where GET_JSON_OBJECT(simple_json.json, '$.employee_id') like 'Emp2'")
        .ordered()
        .baselineColumns("json")
        .baselineValues(TestBuilder.mapOf("employee_id","Emp2","full_name","Kamesh",
            "first_name","Bh","last_name","Venkata","position","Store"))
        .go();
  }

  @Test // DRILL-3272
  public void testIf() throws Exception {
    testBuilder()
        .sqlQuery("select `if`(1999 > 2000, 'latest', 'old') `Period` from hive.kv limit 1")
        .ordered()
        .baselineColumns("Period")
        .baselineValues("old")
        .go();
  }

  @Test // DRILL-4618
  public void testRand() throws Exception {
    String query = "select 2*rand()=2*rand() col1 from (values (1))";
    testBuilder()
            .sqlQuery(query)
            .unOrdered()
            .baselineColumns("col1")
            .baselineValues(false)
            .go();
  }

  @Test //DRILL-4868
  public void testEmbeddedHiveFunctionCall() throws Exception {
    // TODO(DRILL-2326) temporary until we fix the scalar replacement bug for this case
    final OptionValue srOption = QueryTestUtil.setupScalarReplacementOption(bits[0], ClassTransformer.ScalarReplacementOption.TRY);

    try {
      final String[] queries = {
          "SELECT convert_from(unhex(key2), 'INT_BE') as intkey \n" +
              "FROM cp.`functions/conv/conv.json`",
      };

      for (String query: queries) {
        testBuilder()
            .sqlQuery(query)
            .ordered()
            .baselineColumns("intkey")
            .baselineValues(1244739896)
            .baselineValues(new Object[] { null })
            .baselineValues(1313814865)
            .baselineValues(1852782897)
            .build()
            .run();
      }

    } finally {
      // restore the system option
      QueryTestUtil.restoreScalarReplacementOption(bits[0], srOption.string_val);
    }
  }

  @Test
  public void testLastDay() throws Exception {
    testBuilder()
        .sqlQuery("select last_day(to_date('1994-02-01','yyyy-MM-dd')) as `LAST_DAY` from (VALUES(1))")
        .unOrdered()
        .baselineColumns("LAST_DAY")
        .baselineValues("1994-02-28")
        .go();
  }

  @Test
  public void testDatediff() throws Exception {
    testBuilder()
        .sqlQuery("select datediff(date '1996-03-01', timestamp '1997-02-10 17:32:00.0') as `DATEDIFF` from (VALUES(1))")
        .unOrdered()
        .baselineColumns("DATEDIFF")
        .baselineValues(-346)
        .go();
  }

  @Test
  public void testFromUTCTimestamp() throws Exception {
    testBuilder()
        .sqlQuery("select from_utc_timestamp('1970-01-01 08:00:00','PST') as PST_TIMESTAMP from (VALUES(1))")
        .unOrdered()
        .baselineColumns("PST_TIMESTAMP")
        .baselineValues(LocalDateTime.parse("1970-01-01T00:00:00.0"))
        .go();
  }

  @Test
  public void testToUTCTimestamp() throws Exception {
    testBuilder()
        .sqlQuery("select to_utc_timestamp('1970-01-01 00:00:00','PST') as UTC_TIMESTAMP from (VALUES(1))")
        .unOrdered()
        .baselineColumns("UTC_TIMESTAMP")
        .baselineValues(LocalDateTime.parse("1970-01-01T08:00:00.0"))
        .go();
  }

}


text:
import os
from setuptools import setup

ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)

test_requirements = []
requirements = ['splitstream>=1.2.0']

setup(
    name="streamrpc",
    url="https://github.com/evolvIQ/streamrpc",
    author="Rickard Lyrenius",
    author_email="rickard@evolviq.com",
    version='1.0.2',
    description="XML-RPC / JSON-RPC over pipe pair.",
    packages=['streamrpc'],
    install_requires=requirements + test_requirements,
    zip_safe=True,
    classifiers=[
        "License :: OSI Approved :: Apache Software License",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.2",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy"],
    test_suite='tests'
)


text:
//
//  CurioDB.h
//  CurioSDK
//
//  Changed by Can Ciloglu on 30/01/15.
//  Created by Harun Esur on 17/09/14.
//  Copyright (c) 2014 Turkcell. All rights reserved.
//

#import <sqlite3.h>

typedef void(^CurioDBMutexRun)(sqlite3 *db);

@interface CurioDB : NSObject

@property BOOL isDbOpen;

/**
 Returns shared instance of CurioDB

 @return CurioDB shared instance
 */
+ (CS_INSTANCETYPE) shared;

/**
    Executes block in thread-safe mode with Sqlite3 db
 */
- (void) invokeBlockSafe:(CurioDBMutexRun)curioDBMutexRunBlock;

/**
    Executes sql with thread-safe mode

    @return If sql executed successfully with no error
 */
- (BOOL) executeSafe:(NSString *)sql;

@end


text:
<?php

namespace Sonata\DoctrineORMAdminBundle\Filter;

use Doctrine\ORM\QueryBuilder;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Form\Type\Filter\ChoiceType;

class ChoiceFilter extends Filter
{
    /**
     * @param ProxyQueryInterface|QueryBuilder $queryBuilder
     *
     * {@inheritdoc}
     */
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
    {
        if (!$data || !is_array($data) || !array_key_exists('type', $data) || !array_key_exists('value', $data)) {
            return;
        }

        if (is_array($data['value'])) {
            if (count($data['value']) == 0) {
                return;
            }

            if (in_array('all', $data['value'], true)) {
                return;
            }

            // Have to pass IN array value as parameter. See: http://www.doctrine-project.org/jira/browse/DDC-3759
            $completeField = sprintf('%s.%s', $alias, $field);
            $parameterName = $this->getNewParameterName($queryBuilder);
            if ($data['type'] == ChoiceType::TYPE_NOT_CONTAINS) {
                $this->applyWhere($queryBuilder, $queryBuilder->expr()->notIn($completeField, ':'.$parameterName));
            } else {
                $this->applyWhere($queryBuilder, $queryBuilder->expr()->in($completeField, ':'.$parameterName));
            }
            $queryBuilder->setParameter($parameterName, $data['value']);
        } else {
            if ($data['value'] === '' || $data['value'] === null || $data['value'] === false || $data['value'] === 'all') {
                return;
            }

            $parameterName = $this->getNewParameterName($queryBuilder);

            if ($data['type'] == ChoiceType::TYPE_NOT_CONTAINS) {
                $this->applyWhere($queryBuilder, sprintf('%s.%s <> :%s', $alias, $field, $parameterName));
            } else {
                $this->applyWhere($queryBuilder, sprintf('%s.%s = :%s', $alias, $field, $parameterName));
            }

            $queryBuilder->setParameter($parameterName, $data['value']);
        }
    }

    /**
     * @param string $type
     *
     * @return bool
     */
    private function getOperator($type)
    {
        $choices = array(
            ChoiceType::TYPE_CONTAINS         => 'IN',
            ChoiceType::TYPE_NOT_CONTAINS     => 'NOT IN',
            ChoiceType::TYPE_EQUAL            => '=',
        );

        return isset($choices[$type]) ? $choices[$type] : false;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultOptions()
    {
        return array();
    }

    /**
     * {@inheritdoc}
     */
    public function getRenderSettings()
    {
        return array('sonata_type_filter_default', array(
            'operator_type' => 'sonata_type_equal',
            'field_type'    => $this->getFieldType(),
            'field_options' => $this->getFieldOptions(),
            'label'         => $this->getLabel(),
        ));
    }
}


text:
import re
import json
import unittest
import platform
import subprocess
from time import sleep
from os import path, symlink, listdir

TESTS_DIR = path.dirname(path.abspath(__file__))
ANALYZER_ROOT = path.dirname(TESTS_DIR)

def cuckoo_root():
    """ It's ../../cuckoo """
    # ./
    return path.join(path.dirname(ANALYZER_ROOT), "cuckoo")

def submit_job(target, options):
    # Force using OS X machines for running targets
    options.update({"platform" : "darwin"})
    # Too lazy to re-implement this stuff myself, so use an existing tool
    submit_py = path.join(cuckoo_root(), "utils", "submit.py")
    cmd = ["python", submit_py]
    # Transform options into --options and compose a command line args string
    def dummy_flatten(list_of_lists):
        return sum(list_of_lists, [])
    cmd += dummy_flatten([["--"+x, y] for (x, y) in options.items()])
    cmd += [target]
    subprocess.check_call(cmd)

def latest_analysis_results():
    storage_dir = path.realpath(path.join(cuckoo_root(), "storage", "analyses", "latest"))
    with open(path.join(storage_dir, "reports", "report.json"), "r") as report_file:
        report = json.load(report_file)
    return {
        "report": report,
        "files" : listdir(path.join(storage_dir, "files")),
        "logs"  : listdir(path.join(storage_dir, "logs")),
        "analysis_log" : path.join(storage_dir, "analysis.log")
    }

def cuckoo_analysis(target, options):
    """ Returns a dictionary with the following keys:
    :report       => dictionary contents of report.json,
    :files        => list of dropped files (full local paths),
    :logs         => list of log files (full local paths),
    :analysis_log => analysis.log full path
    """
    # Add new analysis job to the Cuckoo database
    submit_job(target, options)
    # then try to read it's output and get analysis results from there
    def read_cuckoo_output():
        return CuckooTests.cuckoo.stderr.readline().rstrip()
    def is_completion(line):
        return None != re.search(r'.*Task #[0-9]{3}: analysis .* completed', line)
    def is_error(line):
        # Nah, don't even care about returning anything on error
        if re.search(r'.*ERROR: Analysis failed:', line) != None:
            raise Exception("Cuckoo analysis failed")
    line = read_cuckoo_output()
    while (not is_completion(line)) and (not is_error(line)):
        line = read_cuckoo_output()
    # Now go to the results directory and parse all the data
    return latest_analysis_results()

def build_target(target_name):
    # Try to build a target when on OS X
    if platform.system() == "Darwin":
        source = target_name + ".c"
        output = target_name
        subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
    # Or try to use the pre-built one otherwise
    elif not path.exists(target_name):
        raise Exception("Unable to build OS X targets on non-darwin machine")

@unittest.skipUnless(path.exists(cuckoo_root()), "Unable to locate Cuckoo")
class CuckooTests(unittest.TestCase):

    cuckoo = None

    @classmethod
    def setUpClass(cls):
        # Symlink the darwin analyzer into Cuckoo's analyzer directory
        source = path.join(ANALYZER_ROOT, "analyzer", "darwin")
        destination = path.join(cuckoo_root(), "analyzer", "darwin")
        # setUpClass() is called even when @unittest.skipUnless skips
        # all the tests, so we verify it again...
        if path.exists(cuckoo_root()):
            if not path.exists(destination):
                symlink(source, destination)
            # Initialize Cuckoo Host
            cls.launch_cuckoo()

    @classmethod
    def tearDownClass(cls):
        if path.exists(cuckoo_root()):
            cls.terminate_cuckoo()

    def current_target(self):
        return path.join(TESTS_DIR, "assets", self._testMethodName)

    def setUp(self):
        # We won't delete compiled targets after tests, so they can be reused
        # on platforms other than OS X (cross compilation is a hell of work, you know)
        build_target(self.current_target())

    #-#-#-#-#-#-#-# #-#-#-#-#-#-#-# #-#-#-#-#-#-#-#
    # Cuckoo management
    #-#-#-#-#-#-#-# #-#-#-#-#-#-#-# #-#-#-#-#-#-#-#

    @classmethod
    def launch_cuckoo(cls):
        # Let's hope Python *is* in PATH
        cmd = ["python", path.join(cuckoo_root(), "cuckoo.py")]
        cls.cuckoo = subprocess.Popen(cmd, stderr=subprocess.PIPE)
        # Now see if it launched successfully.
        # Basically, what we do here is reading Cuckoo's output until we hit the
        # success message *OR* the whole thing is terminated due to an error
        isalive = (lambda x: x.poll() == None)
        while isalive(cls.cuckoo):
            if "Waiting for analysis tasks" in cls.cuckoo.stderr.readline().rstrip():
                break
            sleep(0.1)
        # so if Cuckoo is dead at this moment, something bad has happend
        if not isalive(cls.cuckoo):
            raise Exception("Cuckoo failed to launch. Try scripts/bootstrap_host.sh")

    @classmethod
    def terminate_cuckoo(cls):
        try:
            cls.cuckoo.terminate()
        except OSError as _:
            pass # it's likely to be already terminated

    #-#-#-#-#-#-#-# #-#-#-#-#-#-#-# #-#-#-#-#-#-#-#
    # Test cases
    #-#-#-#-#-#-#-# #-#-#-#-#-#-#-# #-#-#-#-#-#-#-#

    def test_cuckoo_dropped_files(self):
        # given
        target = self.current_target()
        options = {
        }
        # when
        results = cuckoo_analysis(target, options)
        # then
        self.assertTrue(1 == len([x for x in results["files"] if x.endswith("something.txt")]))

    def test_cuckoo_parents_and_children(self):
        # given
        target = self.current_target()
        options = {
        }
        # when
        results = cuckoo_analysis(target, options)
        # then
        # We have a separate log file for each target: one for the parent process
        # and one for the child
        self.assertTrue(len(results["logs"]) == 2)


text:
require 'spec_helper'

describe 'user pages' do
  let(:roster) { create :roster }
  let(:admin_membership) { create :membership, roster: roster, admin: true }
  let(:admin) { admin_membership.user }
  context 'viewing the index' do
    before :each do
      set_current_user(admin)
      visit root_path
      click_link 'Manage users'
    end
    it 'directs you to the appropriate page' do
      expect(current_url).to end_with roster_users_path(admin_membership.roster)
      expect(page).to have_selector 'h1', text: 'Users'
    end
    context 'active users' do
      it 'shows inactive users button' do
        expect(page).to have_link 'Inactive users'
      end
      it 'shows deactivate user button on users' do
        expect(page).to have_selector 'td', text: admin.first_name
        expect(page).to have_button 'Deactivate'
      end
      # deactivate user test under system test directory
    end
    context 'inactive users' do
      before :each do
        @inactive_user = create :user, active: false
        @membership = create :membership, roster: roster, user: @inactive_user
        click_link 'Inactive users'
      end
      it 'shows active users button' do
        expect(page).to have_link 'Active users'
      end
      it 'shows activate user button on users' do
        expect(page).to have_selector 'td', text: @inactive_user.first_name
        expect(page).to have_button 'Activate'
      end
      it 'activates a user' do
        click_button 'Activate'
        expect(page).to have_selector 'div', text: 'User has been updated.'
        expect(page).to have_selector 'td', text: @inactive_user.first_name
      end
    end
  end
end


text:
static unsigned int g_bitFlags; //int is 4 bytes or 32 bits, hence 32 bit flags to work with

//generalized bitflag macros
#define BIT(x) (1 << x)
#define BIT_AND(x,y) (x & y)
#define BIT_OR(x,y) (x | y)
#define  BIT_XOR(x,y) (x ^ y)
#define BIT_NOT(x) ~(x)

//===========================================================================================================

//public math methods
//basic math
float CalcShortestAngularDisplacement(const float& startAngle, const float& destinationAngle);
float Clamp(float inValue, float min, float max);
int ClampInt(int inValue, int min, int max);

float SplitFloat(float inVal, double& outIntPart);
float Round(float inVal);
int RoundFloatToNearestInt(float inVal);

//degree and radian conversions
float ConvertRadiansToDegrees(float radians);
float ConvertDegreesToRadians(float degrees);

//range and asymptotic 0-1 methods
float AsymptoticAdd(float normalizedValueA, float normalizedValueB);
float RangeMap(const float& inValue, const float& inStart, const float& inEnd, float outStart, float outEnd);

//interpolate and easing methods
const float Interpolate(float start, float end, float fractionFromStartToEnd);
float GetLoopedParametric(float t, float maxParametric = 1.0f);

//blend functions

//logarithm helpers
float NaturalLogOf(float x);
float LogOf(float x, float base);

//lerp
template<typename T>
const T Interpolate(const T& start, const T& end, float fractionFromStartToEnd);

float SmoothStart(float normalizedValue);
float SmoothStop(float normalizedValue);
float SmoothStep(float normalizedValue);

//bit flag methods and bit magic
bool IsPowerOfTwo(unsigned int x);
//bool AreBitsSet(unsigned int& bitfield, const unsigned int& bitNum);
bool IsBitSet(unsigned int& bitfield, const unsigned char& bitNums);
void SetBit(unsigned int& bitfield,   const unsigned char& bitNums);
void ClearBit(unsigned int& bitfield, const unsigned char& bitNum);
void ToggleBit(unsigned int& bitfield,const unsigned char& bitNum);

//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///inline methods

//===========================================================================================================
//bit flag methods
inline bool IsBitSet(unsigned int& bitfield, const unsigned char& bitNum ){
	return BIT_AND(bitfield , BIT(bitNum)) != 0;
}

//-----------------------------------------------------------------------------------------------------------

inline void SetBit(unsigned int& bitfield, const unsigned char& bitNum){
	bitfield = BIT_OR( bitfield , BIT(bitNum) ); //or in the num to set bit to 1
}

//-----------------------------------------------------------------------------------------------------------

inline void ClearBit(unsigned int& bitfield, const unsigned char& bitNum){
	bitfield = BIT_AND(bitfield, BIT_NOT( BIT(bitNum) ) );
	//bitfield = bitfield & ~BIT(bitNum); //and with not value to clear only that bit to 0
}

//-----------------------------------------------------------------------------------------------------------

inline void ToggleBit(unsigned int& bitfield, const unsigned char& bitNum){
	bitfield = BIT_XOR( bitfield , BIT(bitNum) ); //xor with 2 ^ bitNuM to swap bit to 0 or 1
}

//-----------------------------------------------------------------------------------------------------------
//splits float into int and dec parts, returns dec part
inline float SplitFloat(float inVal, double& outIntPart){
	return (float)std::modf((double)inVal, (double*)&outIntPart);
}

//-----------------------------------------------------------------------------------------------------------

inline float Round(float inVal) {
	return (float)floor(inVal + 0.5);
}

inline int RoundFloatToNearestInt(float inVal){
	return (int)floor(inVal + 0.5);
}

inline float Floor(float inVal) {
	return (float)floor(inVal);
}

//-----------------------------------------------------------------------------------------------------------

//for when the parametric value is less than or greater than 1.0
inline float GetLoopedParametric(float t, float maxParametric) {

	while (t > maxParametric) {
		t -= maxParametric;
	}

	while (t < 0.0f) {
		t += 1.0f;
	}

	return t;
}

//-----------------------------------------------------------------------------------------------------------

template<typename T>
inline const T Interpolate(const T& start, const T& end, float fractionFromStartToEnd) {
	T lerpedValue = Interpolate(start, end, fractionFromStartToEnd);

	return lerpedValue;
}

//-----------------------------------------------------------------------------------------------------------

//get natural base-e logarithm of x
inline float NaturalLogOf(float x) {
	return log(x);
}

//-----------------------------------------------------------------------------------------------------------

inline float LogOf(float x, float base) {
	return NaturalLogOf(x) / NaturalLogOf(base);
}

//===========================================================================================================

#endif


text:
FOUNDATION_EXPORT double HDBaseProjectVersionNumber;
FOUNDATION_EXPORT const unsigned char HDBaseProjectVersionString[];


text:
namespace blink {

namespace {

inline void addGlyphToBuffer(GlyphBuffer* glyphBuffer, float advance, hb_direction_t direction,
    const SimpleFontData* fontData, const HarfBuzzRunGlyphData& glyphData)
{
    FloatPoint startOffset = HB_DIRECTION_IS_HORIZONTAL(direction)
        ? FloatPoint(advance, 0)
        : FloatPoint(0, advance);
    glyphBuffer->add(glyphData.glyph, fontData, startOffset + glyphData.offset);
}

inline void addEmphasisMark(GlyphBuffer* buffer,
    const GlyphData* emphasisData, FloatPoint glyphCenter,
    float midGlyphOffset)
{
    ASSERT(buffer);
    ASSERT(emphasisData);

    const SimpleFontData* emphasisFontData = emphasisData->fontData;
    ASSERT(emphasisFontData);

    bool isVertical = emphasisFontData->platformData().isVerticalAnyUpright()
        && emphasisFontData->verticalData();

    if (!isVertical) {
        buffer->add(emphasisData->glyph, emphasisFontData,
            midGlyphOffset - glyphCenter.x());
    } else {
        buffer->add(emphasisData->glyph, emphasisFontData,
            FloatPoint(-glyphCenter.x(), midGlyphOffset - glyphCenter.y()));
    }
}

inline unsigned countGraphemesInCluster(const UChar* str, unsigned strLength,
    uint16_t startIndex, uint16_t endIndex)
{
    if (startIndex > endIndex) {
        uint16_t tempIndex = startIndex;
        startIndex = endIndex;
        endIndex = tempIndex;
    }
    uint16_t length = endIndex - startIndex;
    ASSERT(static_cast<unsigned>(startIndex + length) <= strLength);
    TextBreakIterator* cursorPosIterator = cursorMovementIterator(&str[startIndex], length);

    int cursorPos = cursorPosIterator->current();
    int numGraphemes = -1;
    while (0 <= cursorPos) {
        cursorPos = cursorPosIterator->next();
        numGraphemes++;
    }
    return std::max(0, numGraphemes);
}

} // anonymous namespace

template<TextDirection direction>
float ShapeResultBuffer::fillGlyphBufferForRun(GlyphBuffer* glyphBuffer,
    const ShapeResult::RunInfo* run, float initialAdvance, unsigned from, unsigned to,
    unsigned runOffset)
{
    if (!run)
        return 0;
    float advanceSoFar = initialAdvance;
    const unsigned numGlyphs = run->m_glyphData.size();
    for (unsigned i = 0; i < numGlyphs; ++i) {
        const HarfBuzzRunGlyphData& glyphData = run->m_glyphData[i];
        uint16_t currentCharacterIndex = run->m_startIndex +
            glyphData.characterIndex + runOffset;
        if ((direction == RTL && currentCharacterIndex >= to)
            || (direction == LTR && currentCharacterIndex < from)) {
            advanceSoFar += glyphData.advance;
        } else if ((direction == RTL && currentCharacterIndex >= from)
            || (direction == LTR && currentCharacterIndex < to)) {
            addGlyphToBuffer(glyphBuffer, advanceSoFar, run->m_direction,
                run->m_fontData.get(), glyphData);
            advanceSoFar += glyphData.advance;
        }
    }
    return advanceSoFar - initialAdvance;
}

float ShapeResultBuffer::fillGlyphBufferForTextEmphasisRun(GlyphBuffer* glyphBuffer,
    const ShapeResult::RunInfo* run, const TextRun& textRun, const GlyphData* emphasisData,
    float initialAdvance, unsigned from, unsigned to, unsigned runOffset)
{
    if (!run)
        return 0;

    unsigned graphemesInCluster = 1;
    float clusterAdvance = 0;

    FloatPoint glyphCenter = emphasisData->fontData->
        boundsForGlyph(emphasisData->glyph).center();

    TextDirection direction = textRun.direction();

    // A "cluster" in this context means a cluster as it is used by HarfBuzz:
    // The minimal group of characters and corresponding glyphs, that cannot be broken
    // down further from a text shaping point of view.
    // A cluster can contain multiple glyphs and grapheme clusters, with mutually
    // overlapping boundaries. Below we count grapheme clusters per HarfBuzz clusters,
    // then linearly split the sum of corresponding glyph advances by the number of
    // grapheme clusters in order to find positions for emphasis mark drawing.
    uint16_t clusterStart = static_cast<uint16_t>(direction == RTL
        ? run->m_startIndex + run->m_numCharacters + runOffset
        : run->glyphToCharacterIndex(0) + runOffset);

    float advanceSoFar = initialAdvance;
    const unsigned numGlyphs = run->m_glyphData.size();
    for (unsigned i = 0; i < numGlyphs; ++i) {
        const HarfBuzzRunGlyphData& glyphData = run->m_glyphData[i];
        uint16_t currentCharacterIndex = run->m_startIndex + glyphData.characterIndex + runOffset;
        bool isRunEnd = (i + 1 == numGlyphs);
        bool isClusterEnd =  isRunEnd || (run->glyphToCharacterIndex(i + 1) + runOffset != currentCharacterIndex);

        if ((direction == RTL && currentCharacterIndex >= to) || (direction != RTL && currentCharacterIndex < from)) {
            advanceSoFar += glyphData.advance;
            direction == RTL ? --clusterStart : ++clusterStart;
            continue;
        }

        clusterAdvance += glyphData.advance;

        if (textRun.is8Bit()) {
            float glyphAdvanceX = glyphData.advance;
            if (Character::canReceiveTextEmphasis(textRun[currentCharacterIndex])) {
                addEmphasisMark(glyphBuffer, emphasisData, glyphCenter, advanceSoFar + glyphAdvanceX / 2);
            }
            advanceSoFar += glyphAdvanceX;
        } else if (isClusterEnd) {
            uint16_t clusterEnd;
            if (direction == RTL)
                clusterEnd = currentCharacterIndex;
            else
                clusterEnd = static_cast<uint16_t>(isRunEnd ? run->m_startIndex + run->m_numCharacters + runOffset : run->glyphToCharacterIndex(i + 1) + runOffset);

            graphemesInCluster = countGraphemesInCluster(textRun.characters16(), textRun.charactersLength(), clusterStart, clusterEnd);
            if (!graphemesInCluster || !clusterAdvance)
                continue;

            float glyphAdvanceX = clusterAdvance / graphemesInCluster;
            for (unsigned j = 0; j < graphemesInCluster; ++j) {
                // Do not put emphasis marks on space, separator, and control characters.
                if (Character::canReceiveTextEmphasis(textRun[currentCharacterIndex]))
                    addEmphasisMark(glyphBuffer, emphasisData, glyphCenter, advanceSoFar + glyphAdvanceX / 2);
                advanceSoFar += glyphAdvanceX;
            }
            clusterStart = clusterEnd;
            clusterAdvance = 0;
        }
    }
    return advanceSoFar - initialAdvance;
}

float ShapeResultBuffer::fillFastHorizontalGlyphBuffer(GlyphBuffer* glyphBuffer,
    TextDirection dir) const
{
    ASSERT(!hasVerticalOffsets());

    float advance = 0;

    for (unsigned i = 0; i < m_results.size(); ++i) {
        const auto& wordResult =
            isLeftToRightDirection(dir) ? m_results[i] : m_results[m_results.size() - 1 - i];
        ASSERT(!wordResult->hasVerticalOffsets());

        for (const auto& run : wordResult->m_runs) {
            ASSERT(run);
            ASSERT(HB_DIRECTION_IS_HORIZONTAL(run->m_direction));

            for (const auto& glyphData : run->m_glyphData) {
                ASSERT(!glyphData.offset.height());

                glyphBuffer->add(glyphData.glyph, run->m_fontData.get(),
                    advance + glyphData.offset.width());
                advance += glyphData.advance;
            }
        }
    }

    ASSERT(!glyphBuffer->hasVerticalOffsets());

    return advance;
}

float ShapeResultBuffer::fillGlyphBuffer(GlyphBuffer* glyphBuffer, const TextRun& textRun,
    unsigned from, unsigned to) const
{
    // Fast path: full run with no vertical offsets
    if (!from && to == static_cast<unsigned>(textRun.length()) && !hasVerticalOffsets())
        return fillFastHorizontalGlyphBuffer(glyphBuffer, textRun.direction());

    float advance = 0;

    if (textRun.rtl()) {
        unsigned wordOffset = textRun.length();
        for (unsigned j = 0; j < m_results.size(); j++) {
            unsigned resolvedIndex = m_results.size() - 1 - j;
            const RefPtr<ShapeResult>& wordResult = m_results[resolvedIndex];
            for (unsigned i = 0; i < wordResult->m_runs.size(); i++) {
                advance += fillGlyphBufferForRun<RTL>(glyphBuffer,
                    wordResult->m_runs[i].get(), advance, from, to,
                    wordOffset - wordResult->numCharacters());
            }
            wordOffset -= wordResult->numCharacters();
        }
    } else {
        unsigned wordOffset = 0;
        for (unsigned j = 0; j < m_results.size(); j++) {
            const RefPtr<ShapeResult>& wordResult = m_results[j];
            for (unsigned i = 0; i < wordResult->m_runs.size(); i++) {
                advance += fillGlyphBufferForRun<LTR>(glyphBuffer,
                    wordResult->m_runs[i].get(), advance, from, to, wordOffset);
            }
            wordOffset += wordResult->numCharacters();
        }
    }

    return advance;
}

float ShapeResultBuffer::fillGlyphBufferForTextEmphasis(GlyphBuffer* glyphBuffer,
    const TextRun& textRun, const GlyphData* emphasisData, unsigned from, unsigned to) const
{
    float advance = 0;
    unsigned wordOffset = textRun.rtl() ? textRun.length() : 0;

    for (unsigned j = 0; j < m_results.size(); j++) {
        unsigned resolvedIndex = textRun.rtl() ? m_results.size() - 1 - j : j;
        const RefPtr<ShapeResult>& wordResult = m_results[resolvedIndex];
        for (unsigned i = 0; i < wordResult->m_runs.size(); i++) {
            unsigned resolvedOffset = wordOffset -
                (textRun.rtl() ? wordResult->numCharacters() : 0);
            advance += fillGlyphBufferForTextEmphasisRun(
                glyphBuffer, wordResult->m_runs[i].get(), textRun, emphasisData,
                advance, from, to, resolvedOffset);
        }
        wordOffset += wordResult->numCharacters() * (textRun.rtl() ? -1 : 1);
    }

    return advance;
}

FloatRect ShapeResultBuffer::selectionRect(TextDirection direction, float totalWidth,
    const FloatPoint& point, int height, unsigned absoluteFrom, unsigned absoluteTo) const
{
    float currentX = 0;
    float fromX = 0;
    float toX = 0;
    bool foundFromX = false;
    bool foundToX = false;

    if (direction == RTL)
        currentX = totalWidth;

    // The absoluteFrom and absoluteTo arguments represent the start/end offset
    // for the entire run, from/to are continuously updated to be relative to
    // the current word (ShapeResult instance).
    int from = absoluteFrom;
    int to = absoluteTo;

    unsigned totalNumCharacters = 0;
    for (unsigned j = 0; j < m_results.size(); j++) {
        const RefPtr<ShapeResult> result = m_results[j];
        if (direction == RTL) {
            // Convert logical offsets to visual offsets, because results are in
            // logical order while runs are in visual order.
            if (!foundFromX && from >= 0 && static_cast<unsigned>(from) < result->numCharacters())
                from = result->numCharacters() - from - 1;
            if (!foundToX && to >= 0 && static_cast<unsigned>(to) < result->numCharacters())
                to = result->numCharacters() - to - 1;
            currentX -= result->width();
        }
        for (unsigned i = 0; i < result->m_runs.size(); i++) {
            if (!result->m_runs[i])
                continue;
            ASSERT((direction == RTL) == result->m_runs[i]->rtl());
            int numCharacters = result->m_runs[i]->m_numCharacters;
            if (!foundFromX && from >= 0 && from < numCharacters) {
                fromX = result->m_runs[i]->xPositionForVisualOffset(from) + currentX;
                foundFromX = true;
            } else {
                from -= numCharacters;
            }

            if (!foundToX && to >= 0 && to < numCharacters) {
                toX = result->m_runs[i]->xPositionForVisualOffset(to) + currentX;
                foundToX = true;
            } else {
                to -= numCharacters;
            }

            if (foundFromX && foundToX)
                break;
            currentX += result->m_runs[i]->m_width;
        }
        if (direction == RTL)
            currentX -= result->width();
        totalNumCharacters += result->numCharacters();
    }

    // The position in question might be just after the text.
    if (!foundFromX && absoluteFrom == totalNumCharacters) {
        fromX = direction == RTL ? 0 : totalWidth;
        foundFromX = true;
    }
    if (!foundToX && absoluteTo == totalNumCharacters) {
        toX = direction == RTL ? 0 : totalWidth;
        foundToX = true;
    }
    if (!foundFromX)
        fromX = 0;
    if (!foundToX)
        toX = direction == RTL ? 0 : totalWidth;

    // None of our runs is part of the selection, possibly invalid arguments.
    if (!foundToX && !foundFromX)
        fromX = toX = 0;
    if (fromX < toX)
        return FloatRect(point.x() + fromX, point.y(), toX - fromX, height);
    return FloatRect(point.x() + toX, point.y(), fromX - toX, height);
}

int ShapeResultBuffer::offsetForPosition(const TextRun& run, float targetX) const
{
    unsigned totalOffset;
    if (run.rtl()) {
        totalOffset = run.length();
        for (unsigned i = m_results.size(); i; --i) {
            const RefPtr<ShapeResult>& wordResult = m_results[i - 1];
            if (!wordResult)
                continue;
            totalOffset -= wordResult->numCharacters();
            if (targetX >= 0 && targetX <= wordResult->width()) {
                int offsetForWord = wordResult->offsetForPosition(targetX);
                return totalOffset + offsetForWord;
            }
            targetX -= wordResult->width();
        }
    } else {
        totalOffset = 0;
        for (const auto& wordResult : m_results) {
            if (!wordResult)
                continue;
            int offsetForWord = wordResult->offsetForPosition(targetX);
            ASSERT(offsetForWord >= 0);
            totalOffset += offsetForWord;
            if (targetX >= 0 && targetX <= wordResult->width())
                return totalOffset;
            targetX -= wordResult->width();
        }
    }
    return totalOffset;
}

} // namespace blink


text:
package team.crazynetwork.raids.commands.shop;

import org.bukkit.event.Listener;

public class ShopListener implements Listener {

}


text:
module Tigerpants
  def self.say_hello
    puts 'hello, tiger, hey'
    puts 'small change'
  end
end


text:
namespace bft {
  namespace vulkanoo {

    class Instance;

    class BFT_VULKANOO_API Surface
    {
    public:

      virtual ~Surface();

      operator VkSurfaceKHR& ();

      operator VkSurfaceKHR const& () const;

    protected:

      Surface(Instance &instance, VkSurfaceKHR surface);

    private:

      Instance &instance;

      VkSurfaceKHR surface;

    };

  }
}


text:
import Types from './actionTypes';
import * as api from '../utils/apis';
import endpoints from '../utils/endpoints';

export const selectedGroupDetails = groupDetails => ({
  type: Types.SELECT_GROUP_ID_TO_ARCHIVE,
  groupDetails
});

export const getMessages = messages => ({
  type: Types.GET_ALL_MESSAGES_FOR_ARCHIVE,
  messages
});

export const archivedMessages = archived => ({
  type: Types.GET_ARCHIVED_MESSAGES,
  archived
});

export const archive = archiveSuccess => ({
  type: Types.ARCHIVE_MESSAGES,
  archiveSuccess
});

export const archiveFailure = failure => ({
  type: Types.ARCHIVE_MESSAGES_FAILURE,
  failure
});

export const getMessagesFailure = failure => ({
  type: Types.GET_ALL_MESSAGES_FOR_ARCHIVE_FAILURE,
  failure
});

export const archivedMessagesFailure = failure => ({
  type: Types.GET_ARCHIVED_MESSAGES_FAILURE,
  failure
});

/**
 * Async action creators to get messages for archive
 * @param {string} token
 * @param {number} groupId
 * @returns {function} dispatch
 */
export const getGroupWithMessages = (token, groupId) => (dispatch) => {
  return api.getEndpoint(endpoints.GET_ONE_GROUP_AND_MESSAGES_PATH
  .replace(':id', `${groupId}`), token)
  .then(
    (success) => {
      const response = { ...success, ...{ status: !!Object.keys(success) } };
      dispatch(getMessages(response));
    },
    (error) => {
      dispatch(getMessagesFailure(error));
    }
  );
};

/**
 * Async action creators to archive messages in a group
 * @param {string} token
 * @param {array} messageIds
 * @param {number} groupId
 * @returns {function} dispatch
 */
export const archiveMessages = (token, messageIds, groupId) => (dispatch) => {
  return api.updateEndpoint(endpoints.ARCHIVE_MESSAGES
  .replace(':id', `${groupId}`), messageIds, token)
  .then(
    (success) => {
      const response = { status: !!Object.keys(success) };
      dispatch(archive(response));
    },
    (error) => {
      dispatch(archiveFailure(error));
    }
  );
};

/**
 * Async action creators to get archived messages in a group
 * @param {string} token
 * @param {number} groupId
 * @returns {function} dispatch
 */
export const getArchivedMessages = (token, groupId) => (dispatch) => {
  return api.getEndpoint(endpoints.GET_ONE_GROUP_AND_MESSAGES_TRUE_PATH
  .replace(':id', `${groupId}`), token)
  .then(
    (success) => {
      const response = { ...success, ...{ status: !!Object.keys(success) } };
      dispatch(archivedMessages(response));
    },
    (error) => {
      dispatch(archivedMessagesFailure(error));
    }
  );
};


text:
<?php

namespace Magento\Sales\Block\Adminhtml\Order\Status\Assign;

/**
 * Assign order status to order state form
 */
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    /**
     * Collection factory
     *
     * @var \Magento\Sales\Model\Resource\Order\Status\CollectionFactory
     */
    protected $_collectionFactory;

    /**
     * Order config
     *
     * @var \Magento\Sales\Model\Order\Config
     */
    protected $_orderConfig;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Data\FormFactory $formFactory
     * @param \Magento\Sales\Model\Order\Config $orderConfig
     * @param \Magento\Sales\Model\Resource\Order\Status\CollectionFactory $collectionFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Sales\Model\Order\Config $orderConfig,
        \Magento\Sales\Model\Resource\Order\Status\CollectionFactory $collectionFactory,
        array $data = []
    ) {
        $this->_orderConfig = $orderConfig;
        $this->_collectionFactory = $collectionFactory;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Constructor
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('order_status_state');
    }

    /**
     * Prepare form fields
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create(['data' => ['id' => 'edit_form', 'method' => 'post']]);

        $fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Assignment Information')]);

        $statuses = $this->_collectionFactory->create()->toOptionArray();
        array_unshift($statuses, ['value' => '', 'label' => '']);

        $states = $this->_orderConfig->getStates();
        $states = array_merge(['' => ''], $states);

        $fieldset->addField(
            'status',
            'select',
            [
                'name' => 'status',
                'label' => __('Order Status'),
                'class' => 'required-entry',
                'values' => $statuses,
                'required' => true
            ]
        );

        $fieldset->addField(
            'state',
            'select',
            [
                'name' => 'state',
                'label' => __('Order State'),
                'class' => 'required-entry',
                'values' => $states,
                'required' => true
            ]
        );

        $fieldset->addField(
            'is_default',
            'checkbox',
            ['name' => 'is_default', 'label' => __('Use Order Status As Default'), 'value' => 1]
        );

        $fieldset->addField(
            'visible_on_front',
            'checkbox',
            ['name' => 'visible_on_front', 'label' => __('Visible On Frontend'), 'value' => 1]
        );

        $form->setAction($this->getUrl('sales/order_status/assignPost'));
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}


text:
package coordinator

import (
	"bytes"
	"encoding/binary"
	"io"
	"io/ioutil"
	"net"
	"sync"
	"time"

	log "code.google.com/p/log4go"
	"github.com/influxdb/influxdb/protocol"
)

type ProtobufServer struct {
	listener          net.Listener
	port              string
	requestHandler    RequestHandler
	connectionMapLock sync.Mutex
	connectionMap     map[net.Conn]bool
}

const KILOBYTE = 1024
const MEGABYTE = 1024 * KILOBYTE
const MAX_REQUEST_SIZE = MEGABYTE * 2

func NewProtobufServer(port string, requestHandler RequestHandler) *ProtobufServer {
	server := &ProtobufServer{port: port, requestHandler: requestHandler, connectionMap: make(map[net.Conn]bool)}
	return server
}

func (self *ProtobufServer) Close() {
	self.listener.Close()
	self.connectionMapLock.Lock()
	defer self.connectionMapLock.Unlock()
	for conn := range self.connectionMap {
		conn.Close()
	}

	// loop while the port is still accepting connections
	for {
		_, port, _ := net.SplitHostPort(self.port)
		conn, err := net.Dial("tcp", "localhost:"+port)
		if err != nil {
			log.Error("Received error %s, assuming connection is closed.", err)
			break
		}
		conn.Close()

		log.Info("Waiting while the server port is closing")
		time.Sleep(1 * time.Second)
	}
}

func (self *ProtobufServer) ListenAndServe() {
	ln, err := net.Listen("tcp", self.port)
	if err != nil {
		panic(err)
	}
	self.listener = ln
	log.Info("ProtobufServer listening on %s", self.port)
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Error("Error with TCP connection. Assuming server is closing: %s", err)
			break
		}
		self.connectionMapLock.Lock()
		self.connectionMap[conn] = true
		self.connectionMapLock.Unlock()
		go self.handleConnection(conn)
	}
}

func (self *ProtobufServer) handleConnection(conn net.Conn) {
	log.Info("ProtobufServer: client connected: %s", conn.RemoteAddr().String())

	message := make([]byte, 0, MAX_REQUEST_SIZE)
	buff := bytes.NewBuffer(message)
	var messageSizeU uint32
	for {
		err := binary.Read(conn, binary.LittleEndian, &messageSizeU)
		if err != nil {
			log.Error("Error reading from connection (%s): %s", conn.RemoteAddr().String(), err)
			self.connectionMapLock.Lock()
			delete(self.connectionMap, conn)
			self.connectionMapLock.Unlock()
			conn.Close()
			return
		}

		messageSize := int64(messageSizeU)
		if messageSize > MAX_REQUEST_SIZE {
			err = self.handleRequestTooLarge(conn, messageSize)
		} else {
			err = self.handleRequest(conn, messageSize, buff)
		}

		if err != nil {
			log.Error("Error, closing connection: %s", err)
			self.connectionMapLock.Lock()
			delete(self.connectionMap, conn)
			self.connectionMapLock.Unlock()
			conn.Close()
			return
		}
		buff.Reset()
	}
}

func (self *ProtobufServer) handleRequest(conn net.Conn, messageSize int64, buff *bytes.Buffer) error {
	reader := io.LimitReader(conn, messageSize)
	_, err := io.Copy(buff, reader)
	if err != nil {
		return err
	}
	request, err := protocol.DecodeRequest(buff)
	if err != nil {
		return err
	}

	log.Debug("Received %s request: %d", request.GetType(), request.GetRequestNumber())

	return self.requestHandler.HandleRequest(request, conn)
}

func (self *ProtobufServer) handleRequestTooLarge(conn net.Conn, messageSize int64) error {
	log.Error("request too large, dumping: %s (%d)", conn.RemoteAddr().String(), messageSize)
	for messageSize > 0 {
		reader := io.LimitReader(conn, MAX_REQUEST_SIZE)
		_, err := io.Copy(ioutil.Discard, reader)
		if err != nil {
			return err
		}
		messageSize -= MAX_REQUEST_SIZE
	}
	return self.sendErrorResponse(conn, protocol.Response_REQUEST_TOO_LARGE, "request too large")
}

func (self *ProtobufServer) sendErrorResponse(conn net.Conn, code protocol.Response_ErrorCode, message string) error {
	response := &protocol.Response{ErrorCode: &code, ErrorMessage: &message}
	data, err := response.Encode()
	if err != nil {
		return err
	}

	buff := bytes.NewBuffer(make([]byte, 0, len(data)+4))
	err = binary.Write(buff, binary.LittleEndian, uint32(len(data)))

	if err != nil {
		return err
	}

	_, err = conn.Write(append(buff.Bytes(), data...))
	return err
}


text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=UTF-8"><META HTTP-EQUIV="Refresh" CONTENT="0; URL=2005/02/23/selling-standards-the-sweet-way/index.html"><TITLE>Page has moved</TITLE>

Click here...


text: puts "Run rake i18n:setup to copy messages.js and i18n.js"


text:
package com.mgmtp.jfunk.core.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

/**
 * Qualifier annotation for the property {@code screenshot.onModuleError}
 *
 * @author rnaegele
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
@Qualifier
public @interface CaptureScreenOnError {
	//
}


text:
package com.intellij.find.editorHeaderActions;

import com.intellij.execution.impl.ConsoleViewUtil;
import com.intellij.find.EditorSearchSession;
import com.intellij.find.FindModel;
import com.intellij.ide.lightEdit.LightEditCompatible;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAwareAction;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class SwitchToReplace extends DumbAwareAction implements LightEditCompatible {
  public SwitchToReplace(@NotNull JComponent shortcutHolder) {
    AnAction replaceAction = ActionManager.getInstance().getAction(IdeActions.ACTION_REPLACE);
    if (replaceAction != null) {
      registerCustomShortcutSet(replaceAction.getShortcutSet(), shortcutHolder);
    }
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    EditorSearchSession search = e.getData(EditorSearchSession.SESSION_KEY);
    Editor editor = search != null ? search.getEditor() : e.getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE);
    e.getPresentation().setEnabled(editor != null && search != null && !ConsoleViewUtil.isConsoleViewEditor(editor));
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    EditorSearchSession search = e.getRequiredData(EditorSearchSession.SESSION_KEY);
    FindModel findModel = search.getFindModel();
    if (!findModel.isReplaceState()) {
      findModel.setReplaceState(true);
    }
    search.getComponent().getSearchTextComponent().selectAll();
  }
}


text:
> A Test Framework Helper for Fun

Document: [基于Virtual DOM与Diff DOM的测试代码生成](https://www.phodal.com/blog/virtual-dom-diff-dom-generate-test/)

**Process**

1. Fixtures HTML -> HyperScript
2. Changed HTML -> HyperScript
3. HyperScript -> Virtual Node
4. Diff Virtual Node -> Generate Change

###GOAL

1. HighLight DOM Change
2. Generator Test

![Screenshot](screenshot.jpg)

##License##

© 2015 [Phodal Huang](http://www.phodal.com). This code is distributed under the MIT license. See `LICENSE` in this directory.

[待我代码编成,娶你为妻可好](http://www.xuntayizhan.com/person/ji-ke-ai-qing-zhi-er-shi-dai-wo-dai-ma-bian-cheng-qu-ni-wei-qi-ke-hao-wan/)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus alutipes Lasch

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Buzzbox_Common;
using Buzzbox_Common.Encoders;

namespace Buzzbox_Stream
{
    class StreamEncode
    {
        public bool LoopForever;
        public bool ShuffleFields;
        public bool IncludeFlavorText;

        public bool NameReplacement;
        public NameCollection NameCollection;

        private MtgEncodeFormatEncoder _encoder;
        private CardCollection _cardCollection;
        private StreamWriter _stream;
        private ConsoleLog _consoleLog;

        public StreamEncode(CardCollection cardCollection, StreamWriter stream)
        {
            _encoder = new MtgEncodeFormatEncoder();

            _consoleLog = ConsoleLog.Instance;

            _cardCollection = cardCollection;
            _stream = stream;
        }

        public void ThreadEntry()
        {
            _encoder.IncludeFlavorText = IncludeFlavorText;

            do
            {
                _cardCollection.Cards.Shuffle();

                foreach (var card in _cardCollection.Cards)
                {
                    if (!(card.Type == "MINION" || card.Type == "SPELL" || card.Type == "WEAPON"))
                    {
                        //Console.WriteLine(card.Type);
                        continue;
                    }

                    //See if names should be replaced, roll dice, replace name.
                    if (card.Type != "HERO" && NameReplacement && NameCollection.ReplaceName())
                    {
                        string newName;
                        try
                        {
                            newName = NameCollection.RandomName(card.CardClass, card.Type);
                        }
                        catch (Exception e)
                        {
                            _consoleLog.VerboseWriteLine($"Error trying to find a new card name for {card.Name}[{card.CardClass}-{card.Type}]: {e.Message}");
                            newName = "None";
                        }

                        if (newName != "None")
                        {
                            card.Name = newName;
                        }
                    }

                    var outputLine = _encoder.EncodeCard(card);

                    if (string.IsNullOrWhiteSpace(outputLine))
                    {
                        continue;
                    }

                    if (ShuffleFields)
                    {
                        outputLine = ShuffleCardFields(outputLine);
                    }

                    _stream.Write(outputLine + "\n\n");

                }

            } while (LoopForever);

            _stream.Close();
        }

        private string ShuffleCardFields(string cardLine)
        {
            cardLine = cardLine.TrimEnd('|').TrimStart('|');
            List<string> fields = cardLine.Split('|').ToList();
            fields.Shuffle();
            return $"|{string.Join("|", fields)}|";
        }
    }
}


text:
\makeatletter
\dspdeclareoperator{dspvoidshapeadder}{
  % Coordinate offset for the plus
  \pgfutil@tempdima=\radius
  \pgfutil@tempdima=0.55\pgfutil@tempdima
  \pgfusepathqstroke
}
\tikzset{
  vdspadder/.style={
    shape=dspvoidshapeadder,
    line cap=rect,
    line join=rect,
    line width=\dspblocklinewidth,
    minimum size=\dspoperatordiameter,
    label={185:$+$},
    label={265:$-$}
  },
  vadspadder/.style={
    shape=dspvoidshapeadder,
    line cap=rect,
    line join=rect,
    line width=\dspblocklinewidth,
    minimum size=\dspoperatordiameter,
    label=below right:$-$,
    label=above right:$+$
  },
  vkdspadder/.style={
    shape=dspvoidshapeadder,
    line cap=rect,
    line join=rect,
    line width=\dspblocklinewidth,
    minimum size=\dspoperatordiameter,
    label=below right:$-$,
    label=below left:$+$
  },
  vjdspadder/.style={
    shape=dspvoidshapeadder,
    line cap=rect,
    line join=rect,
    line width=\dspblocklinewidth,
    minimum size=\dspoperatordiameter,
    label=above right:$+$,
    label=below right:$-$
  },
  edspadder/.style={
    shape=dspvoidshapeadder,
    line cap=rect,
    line join=rect,
    line width=\dspblocklinewidth,
    minimum size=\dspoperatordiameter
  }
}
\makeatother

\tikzset{dspblock/.style={inner xsep = 5pt, inner ysep = 5pt}}
\tikzset{dspblock2/.style={inner xsep = 5pt, inner ysep = 10pt}}
\tikzset{dspblock3/.style={inner xsep = 5pt, inner ysep = 20pt}}


text:
#include "include/save_model.h"
#include <fcntl.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include "gflags/gflags.h"
#include "paddle/fluid/framework/feed_fetch_method.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/prune.h"
#include "paddle/fluid/framework/reader.h"
#include "paddle/fluid/platform/place.h"

using std::unique_ptr;

namespace paddle {
namespace framework {
void save_model(const unique_ptr<ProgramDesc>& main_program, Scope* scope,
                const std::vector<std::string>& param_names,
                const std::string& model_name, bool save_combine) {
  auto place = platform::CPUPlace();
  const BlockDesc& global_block = main_program->Block(0);
  std::vector<std::string> paralist;
  for (auto* var : global_block.AllVars()) {
    bool is_model_param = false;
    for (auto param_name : param_names) {
      if (var->Name() == param_name) {
        is_model_param = true;
        break;
      }
    }

    if (!is_model_param) continue;

    if (!save_combine) {
      VLOG(3) << "model var name: %s" << var->Name().c_str();

      paddle::framework::AttributeMap attrs;
      attrs.insert({"file_path", model_name + "/" + var->Name()});
      auto save_op = paddle::framework::OpRegistry::CreateOp(
          "save", {{"X", {var->Name()}}}, {}, attrs);

      save_op->Run(*scope, place);
    } else {
      paralist.push_back(var->Name());
    }
  }
  if (save_combine) {
    std::sort(paralist.begin(), paralist.end());
    paddle::framework::AttributeMap attrs;
    attrs.insert({"file_path", model_name});
    auto save_op = paddle::framework::OpRegistry::CreateOp(
        "save_combine", {{"X", paralist}}, {}, attrs);
    save_op->Run(*scope, place);
  }
}
}  // namespace framework
}  // namespace paddle


text:
import pandas as pd
import matplotlib.pyplot as plt
import random
import outlie as ou

file=pd.read_csv("/Users/maitree/countrycode.csv",sep=',',delimiter=None)
data = file[['Country','Countrycode']]
file['outlier']=ou.outlie(data,threshold=1)
print(file['outlier'])


text:
<?php

declare(strict_types=1);

namespace Krizalys\Onedrive\Parameter;

/**
 * An interface defining the contract for a parameter builder.
 *
 * @since 2.3.0
 */
interface ParameterBuilderInterface
{
    /**
     * Builds parameters from this instance.
     *
     * @param \Krizalys\Onedrive\Definition\Parameter\ParameterDefinitionInterface[string] $parameterDefinitions
     *        The parameter definitions.
     * @param mixed[string] $options
     *        The options.
     *
     * @return string[string]
     *         The parameters.
     *
     * @since 2.3.0
     */
    public function build(array $parameterDefinitions, array $options);
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>报表首页</title>
    <script src="/static/jquery.js" type="text/javascript"></script>
    <script src="/static/semantic/semantic.min.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/semantic.css">
    <script src="/static/semantic/components/checkbox.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/checkbox.min.css">
    <script src="/static/semantic/components/search.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/search.min.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/reset.min.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/application.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/menu.min.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/dropdown.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/popup.min.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/transition.min.css">
    <script type="text/javascript" src="/static/semantic/components/dropdown.js"></script>
    <script type="text/javascript" src="/static/semantic/components/popup.js"></script>
    <script type="text/javascript" src="/static/semantic/components/transition.js"></script>
    <script type="text/javascript" src="/static/c3/d3.js"></script>
    <script type="text/javascript" src="/static/c3/c3.js"></script>
    <link rel="stylesheet" type="text/css" class="ui" href="/static/c3/c3.css">

    <script type="text/javascript" src="/static/semantic/components/form.js"></script>
    <script type="text/javascript" src="/static/semantic/components/sidebar.js"></script>
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/sidebar.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/form.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/icon.css">
    <link rel="stylesheet" type="text/css" class="ui" href="/static/layout.css">

    <link rel="stylesheet" type="text/css" class="ui" href="/static/semantic/components/input.min.css">

</head>
<body>
{% block body %}{% endblock %}
<script type="text/javascript" src="/static/applications/app.js"></script>
</body>
</html>


text:
using System.ComponentModel.Composition;
using Autofac.Core;
using Autofac.Integration.Mef.Test.TestTypes;

namespace Autofac.Integration.Mef.Test;

public class LazyWithMetadataWhenNoMatchingMetadataIsSuppliedTests
{
    private readonly IContainer _container;

    public LazyWithMetadataWhenNoMatchingMetadataIsSuppliedTests()
    {
        var builder = new ContainerBuilder();
        builder.RegisterMetadataRegistrationSources();
        builder.RegisterType<object>();
        _container = builder.Build();
    }

    [Fact]
    public void ResolvingStronglyTypedMetadataWithoutDefaultValueThrowsException()
    {
        var dx = Assert.Throws<DependencyResolutionException>(() => _container.Resolve<Lazy<object, IMeta>>());

        Assert.IsType<CompositionContractMismatchException>(dx.InnerException);
    }

    [Fact]
    public void ResolvingStronglyTypedMetadataWithDefaultValueProvidesDefault()
    {
        var m = _container.Resolve<Lazy<object, IMetaWithDefault>>();
        Assert.Equal(42, m.Metadata.TheInt);
    }
}


text:
from collections import OrderedDict

expected = [
    OrderedDict(
        [
            ("type", "section"),
            ("id", u"s1"),
            ("content", [OrderedDict([("type", "paragraph"), ("text", u"Content")])]),
            ("title", "Main text"),
        ]
    )
]


text:
<?php
namespace Asset\Model;

require_once 'PHPUnit/Framework.php';

/**
 * Test class for Type.
 * Generated by PHPUnit on 2010-02-23 at 11:51:11.
 */
class TypeTest extends \PHPUnit_Framework_TestCase {
    /**
     * @var Type
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp() {
        $this->object = new Type('image', 'Image');
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown() {
    }

    public function test__constructor() {
        $this->assertEquals('image', $this->object->getSysname());
        $this->assertEquals('Image', $this->object->getTitle());
    }
}
?>


text:
'use strict';

const debug = require('debug')('migro:drivers:mysql');

const Promise = require('bluebird');
const mysql = require('mysql');

const queries = require('./queries');

class MySQLDriver {
  constructor (config) {
    this.config = config;
    this._mysql = Promise.promisifyAll(mysql.createConnection(config));

    this._initialized = false;
  }

  async init () {
    try {
      await this._mysql.connectAsync();

      const res = await this._mysql.queryAsync(queries.mysql.CHECK_MIGRATIONS_TABLE_EXISTENCE, [this.config.database]);

      if (res[0].exists) {
        this._initialized = true;
        return;
      }

      await this._mysql.queryAsync(queries.mysql.CREATE_MIGRATIONS_TABLE);
      this._initialized = true;
    } catch (err) {
      this._lastError = err;
      debug(err);
      this._initialized = false;
    }
  }

  async getLastMigration () {
    debug('getLastMigration');

    if (!this._initialized) {
      await this.init();
    }

    const res = await this._mysql.queryAsync(queries.mysql.GET_LAST_VERSION_AND_MIGRATION);
    debug('last version & migration:', res[0]);

    return {
      version: (res[0] || {}).version,
      name: (res[0] || {}).name
    };
  }

  async getLastVersionMigrations () {
    debug('getLastVersionMigrations');

    if (!this._initialized) {
      await this.init();
    }

    const res = await this._mysql.queryAsync(queries.mysql.GET_LAST_VERSION_AND_ALL_ITS_MIGRATIONS);
    debug('last version & all its migration:', res);

    return res.map(row => ({
      version: (row || {}).version,
      name: (row || {}).name
    }));
  }

  async getLastNMigrations (count) {
    debug('getLastNMigrations');

    if (!this._initialized) {
      await this.init();
    }

    const res = await this._mysql.queryAsync(queries.mysql.GET_LAST_N_MIGRATIONS, [parseInt(count)]);
    debug(`last ${count} migrations`, res);

    return res.map(row => ({
      version: (row || {}).version,
      name: (row || {}).name
    }));
  }

  async execute (version, name, fn, isUp = true) {
    if (!this._initialized) {
      await this.init();
    }

    await this._mysql.queryAsync('START TRANSACTION;');

    try {
      await fn(this._mysql);
      await this._mysql.queryAsync(isUp ? queries.mysql.INSERT_MIGRATION : queries.mysql.DELETE_MIGRATION, [version, name]);
      await this._mysql.queryAsync('COMMIT;');
    } catch (err) {
      debug(`Error during migration ${version}:${name}`, err);
      await this._mysql.queryAsync('ROLLBACK;');
    }
  }

  async exit () {
    await this._mysql.endAsync();
  }
}

module.exports = MySQLDriver;


text:
<?php
if (!class_exists('SubordinatesModulesManager')) {

	class SubordinatesModulesManager extends AbstractModuleManager{

		public function initializeUserClasses(){

		}

		public function initializeFieldMappings(){

		}

		public function initializeDatabaseErrorMappings(){

		}

		public function setupModuleClassDefinitions(){

		}

	}
}


text:
export interface IInquiry {
	_id: string;
	_updatedAt?: Date;
	department?: string;
}


text:
import java.util.*;

class Test extends GregorianCalendar {
    public boolean isSaturday() {
        return newMethod() == SATURDAY;
    }

    private int newMethod() {
        return get(Calendar.DAY_OF_WEEK);
    }
}


text:
'use strict';

galleryApp.factory('createPost', function ($resource, $q, $http) {
    var remoteUrl = 'http://localhost:6299/';

    return {
        createNewPost: function (postObj) {
            var deferred = $q.defer();

            $http.post(remoteUrl + 'api/posts', {
                    title: postObj.title,
                    description: postObj.description,
                    userId: postObj.userId,
                    townId: postObj.townId,
                    isDeleted: postObj.isDeleted,
                    pictureData: postObj.pictureData
                },
                {
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                        'Access-Control-Allow-Origin': '*'
                    }
                }
            )
                .success(function (data) {
                    toastr.success('A new post has been successfully added :)', '', {"positionClass": "toast-bottom-right"});
                    deferred.resolve(data);
                })
                .error(function (error) {
                    toastr.error('Something went wrong. Please try again.', '', {"positionClass": "toast-bottom-right"});
                    deferred.reject(error);
                });

            return deferred.promise;
        }
    };
});


text:
**This Plugin is deprecated.**

**Please see https://esdoc.org/manual/usage/feature.html#ecmascript-proposal**

----

[![Build Status](https://travis-ci.org/esdoc/esdoc-es7-plugin.svg?branch=master)](https://travis-ci.org/esdoc/esdoc-es7-plugin)
[![Coverage Status](https://coveralls.io/repos/esdoc/esdoc-es7-plugin/badge.svg)](https://coveralls.io/r/esdoc/esdoc-es7-plugin)
[![Document](https://doc.esdoc.org/github.com/esdoc/esdoc-es7-plugin/badge.svg)](https://doc.esdoc.org/github.com/esdoc/esdoc-es7-plugin)

# ESDoc ES7 Plugin
**This is an experimental plugin.**

This plugin only **ignores ES7 syntax**(does not optimize) to produce the documentation.
So, ES7 information(ClassProperties, AsyncFunctions and etc...) is not presented in the documentation.

Now, ignore the following syntax.

- es7.comprehensions
- es7.classProperties
- es7.functionBind
- es7.asyncFunctions
- es7.decorators
- es7.exportExtensions
- es7.objectRestSpread
- es7.trailingFunctionCommas
- es7.exponentiationOperator

FYI: https://babeljs.io/docs/usage/experimental/

# Install and Usage
```sh
npm install esdoc-es7-plugin
```

setup ``plugin`` property in ``esdoc.json``

```json
{
  "source": "./src",
  "destination": "./doc",
  "plugins": [
    {"name": "esdoc-es7-plugin"}
  ]
}
```

execute ESDoc

```json
esdoc -c esdoc.json
```

# LICENSE
MIT

# Author
[Ryo Maruyama@h13i32maru](https://twitter.com/h13i32maru)