text:
import getpass
import sys
import threading

import requests
from dcos import util
from dcos.errors import DCOSException, DCOSHTTPException
from requests.auth import HTTPBasicAuth

from six.moves.urllib.parse import urlparse

logger = util.get_logger(__name__)
lock = threading.Lock()

DEFAULT_TIMEOUT = 5

# only accessed from _request_with_auth
AUTH_CREDS = {}  # (hostname, realm) -> AuthBase()

def _default_is_success(status_code):
    """Returns true if the success status is between [200, 300).

    :param response_status: the http response status
    :type response_status: int
    :returns: True for success status; False otherwise
    :rtype: bool
    """

    return 200 <= status_code < 300

@util.duration
def _request(method,
             url,
             is_success=_default_is_success,
             timeout=DEFAULT_TIMEOUT,
             auth=None,
             **kwargs):
    """Sends an HTTP request.

    :param method: method for the new Request object
    :type method: str
    :param url: URL for the new Request object
    :type url: str
    :param is_success: Defines successful status codes for the request
    :type is_success: Function from int to bool
    :param timeout: request timeout
    :type timeout: int
    :param auth: authentication
    :type auth: AuthBase
    :param kwargs: Additional arguments to requests.request
        (see http://docs.python-requests.org/en/latest/api/#requests.request)
    :type kwargs: dict
    :rtype: Response
    """

    logger.info(
        'Sending HTTP [%r] to [%r]: %r',
        method,
        url,
        kwargs.get('headers'))

    try:
        response = requests.request(
            method=method,
            url=url,
            timeout=timeout,
            auth=auth,
            **kwargs)
    except requests.exceptions.ConnectionError as e:
        logger.exception("HTTP Connection Error")
        raise DCOSException('URL [{0}] is unreachable: {1}'.format(
            e.request.url, e))
    except requests.exceptions.Timeout as e:
        logger.exception("HTTP Timeout")
        raise DCOSException('Request to URL [{0}] timed out.'.format(
            e.request.url))
    except requests.exceptions.RequestException as e:
        logger.exception("HTTP Exception")
        raise DCOSException('HTTP Exception: {}'.format(e))

    logger.info('Received HTTP response [%r]: %r',
                response.status_code,
                response.text)

    return response

def _request_with_auth(response,
                       method,
                       url,
                       is_success=_default_is_success,
                       timeout=None,
                       **kwargs):
    """Try request (3 times) with credentials if 401 returned from server

    :param response: requests.response
    :type response: requests.Response
    :param method: method for the new Request object
    :type method: str
    :param url: URL for the new Request object
    :type url: str
    :param is_success: Defines successful status codes for the request
    :type is_success: Function from int to bool
    :param timeout: request timeout
    :type timeout: int
    :param kwargs: Additional arguments to requests.request
        (see http://docs.python-requests.org/en/latest/api/#requests.request)
    :type kwargs: dict
    :rtype: requests.Response
    """
    i = 0
    while i < 3 and response.status_code == 401:
        hostname = urlparse(response.url).hostname
        creds = (hostname, _get_realm(response))

        with lock:
            if creds not in AUTH_CREDS:
                auth = _get_http_auth_credentials(response)
            else:
                auth = AUTH_CREDS[creds]

        # try request again, with auth
        response = _request(method, url, is_success, timeout, auth, **kwargs)

        # only store credentials if they're valid
        with lock:
            if creds not in AUTH_CREDS and response.status_code == 200:
                AUTH_CREDS[creds] = auth

        i += 1

    if response.status_code == 401:
        raise DCOSException("Authentication failed")

    return response

def request(method,
            url,
            is_success=_default_is_success,
            timeout=None,
            **kwargs):
    """Sends an HTTP request. If the server responds with a 401, ask the
    user for their credentials, and try request again (up to 3 times).

    :param method: method for the new Request object
    :type method: str
    :param url: URL for the new Request object
    :type url: str
    :param is_success: Defines successful status codes for the request
    :type is_success: Function from int to bool
    :param timeout: request timeout
    :type timeout: int
    :param kwargs: Additional arguments to requests.request
        (see http://docs.python-requests.org/en/latest/api/#requests.request)
    :type kwargs: dict
    :rtype: Response
    """

    if 'headers' not in kwargs:
        kwargs['headers'] = {'Accept': 'application/json'}

    response = _request(method, url, is_success, timeout, **kwargs)

    if response.status_code == 401:
        response = _request_with_auth(response, method, url, is_success,
                                      timeout, **kwargs)

    if is_success(response.status_code):
        return response
    else:
        raise DCOSHTTPException(response)

