text:
#ifndef VECTOR2_H_
#define VECTOR2_H_

namespace gameplay
{

class Matrix;

/**
 * Defines a 2-element floating point vector.
 */
class Vector2
{
public:

    /**
     * The x coordinate.
     */
    float x;

    /**
     * The y coordinate.
     */
    float y;

    /**
     * Constructs a new vector initialized to all zeros.
     */
    Vector2();

    /**
     * Constructs a new vector initialized to the specified values.
     *
     * @param x The x coordinate.
     * @param y The y coordinate.
     */
    Vector2(float x, float y);

    /**
     * Constructs a new vector from the values in the specified array.
     *
     * @param array An array containing the elements of the vector in the order x, y.
     */
    Vector2(const float* array);

    /**
     * Constructs a vector that describes the direction between the specified points.
     *
     * @param p1 The first point.
     * @param p2 The second point.
     */
    Vector2(const Vector2& p1, const Vector2& p2);

    /**
     * Constructs a new vector that is a copy of the specified vector.
     *
     * @param copy The vector to copy.
     */
    Vector2(const Vector2& copy);

    /**
     * Destructor.
     */
    ~Vector2();

    /**
     * Returns the zero vector.
     *
     * @return The 2-element vector of 0s.
     */
    static const Vector2& zero();

    /**
     * Returns the one vector.
     *
     * @return The 2-element vector of 1s.
     */
    static const Vector2& one();

    /**
     * Returns the unit x vector.
     *
     * @return The 2-element unit vector along the x axis.
     */
    static const Vector2& unitX();

    /**
     * Returns the unit y vector.
     *
     * @return The 2-element unit vector along the y axis.
     */
    static const Vector2& unitY();

    /**
     * Returns the random vector.
     *
     * @return The 2-element vector, which coordinates lies in (-1,1).
     */
    static Vector2 random();

    /**
     * Indicates whether this vector contains all zeros.
     *
     * @return true if this vector contains all zeros, false otherwise.
     */
    bool isZero() const;

    /**
     * Indicates whether this vector contains all ones.
     *
     * @return true if this vector contains all ones, false otherwise.
     */
    bool isOne() const;

    /**
     * Returns the angle (in radians) between the specified vectors.
     *
     * @param v1 The first vector.
     * @param v2 The second vector.
     *
     * @return The angle between the two vectors (in radians).
     */
    static float angle(const Vector2& v1, const Vector2& v2);

    /**
     * Adds the elements of the specified vector to this one.
     *
     * @param v The vector to add.
     */
    void add(const Vector2& v);

    /**
     * Adds the specified vectors and stores the result in dst.
     *
     * @param v1 The first vector.
     * @param v2 The second vector.
     * @param dst A vector to store the result in.
     */
    static void add(const Vector2& v1, const Vector2& v2, Vector2* dst);

    /**
     * Clamps this vector within the specified range.
     *
     * @param min The minimum value.
     * @param max The maximum value.
     */
    void clamp(const Vector2& min, const Vector2& max);

    /**
     * Clamps the specified vector within the specified range and returns it in dst.
     *
     * @param v The vector to clamp.
     * @param min The minimum value.
     * @param max The maximum value.
     * @param dst A vector to store the result in.
     */
    static void clamp(const Vector2& v, const Vector2& min, const Vector2& max, Vector2* dst);

    /**
     * Returns the distance between this vector and v.
     *
     * @param v The other vector.
     *
     * @return The distance between this vector and v.
     *
     * @see distanceSquared
     */
    float distance(const Vector2& v) const;

    /**
     * Returns the squared distance between this vector and v.
     *
     * When it is not necessary to get the exact distance between
     * two vectors (for example, when simply comparing the
     * distance between different vectors), it is advised to use
     * this method instead of distance.
     *
     * @param v The other vector.
     *
     * @return The squared distance between this vector and v.
     *
     * @see distance
     */
    float distanceSquared(const Vector2& v) const;

    /**
     * Returns the dot product of this vector and the specified vector.
     *
     * @param v The vector to compute the dot product with.
     *
     * @return The dot product.
     */
    float dot(const Vector2& v) const;

    /**
     * Returns the dot product between the specified vectors.
     *
     * @param v1 The first vector.
     * @param v2 The second vector.
     *
     * @return The dot product between the vectors.
     */
    static float dot(const Vector2& v1, const Vector2& v2);

    /**
     * Computes the length of this vector.
     *
     * @return The length of the vector.
     *
     * @see lengthSquared
     */
    float length() const;

    /**
     * Returns the squared length of this vector.
     *
     * When it is not necessary to get the exact length of a
     * vector (for example, when simply comparing the lengths of
     * different vectors), it is advised to use this method
     * instead of length.
     *
     * @return The squared length of the vector.
     *
     * @see length
     */
    float lengthSquared() const;

    /**
     * Negates this vector.
     */
    void negate();

    /**
     * Normalizes this vector.
     *
     * This method normalizes this Vector2 so that it is of
     * unit length (in other words, the length of the vector
     * after calling this method will be 1.0f). If the vector
     * already has unit length or if the length of the vector
     * is zero, this method does nothing.
     *
     * @return This vector, after the normalization occurs.
     */
    Vector2& normalize();

    /**
     * Normalizes this vector and stores the result in dst.
     *
     * If the vector already has unit length or if the length
     * of the vector is zero, this method simply copies the
     * current vector into dst.
     *
     * @param dst The destination vector.
     */
    void normalize(Vector2* dst) const;

    /**
     * Scales all elements of this vector by the specified value.
     *
     * @param scalar The scalar value.
     */
    void scale(float scalar);

    /**
     * Scales each element of this vector by the matching component of scale.
     *
     * @param scale The vector to scale by.
     */
    void scale(const Vector2& scale);

    /**
     * Rotates this vector by angle (specified in radians) around the given point.
     *
     * @param point The point to rotate around.
     * @param angle The angle to rotate by (in radians).
     */
    void rotate(const Vector2& point, float angle);

    /**
     * Sets the elements of this vector to the specified values.
     *
     * @param x The new x coordinate.
     * @param y The new y coordinate.
     */
    void set(float x, float y);

    /**
     * Sets the elements of this vector from the values in the specified array.
     *
     * @param array An array containing the elements of the vector in the order x, y.
     */
    void set(const float* array);

    /**
     * Sets the elements of this vector to those in the specified vector.
     *
     * @param v The vector to copy.
     */
    void set(const Vector2& v);

    /**
     * Sets this vector to the directional vector between the specified points.
     *
     * @param p1 The first point.
     * @param p2 The second point.
     */
    void set(const Vector2& p1, const Vector2& p2);

    /**
     * Subtracts this vector and the specified vector as (this - v)
     * and stores the result in this vector.
     *
     * @param v The vector to subtract.
     */
    void subtract(const Vector2& v);

    /**
     * Subtracts the specified vectors and stores the result in dst.
     * The resulting vector is computed as (v1 - v2).
     *
     * @param v1 The first vector.
     * @param v2 The second vector.
     * @param dst The destination vector.
     */
    static void subtract(const Vector2& v1, const Vector2& v2, Vector2* dst);

    /**
     * Updates this vector towards the given target using a smoothing function.
     * The given response time determines the amount of smoothing (lag). A longer
     * response time yields a smoother result and more lag. To force this vector to
     * follow the target closely, provide a response time that is very small relative
     * to the given elapsed time.
     *
     * @param target target value.
     * @param elapsedTime elapsed time between calls.
     * @param responseTime response time (in the same units as elapsedTime).
     */
    void smooth(const Vector2& target, float elapsedTime, float responseTime);

    /**
     * Calculates the sum of this vector with the given vector.
     *
     * Note: this does not modify this vector.
     *
     * @param v The vector to add.
     * @return The vector sum.
     */
    inline const Vector2 operator+(const Vector2& v) const;

    /**
     * Adds the given vector to this vector.
     *
     * @param v The vector to add.
     * @return This vector, after the addition occurs.
     */
    inline Vector2& operator+=(const Vector2& v);

    /**
     * Calculates the sum of this vector with the given vector.
     *
     * Note: this does not modify this vector.
     *
     * @param v The vector to add.
     * @return The vector sum.
     */
    inline const Vector2 operator-(const Vector2& v) const;

    /**
     * Subtracts the given vector from this vector.
     *
     * @param v The vector to subtract.
     * @return This vector, after the subtraction occurs.
     */
    inline Vector2& operator-=(const Vector2& v);

    /**
     * Calculates the negation of this vector.
     *
     * Note: this does not modify this vector.
     *
     * @return The negation of this vector.
     */
    inline const Vector2 operator-() const;

    /**
     * Calculates the scalar product of this vector with the given value.
     *
     * Note: this does not modify this vector.
     *
     * @param x The value to scale by.
     * @return The scaled vector.
     */
    inline const Vector2 operator*(float x) const;

    /**
     * Scales this vector by the given value.
     *
     * @param x The value to scale by.
     * @return This vector, after the scale occurs.
     */
    inline Vector2& operator*=(float x);

    /**
     * Returns the components of this vector divided by the given constant
     *
     * Note: this does not modify this vector.
     *
     * @param x the constant to divide this vector with
     * @return a smaller vector
     */
    inline const Vector2 operator/(float x) const;

    /**
     * Determines if this vector is less than the given vector.
     *
     * @param v The vector to compare against.
     *
     * @return True if this vector is less than the given vector, false otherwise.
     */
    inline bool operator<(const Vector2& v) const;

    /**
     * Determines if this vector is equal to the given vector.
     *
     * @param v The vector to compare against.
     *
     * @return True if this vector is equal to the given vector, false otherwise.
     */
    inline bool operator==(const Vector2& v) const;