def head(url, **kwargs):
    """Sends a HEAD request.

    :param url: URL for the new Request object
    :type url: str
    :param kwargs: Additional arguments to requests.request
                   (see py:func:`request`)
    :type kwargs: dict
    :rtype: Response
    """

    return request('head', url, **kwargs)

def get(url, **kwargs):
    """Sends a GET request.

    :param url: URL for the new Request object
    :type url: str
    :param kwargs: Additional arguments to requests.request
                   (see py:func:`request`)
    :type kwargs: dict
    :rtype: Response
    """

    return request('get', url, **kwargs)

def post(url, data=None, json=None, **kwargs):
    """Sends a POST request.

    :param url: URL for the new Request object
    :type url: str
    :param data: Request body
    :type data: dict, bytes, or file-like object
    :param json: JSON request body
    :type data: dict
    :param kwargs: Additional arguments to requests.request
                   (see py:func:`request`)
    :type kwargs: dict
    :rtype: Response
    """

    return request('post', url, data=data, json=json, **kwargs)

def put(url, data=None, **kwargs):
    """Sends a PUT request.

    :param url: URL for the new Request object
    :type url: str
    :param data: Request body
    :type data: dict, bytes, or file-like object
    :param kwargs: Additional arguments to requests.request
                   (see py:func:`request`)
    :type kwargs: dict
    :rtype: Response
    """

    return request('put', url, data=data, **kwargs)

def patch(url, data=None, **kwargs):
    """Sends a PATCH request.

    :param url: URL for the new Request object
    :type url: str
    :param data: Request body
    :type data: dict, bytes, or file-like object
    :param kwargs: Additional arguments to requests.request
                   (see py:func:`request`)
    :type kwargs: dict
    :rtype: Response
    """

    return request('patch', url, data=data, **kwargs)

def delete(url, **kwargs):
    """Sends a DELETE request.

    :param url: URL for the new Request object
    :type url: str
    :param kwargs: Additional arguments to requests.request
                   (see py:func:`request`)
    :type kwargs: dict
    :rtype: Response
    """

    return request('delete', url, **kwargs)

def silence_requests_warnings():
    """Silence warnings from requests.packages.urllib3.  See DCOS-1007."""
    requests.packages.urllib3.disable_warnings()

def _get_basic_auth_credentials(username, hostname):
    """Get username/password for basic auth

    :param username: username user for authentication
    :type username: str
    :param hostname: hostname for credentials
    :type hostname: str
    :returns: HTTPBasicAuth
    :rtype: requests.auth.HTTPBasicAuth
    """

    if username is None:
        sys.stdout.write("{}'s username: ".format(hostname))
        sys.stdout.flush()
        username = sys.stdin.readline().strip().lower()

    password = getpass.getpass("{}@{}'s password: ".format(username, hostname))

    return HTTPBasicAuth(username, password)

def _get_realm(response):
    """Return authentication realm requested by server for 'Basic' type or None

    :param response: requests.response
    :type response: requests.Response
    :returns: realm
    :rtype: str | None
    """

    if 'www-authenticate' in response.headers:
        auths = response.headers['www-authenticate'].split(',')
        basic_realm = next((auth_type for auth_type in auths
                           if auth_type.rstrip().lower().startswith("basic")),
                           None)
        if basic_realm:
            realm = basic_realm.split('=')[-1].strip(' \'\"').lower()
            return realm
        else:
            return None
    else:
        return None

def _get_http_auth_credentials(response):
    """Get authentication credentials required by server

    :param response: requests.response
    :type response: requests.Response
    :returns: HTTPBasicAuth
    :rtype: HTTPBasicAuth
    """

    parsed_url = urlparse(response.url)
    hostname = parsed_url.hostname
    user = parsed_url.username

    if 'www-authenticate' in response.headers:
        realm = _get_realm(response)
        if realm:
            return _get_basic_auth_credentials(user, hostname)
        else:
            msg = ("Server responded with an HTTP 'www-authenticate' field of "
                   "'{}', DCOS only supports 'Basic'".format(
                       response.headers['www-authenticate']))
            raise DCOSException(msg)
    else:
        msg = ("Invalid HTTP response: server returned an HTTP 401 response "
               "with no 'www-authenticate' field")
        raise DCOSException(msg)


text:
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <mml/window/joystick_impl.hpp>
#include <mml/system/err.hpp>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <map>
#include <string>
#include <utility>

////////////////////////////////////////////////////////////
/// \brief This file implements FreeBSD driver joystick
///
/// It has been tested on a Saitek gamepad with 12 buttons,
/// 2 analog axis and one hat.
///
/// Note: old joy(4) drivers are not supported and no one use that
/// anymore.
////////////////////////////////////////////////////////////

namespace
{
    std::map<unsigned int, std::string> plugged;
    std::map<int, std::pair<int, int> > hatValueMap;

    bool is_joystick(const char *name)
    {
        int file = ::open(name, O_RDONLY | O_NONBLOCK);

        if (file < 0)
            return false;

        report_desc_t desc = hid_get_report_desc(file);

        if (!desc)
        {
            ::close(file);
            return false;
        }

        int id = hid_get_report_id(file);
        hid_data_t data = hid_start_parse(desc, 1 << hid_input, id);

        if (!data)
        {
            hid_dispose_report_desc(desc);
            ::close(file);
            return false;
        }

        hid_item_t item;

        // Assume it isn't
        bool result = false;

        while (hid_get_item(data, &item) > 0)
        {
            if ((item.kind == hid_collection) && (HID_PAGE(item.usage) == HUP_GENERIC_DESKTOP))
            {
                if ((HID_USAGE(item.usage) == HUG_JOYSTICK) || (HID_USAGE(item.usage) == HUG_GAME_PAD))
                {
                    result = true;
                }
            }
        }

        hid_end_parse(data);
        hid_dispose_report_desc(desc);
        ::close(file);

        return result;
    }

    void update_plugged_list()
    {
        /*
         * Devices /dev/uhid<x> are shared between joystick and any other
         * human interface device. We need to iterate over all found devices
         * and check if they are joysticks. The index of JoystickImpl::open
         * does not match the /dev/uhid<index> device!
         */
        DIR* directory = opendir("/dev");

        if (directory)
        {
            int joystickCount = 0;
            struct dirent* directoryEntry = readdir(directory);

            while (directoryEntry && joystickCount < mml::Joystick::Count)
            {
                if (!std::strncmp(directoryEntry->d_name, "uhid", 4))
                {
                    std::string name("/dev/");
                    name += directoryEntry->d_name;

                    if (is_joystick(name.c_str()))
                        plugged[joystickCount++] = name;
                }

                directoryEntry = readdir(directory);
            }

            closedir(directory);
        }
    }

    int usageToAxis(int usage)
    {
        switch (usage)
        {
            case HUG_X:  return mml::Joystick::X;
            case HUG_Y:  return mml::Joystick::Y;
            case HUG_Z:  return mml::Joystick::Z;
            case HUG_RZ: return mml::Joystick::R;
            case HUG_RX: return mml::Joystick::U;
            case HUG_RY: return mml::Joystick::V;
            default:     return -1;
        }
    }

    void hatValueToSfml(int value, mml::priv::JoystickState& state)
    {
        state.axes[mml::Joystick::PovX] = hatValueMap[value].first;
        state.axes[mml::Joystick::PovY] = hatValueMap[value].second;
    }
}