    /**
     * Determines if this vector is not equal to the given vector.
     *
     * @param v The vector to compare against.
     *
     * @return True if this vector is not equal to the given vector, false otherwise.
     */
    inline bool operator!=(const Vector2& v) const;
};

/**
 * Calculates the scalar product of the given vector with the given value.
 *
 * @param x The value to scale by.
 * @param v The vector to scale.
 * @return The scaled vector.
 */
inline const Vector2 operator*(float x, const Vector2& v);

}

#include "Vector2.inl"

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Space XY</string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ONGR\ElasticsearchDSL\Tests\Unit\InnerHit;

use ONGR\ElasticsearchDSL\InnerHit\NestedInnerHit;
use ONGR\ElasticsearchDSL\Query\FullText\MatchQuery;
use ONGR\ElasticsearchDSL\Query\Joining\NestedQuery;
use ONGR\ElasticsearchDSL\Search;

class NestedInnerHitTest extends \PHPUnit\Framework\TestCase
{
    /**
     * Data provider for testToArray().
     *
     * @return array
     */
    public function getTestToArrayData()
    {
        $out = [];

        $matchQuery = new MatchQuery('foo.bar.aux', 'foo');
        $nestedQuery = new NestedQuery('foo.bar', $matchQuery);
        $searchQuery = new Search();
        $searchQuery->addQuery($nestedQuery);

        $matchSearch = new Search();
        $matchSearch->addQuery($matchQuery);

        $innerHit = new NestedInnerHit('acme', 'foo', $searchQuery);
        $emptyInnerHit = new NestedInnerHit('acme', 'foo');

        $nestedInnerHit1 = new NestedInnerHit('aux', 'foo.bar.aux', $matchSearch);
        $nestedInnerHit2 = new NestedInnerHit('lux', 'foo.bar.aux', $matchSearch);
        $searchQuery->addInnerHit($nestedInnerHit1);
        $searchQuery->addInnerHit($nestedInnerHit2);

        $out[] = [
            $emptyInnerHit,
            [
                'path' => [
                    'foo' => new \stdClass(),
                ],
            ],
        ];

        $out[] = [
            $nestedInnerHit1,
            [
                'path' => [
                    'foo.bar.aux' => [
                        'query' => $matchQuery->toArray(),
                    ],
                ],
            ],
        ];

        $out[] = [
            $innerHit,
            [
                'path' => [
                    'foo' => [
                        'query' => $nestedQuery->toArray(),
                        'inner_hits' => [
                            'aux' => [
                                'path' => [
                                    'foo.bar.aux' => [
                                        'query' => $matchQuery->toArray(),
                                    ],
                                ],
                            ],
                            'lux' => [
                                'path' => [
                                    'foo.bar.aux' => [
                                        'query' => $matchQuery->toArray(),
                                    ],
                                ],
                            ]
                        ],
                    ],
                ],
            ],
        ];

        return $out;
    }

    /**
     * Tests toArray() method.
     *
     * @param NestedInnerHit $innerHit
     * @param array          $expected
     *
     * @dataProvider getTestToArrayData
     */
    public function testToArray($innerHit, $expected)
    {
        $this->assertEquals($expected, $innerHit->toArray());
    }

    /**
     * Tests getters and setters for $name, $path and $query
     */
    public function testGettersAndSetters()
    {
        $query = new MatchQuery('acme', 'test');
        $search = new Search();
        $search->addQuery($query);

        $hit = new NestedInnerHit('test', 'acme', new Search());
        $hit->setName('foo');
        $hit->setPath('bar');
        $hit->setSearch($search);

        $this->assertEquals('foo', $hit->getName());
        $this->assertEquals('bar', $hit->getPath());
        $this->assertEquals($search, $hit->getSearch());
    }
}


text:
var SPNS = SPNS || {};

SPNS.search = (function () {
               var HighlightClassName = "MyAppHighlight100500uniqueName";
               var SearchResultCount = 0;
               var FoundElements = new Array();
               var FoundElementsCurrentPosition = 0;

               //// public functions ////
               // search with text, main entry point
               var search = function (keyword) {
               if (keyword.length !== 0) {
               SearchAllOccurencesOfString(keyword);
               }
               };

               // search function which takes value from element with identifier
               var searchFromElement = function (identifier) {
               var searchStr = document.getElementById(identifier).value;
               search(searchStr);
               };

               // scroll to the next found element
               var highlightNextResult = function () {
               var index = (FoundElementsCurrentPosition + 1) % SearchResultCount;

               var oldEl = FoundElements[FoundElementsCurrentPosition];
               oldEl.style.backgroundColor = "yellow";

               var newEl = FoundElements[index];
               newEl.style.backgroundColor = "orange";

               ScrollToFoundElement(index);
               };

               // scroll to the previous found element
               var highlightPreviousResult = function () {
               var index = FoundElementsCurrentPosition - 1;
               if (index < 1) index = SearchResultCount;

               var oldEl = FoundElements[FoundElementsCurrentPosition];
               oldEl.style.backgroundColor = "yellow";

               var newEl = FoundElements[index];
               newEl.style.backgroundColor = "orange";

               ScrollToFoundElement(index);
               };

               //// private functions ////
               // highlight all occurences with text and scroll to the first found
               var SearchAllOccurencesOfString = function (keyword) {
               HighlightAllOccurencesOfString(keyword);
               if (SearchResultCount > 0) {
               ScrollToFoundElement(0);
               }
               };

               // does the actual highlight operation after clearing all the mess from previous search
               var HighlightAllOccurencesOfString = function (keyword) {
               RemoveAllHighlights();
               HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());

               if (SearchResultCount > 0) {
               // sort elements by their top offset from smaller to higher
               FoundElements.sort(function (a, b) {
                                  var offsetA = a.offsetTop;
                                  var offsetB = b.offsetTop;
                                  return offsetA - offsetB;
                                  });
               }
               };

               // helper function, recursively searches in elements and their child nodes
               var HighlightAllOccurencesOfStringForElement = function (element, keyword) {
               if (element) {
               if (element.nodeType == 3) { // Text node
               while (true) {
               var value = element.nodeValue; // Search for keyword in text node
               var idx = value.toLowerCase().indexOf(keyword);

               if (idx < 0) break; // not found, abort

               var span = document.createElement("span");
               var text = document.createTextNode(value.substr(idx, keyword.length));
               span.appendChild(text);
               span.setAttribute("class", HighlightClassName);
               span.style.backgroundColor = "yellow";
               span.style.color = "black";
               text = document.createTextNode(value.substr(idx + keyword.length));
               element.deleteData(idx, value.length - idx);
               var next = element.nextSibling;
               element.parentNode.insertBefore(span, next);
               element.parentNode.insertBefore(text, next);
               element = text;
               SearchResultCount++; // update the counter
               FoundElements.push(span);
               }
               } else if (element.nodeType == 1) { // Element node
               if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
               for (var i = element.childNodes.length - 1; i >= 0; i--) {
               HighlightAllOccurencesOfStringForElement(element.childNodes[i], keyword);
               }
               }
               }
               }
               };

               // the main entry point to remove the highlights
               var RemoveAllHighlights = function () {
               SearchResultCount = 0;
               FoundElementsCurrentPosition = 0;
               FoundElements = new Array();
               RemoveAllHighlightsForElement(document.body);
               };

               // helper function, recursively removes the highlights in elements and their childs
               var RemoveAllHighlightsForElement = function (element) {
               if (element) {
               if (element.nodeType == 1) {
               if (element.getAttribute("class") == HighlightClassName) {
               var text = element.removeChild(element.firstChild);
               element.parentNode.insertBefore(text, element);
               element.parentNode.removeChild(element);
               return true;
               } else {
               var normalize = false;
               for (var i = element.childNodes.length - 1; i >= 0; i--) {
               if (RemoveAllHighlightsForElement(element.childNodes[i])) {
               normalize = true;
               }
               }
               if (normalize) {
               element.normalize();
               }
               }
               }
               }
               return false;
               };

               // scrolls to element taken by index from FoundElements array
               var ScrollToFoundElement = function (index) {
               FoundElementsCurrentPosition = index;
               var e = FoundElements[index];
               // var offset = getOffset(e);
               // var x = offset.left;
               // var y = offset.top;
               // window.scrollTo(x, y);
               var yPos = e.offsetTop - window.screen.availHeight*0.2; //offset top in the y axis, reversed for css3 scrolling
               var xPos = e.offsetLeft - window.screen.availWidth*0.5;
               window.scrollTo(xPos,yPos);
               };

               return {
               // public functions declaration
               search: search,
               searchFromElement: searchFromElement,
               highlightNextResult: highlightNextResult,
               highlightPreviousResult: highlightPreviousResult,
               SearchResultCount: SearchResultCount,
               FoundElementsCurrentPosition: FoundElementsCurrentPosition
               };
               })();


text:
import { User } from 'models'
import { hashSync } from 'bcrypt'
import { formatNumber, parseNumber } from 'libphonenumber-js'
import {
  userValidation, createToken, createId,
  filterUserFields
} from 'utils'
import { tokenHeader } from 'constants/urls'

export default (req, res) => {
  let {
    name, phone, email,
    password, location
  } = req.body;

  try {
    phone = formatNumber(parseNumber(phone, 'RU'), 'International');
  } catch (e) {
    return res.status(400).json({
      success: false,
      errors: {phone: 'Введите свой мобильный номер.'}
    })
  }
  password = password ? password : createId();

  userValidation({phone})
    .then(({isValid, errors}) => {
      if (!isValid) {
        return res.status(400).json({
          errors: {
            ...errors,
            formImport: true
          }
        })
      }

      const user = new User({
        name, phone, email,
        password_digest: hashSync(password, 10),
        location
      });

      user.save().then(data => {
        const token = createToken(data);
        return User.findByIdAndUpdate((data._id || data.id), {token})
          .then(() => {
            res
              .status(200)
              .set({
                [tokenHeader]: token
              })
              .json({
                success: true,
                data: {
                  ...filterUserFields(data),
                  isNewUser: true
                }
              });
          })
          .catch(err => {
            res.status(500).json({
              message: err
            })
          })
      }).catch(err => {
        res.status(500).json({
          message: err
        })
      })
    })
};