namespace mml
{
namespace priv
{
////////////////////////////////////////////////////////////
void joystick_impl::initialize()
{
    hid_init(NULL);

    // Do an initial scan
    update_plugged_list();

    // Map of hat values
    hatValueMap[0] = std::make_pair(   0,    0); // center

    hatValueMap[1] = std::make_pair(   0, -100); // top
    hatValueMap[3] = std::make_pair( 100,    0); // right
    hatValueMap[5] = std::make_pair(   0,  100); // bottom
    hatValueMap[7] = std::make_pair(-100,    0); // left

    hatValueMap[2] = std::make_pair( 100, -100); // top-right
    hatValueMap[4] = std::make_pair( 100,  100); // bottom-right
    hatValueMap[6] = std::make_pair(-100,  100); // bottom-left
    hatValueMap[8] = std::make_pair(-100, -100); // top-left
}

////////////////////////////////////////////////////////////
void joystick_impl::cleanup()
{
}

////////////////////////////////////////////////////////////
bool joystick_impl::isConnected(unsigned int index)
{
    return plugged.find(index) != plugged.end();
}

////////////////////////////////////////////////////////////
bool joystick_impl::open(unsigned int index)
{
    if (isConnected(index))
    {
        // Open the joystick's file descriptor (read-only and non-blocking)
        _file = ::open(plugged[index].c_str(), O_RDONLY | O_NONBLOCK);
        if (_file >= 0)
        {
            // Reset the joystick state
            _state = JoystickState();

            // Get the report descriptor
            m_desc = hid_get_report_desc(_file);
            if (!m_desc)
            {
                ::close(_file);
                return false;
            }

            // And the id
            m_id = hid_get_report_id(_file);

            // Then allocate a buffer for data retrieval
            m_length = hid_report_size(m_desc, hid_input, m_id);
            m_buffer.resize(m_length);

            _state.connected = true;

            return true;
        }
    }

    return false;
}

////////////////////////////////////////////////////////////
void joystick_impl::close()
{
    ::close(_file);
    hid_dispose_report_desc(m_desc);
}

////////////////////////////////////////////////////////////
JoystickCaps joystick_impl::get_capabilities() const
{
    JoystickCaps caps;
    hid_item_t item;

    hid_data_t data = hid_start_parse(m_desc, 1 << hid_input, m_id);

    while (hid_get_item(data, &item))
    {
        if (item.kind == hid_input)
        {
            int usage = HID_USAGE(item.usage);

            if (usage == HUP_BUTTON)
            {
                caps.buttonCount++;
                break;
            }
            else if (usage == HUP_GENERIC_DESKTOP)
            {
                int axis = usageToAxis(usage);

                if (usage == HUG_HAT_SWITCH)
                {
                    caps.axes[Joystick::PovX] = true;
                    caps.axes[Joystick::PovY] = true;
                }
                else if (axis != -1)
                {
                    caps.axes[axis] = true;
                }
            }
        }
    }

    hid_end_parse(data);

    return caps;
}

////////////////////////////////////////////////////////////
Joystick::Identification joystick_impl::getIdentification() const
{
    return _identification;
}

////////////////////////////////////////////////////////////
JoystickState joystick_impl::joystick_impl::update()
{
    while (read(_file, &m_buffer[0], m_length) == m_length)
    {
        hid_data_t data = hid_start_parse(m_desc, 1 << hid_input, m_id);

        // No memory?
        if (!data)
            continue;

        int buttonIndex = 0;
        hid_item_t item;

        while (hid_get_item(data, &item))
        {
            if (item.kind == hid_input)
            {
                int usage = HID_USAGE(item.usage);

                if (usage == HUP_BUTTON)
                {
                    _state.buttons[buttonIndex++] = hid_get_data(&m_buffer[0], &item);
                }
                else if (usage == HUP_GENERIC_DESKTOP)
                {
                    int value = hid_get_data(&m_buffer[0], &item);
                    int axis = usageToAxis(usage);

                    if (usage == HUG_HAT_SWITCH)
                    {
                        hatValueToSfml(value, _state);
                    }
                    else if (axis != -1)
                    {
                        int minimum = item.logical_minimum;
                        int maximum = item.logical_maximum;

                        value = (value - minimum) * 200 / (maximum - minimum) - 100;
                        _state.axes[axis] = value;
                    }
                }
            }
        }

        hid_end_parse(data);
    }

    return _state;
}

} // namespace priv

} // namespace sf

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>jp.azw</groupId>
	<artifactId>kancolleague</artifactId>
	<version>0.2.9</version>
	<packaging>jar</packaging>

	<name>KanColleague</name>
	<url>http://azw.jp/</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>
		<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
		<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.2</version>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-server</artifactId>
			<version>9.0.5.v20130815</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-servlet</artifactId>
			<version>9.0.5.v20130815</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-proxy</artifactId>
			<version>9.0.5.v20130815</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>

		<!-- test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.10.19</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
namespace Lucene
{
    class MultiPhraseWeight : public Weight
    {
    public:
        MultiPhraseWeight(MultiPhraseQueryPtr query, SearcherPtr searcher);
        virtual ~MultiPhraseWeight();

        LUCENE_CLASS(MultiPhraseWeight);

    protected:
        MultiPhraseQueryPtr query;
        SimilarityPtr similarity;
        double value;
        double idf;
        double queryNorm;
        double queryWeight;

    public:
        virtual QueryPtr getQuery();
        virtual double getValue();
        virtual double sumOfSquaredWeights();
        virtual void normalize(double norm);
        virtual ScorerPtr scorer(IndexReaderPtr reader, bool scoreDocsInOrder, bool topScorer);
        virtual ExplanationPtr explain(IndexReaderPtr reader, int32_t doc);
    };
}

#endif


text:
var util = require('./util'),
    format = require('./format');

var context = {
  formats:    [],
  format_map: {},
  truncate:   util.truncate,
  pad:        util.pad
};

function template(text) {
  var src = source(text, 'd');
  src = 'var __t; return ' + src + ';';

  /* jshint evil: true */
  return (new Function('d', src)).bind(context);
}

template.source = source;
template.context = context;
module.exports = template;

// Clear cache of format objects.
// This can *break* prior template functions, so invoke with care!
template.clearFormatCache = function() {
  context.formats = [];
  context.format_map = {};
};

// Generate property access code for use within template source.
// object: the name of the object (variable) containing template data
// property: the property access string, verbatim from template tag
template.property = function(object, property) {
  var src = util.field(property).map(util.str).join('][');
  return object + '[' + src + ']';
};

// Generate source code for a template function.
// text: the template text
// variable: the name of the data object variable ('obj' by default)
// properties: optional hash for collecting all accessed properties
function source(text, variable, properties) {
  variable = variable || 'obj';
  var index = 0;
  var src = '\'';
  var regex = template_re;

  // Compile the template source, escaping string literals appropriately.
  text.replace(regex, function(match, interpolate, offset) {
    src += text
      .slice(index, offset)
      .replace(template_escaper, template_escapeChar);
    index = offset + match.length;

    if (interpolate) {
      src += '\'\n+((__t=(' +
        template_var(interpolate, variable, properties) +
        '))==null?\'\':__t)+\n\'';
    }

    // Adobe VMs need the match returned to produce the correct offest.
    return match;
  });
  return src + '\'';
}

function template_var(text, variable, properties) {
  var filters = text.match(filter_re);
  var prop = filters.shift().trim();
  var stringCast = true;

  function strcall(fn) {
    fn = fn || '';
    if (stringCast) {
      stringCast = false;
      src = 'String(' + src + ')' + fn;
    } else {
      src += fn;
    }
    return src;
  }

  function date() {
    return '(typeof ' + src + '==="number"?new Date('+src+'):'+src+')';
  }

  function number_format(fmt, key) {
    a = template_format(args[0], key, fmt);
    stringCast = false;
    src = 'this.formats['+a+']('+src+')';
  }

  function time_format(fmt, key) {
    a = template_format(args[0], key, fmt);
    stringCast = false;
    src = 'this.formats['+a+']('+date()+')';
  }

  if (properties) properties[prop] = 1;
  var src = template.property(variable, prop);

  for (var i=0; i<filters.length; ++i) {
    var f = filters[i], args = null, pidx, a, b;

    if ((pidx=f.indexOf(':')) > 0) {
      f = f.slice(0, pidx);
      args = filters[i].slice(pidx+1)
        .match(args_re)
        .map(function(s) { return s.trim(); });
    }
    f = f.trim();

    switch (f) {
      case 'length':
        strcall('.length');
        break;
      case 'lower':
        strcall('.toLowerCase()');
        break;
      case 'upper':
        strcall('.toUpperCase()');
        break;
      case 'lower-locale':
        strcall('.toLocaleLowerCase()');
        break;
      case 'upper-locale':
        strcall('.toLocaleUpperCase()');
        break;
      case 'trim':
        strcall('.trim()');
        break;
      case 'left':
        a = util.number(args[0]);
        strcall('.slice(0,' + a + ')');
        break;
      case 'right':
        a = util.number(args[0]);
        strcall('.slice(-' + a +')');
        break;
      case 'mid':
        a = util.number(args[0]);
        b = a + util.number(args[1]);
        strcall('.slice(+'+a+','+b+')');
        break;
      case 'slice':
        a = util.number(args[0]);
        strcall('.slice('+ a +
          (args.length > 1 ? ',' + util.number(args[1]) : '') +
          ')');
        break;
      case 'truncate':
        a = util.number(args[0]);
        b = args[1];
        b = (b!=='left' && b!=='middle' && b!=='center') ? 'right' : b;
        src = 'this.truncate(' + strcall() + ',' + a + ',\'' + b + '\')';
        break;
      case 'pad':
        a = util.number(args[0]);
        b = args[1];
        b = (b!=='left' && b!=='middle' && b!=='center') ? 'right' : b;
        src = 'this.pad(' + strcall() + ',' + a + ',\'' + b + '\')';
        break;
      case 'number':
        number_format(format.number, 'number');
        break;
      case 'time':
        time_format(format.time, 'time');
        break;
      case 'time-utc':
        time_format(format.utc, 'time-utc');
        break;
      default:
        throw Error('Unrecognized template filter: ' + f);
    }
  }

  return src;
}