text:
'use strict';

// Stub for an account management service.

const proxyquire = require('proxyquire');
const request = require('cf-abacus-request');

// Mock the cluster module
const webapp = proxyquire('cf-abacus-webapp', { 'cf-abacus-cluster': (app) => app });

const provisioning = proxyquire('..', { 'cf-abacus-webapp': webapp });

describe('cf-abacus-account-stub', () => {
    it('returns information about an account', (done) => {
        // Create a test provisioning app
        const app = provisioning();

        // Listen on an ephemeral port
        const server = app.listen(0);

        // Get an account, expecting our stub test account
        const account = { account_id: '1234', organizations: ['org_123', 'org_456', 'org_789'] };
        request.get('http://localhost::p/v1/accounts/:account_id', { p: server.address().port, account_id: '1234' }, (err, val) => {
            expect(err).to.equal(undefined);
            expect(val.statusCode).to.equal(200);
            expect(val.body).to.deep.equal(account);
            done();
        });
    });

    it('returns information about the account containing an org', (done) => {
        // Create a test provisioning app
        const app = provisioning();

        // Listen on an ephemeral port
        const server = app.listen(0);

        // Get the account containing an org, expecting our stub test account
        const account = { account_id: '1234', organizations: ['org_123', 'org_456', 'org_789'] };
        request.get('http://localhost::p/v1/orgs/:org_id/account', { p: server.address().port, org_id: 'org_123' }, (err, val) => {
            expect(err).to.equal(undefined);
            expect(val.statusCode).to.equal(200);
            expect(val.body).to.deep.equal(account);
            done();
        });
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:src="@color/LightGrey"
        />
    <TextView
        android:id="@+id/textview_item_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="精品推荐"
        android:textColor="@color/red"
        android:textSize="15dp"
        android:layout_margin="8dp"
        android:layout_below="@+id/banner"
        />
    <ImageView
        android:id="@+id/image_item_line"
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="@color/LightGrey"
        android:layout_below="@+id/textview_item_title"
        />
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager_second"
        android:layout_below="@+id/image_item_line"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        />
    <LinearLayout
        android:id="@+id/dot_group_second"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:paddingBottom="5dp"
        />

</LinearLayout>


text:
require 'simplecov'
SimpleCov.start

require 'akero'


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_ValueType3507792607.h"
#include "mscorlib_System_Decimal724701077.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Networking.UIntDecimal
struct  UIntDecimal_t1232155165
{
public:
	union
	{
		#pragma pack(push, tp, 1)
		struct
		{
			// System.UInt64 UnityEngine.Networking.UIntDecimal::longValue1
			uint64_t ___longValue1_0;
		};
		#pragma pack(pop, tp)
		struct
		{
			uint64_t ___longValue1_0_forAlignmentOnly;
		};
		#pragma pack(push, tp, 1)
		struct
		{
			char ___longValue2_1_OffsetPadding[8];
			// System.UInt64 UnityEngine.Networking.UIntDecimal::longValue2
			uint64_t ___longValue2_1;
		};
		#pragma pack(pop, tp)
		struct
		{
			char ___longValue2_1_OffsetPadding_forAlignmentOnly[8];
			uint64_t ___longValue2_1_forAlignmentOnly;
		};
		#pragma pack(push, tp, 1)
		struct
		{
			// System.Decimal UnityEngine.Networking.UIntDecimal::decimalValue
			Decimal_t724701077  ___decimalValue_2;
		};
		#pragma pack(pop, tp)
		struct
		{
			Decimal_t724701077  ___decimalValue_2_forAlignmentOnly;
		};
	};

public:
	inline static int32_t get_offset_of_longValue1_0() { return static_cast<int32_t>(offsetof(UIntDecimal_t1232155165, ___longValue1_0)); }
	inline uint64_t get_longValue1_0() const { return ___longValue1_0; }
	inline uint64_t* get_address_of_longValue1_0() { return &___longValue1_0; }
	inline void set_longValue1_0(uint64_t value)
	{
		___longValue1_0 = value;
	}

	inline static int32_t get_offset_of_longValue2_1() { return static_cast<int32_t>(offsetof(UIntDecimal_t1232155165, ___longValue2_1)); }
	inline uint64_t get_longValue2_1() const { return ___longValue2_1; }
	inline uint64_t* get_address_of_longValue2_1() { return &___longValue2_1; }
	inline void set_longValue2_1(uint64_t value)
	{
		___longValue2_1 = value;
	}

	inline static int32_t get_offset_of_decimalValue_2() { return static_cast<int32_t>(offsetof(UIntDecimal_t1232155165, ___decimalValue_2)); }
	inline Decimal_t724701077  get_decimalValue_2() const { return ___decimalValue_2; }
	inline Decimal_t724701077 * get_address_of_decimalValue_2() { return &___decimalValue_2; }
	inline void set_decimalValue_2(Decimal_t724701077  value)
	{
		___decimalValue_2 = value;
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
package twitter4j.internal.http;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

/**
 * @author Yusuke Yamamoto - yusuke at mac.com
 * @since Twitter4J 2.1.2
 */
public class HttpResponseImpl extends HttpResponse {
    private HttpURLConnection con;

    HttpResponseImpl(HttpURLConnection con, HttpClientConfiguration conf) throws IOException {
        super(conf);
        this.con = con;
        this.statusCode = con.getResponseCode();
        if (null == (is = con.getErrorStream())) {
            is = con.getInputStream();
        }
        if (is != null && "gzip".equals(con.getContentEncoding())) {
            // the response is gzipped
            is = new StreamingGZIPInputStream(is);
        }
    }

    // for test purpose
    /*package*/ HttpResponseImpl(String content) {
        super();
        this.responseAsString = content;
    }

    @Override
    public String getResponseHeader(String name) {
        return con.getHeaderField(name);
    }

    @Override
    public Map<String, List<String>> getResponseHeaderFields() {
        return con.getHeaderFields();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void disconnect() {
        con.disconnect();
    }
}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.Globalization.TextInfo/Data
struct Data_t2454578866;
struct Data_t2454578866_marshaled_pinvoke;
struct Data_t2454578866_marshaled_com;

#include "codegen/il2cpp-codegen.h"

// Methods for marshaling
struct Data_t2454578866;
struct Data_t2454578866_marshaled_pinvoke;

extern "C" void Data_t2454578866_marshal_pinvoke(const Data_t2454578866& unmarshaled, Data_t2454578866_marshaled_pinvoke& marshaled);
extern "C" void Data_t2454578866_marshal_pinvoke_back(const Data_t2454578866_marshaled_pinvoke& marshaled, Data_t2454578866& unmarshaled);
extern "C" void Data_t2454578866_marshal_pinvoke_cleanup(Data_t2454578866_marshaled_pinvoke& marshaled);

// Methods for marshaling
struct Data_t2454578866;
struct Data_t2454578866_marshaled_com;

extern "C" void Data_t2454578866_marshal_com(const Data_t2454578866& unmarshaled, Data_t2454578866_marshaled_com& marshaled);
extern "C" void Data_t2454578866_marshal_com_back(const Data_t2454578866_marshaled_com& marshaled, Data_t2454578866& unmarshaled);
extern "C" void Data_t2454578866_marshal_com_cleanup(Data_t2454578866_marshaled_com& marshaled);


text:
require 'tempfile'

# This module provides methods that make it easier to test Cops.
module CopHelper
  extend RSpec::SharedContext

  let(:ruby_version) { 2.4 }
  let(:rails_version) { false }

  def inspect_source_file(source)
    Tempfile.open('tmp') { |f| inspect_source(source, f) }
  end

  def inspect_source(source, file = nil)
    RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
    RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
    processed_source = parse_source(source, file)
    raise 'Error parsing example code' unless processed_source.valid_syntax?

    _investigate(cop, processed_source)
  end

  def parse_source(source, file = nil)
    if file&.respond_to?(:write)
      file.write(source)
      file.rewind
      file = file.path
    end

    RuboCop::ProcessedSource.new(source, ruby_version, file)
  end

  def autocorrect_source_file(source)
    Tempfile.open('tmp') { |f| autocorrect_source(source, f) }
  end

  def autocorrect_source(source, file = nil)
    RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
    RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
    cop.instance_variable_get(:@options)[:auto_correct] = true
    processed_source = parse_source(source, file)
    _investigate(cop, processed_source)

    corrector =
      RuboCop::Cop::Corrector.new(processed_source.buffer, cop.corrections)
    corrector.rewrite
  end

  def _investigate(cop, processed_source)
    team = RuboCop::Cop::Team.new([cop], nil, raise_error: true)
    team.inspect_file(processed_source)
  end
end

module RuboCop
  module Cop
    # Monkey-patch Cop for tests to provide easy access to messages and
    # highlights.
    class Cop
      def messages
        offenses.sort.map(&:message)
      end

      def highlights
        offenses.sort.map { |o| o.location.source }
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.opengamma.commons</groupId>
    <artifactId>og-commons-parent</artifactId>
    <version>0.9.0-SNAPSHOT</version>
    <relativePath>../modules</relativePath>
  </parent>
  <artifactId>og-commons-examples</artifactId>
  <version>0.9.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>OG-Commons-Examples</name>
  <description>Example code to demonstrate use of OG-Commons</description>

  <dependencies>

    <dependency>
      <groupId>com.opengamma.commons</groupId>
      <artifactId>og-basics</artifactId>
      <version>0.9.0-SNAPSHOT</version>
    </dependency>
  </dependencies>

  <properties>

    <maven.install.skip>true</maven.install.skip>
    <maven.deploy.skip>true</maven.deploy.skip>

    <windowtitle>OG-Commons-Examples</windowtitle>
    <doctitle><![CDATA[
OpenGamma Commons Examples
]]></doctitle>
  </properties>

</project>


text:
#pragma once

#include "common.h"
#include STRINGIFY(arch/TARGET_FOLDER/interface/arch_atomic.h)


text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <title>An Odo chart using the CSV reader</title>

    <meta name="robots" content="noindex,nofollow" />
    <meta name="description" content="A Odo chart using the CSV reader" />

An Odo chart using the CSV reader

        Note:
        For browser security reasons the AJAX demos don't work offline. You can view the demos on the RGraph website here:
        http://www.rgraph.net/demos

    <canvas id="cvs" width="300" height="300">[No canvas support]</canvas>

        « Back


text:
/**
 *
 */

//
var isBorderOfContent = function() {
  var elements = $('.load-more');
  if (elements && elements[0]) {
    var rect = elements[0].getBoundingClientRect();
    return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && //* or $(window).height()
    rect.right <= (window.innerWidth || document.documentElement.clientWidth) //* or $(window).width()
    );
  }

  return false;
};

InfiniteScrollTrigger = {
  bind: function(callback, interval) {
    interval = interval || 50;
    return Meteor.setInterval(() => {
      if (isBorderOfContent()) callback();
    }, interval);
  },

  /**
   * scroll event를 unbind한다.
   *
   * @param handle setInterval 핸들
   */
  unbind: function(handle) {
    if (handle) Meteor.clearInterval(handle);
  }
};


text:
use std::cmp::min;
use std::fmt;
use std::io::{mod, Reader, IoResult, BufWriter};
use std::num::from_u16;
use std::str::{mod, SendStr, Slice, Owned};

use url::Url;

use method;
use status::StatusCode;
use uri;
use uri::RequestUri::{AbsolutePath, AbsoluteUri, Authority, Star};
use version::HttpVersion;
use version::HttpVersion::{Http09, Http10, Http11, Http20};
use HttpError::{HttpHeaderError, HttpIoError, HttpMethodError, HttpStatusError,
                HttpUriError, HttpVersionError};
use HttpResult;

use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader};
use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};

/// Readers to handle different Transfer-Encodings.
///
/// If a message body does not include a Transfer-Encoding, it *should*
/// include a Content-Length header.
pub enum HttpReader<R> {
    /// A Reader used when a Content-Length header is passed with a positive integer.
    SizedReader(R, uint),
    /// A Reader used when Transfer-Encoding is `chunked`.
    ChunkedReader(R, Option<uint>),
    /// A Reader used for responses that don't indicate a length or chunked.
    ///
    /// Note: This should only used for `Response`s. It is illegal for a
    /// `Request` to be made with both `Content-Length` and
    /// `Transfer-Encoding: chunked` missing, as explained from the spec:
    ///
    /// > If a Transfer-Encoding header field is present in a response and
    /// > the chunked transfer coding is not the final encoding, the
    /// > message body length is determined by reading the connection until
    /// > it is closed by the server.  If a Transfer-Encoding header field
    /// > is present in a request and the chunked transfer coding is not
    /// > the final encoding, the message body length cannot be determined
    /// > reliably; the server MUST respond with the 400 (Bad Request)
    /// > status code and then close the connection.
    EofReader(R),
    /// A Reader used for messages that should never have a body.
    ///
    /// See https://tools.ietf.org/html/rfc7230#section-3.3.3
    EmptyReader(R),
}

impl<R: Reader> HttpReader<R> {

    /// Unwraps this HttpReader and returns the underlying Reader.
    pub fn unwrap(self) -> R {
        match self {
            SizedReader(r, _) => r,
            ChunkedReader(r, _) => r,
            EofReader(r) => r,
            EmptyReader(r) => r,
        }
    }
}

impl<R: Reader> Reader for HttpReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        match *self {
            SizedReader(ref mut body, ref mut remaining) => {
                debug!("Sized read, remaining={}", remaining);
                if *remaining == 0 {
                    Err(io::standard_error(io::EndOfFile))
                } else {
                    let num = try!(body.read(buf));
                    if num > *remaining {
                        *remaining = 0;
                    } else {
                        *remaining -= num;
                    }
                    Ok(num)
                }
            },
            ChunkedReader(ref mut body, ref mut opt_remaining) => {
                let mut rem = match *opt_remaining {
                    Some(ref rem) => *rem,
                    // None means we don't know the size of the next chunk
                    None => try!(read_chunk_size(body))
                };
                debug!("Chunked read, remaining={}", rem);

                if rem == 0 {
                    *opt_remaining = Some(0);

                    // chunk of size 0 signals the end of the chunked stream
                    // if the 0 digit was missing from the stream, it would
                    // be an InvalidInput error instead.
                    debug!("end of chunked");
                    return Err(io::standard_error(io::EndOfFile));
                }

                let to_read = min(rem, buf.len());
                let count = try!(body.read(buf.slice_to_mut(to_read)));

                rem -= count;
                *opt_remaining = if rem > 0 {
                    Some(rem)
                } else {
                    try!(eat(body, LINE_ENDING));
                    None
                };
                Ok(count)
            },
            EofReader(ref mut body) => {
                body.read(buf)
            },
            EmptyReader(_) => Err(io::standard_error(io::EndOfFile))
        }
    }
}

fn eat<R: Reader>(rdr: &mut R, bytes: &[u8]) -> IoResult<()> {
    for &b in bytes.iter() {
        match try!(rdr.read_byte()) {
            byte if byte == b => (),
            _ => return Err(io::standard_error(io::InvalidInput))
        }
    }
    Ok(())
}

/// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk.
fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<uint> {
    let mut size = 0u;
    let radix = 16;
    let mut in_ext = false;
    loop {
        match try!(rdr.read_byte()) {
            b@b'0'...b'9' if !in_ext => {
                size *= radix;
                size += (b - b'0') as uint;
            },
            b@b'a'...b'f' if !in_ext => {
                size *= radix;
                size += (b + 10 - b'a') as uint;
            },
            b@b'A'...b'F' if !in_ext => {
                size *= radix;
                size += (b + 10 - b'A') as uint;
            },
            CR => {
                match try!(rdr.read_byte()) {
                    LF => break,
                    _ => return Err(io::standard_error(io::InvalidInput))
                }
            },
            ext => {
                in_ext = true;
                todo!("chunk extension byte={}", ext);
            }
        }
    }
    debug!("chunk size={}", size);
    Ok(size)
}

/// Writers to handle different Transfer-Encodings.
pub enum HttpWriter<W: Writer> {
    /// A no-op Writer, used initially before Transfer-Encoding is determined.
    ThroughWriter(W),
    /// A Writer for when Transfer-Encoding includes `chunked`.
    ChunkedWriter(W),
    /// A Writer for when Content-Length is set.
    ///
    /// Enforces that the body is not longer than the Content-Length header.
    SizedWriter(W, uint),
    /// A writer that should not write any body.
    EmptyWriter(W),
}

impl<W: Writer> HttpWriter<W> {
    /// Unwraps the HttpWriter and returns the underlying Writer.
    #[inline]
    pub fn unwrap(self) -> W {
        match self {
            ThroughWriter(w) => w,
            ChunkedWriter(w) => w,
            SizedWriter(w, _) => w,
            EmptyWriter(w) => w,
        }
    }

    /// Ends the HttpWriter, and returns the underlying Writer.
    ///
    /// A final `write()` is called with an empty message, and then flushed.
    /// The ChunkedWriter variant will use this to write the 0-sized last-chunk.
    #[inline]
    pub fn end(mut self) -> IoResult<W> {
        try!(self.write(&[]));
        try!(self.flush());
        Ok(self.unwrap())
    }
}

impl<W: Writer> Writer for HttpWriter<W> {
    #[inline]
    fn write(&mut self, msg: &[u8]) -> IoResult<()> {
        match *self {
            ThroughWriter(ref mut w) => w.write(msg),
            ChunkedWriter(ref mut w) => {
                let chunk_size = msg.len();
                try!(write!(w, "{:X}{}{}", chunk_size, CR as char, LF as char));
                try!(w.write(msg));
                w.write(LINE_ENDING)
            },
            SizedWriter(ref mut w, ref mut remaining) => {
                let len = msg.len();
                if len > *remaining {
                    let len = *remaining;
                    *remaining = 0;
                    try!(w.write(msg.slice_to(len))); // msg[...len]
                    Err(io::standard_error(io::ShortWrite(len)))
                } else {
                    *remaining -= len;
                    w.write(msg)
                }
            },
            EmptyWriter(..) => {
                let bytes = msg.len();
                if bytes == 0 {
                    Ok(())
                } else {
                    Err(io::IoError {
                        kind: io::ShortWrite(bytes),
                        desc: "EmptyWriter cannot write any bytes",
                        detail: Some("Cannot include a body with this kind of message".into_string())
                    })
                }
            }
        }
    }

    #[inline]
    fn flush(&mut self) -> IoResult<()> {
        match *self {
            ThroughWriter(ref mut w) => w.flush(),
            ChunkedWriter(ref mut w) => w.flush(),
            SizedWriter(ref mut w, _) => w.flush(),
            EmptyWriter(ref mut w) => w.flush(),
        }
    }
}

pub const SP: u8 = b' ';
pub const CR: u8 = b'\r';
pub const LF: u8 = b'\n';
pub const STAR: u8 = b'*';
pub const LINE_ENDING: &'static [u8] = &[CR, LF];

/// A `Show`able struct to easily write line endings to a formatter.
pub struct LineEnding;

impl fmt::Show for LineEnding {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write(LINE_ENDING)
    }
}

impl AsSlice<u8> for LineEnding {
    fn as_slice(&self) -> &[u8] {
        LINE_ENDING
    }
}

/// Determines if byte is a token char.
///
/// > ```notrust
/// > token          = 1*tchar
/// >
/// > tchar          = "!" / "#" / "$" / "%" / "&" / "'" / "*"
/// >                / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
/// >                / DIGIT / ALPHA
/// >                ; any VCHAR, except delimiters
/// > ```
#[inline]
pub fn is_token(b: u8) -> bool {
    match b {
        b'a'...b'z' |
        b'A'...b'Z' |
        b'0'...b'9' |
        b'!' |
        b'#' |
        b'$' |
        b'%' |
        b'&' |
        b'\''|
        b'*' |
        b'+' |
        b'-' |
        b'.' |
        b'^' |
        b'_' |
        b'`' |
        b'|' |
        b'~' => true,
        _ => false
    }
}

/// Read token bytes from `stream` into `buf` until a space is encountered.
/// Returns `Ok(true)` if we read until a space,
/// `Ok(false)` if we got to the end of `buf` without encountering a space,
/// otherwise returns any error encountered reading the stream.
///
/// The remaining contents of `buf` are left untouched.
fn read_token_until_space<R: Reader>(stream: &mut R, buf: &mut [u8]) -> HttpResult<bool> {
    use std::io::BufWriter;
    let mut bufwrt = BufWriter::new(buf);

    loop {
        let byte = try!(stream.read_byte());

        if byte == SP {
            break;
        } else if !is_token(byte) {
            return Err(HttpMethodError);
        // Read to end but there's still more
        } else if bufwrt.write_u8(byte).is_err() {
            return Ok(false);
        }
    }

    if bufwrt.tell().unwrap() == 0 {
        return Err(HttpMethodError);
    }

    Ok(true)
}

/// Read a `Method` from a raw stream, such as `GET`.
/// ### Note:
/// Extension methods are only parsed to 16 characters.
pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> {
    let mut buf = [SP, ..16];

    if !try!(read_token_until_space(stream, &mut buf)) {
        return Err(HttpMethodError);
    }

    debug!("method buf = {}", buf[].to_ascii());

    let maybe_method = match buf[0..7] {
        b"GET    " => Some(method::Method::Get),
        b"PUT    " => Some(method::Method::Put),
        b"POST   " => Some(method::Method::Post),
        b"HEAD   " => Some(method::Method::Head),
        b"PATCH  " => Some(method::Method::Patch),
        b"TRACE  " => Some(method::Method::Trace),
        b"DELETE " => Some(method::Method::Delete),
        b"CONNECT" => Some(method::Method::Connect),
        b"OPTIONS" => Some(method::Method::Options),
        _ => None,
    };

    debug!("maybe_method = {}", maybe_method);

    match (maybe_method, buf[]) {
        (Some(method), _) => Ok(method),
        (None, ext) => {
            // We already checked that the buffer is ASCII
            Ok(method::Method::Extension(unsafe { str::from_utf8_unchecked(ext) }.trim().into_string()))
        },
    }
}

/// Read a `RequestUri` from a raw stream.
pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> {
    let mut b = try!(stream.read_byte());
    while b == SP {
        b = try!(stream.read_byte());
    }

    let mut s = String::new();
    if b == STAR {
        try!(expect(stream.read_byte(), SP));
        return Ok(Star)
    } else {
        s.push(b as char);
        loop {
            match try!(stream.read_byte()) {
                SP => {
                    break;
                },
                CR | LF => {
                    return Err(HttpUriError)
                },
                b => s.push(b as char)
            }
        }
    }

    debug!("uri buf = {}", s);

    if s.as_slice().starts_with("/") {
        Ok(AbsolutePath(s))
    } else if s.as_slice().contains("/") {
        match Url::parse(s.as_slice()) {
            Ok(u) => Ok(AbsoluteUri(u)),
            Err(_e) => {
                debug!("URL err {}", _e);
                Err(HttpUriError)
            }
        }
    } else {
        let mut temp = "http://".to_string();
        temp.push_str(s.as_slice());
        match Url::parse(temp.as_slice()) {
            Ok(_u) => {
                todo!("compare vs u.authority()");
                Ok(Authority(s))
            }
            Err(_e) => {
                debug!("URL err {}", _e);
                Err(HttpUriError)
            }
        }
    }

}

/// Read the `HttpVersion` from a raw stream, such as `HTTP/1.1`.
pub fn read_http_version<R: Reader>(stream: &mut R) -> HttpResult<HttpVersion> {
    try!(expect(stream.read_byte(), b'H'));
    try!(expect(stream.read_byte(), b'T'));
    try!(expect(stream.read_byte(), b'T'));
    try!(expect(stream.read_byte(), b'P'));
    try!(expect(stream.read_byte(), b'/'));

    match try!(stream.read_byte()) {
        b'0' => {
            try!(expect(stream.read_byte(), b'.'));
            try!(expect(stream.read_byte(), b'9'));
            Ok(Http09)
        },
        b'1' => {
            try!(expect(stream.read_byte(), b'.'));
            match try!(stream.read_byte()) {
                b'0' => Ok(Http10),
                b'1' => Ok(Http11),
                _ => Err(HttpVersionError)
            }
        },
        b'2' => {
            try!(expect(stream.read_byte(), b'.'));
            try!(expect(stream.read_byte(), b'0'));
            Ok(Http20)
        },
        _ => Err(HttpVersionError)
    }
}

/// The raw bytes when parsing a header line.
///
/// A String and Vec<u8>, divided by COLON (`:`). The String is guaranteed
/// to be all `token`s. See `is_token` source for all valid characters.
pub type RawHeaderLine = (String, Vec<u8>);

/// Read a RawHeaderLine from a Reader.
///
/// From [spec](https://tools.ietf.org/html/http#section-3.2):
///
/// > Each header field consists of a case-insensitive field name followed
/// > by a colon (":"), optional leading whitespace, the field value, and
/// > optional trailing whitespace.
/// >
/// > ```notrust
/// > header-field   = field-name ":" OWS field-value OWS
/// >
/// > field-name     = token
/// > field-value    = *( field-content / obs-fold )
/// > field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
/// > field-vchar    = VCHAR / obs-text
/// >
/// > obs-fold       = CRLF 1*( SP / HTAB )
/// >                ; obsolete line folding
/// >                ; see Section 3.2.4
/// > ```
pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine>> {
    let mut name = String::new();
    let mut value = vec![];

    loop {
        match try!(stream.read_byte()) {
            CR if name.len() == 0 => {
                match try!(stream.read_byte()) {
                    LF => return Ok(None),
                    _ => return Err(HttpHeaderError)
                }
            },
            b':' => break,
            b if is_token(b) => name.push(b as char),
            _nontoken => return Err(HttpHeaderError)
        };
    }

    debug!("header name = {}", name);

    let mut ows = true; //optional whitespace

    todo!("handle obs-folding (gross!)");
    loop {
        match try!(stream.read_byte()) {
            CR => break,
            LF => return Err(HttpHeaderError),
            b' ' if ows => {},
            b => {
                ows = false;
                value.push(b)
            }
        };
    }

    debug!("header value = {}", value);

    match try!(stream.read_byte()) {
        LF => Ok(Some((name, value))),
        _ => Err(HttpHeaderError)
    }

}

/// `request-line   = method SP request-target SP HTTP-version CRLF`
pub type RequestLine = (method::Method, uri::RequestUri, HttpVersion);

/// Read the `RequestLine`, such as `GET / HTTP/1.1`.
pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> {
    debug!("read request line");
    let method = try!(read_method(stream));
    debug!("method = {}", method);
    let uri = try!(read_uri(stream));
    debug!("uri = {}", uri);
    let version = try!(read_http_version(stream));
    debug!("version = {}", version);

    if try!(stream.read_byte()) != CR {
        return Err(HttpVersionError);
    }
    if try!(stream.read_byte()) != LF {
        return Err(HttpVersionError);
    }

    Ok((method, uri, version))
}

/// `status-line = HTTP-version SP status-code SP reason-phrase CRLF`
///
/// However, reason-phrase is absolutely useless, so its tossed.
pub type StatusLine = (HttpVersion, RawStatus);

/// The raw status code and reason-phrase.
#[deriving(PartialEq, Show, Clone)]
pub struct RawStatus(pub u16, pub SendStr);

/// Read the StatusLine, such as `HTTP/1.1 200 OK`.
///
/// > The first line of a response message is the status-line, consisting
/// > of the protocol version, a space (SP), the status code, another
/// > space, a possibly empty textual phrase describing the status code,
/// > and ending with CRLF.
/// >
/// >```notrust
/// > status-line = HTTP-version SP status-code SP reason-phrase CRLF
/// > status-code    = 3DIGIT
/// > reason-phrase  = *( HTAB / SP / VCHAR / obs-text )
/// >```
pub fn read_status_line<R: Reader>(stream: &mut R) -> HttpResult<StatusLine> {
    let version = try!(read_http_version(stream));
    if try!(stream.read_byte()) != SP {
        return Err(HttpVersionError);
    }
    let code = try!(read_status(stream));

    Ok((version, code))
}

/// Read the StatusCode from a stream.
pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> {
    let code = [
        try!(stream.read_byte()),
        try!(stream.read_byte()),
        try!(stream.read_byte()),
    ];

    let code = match str::from_utf8(code.as_slice()).and_then(from_str::<u16>) {
        Some(num) => num,
        None => return Err(HttpStatusError)
    };

    match try!(stream.read_byte()) {
        b' ' => (),
        _ => return Err(HttpStatusError)
    }

    let mut buf = [b' ', ..16];

    {
        let mut bufwrt = BufWriter::new(&mut buf);
        loop {
            match try!(stream.read_byte()) {
                CR => match try!(stream.read_byte()) {
                    LF => break,
                    _ => return Err(HttpStatusError)
                },
                b => match bufwrt.write_u8(b) {
                    Ok(_) => (),
                    Err(_) => {
                        // what sort of reason phrase is this long?
                        return Err(HttpStatusError);
                    }
                }
            }
        }
    }

    let reason = match str::from_utf8(buf[]) {
        Some(s) => s.trim(),
        None => return Err(HttpStatusError)
    };

    let reason = match from_u16::<StatusCode>(code) {
        Some(status) => match status.canonical_reason() {
            Some(phrase) => {
                if phrase == reason {
                    Slice(phrase)
                } else {
                    Owned(reason.into_string())
                }
            }
            _ => Owned(reason.into_string())
        },
        None => return Err(HttpStatusError)
    };

    Ok(RawStatus(code, reason))
}

#[inline]
fn expect(r: IoResult<u8>, expected: u8) -> HttpResult<()> {
    match r {
        Ok(b) if b == expected => Ok(()),
        Ok(_) => Err(HttpVersionError),
        Err(e) => Err(HttpIoError(e))
    }
}

#[cfg(test)]
mod tests {
    use std::io::{mod, MemReader, MemWriter};
    use std::str::{Slice, Owned};
    use test::Bencher;
    use uri::RequestUri;
    use uri::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority};
    use method;
    use version::HttpVersion;
    use version::HttpVersion::{Http10, Http11, Http20};
    use HttpError::{HttpVersionError, HttpMethodError};
    use HttpResult;
    use url::Url;

    use super::{read_method, read_uri, read_http_version, read_header,
                RawHeaderLine, read_status, RawStatus};

    fn mem(s: &str) -> MemReader {
        MemReader::new(s.as_bytes().to_vec())
    }

    #[test]
    fn test_read_method() {
        fn read(s: &str, result: HttpResult<method::Method>) {
            assert_eq!(read_method(&mut mem(s)), result);
        }

        read("GET /", Ok(method::Method::Get));
        read("POST /", Ok(method::Method::Post));
        read("PUT /", Ok(method::Method::Put));
        read("HEAD /", Ok(method::Method::Head));
        read("OPTIONS /", Ok(method::Method::Options));
        read("CONNECT /", Ok(method::Method::Connect));
        read("TRACE /", Ok(method::Method::Trace));
        read("PATCH /", Ok(method::Method::Patch));
        read("FOO /", Ok(method::Method::Extension("FOO".to_string())));
        read("akemi!~#HOMURA /", Ok(method::Method::Extension("akemi!~#HOMURA".to_string())));
        read(" ", Err(HttpMethodError));
    }

    #[test]
    fn test_read_uri() {
        fn read(s: &str, result: HttpResult<RequestUri>) {
            assert_eq!(read_uri(&mut mem(s)), result);
        }

        read("* ", Ok(Star));
        read("http://hyper.rs/ ", Ok(AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())));
        read("hyper.rs ", Ok(Authority("hyper.rs".to_string())));
        read("/ ", Ok(AbsolutePath("/".to_string())));
    }

    #[test]
    fn test_read_http_version() {
        fn read(s: &str, result: HttpResult<HttpVersion>) {
            assert_eq!(read_http_version(&mut mem(s)), result);
        }

        read("HTTP/1.0", Ok(Http10));
        read("HTTP/1.1", Ok(Http11));
        read("HTTP/2.0", Ok(Http20));
        read("HTP/2.0", Err(HttpVersionError));
        read("HTTP.2.0", Err(HttpVersionError));
        read("HTTP 2.0", Err(HttpVersionError));
        read("TTP 2.0", Err(HttpVersionError));
    }

    #[test]
    fn test_read_status() {
        fn read(s: &str, result: HttpResult<RawStatus>) {
            assert_eq!(read_status(&mut mem(s)), result);
        }

        read("200 OK\r\n", Ok(RawStatus(200, Slice("OK"))));
        read("404 Not Found\r\n", Ok(RawStatus(404, Slice("Not Found"))));
        read("200 crazy pants\r\n", Ok(RawStatus(200, Owned("crazy pants".to_string()))));
    }

    #[test]
    fn test_read_header() {
        fn read(s: &str, result: HttpResult<Option<RawHeaderLine>>) {
            assert_eq!(read_header(&mut mem(s)), result);
        }

        read("Host: rust-lang.org\r\n", Ok(Some(("Host".to_string(),
                                                "rust-lang.org".as_bytes().to_vec()))));
    }

    #[test]
    fn test_write_chunked() {
        use std::str::from_utf8;
        let mut w = super::HttpWriter::ChunkedWriter(MemWriter::new());
        w.write(b"foo bar").unwrap();
        w.write(b"baz quux herp").unwrap();
        let buf = w.end().unwrap().unwrap();
        let s = from_utf8(buf.as_slice()).unwrap();
        assert_eq!(s, "7\r\nfoo bar\r\nD\r\nbaz quux herp\r\n0\r\n\r\n");
    }

    #[test]
    fn test_write_sized() {
        use std::str::from_utf8;
        let mut w = super::HttpWriter::SizedWriter(MemWriter::new(), 8);
        w.write(b"foo bar").unwrap();
        assert_eq!(w.write(b"baz"), Err(io::standard_error(io::ShortWrite(1))));

        let buf = w.end().unwrap().unwrap();
        let s = from_utf8(buf.as_slice()).unwrap();
        assert_eq!(s, "foo barb");
    }

    #[bench]
    fn bench_read_method(b: &mut Bencher) {
        b.bytes = b"CONNECT ".len() as u64;
        b.iter(|| assert_eq!(read_method(&mut mem("CONNECT ")), Ok(method::Method::Connect)));
    }

    #[bench]
    fn bench_read_status(b: &mut Bencher) {
        b.bytes = b"404 Not Found\r\n".len() as u64;
        b.iter(|| assert_eq!(read_status(&mut mem("404 Not Found\r\n")), Ok(RawStatus(404, Slice("Not Found")))));
    }

}