var template_re = /\{\{(.+?)\}\}|$/g,
    filter_re = /(?:"[^"]*"|\'[^\']*\'|[^\|"]+|[^\|\']+)+/g,
    args_re = /(?:"[^"]*"|\'[^\']*\'|[^,"]+|[^,\']+)+/g;

// Certain characters need to be escaped so that they can be put into a
// string literal.
var template_escapes = {
  '\'':     '\'',
  '\\':     '\\',
  '\r':     'r',
  '\n':     'n',
  '\u2028': 'u2028',
  '\u2029': 'u2029'
};

var template_escaper = /\\|'|\r|\n|\u2028|\u2029/g;

function template_escapeChar(match) {
  return '\\' + template_escapes[match];
}

function template_format(pattern, key, fmt) {
  if ((pattern[0] === '\'' && pattern[pattern.length-1] === '\'') ||
      (pattern[0] === '"'  && pattern[pattern.length-1] === '"')) {
    pattern = pattern.slice(1, -1);
  } else {
    throw Error('Format pattern must be quoted: ' + pattern);
  }
  key = key + ':' + pattern;
  if (!context.format_map[key]) {
    var f = fmt(pattern);
    var i = context.formats.length;
    context.formats.push(f);
    context.format_map[key] = i;
  }
  return context.format_map[key];
}


text:
module Locomotive
  class SiteService < Struct.new(:account)

    include Locomotive::Concerns::ActivityService
    include Morphine

    register :page_service do
      Locomotive::PageService.new(nil, account)
    end

    register :content_entry_service do
      Locomotive::ContentEntryService.new(nil, account)
    end

    def list
      sorter = lambda do |site_a, site_b|
        site_a.name.downcase <=> site_b.name.downcase
      end

      account.sites.order_by(:name.asc).to_a.sort(&sorter)
    end

    def build_new
      Site.new(handle: unique_handle)
    end

    def create(attributes, raise_if_not_valid = false)
      if attributes[:handle].blank?
        attributes[:handle] = unique_handle
      end

      Site.new(attributes).tap do |site|
        site.memberships.build account: account, role: 'admin'

        success = raise_if_not_valid ? site.save! : site.save

        track_activity 'site.created', site: site, parameters: { name: site.name } if success
      end
    end

    def create!(attributes)
      create(attributes, true)
    end

    def update(site, attributes)
      site.attributes = attributes

      new_locales = site.locales_changed? ? site.locales - site.locales_was : nil
      previous_default_locale = site.default_locale_was

      site.save.tap do |success|
        if success
          localize_pages_and_content_entries(site, new_locales, previous_default_locale)
        end
      end
    end

    private

    def localize_pages_and_content_entries(site, new_locales, previous_default_locale)
      return unless new_locales.present?

      # localize all the existing pages
      page_service.site = site
      page_service.localize(new_locales, previous_default_locale)

      # localize all the content entries of localized content types
      site.localized_content_types.each do |content_type|
        content_entry_service.content_type = content_type
        content_entry_service.localize(new_locales, previous_default_locale)
      end
    end

    def unique_handle
      Bazaar.heroku do |value|
        Site.where(handle: value).exists?
      end
    end

  end
end


text:
package at.medunigraz.imi.abbres.model.context;

public class RightContext extends Context {

	public RightContext(String text) {
		super(text);
	}

	@Override
	protected String getNGram(int n) {
		if (n < 1) {
			return "";
		}

		String[] tokenizedText = text.split(TOKEN_SEPARATOR);

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < n && i < tokenizedText.length; i++) {
			sb.append(tokenizedText[i]);
			sb.append(TOKEN_SEPARATOR);
		}
		return sb.toString().trim();
	}
}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Octokit;

namespace libgitface
{
	public class CreateSubmoduleBumpPRAction : IAction
	{
		string AutoBumpBranchName => $"{Client.BranchName}-bump-submodules";
		GitClient Client { get; }
		SubmoduleInformation[] Submodules { get; }

		public string[] Grouping { get; }
		public string ShortDescription => $"Bump submodules ({Client.Repository.Name}/{Client.BranchName})";
		public string Tooltip => CreateTitleText ();

		public bool AllowPostActions { get; set; }

		public CreateSubmoduleBumpPRAction (GitClient client, SubmoduleInformation[] submodules, params string[] grouping)
		{
			Client = client;
			Submodules = submodules;
			Grouping = grouping;
		}

		public async void Execute()
		{
			try {
				var branchName = await CreateBranchWithBump ();
				await Client.CreateAndOpenPullRequest (branchName, CreateTitleText (), CreateBodyText (), openPrInBrowser: AllowPostActions);
			} catch {

			}
		}

		async Task<string> CreateBranchWithBump ()
		{
			var headSha = await Client.GetHeadSha ();
			var tree = new NewTree { BaseTree = headSha };
			foreach (var submodule in Submodules) {
				tree.Tree.Add(new NewTreeItem {
					Mode = FileMode.Submodule,
					Sha = submodule.HeadSha,
					Path = submodule.Path,
					Type = TreeType.Commit,
				});
			}

			var newTreeSha = await Client.CreateTree (tree);
			var commitSha = await Client.CreateCommit (CreateTitleText () + "\r\n\r\n" + CreateBodyText (), newTreeSha, headSha);
			if (await Client.BranchExists (AutoBumpBranchName))
				await Client.DeleteBranch (AutoBumpBranchName);
			await Client.CreateBranch (AutoBumpBranchName, commitSha);
			return AutoBumpBranchName;
		}

		string CreateTitleText ()
		{
			var submoduleNames = string.Join (", ", Submodules.Select (t => t.Repository.Name));
			return $"[{Client.BranchName}] Bump {submoduleNames}";
		}

		string CreateBodyText ()
		{
			var urls = Submodules.Select (s => $"{s.Repository.Uri}/compare/{s.CurrentSha}...{s.HeadSha}");
			return string.Join ("\r\n", urls);
		}
	}
}


text:
import os.path
import functools

from robot.api.deco import library

__version__ = 'N/A'  # This should be ignored when version is parsed

class NameLibrary:    # Old-style class on purpose!
    handler_count = 10

    def simple1(self):
        """Simple 1"""

    def simple2___(self):
        """Simple 2"""

    def underscore_name(self):
        """Underscore Name"""

    def underscore_name2_(self):
        """Underscore Name2"""

    def un_der__sco_r__e_3(self):
        """Un Der Sco R E 3"""

    def MiXeD_CAPS(self):
        """MiXeD CAPS"""

    def camelCase(self):
        """Camel Case"""

    def camelCase2(self):
        """Camel Case 2"""

    def mixedCAPSCamel(self):
        """Mixed CAPS Camel"""

    def camelCase_and_underscores_doesNot_work(self):
        """CamelCase And Underscores DoesNot Work"""

    def _skipped1(self):
        """Starts with underscore"""

    skipped2 = "Not a function"

class DocLibrary:
    handler_count = 4

    def no_doc(self):
        pass

    no_doc.expected_doc = ''
    no_doc.expected_shortdoc = ''

    def one_line_doc(self):
        """One line doc"""

    one_line_doc.expected_doc = 'One line doc'
    one_line_doc.expected_shortdoc = 'One line doc'

    def multiline_doc(self):
        """First line is short doc.

        Full doc spans
        multiple lines.
        """

    multiline_doc.expected_doc = 'First line is short doc.\n\nFull doc spans\nmultiple lines.'
    multiline_doc.expected_shortdoc = 'First line is short doc.'

    def multiline_doc_with_split_short_doc(self):
        """Short doc can be split into
        multiple
        physical
        lines.

        This is documentation body and not included
        in short doc.

        Still body.
        """

    multiline_doc_with_split_short_doc.expected_doc = '''\
Short doc can be split into
multiple
physical
lines.

This is documentation body and not included
in short doc.

Still body.'''
    multiline_doc_with_split_short_doc.expected_shortdoc = '''\
Short doc can be split into
multiple
physical
lines.'''

class ArgInfoLibrary:
    handler_count = 13

    def no_args(self):
        """[], {}, None, None"""
        # Argument inspection had a bug when there was args on function body
        # so better keep some of them around here.
        a=b=c=1

    def required1(self, one):
        """['one'], {}, None, None"""

    def required2(self, one, two):
        """['one', 'two'], {}, None, None"""

    def required9(self, one, two, three, four, five, six, seven, eight, nine):
        """['one','two','three','four','five','six','seven','eight','nine'], \
           {}, None, None"""

    def default1(self, one=1):
        """['one'], {'one': 1}, None, None"""

    def default5(self, one='', two=None, three=3, four='huh', five=True):
        """['one', 'two', 'three', 'four', 'five'], \
           {'one': '', 'two': None, 'three': 3, 'four': 'huh', 'five': True}, \
           None, None"""

    def required1_default1(self, one, two=''):
        """['one', 'two'], {'two': ''}, None, None"""

    def required2_default3(self, one, two, three=3, four=4, five=5):
        """['one', 'two', 'three', 'four', 'five'], \
           {'three': 3, 'four': 4, 'five': 5}, None, None"""

    def varargs(self,*one):
        """[], {}, 'one', None"""

    def required2_varargs(self, one, two, *three):
        """['one', 'two'], {}, 'three', None"""

    def req4_def2_varargs(self, one, two, three, four, five=5, six=6, *seven):
        """['one', 'two', 'three', 'four', 'five', 'six'], \
           {'five': 5, 'six': 6}, 'seven', None"""

    def req2_def3_varargs_kwargs(self, three, four, five=5, six=6, seven=7, *eight, **nine):
        """['three', 'four', 'five', 'six', 'seven'], \
          {'five': 5, 'six': 6, 'seven': 7}, 'eight', 'nine'"""

    def varargs_kwargs(self,*one, **two):
        """[], {}, 'one', 'two'"""

class GetattrLibrary:
    handler_count = 3
    keyword_names = ['foo','bar','zap']

    def get_keyword_names(self):
        return self.keyword_names

    def __getattr__(self, name):
        def handler(*args):
            return name, args
        if name not in self.keyword_names:
            raise AttributeError
        return handler