text:
module Octokit
  class Client
    module Repositories
      def search_repositories(q, options={})
        get("/legacy/repos/search/#{q}", options, 3)['repositories']
      end
      alias :search_repos :search_repositories

      def repository(repo, options={})
        get "/repos/#{Repository.new repo}", options, 3
      end
      alias :repo :repository

      def edit_repository(repo, options={})
        patch "/repos/#{Repository.new repo}", options, 3
      end
      alias :edit :edit_repository
      alias :update_repository :edit_repository
      alias :update :edit_repository

      def repositories(username=nil, options={})
        if username.nil?
          get '/user/repos', options, 3
        else
          get "/users/#{username}/repos", options, 3
        end
      end
      alias :list_repositories :repositories
      alias :list_repos :repositories
      alias :repos :repositories

      def watch(repo, options={})
        put "/user/watched/#{Repository.new repo}", options, 3
      end

      def unwatch(repo, options={})
        delete "/user/watched/#{Repository.new repo}", options, 3
      end

      def fork(repo, options={})
        post "/repos/#{Repository.new repo}/forks", options, 3
      end

      def create_repository(name, options={})
        organization = options.delete :organization
        options.merge! :name => name

        if organization.nil?
          post '/user/repos', options, 3
        else
          post "/orgs/#{organization}/repos", options, 3
        end
      end
      alias :create_repo :create_repository
      alias :create :create_repository

      def set_private(repo, options={})
        update_repository repo, options.merge({ :public => false })
      end

      def set_public(repo, options={})
        update_repository repo, options.merge({ :public => true })
      end

      def deploy_keys(repo, options={})
        get "/repos/#{Repository.new repo}/keys", options, 3
      end
      alias :list_deploy_keys :deploy_keys

      def add_deploy_key(repo, title, key, options={})
        post "/repos/#{Repository.new repo}/keys", options.merge(:title => title, :key => key), 3
      end

      def remove_deploy_key(repo, id, options={})
        delete "/repos/#{Repository.new repo}/keys/#{id}", options, 3
      end

      def collaborators(repo, options={})
        get "/repos/#{Repository.new repo}/collaborators", options, 3
      end
      alias :collabs :collaborators

      def add_collaborator(repo, collaborator, options={})
        put "/repos/#{Repository.new repo}/collaborators/#{collaborator}", options, 3
      end
      alias :add_collab :add_collaborator

      def remove_collaborator(repo, collaborator, options={})
        delete "/repos/#{Repository.new repo}/collaborators/#{collaborator}", options, 3
      end
      alias :remove_collab :remove_collaborator

      def pushable(options={})
        # There isn't a matching method in V3 of the api
        get("/api/v2/json/repos/pushable", options, 2)['repositories']
      end

      def repository_teams(repo, options={})
        get "/repos/#{Repository.new repo}/teams", options, 3
      end
      alias :repo_teams :repository_teams
      alias :teams :repository_teams

      def contributors(repo, anon=false, options={})
        get "/repos/#{Repository.new repo}/contributors", options.merge(:anon => anon), 3
      end
      alias :contribs :contributors

      def watchers(repo, options={})
        get "/repos/#{Repository.new repo}/watchers", options, 3
      end

      def forks(repo, options={})
        get "/repos/#{Repository.new repo}/forks", options, 3
      end
      alias :network :forks

      def languages(repo, options={})
        get "/repos/#{Repository.new repo}/languages", options, 3
      end

      def tags(repo, options={})
        get "/repos/#{Repository.new repo}/tags", options, 3
      end

      def branches(repo, options={})
        get "/repos/#{Repository.new repo}/branches", options, 3
      end

      # Get all Issue Events for a given Repository
      #
      # @param repo [String, Repository, Hash] A GitHub repository
      #
      # @return [Array] Array of all Issue Events for this Repository
      # @see http://developer.github.com/v3/issues/events/#list-events-for-a-repository
      # @example Get all Issue Events for Octokit
      #   Octokit.repository_issue_events("pengwynn/octokit")
      def repository_issue_events(repo, options={})
        get "/repos/#{Repository.new repo}/issues/events", options, 3
      end
      alias :repo_issue_events :repository_issue_events

    end
  end