class SynonymLibrary:
    handler_count = 3

    def handler(self):
        pass

    synonym_handler = handler
    another_synonym = handler

@library(auto_keywords=True)
class VersionLibrary:
    ROBOT_LIBRARY_VERSION = '0.1'
    ROBOT_LIBRARY_DOC_FORMAT = 'html'
    kw = lambda x:None

class VersionObjectLibrary:

    class _Version:
        def __init__(self, ver):
            self._ver = ver
        def __str__(self):
            return self._ver

    ROBOT_LIBRARY_VERSION = _Version('ver')
    kw = lambda x:None

class RecordingLibrary:
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'

    def __init__(self):
        self.kw_accessed = 0
        self.kw_called = 0

    def kw(self):
        self.kw_called += 1

    def __getattribute__(self, name):
        if name == 'kw':
            self.kw_accessed += 1
        return object.__getattribute__(self, name)

class ArgDocDynamicLibrary:

    def __init__(self):
        kws = [('No Arg', [], None),
               ('One Arg', ['arg'], None),
               ('One or Two Args', ['arg', 'darg=dvalue'], None),
               ('Default as tuple', [('arg',), ('d1', False), ('d2', None)], None),
               ('Many Args', ['*args'], None),
               ('No Arg Spec', None, None),
               ('Multiline', None, 'Multiline\nshort doc!\n\nBody\nhere.')]
        self._keywords = dict((name, _KeywordInfo(name, argspec, doc))
                              for name, argspec, doc in kws)

    def get_keyword_names(self):
        return sorted(self._keywords)

    def run_keyword(self, name, args):
        print('*INFO* Executed keyword "%s" with arguments %s.' % (name, args))

    def get_keyword_documentation(self, name):
        return self._keywords[name].doc

    def get_keyword_arguments(self, name):
        return self._keywords[name].argspec

class ArgDocDynamicLibraryWithKwargsSupport(ArgDocDynamicLibrary):

    def __init__(self):
        ArgDocDynamicLibrary.__init__(self)
        for name, argspec in [('Kwargs', ['**kwargs']),
                              ('Varargs and Kwargs', ['*args', '**kwargs'])]:
            self._keywords[name] = _KeywordInfo(name, argspec)

    def run_keyword(self, name, args, kwargs={}):
        argstr = ' '.join([str(a) for a in args] +
                          ['%s:%s' % kv for kv in sorted(kwargs.items())])
        print('*INFO* Executed keyword %s with arguments %s' % (name, argstr))

class DynamicWithSource:
    path = os.path.normpath(os.path.dirname(__file__) + '/classes.py')
    keywords = {'only path': path,
                'path & lineno': path + ':42',
                'lineno only': ':6475',
                'invalid path': 'path validity is not validated',
                'path w/ colon': r'c:\temp\lib.py',
                'path w/ colon & lineno': r'c:\temp\lib.py:1234567890',
                'no source': None,
                'nön-äscii': 'hyvä esimerkki',
                'nön-äscii utf-8': b'\xe7\xa6\x8f:88',
                'invalid source': 666}

    def get_keyword_names(self):
        return list(self.keywords)

    def run_keyword(self, name, args, kws):
        pass

    def get_keyword_source(self, name):
        return self.keywords[name]

class _KeywordInfo:
    doc_template = 'Keyword documentation for %s'

    def __init__(self, name, argspec, doc=None):
        self.doc = doc or self.doc_template % name
        self.argspec = argspec

class InvalidGetDocDynamicLibrary(ArgDocDynamicLibrary):

    def get_keyword_documentation(self, name, invalid_arg):
        pass

class InvalidGetArgsDynamicLibrary(ArgDocDynamicLibrary):

    def get_keyword_arguments(self, name):
        1/0

class InvalidAttributeDynamicLibrary(ArgDocDynamicLibrary):
    get_keyword_documentation = True
    get_keyword_arguments = False

def noop(x):
    return x

def wraps(x):
    @functools.wraps(x)
    def wrapper(*a, **k):
        return x(*a, **k)
    return wrapper

@noop
@noop
@functools.total_ordering
class Decorated:

    @noop
    def no_wrapper(self):
        pass

    @noop
    @wraps
    @noop
    @wraps
    def wrapper(self):
        pass

    if hasattr(functools, 'lru_cache'):
        @functools.lru_cache()
        def external(self):
            pass

    no_def = lambda self: None

    def __eq__(self, other):
        return self is other

    def __lt__(self, other):
        return True

NoClassDefinition = type('NoClassDefinition', (), {})


text:
namespace app {
namespace Uno {

::uDelegateType* Comparison__Uno_Collections_Dictionary_Outracks_Simulator_Bytecode_TypeName_Uno_Type___typeof();

}}

#endif