end


text:
package kafka.server

import kafka.utils._
import kafka.metrics.KafkaMetricsGroup

import java.util
import java.util.concurrent._
import java.util.concurrent.atomic._
import scala.collection._

import com.yammer.metrics.core.Gauge

/**
 * An operation whose processing needs to be delayed for at most the given delayMs. For example
 * a delayed produce operation could be waiting for specified number of acks; or
 * a delayed fetch operation could be waiting for a given number of bytes to accumulate.
 *
 * The logic upon completing a delayed operation is defined in onComplete() and will be called exactly once.
 * Once an operation is completed, isCompleted() will return true. onComplete() can be triggered by either
 * forceComplete(), which forces calling onComplete() after delayMs if the operation is not yet completed,
 * or tryComplete(), which first checks if the operation can be completed or not now, and if yes calls
 * forceComplete().
 *
 * A subclass of DelayedOperation needs to provide an implementation of both onComplete() and tryComplete().
 */
abstract class DelayedOperation(delayMs: Long) extends DelayedItem(delayMs) {
  private val completed = new AtomicBoolean(false)

  /*
   * Force completing the delayed operation, if not already completed.
   * This function can be triggered when
   *
   * 1. The operation has been verified to be completable inside tryComplete()
   * 2. The operation has expired and hence needs to be completed right now
   *
   * Return true iff the operation is completed by the caller: note that
   * concurrent threads can try to complete the same operation, but only
   * the first thread will succeed in completing the operation and return
   * true, others will still return false
   */
  def forceComplete(): Boolean = {
    if (completed.compareAndSet(false, true)) {
      onComplete()
      true
    } else {
      false
    }
  }

  /**
   * Check if the delayed operation is already completed
   */
  def isCompleted(): Boolean = completed.get()

  /**
   * Call-back to execute when a delayed operation expires, but before completion.
   */
  def onExpiration(): Unit

  /**
   * Process for completing an operation; This function needs to be defined
   * in subclasses and will be called exactly once in forceComplete()
   */
  def onComplete(): Unit

  /*
   * Try to complete the delayed operation by first checking if the operation
   * can be completed by now. If yes execute the completion logic by calling
   * forceComplete() and return true iff forceComplete returns true; otherwise return false
   *
   * This function needs to be defined in subclasses
   */
  def tryComplete(): Boolean
}

/**
 * A helper purgatory class for bookkeeping delayed operations with a timeout, and expiring timed out operations.
 */
class DelayedOperationPurgatory[T <: DelayedOperation](purgatoryName: String, brokerId: Int = 0, purgeInterval: Int = 1000)
        extends Logging with KafkaMetricsGroup {

  /* a list of operation watching keys */
  private val watchersForKey = new Pool[Any, Watchers](Some((key: Any) => new Watchers))

  /* background thread expiring operations that have timed out */
  private val expirationReaper = new ExpiredOperationReaper

  private val metricsTags = Map("delayedOperation" -> purgatoryName)

  newGauge(
    "PurgatorySize",
    new Gauge[Int] {
      def value = watched()
    },
    metricsTags
  )

  newGauge(
    "NumDelayedOperations",
    new Gauge[Int] {
      def value = delayed()
    },
    metricsTags
  )

  expirationReaper.start()

  /**
   * Check if the operation can be completed, if not watch it based on the given watch keys
   *
   * Note that a delayed operation can be watched on multiple keys. It is possible that
   * an operation is completed after it has been added to the watch list for some, but
   * not all of the keys. In this case, the operation is considered completed and won't
   * be added to the watch list of the remaining keys. The expiration reaper thread will
   * remove this operation from any watcher list in which the operation exists.
   *
   * @param operation the delayed operation to be checked
   * @param watchKeys keys for bookkeeping the operation
   * @return true iff the delayed operations can be completed by the caller
   */
  def tryCompleteElseWatch(operation: T, watchKeys: Seq[Any]): Boolean = {
    assert(watchKeys.size > 0, "The watch key list can't be empty")

    // The cost of tryComplete() is typically proportional to the number of keys. Calling
    // tryComplete() for each key is going to be expensive if there are many keys. Instead,
    // we do the check in the following way. Call tryComplete(). If the operation is not completed,
    // we just add the operation to all keys. Then we call tryComplete() again. At this time, if
    // the operation is still not completed, we are guaranteed that it won't miss any future triggering
    // event since the operation is already on the watcher list for all keys. This does mean that
    // if the operation is completed (by another thread) between the two tryComplete() calls, the
    // operation is unnecessarily added for watch. However, this is a less severe issue since the
    // expire reaper will clean it up periodically.

    var isCompletedByMe = operation synchronized operation.tryComplete()
    if (isCompletedByMe)
      return true

    for(key <- watchKeys) {
      // If the operation is already completed, stop adding it to the rest of the watcher list.
      if (operation.isCompleted())
        return false
      val watchers = watchersFor(key)
      watchers.watch(operation)
    }

    isCompletedByMe = operation synchronized operation.tryComplete()
    if (isCompletedByMe)
      return true

    // if it cannot be completed by now and hence is watched, add to the expire queue also
    if (! operation.isCompleted())
      expirationReaper.enqueue(operation)

    false
  }

  /**
   * Check if some some delayed operations can be completed with the given watch key,
   * and if yes complete them.
   *
   * @return the number of completed operations during this process
   */
  def checkAndComplete(key: Any): Int = {
    val watchers = watchersForKey.get(key)
    if(watchers == null)
      0
    else
      watchers.tryCompleteWatched()
  }

  /**
   * Return the total size of watch lists the purgatory. Since an operation may be watched
   * on multiple lists, and some of its watched entries may still be in the watch lists
   * even when it has been completed, this number may be larger than the number of real operations watched
   */
  def watched() = watchersForKey.values.map(_.watched).sum

  /**
   * Return the number of delayed operations in the expiry queue
   */
  def delayed() = expirationReaper.delayed

  /*
   * Return the watch list of the given key
   */
  private def watchersFor(key: Any) = watchersForKey.getAndMaybePut(key)

  /**
   * Shutdown the expire reaper thread
   */
  def shutdown() {
    expirationReaper.shutdown()
  }

  /**
   * A linked list of watched delayed operations based on some key
   */
  private class Watchers {
    private val operations = new util.LinkedList[T]

    def watched = operations.size()

    // add the element to watch
    def watch(t: T) {
      synchronized {
        operations.add(t)
      }
    }

    // traverse the list and try to complete some watched elements
    def tryCompleteWatched(): Int = {
      var completed = 0
      synchronized {
        val iter = operations.iterator()
        while(iter.hasNext) {
          val curr = iter.next
          if (curr.isCompleted()) {
            // another thread has completed this operation, just remove it
            iter.remove()
          } else {
            if(curr synchronized curr.tryComplete()) {
              iter.remove()
              completed += 1
            }
          }
        }
      }
      completed
    }

    // traverse the list and purge elements that are already completed by others
    def purgeCompleted(): Int = {
      var purged = 0
      synchronized {
        val iter = operations.iterator()
        while (iter.hasNext) {
          val curr = iter.next
          if(curr.isCompleted()) {
            iter.remove()
            purged += 1
          }
        }
      }
      purged
    }
  }

  /**
   * A background reaper to expire delayed operations that have timed out
   */
  private class ExpiredOperationReaper extends ShutdownableThread(
    "ExpirationReaper-%d".format(brokerId),
    false) {

    /* The queue storing all delayed operations */
    private val delayedQueue = new DelayQueue[T]

    /*
     * Return the number of delayed operations kept by the reaper
     */
    def delayed() = delayedQueue.size()

    /*
     * Add an operation to be expired
     */
    def enqueue(t: T) {
      delayedQueue.add(t)
    }

    /**
     * Try to get the next expired event and force completing it
     */
    private def expireNext() {
      val curr = delayedQueue.poll(200L, TimeUnit.MILLISECONDS)
      if (curr != null.asInstanceOf[T]) {
        // if there is an expired operation, try to force complete it
        val completedByMe: Boolean = curr synchronized {
          curr.onExpiration()
          curr.forceComplete()
        }
        if (completedByMe)
          debug("Force complete expired delayed operation %s".format(curr))
      }
    }

    /**
     * Delete all satisfied events from the delay queue and the watcher lists
     */
    private def purgeCompleted(): Int = {
      var purged = 0

      // purge the delayed queue
      val iter = delayedQueue.iterator()
      while (iter.hasNext) {
        val curr = iter.next()
        if (curr.isCompleted()) {
          iter.remove()
          purged += 1
        }
      }

      purged
    }

    override def doWork() {
      // try to get the next expired operation and force completing it
      expireNext()
      // see if we need to purge the watch lists
      if (DelayedOperationPurgatory.this.watched() >= purgeInterval) {
        debug("Begin purging watch lists")
        val purged = watchersForKey.values.map(_.purgeCompleted()).sum
        debug("Purged %d elements from watch lists.".format(purged))
      }
      // see if we need to purge the delayed operation queue
      if (delayed() >= purgeInterval) {
        debug("Begin purging delayed queue")
        val purged = purgeCompleted()
        debug("Purged %d operations from delayed queue.".format(purged))
      }
    }
  }
}


text:
package org.springframework.boot.context.embedded.tomcat;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;

import org.apache.tomcat.JarScanner;
import org.apache.tomcat.JarScannerCallback;
import org.apache.tomcat.util.scan.StandardJarScanFilter;
import org.apache.tomcat.util.scan.StandardJarScanner;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

/**
 * {@link JarScanner} decorator allowing alternative default jar pattern matching. This
 * class extends {@link StandardJarScanner} rather than implementing the
 * {@link JarScanner} due to API changes introduced in Tomcat 8.
 *
 * @author Phillip Webb
 * @see #apply(TomcatEmbeddedContext, String)
 */
class SkipPatternJarScanner extends StandardJarScanner {

	private static final String JAR_SCAN_FILTER_CLASS = "org.apache.tomcat.JarScanFilter";

	private final JarScanner jarScanner;

	private final SkipPattern pattern;

	SkipPatternJarScanner(JarScanner jarScanner, String pattern) {
		Assert.notNull(jarScanner, "JarScanner must not be null");
		this.jarScanner = jarScanner;
		this.pattern = (pattern == null ? new SkipPattern() : new SkipPattern(pattern));
		setPatternToTomcat8SkipFilter(this.pattern);
	}

	private void setPatternToTomcat8SkipFilter(SkipPattern pattern) {
		if (ClassUtils.isPresent(JAR_SCAN_FILTER_CLASS, null)) {
			new Tomcat8TldSkipSetter(this).setSkipPattern(pattern);
		}
	}

	// For Tomcat 7 compatibility
	public void scan(ServletContext context, ClassLoader classloader,
			JarScannerCallback callback, Set<String> jarsToSkip) {
		Method scanMethod = ReflectionUtils.findMethod(this.jarScanner.getClass(),
				"scan", ServletContext.class, ClassLoader.class,
				JarScannerCallback.class, Set.class);
		Assert.notNull(scanMethod, "Unable to find scan method");
		try {
			scanMethod.invoke(this.jarScanner, context, classloader, callback,
					(jarsToSkip == null ? this.pattern.asSet() : jarsToSkip));
		}
		catch (Exception ex) {
			throw new IllegalStateException("Tomcat 7 reflection failed", ex);
		}
	}

	/**
	 * Apply this decorator the specified context.
	 * @param context the context to apply to
	 * @param pattern the jar skip pattern or {@code null} for defaults
	 */
	public static void apply(TomcatEmbeddedContext context, String pattern) {
		SkipPatternJarScanner scanner = new SkipPatternJarScanner(
				context.getJarScanner(), pattern);
		context.setJarScanner(scanner);
	}

	/**
	 * Tomcat 8 specific logic to setup the scanner.
	 */
	private static class Tomcat8TldSkipSetter {

		private final StandardJarScanner jarScanner;

		public Tomcat8TldSkipSetter(StandardJarScanner jarScanner) {
			this.jarScanner = jarScanner;
		}

		public void setSkipPattern(SkipPattern pattern) {
			StandardJarScanFilter filter = new StandardJarScanFilter();
			filter.setTldSkip(pattern.asCommaDelimitedString());
			this.jarScanner.setJarScanFilter(filter);
		}

	}

	/**
	 * Skip patterns used by Spring Boot
	 */
	private static class SkipPattern {

		private Set<String> patterns = new LinkedHashSet<String>();

		protected SkipPattern() {
			// Same as Tomcat
			add("ant-*.jar");
			add("aspectj*.jar");
			add("commons-beanutils*.jar");
			add("commons-codec*.jar");
			add("commons-collections*.jar");
			add("commons-dbcp*.jar");
			add("commons-digester*.jar");
			add("commons-fileupload*.jar");
			add("commons-httpclient*.jar");
			add("commons-io*.jar");
			add("commons-lang*.jar");
			add("commons-logging*.jar");
			add("commons-math*.jar");
			add("commons-pool*.jar");
			add("geronimo-spec-jaxrpc*.jar");
			add("h2*.jar");
			add("hamcrest*.jar");
			add("hibernate*.jar");
			add("jmx*.jar");
			add("jmx-tools-*.jar");
			add("jta*.jar");
			add("junit-*.jar");
			add("httpclient*.jar");
			add("log4j-*.jar");
			add("mail*.jar");
			add("org.hamcrest*.jar");
			add("slf4j*.jar");
			add("tomcat-embed-core-*.jar");
			add("tomcat-embed-logging-*.jar");
			add("tomcat-jdbc-*.jar");
			add("tomcat-juli-*.jar");
			add("tools.jar");
			add("wsdl4j*.jar");
			add("xercesImpl-*.jar");
			add("xmlParserAPIs-*.jar");
			add("xml-apis-*.jar");

			// Additional
			add("antlr-*.jar");
			add("aopalliance-*.jar");
			add("aspectjrt-*.jar");
			add("aspectjweaver-*.jar");
			add("classmate-*.jar");
			add("dom4j-*.jar");
			add("ecj-*.jar");
			add("ehcache-core-*.jar");
			add("hibernate-core-*.jar");
			add("hibernate-commons-annotations-*.jar");
			add("hibernate-entitymanager-*.jar");
			add("hibernate-jpa-2.1-api-*.jar");
			add("hibernate-validator-*.jar");
			add("hsqldb-*.jar");
			add("jackson-annotations-*.jar");
			add("jackson-core-*.jar");
			add("jackson-databind-*.jar");
			add("jandex-*.jar");
			add("javassist-*.jar");
			add("jboss-logging-*.jar");
			add("jboss-transaction-api_*.jar");
			add("jcl-over-slf4j-*.jar");
			add("jdom-*.jar");
			add("joda-time-*.jar");
			add("jul-to-slf4j-*.jar");
			add("log4j-over-slf4j-*.jar");
			add("logback-classic-*.jar");
			add("logback-core-*.jar");
			add("rome-*.jar");
			add("slf4j-api-*.jar");
			add("spring-aop-*.jar");
			add("spring-aspects-*.jar");
			add("spring-beans-*.jar");
			add("spring-boot-*.jar");
			add("spring-core-*.jar");
			add("spring-context-*.jar");
			add("spring-data-*.jar");
			add("spring-expression-*.jar");
			add("spring-jdbc-*.jar,");
			add("spring-orm-*.jar");
			add("spring-oxm-*.jar");
			add("spring-tx-*.jar");
			add("snakeyaml-*.jar");
			add("tomcat-embed-el-*.jar");
			add("validation-api-*.jar");
			add("xml-apis-*.jar");
		}

		public SkipPattern(String patterns) {
			StringTokenizer tokenizer = new StringTokenizer(patterns, ",");
			while (tokenizer.hasMoreElements()) {
				add(tokenizer.nextToken());
			}
		}

		protected void add(String patterns) {
			Assert.notNull(patterns, "Patterns must not be null");
			if (patterns.length() > 0 && !patterns.trim().startsWith(",")) {
				this.patterns.add(",");
			}
			this.patterns.add(patterns);
		}

		public String asCommaDelimitedString() {
			return StringUtils.collectionToCommaDelimitedString(this.patterns);
		}

		public Set<String> asSet() {
			return Collections.unmodifiableSet(this.patterns);
		}

	}

}


text:
package org.apache.reef.examples.distributedshell;

import org.apache.reef.driver.evaluator.AllocatedEvaluator;
import org.apache.reef.driver.evaluator.EvaluatorRequest;
import org.apache.reef.driver.evaluator.EvaluatorRequestor;
import org.apache.reef.driver.task.TaskConfiguration;
import org.apache.reef.examples.library.Command;
import org.apache.reef.examples.library.ShellTask;
import org.apache.reef.tang.Configuration;
import org.apache.reef.tang.JavaConfigurationBuilder;
import org.apache.reef.tang.Tang;
import org.apache.reef.tang.annotations.Parameter;
import org.apache.reef.tang.annotations.Unit;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.time.event.StartTime;

import javax.inject.Inject;
import java.util.logging.Level;
import java.util.logging.Logger;

/** The Driver code for REEF distributed shell application. */
@Unit
final class ShellDriver {

  private static final Logger LOG = Logger.getLogger(ShellDriver.class.getName());

  private static final Configuration STATIC_TASK_CONFIG = TaskConfiguration.CONF
      .set(TaskConfiguration.IDENTIFIER, "ShellTask")
      .set(TaskConfiguration.TASK, ShellTask.class)
      .build();

  private final EvaluatorRequestor requestor;
  private final int numEvaluators;
  private final String command;

  @Inject
  private ShellDriver(
      final EvaluatorRequestor requestor,
      @Parameter(NumEvaluators.class) final int numEvaluators,
      @Parameter(Command.class) final String command) {

    this.requestor = requestor;
    this.numEvaluators = numEvaluators;
    this.command = command;
  }

  /** Driver start event: Request the evaluators. */
  final class StartHandler implements EventHandler<StartTime> {
    @Override
    public void onNext(final StartTime startTime) {
      requestor.submit(EvaluatorRequest.newBuilder()
          .setNumber(numEvaluators)
          .setMemory(64)
          .setNumberOfCores(1)
          .build());
    }
  }

  /** AllocatedEvaluator event: Submit the distributed shell task. */
  final class EvaluatorAllocatedHandler implements EventHandler<AllocatedEvaluator> {
    @Override
    public void onNext(final AllocatedEvaluator allocatedEvaluator) {

      LOG.log(Level.INFO,
          "Submitting command {0} task to evaluator: {1}", new Object[] {command, allocatedEvaluator});

      final JavaConfigurationBuilder taskConfigBuilder =
          Tang.Factory.getTang().newConfigurationBuilder(STATIC_TASK_CONFIG);

      taskConfigBuilder.bindNamedParameter(Command.class, command);

      allocatedEvaluator.submitTask(taskConfigBuilder.build());
    }
  }
}


text:
#import "ABI11_0_0RNSVGRenderableManager.h"

@interface ABI11_0_0RNSVGCircleManager : ABI11_0_0RNSVGRenderableManager

@end


text:
let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .extract(['vue', 'jquery', 'axios'], 'public/js/vendor.js');

if (mix.inProduction()) {
    mix.version();
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface UICollectionReusableView (AGViewModel)
<AGCollectionFooterViewReusable, AGCollectionHeaderViewReusable>

@end

NS_ASSUME_NONNULL_END


text:
import { OnChanges, SimpleChange } from '@angular/core';
export declare class MdlProgressComponent implements OnChanges {
    progress: number;
    buffer: number;
    aux: number;
    indeterminate: boolean;
    ngOnChanges(changes: {
        [propertyName: string]: SimpleChange;
    }): void;
    private setBuffer(b);
}
/** @deprecated */
export declare const MDL_PROGRESS_DIRECTIVES: typeof MdlProgressComponent[];
export declare class MdlProgressModule {
}