text:
# subzero [![npm version](https://badge.fury.io/js/subzero.svg)](https://badge.fury.io/js/subzero) [![Build Status](https://travis-ci.org/msteckyefantis/subzero.svg?branch=master)](https://travis-ci.org/msteckyefantis/subzero)

[![mksfw.gif](https://s30.postimg.org/vd4asvu9t/mksfw.gif)](https://postimg.org/image/vd4asvu9p/)

## About:

Freeze a class, freeze a function, or freeze an object. For Node version 6 or greater.

## install:

```
npm install subzero
```

## usage:

#### function list (each function explained in more detail below):

1. [subzero.megaFreeze](#1-subzeromegafreeze-functionorclassorobjecttofreeze-)

>Note: the mega freeze function was inspired by [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) and  [deep-freeze](https://github.com/substack/deep-freeze).

[![freezer.jpg](https://s29.postimg.org/gjwm9hhmv/freezer.jpg)](https://postimg.org/image/6zczmlsar/)

<br>

### 1) subzero.megaFreeze( functionOrClassOrObjectToFreeze )
Deep freeze a class, a function, or an object. This will freeze any classes, functions, and objects within the class/function/object being mega-frozen. It works by recursively freezing anything of type `"object"` or `"function"`.

```.js
'use strict';

const subzero = require( 'subzero' );

/*
	this example uses a function,
    subzero.megaFreeze also works with objects and classes
*/
function f() {}

const InnerClass = class {};

InnerClass.x = {

    y: {}
};

const innerFunction = function() {};

innerFunction.x = {

    y: {}
};

const objectInsideAlreadyFrozenObject = {};

const functionInsideAlreadyFrozenObject = function() {};

const objectInsideAlreadyFrozenFunction = {};

const functionInsideAlreadyFrozenFunction = function() {};

const functionToFreeze = function() {};

functionToFreeze.objectInsideAlreadyFrozenFunction = objectInsideAlreadyFrozenFunction;

functionToFreeze.functionInsideAlreadyFrozenFunction = functionInsideAlreadyFrozenFunction;

const frozenFunctionWithNonFrozenObjectAndFunctionInside = Object.freeze( functionToFreeze );

const buff = new Buffer( 69 );

buff.x = {

    y: {},

    f: function() {}
};

f.a = {

    b: {

        c: {

            d: {

                InnerClass,

                innerFunction,

                buff,

                e: Object.freeze({

                    objectInsideAlreadyFrozenObject,

                    functionInsideAlreadyFrozenObject
                }),

                frozenFunctionWithNonFrozenObjectAndFunctionInside
            }
        }
    }
};

f.prototype.x = {

    y: {

        z: {}
    },

    w: {}
};

/*
    It's time to freeze your opponent for the flawless victory with fatality.

	None of the following assertions will throw an AssertionError:
*/

console.assert( !Object.isFrozen( f ) );
console.assert( !Object.isFrozen( f.prototype ) );
console.assert( !Object.isFrozen( f.a ) );
console.assert( !Object.isFrozen( f.a.b ) );
console.assert( !Object.isFrozen( f.a.b.c ) );
console.assert( !Object.isFrozen( f.a.b.c.d ) );
console.assert( !Object.isFrozen( f.prototype.x ) );
console.assert( !Object.isFrozen( f.prototype.x.y ) );
console.assert( !Object.isFrozen( f.prototype.x.y.z ) );
console.assert( !Object.isFrozen( f.prototype.x.w ) );
console.assert( !Object.isFrozen( InnerClass ) );
console.assert( !Object.isFrozen( InnerClass.prototype ) );
console.assert( !Object.isFrozen( InnerClass.x ) );
console.assert( !Object.isFrozen( InnerClass.x.y ) );
console.assert( !Object.isFrozen( innerFunction ) );
console.assert( !Object.isFrozen( innerFunction.prototype ) );
console.assert( !Object.isFrozen( innerFunction.x ) );
console.assert( !Object.isFrozen( innerFunction.x.y ) );
console.assert( !Object.isFrozen( objectInsideAlreadyFrozenObject ) );
console.assert( !Object.isFrozen( objectInsideAlreadyFrozenFunction ) );
console.assert( !Object.isFrozen( functionInsideAlreadyFrozenObject ) );
console.assert( !Object.isFrozen( functionInsideAlreadyFrozenObject.prototype ) );
console.assert( !Object.isFrozen( functionInsideAlreadyFrozenFunction ) );
console.assert( !Object.isFrozen( functionInsideAlreadyFrozenFunction.prototype ) );
console.assert( !Object.isSealed( buff ) ); // you cannot freeze buffers
console.assert( !Object.isFrozen( buff.x ) );
console.assert( !Object.isFrozen( buff.x.y ) );
console.assert( !Object.isFrozen( buff.x.f ) );
console.assert( !Object.isFrozen( buff.x.f.prototype ) );

// Mega Freeze f
const reference = subzero.megaFreeze( f );

console.assert( ( reference === f ) );

console.assert( Object.isFrozen( f ) );
console.assert( Object.isFrozen( f.prototype ) );
console.assert( Object.isFrozen( f.a ) );
console.assert( Object.isFrozen( f.a.b ) );
console.assert( Object.isFrozen( f.a.b.c ) );
console.assert( Object.isFrozen( f.a.b.c.d ) );
console.assert( Object.isFrozen( f.prototype.x ) );
console.assert( Object.isFrozen( f.prototype.x.y ) );
console.assert( Object.isFrozen( f.prototype.x.y.z ) );
console.assert( Object.isFrozen( f.prototype.x.w ) );
console.assert( Object.isFrozen( InnerClass ) );
console.assert( Object.isFrozen( InnerClass.prototype ) );
console.assert( Object.isFrozen( InnerClass.x ) );
console.assert( Object.isFrozen( InnerClass.x.y ) );
console.assert( Object.isFrozen( innerFunction ) );
console.assert( Object.isFrozen( innerFunction.prototype ) );
console.assert( Object.isFrozen( innerFunction.x ) );
console.assert( Object.isFrozen( innerFunction.x.y ) );
console.assert( Object.isFrozen( objectInsideAlreadyFrozenObject ) );
console.assert( Object.isFrozen( objectInsideAlreadyFrozenFunction ) );
console.assert( Object.isFrozen( functionInsideAlreadyFrozenObject ) );
console.assert( Object.isFrozen( functionInsideAlreadyFrozenObject.prototype ) );
console.assert( Object.isFrozen( functionInsideAlreadyFrozenFunction ) );
console.assert( Object.isFrozen( functionInsideAlreadyFrozenFunction.prototype ) );
console.assert( Object.isSealed( buff ) );
console.assert( Object.isFrozen( buff.x ) );
console.assert( Object.isFrozen( buff.x.y ) );
console.assert( Object.isFrozen( buff.x.f ) );
console.assert( Object.isFrozen( buff.x.f.prototype ) );
```

[![letitgo.gif](https://s27.postimg.org/gym5t7iib/letitgo.gif)](https://postimg.org/image/ptn03q7an/)

#### no-op:
If the input value is not an object, a function, or a class for subzero's megaFreeze function, the return value will be the input value unaltered.

[![frieza22.gif](https://s23.postimg.org/d6ri2wwm3/frieza22.gif)](https://postimg.org/image/djiw93evr/)


text:
import checkdigit from 'checkdigit';

(checkdigit.mod10.isValid('2345676'): boolean);
(checkdigit.mod10.create('234567'): string);
(checkdigit.mod10.apply('234567'): string);

(checkdigit.mod11.isValid('2345676'): boolean);
(checkdigit.mod11.create('234567'): string);
(checkdigit.mod11.apply('234567'): string);

// $ExpectError
checkdigit.mod10.isValid();
// $ExpectError
checkdigit.mod10.create();
// $ExpectError
checkdigit.mod10.apply();

// $ExpectError
checkdigit.mod11.isValid();
// $ExpectError
checkdigit.mod11.create();
// $ExpectError
checkdigit.mod11.apply();

// $ExpectError
checkdigit.mod10.isValid(123);
// $ExpectError
checkdigit.mod10.create(123);
// $ExpectError
checkdigit.mod10.apply(123);

// $ExpectError
checkdigit.mod11.isValid(123);
// $ExpectError
checkdigit.mod11.create(123);
// $ExpectError
checkdigit.mod11.apply(123);

redpajama_set_name: RedPajamaGithub


text:
package io.grpc.internal;

import io.grpc.Attributes;
import io.grpc.EquivalentAddressGroup;
import io.grpc.Grpc;
import io.grpc.NameResolver;
import io.grpc.SecurityLevel;
import java.util.Map;

/**
 * Special attributes that are only useful to gRPC.
 */
public final class GrpcAttributes {
  /**
   * Attribute key for service config.
   */
  @NameResolver.ResolutionResultAttr
  public static final Attributes.Key<Map<String, ?>> NAME_RESOLVER_SERVICE_CONFIG =
      Attributes.Key.create("service-config");

  /**
   * The naming authority of a gRPC LB server address.  It is an address-group-level attribute,
   * present when the address group is a LoadBalancer.
   */
  @EquivalentAddressGroup.Attr
  public static final Attributes.Key<String> ATTR_LB_ADDR_AUTHORITY =
      Attributes.Key.create("io.grpc.grpclb.lbAddrAuthority");

  /**
   * Whether this EquivalentAddressGroup was provided by a GRPCLB server. It would be rare for this
   * value to be {@code false}; generally it would be better to not have the key present at all.
   */
  @EquivalentAddressGroup.Attr
  public static final Attributes.Key<Boolean> ATTR_LB_PROVIDED_BACKEND =
      Attributes.Key.create("io.grpc.grpclb.lbProvidedBackend");

  /**
   * The security level of the transport.  If it's not present, {@link SecurityLevel#NONE} should be
   * assumed.
   */
  @Grpc.TransportAttr
  public static final Attributes.Key<SecurityLevel> ATTR_SECURITY_LEVEL =
      Attributes.Key.create("io.grpc.internal.GrpcAttributes.securityLevel");

  /**
   * Attribute key for the attributes of the {@link EquivalentAddressGroup} ({@link
   * EquivalentAddressGroup#getAttributes}) that the transport's server address is from.  This is a
   * client-side-only transport attribute, and available right after the transport is started.
   */
  @Grpc.TransportAttr
  public static final Attributes.Key<Attributes> ATTR_CLIENT_EAG_ATTRS =
      Attributes.Key.create("io.grpc.internal.GrpcAttributes.clientEagAttrs");

  private GrpcAttributes() {}
}


text:
#ifndef __APPLE_MANIFEST__
#define __APPLE_MANIFEST__

#include "ManifestSigner.h"
#include <Security/SecCmsBase.h>
#include <vector>

typedef std::vector<SecIdentityRef> SignerList;

class AppleManifest : public ManifestSigner
{
protected:
	void AddDataBlobToManifest (CFMutableDataRef manifest, ManifestDataBlobItem* db);
	void AddDirectoryToManifest (CFMutableDataRef manifest, ManifestDirectoryItem* directory);
	void AddFileToManifest (CFMutableDataRef manifest, ManifestFileItem* file);
	void AddSymLinkToManifest (CFMutableDataRef manifest, ManifestSymLinkItem* file);
	void AddOtherToManifest (CFMutableDataRef manifest, ManifestOtherItem* other);
	void AddManifestItemListToManifest (CFMutableDataRef manifest, ManifestItemList &itemList);
	void CreateManifest (CFMutableDataRef manifest, ManifestInternal& internalManifest);

	void AddSignersToCmsMessage (SecCmsMessageRef cmsMessage, SecCmsSignedDataRef signedData);

	void ReconstructDataBlob (uint32& finger, const uint8* data, ManifestDataBlobItem*& db);
	void ReconstructDirectory (uint32& finger, const uint8* data, ManifestDirectoryItem*& directory);
	void ReconstructFile (uint32& finger, const uint8* data, ManifestFileItem *& file);
	void ReconstructSymLink (uint32& finger, const uint8* data, ManifestSymLinkItem*& file);
	void ReconstructOther (uint32& finger, const uint8* data, ManifestOtherItem*& other);
	void ReconstructManifestItemList (uint32 &finger, const uint8* data, ManifestItemList &itemList);
	void ReconstructManifest (uint8* data, uint32 length, ManifestInternal& manifest);

	SignerList mSignerList;

	SecCmsMessageRef GetCmsMessageFromData (CFDataRef data);

public:
	AppleManifest ();
	virtual ~AppleManifest ();

	virtual CFDataRef Export (ManifestInternal& manifest);
	void Verify (CFDataRef data, SecManifestTrustSetupCallback setupCallback, void* setupContext,
				 SecManifestTrustEvaluateCallback evaluateCallback, void* evaluateContext,
				 SecPolicyRef policyRef, ManifestInternal *manifest);
	virtual void AddSigner (SecIdentityRef identityRef);
};

#endif


text:
package examples.stateless;

import java.util.Collection;

import examples.model.Employee;

public interface EmployeeService {
    public Collection<Employee> findAllEmployees();
    public Employee findEmployeeByName(String name);
    public Employee findEmployeeByPrimaryKey(int id);
    public long findSalaryForNameAndDepartment(String deptName, String empName);
}


text:
from unittest import TestCase

from spockbot.plugins.base import PluginBase

class PluginLoaderMock(object):
    events = {}

    def requires(self, *args, **kwargs):
        return True

    def reg_event_handler(self, event, handler):
        self.events[event] = [] if event not in self.events else self.events[
            event]
        self.events[event].append(handler)

class TestPluginBase(PluginBase):
    requires = ('Net', 'Auth')
    defaults = {'foo': 'bar'}
    events = {'test': 'callback'}

    def callback(self):
        pass

class PluginBaseTest(TestCase):
    def setUp(self):
        self.ploader = PluginLoaderMock()
        self.plug = TestPluginBase(self.ploader, {})

    def tearDown(self):
        delattr(self, 'ploader')
        delattr(self, 'plug')

    def test_requirements_get_loaded(self):
        self.assertTrue(getattr(self.plug, 'net', False))
        self.assertTrue(getattr(self.plug, 'auth', False))

    def test_default_settings_applied(self):
        # Only assert that settings are set. Checking whether settings and
        # defaults merge correctly should be tested in
        # spockbot.utils.get_settings.
        self.assertEqual(self.plug.settings['foo'], 'bar')

    def test_event_listeners_registration_succeeds(self):
        self.assertIn(self.plug.callback, self.ploader.events['test'])


text:
import mock
from oslo_serialization import jsonutils
import webob.exc

from searchlight.api.v1 import search as search
from searchlight.common import exception
from searchlight.common import utils
import searchlight.elasticsearch
import searchlight.gateway
from searchlight.tests.unit import base
import searchlight.tests.unit.utils as unit_test_utils
import searchlight.tests.utils as test_utils

def _action_fixture(op_type, data, index=None, doc_type=None, _id=None,
                    **kwargs):
    action = {
        'action': op_type,
        'id': _id,
        'index': index,
        'type': doc_type,
        'data': data,
    }
    if kwargs:
        action.update(kwargs)

    return action

def _image_fixture(op_type, _id=None, index='glance', doc_type='image',
                   data=None, **kwargs):
    image_data = {
        'name': 'image-1',
        'disk_format': 'raw',
    }
    if data is not None:
        image_data.update(data)

    return _action_fixture(op_type, image_data, index, doc_type, _id, **kwargs)

class TestSearchController(base.IsolatedUnitTest):

    def setUp(self):
        super(TestSearchController, self).setUp()
        self.search_controller = search.SearchController()

    def test_search_all(self):
        request = unit_test_utils.get_fake_request()
        self.search_controller.search = mock.Mock(return_value="{}")

        query = {"match_all": {}}
        index = "glance"
        doc_type = "metadef"
        fields = None
        offset = 0
        limit = 10
        self.search_controller.search(
            request, query, index, doc_type, fields, offset, limit)
        self.search_controller.search.assert_called_once_with(
            request, query, index, doc_type, fields, offset, limit)

    def test_search_all_repo(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.search = mock.Mock(return_value="{}")
        query = {"match_all": {}}
        index = "glance"
        doc_type = "metadef"
        fields = []
        offset = 0
        limit = 10
        self.search_controller.search(
            request, query, index, doc_type, fields, offset, limit)
        repo.search.assert_called_once_with(
            index, doc_type, query, fields, offset, limit, True)

    def test_search_forbidden(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.search = mock.Mock(side_effect=exception.Forbidden)

        query = {"match_all": {}}
        index = "glance"
        doc_type = "metadef"
        fields = []
        offset = 0
        limit = 10

        self.assertRaises(
            webob.exc.HTTPForbidden, self.search_controller.search,
            request, query, index, doc_type, fields, offset, limit)

    def test_search_not_found(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.search = mock.Mock(side_effect=exception.NotFound)

        query = {"match_all": {}}
        index = "glance"
        doc_type = "metadef"
        fields = []
        offset = 0
        limit = 10

        self.assertRaises(
            webob.exc.HTTPNotFound, self.search_controller.search, request,
            query, index, doc_type, fields, offset, limit)

    def test_search_duplicate(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.search = mock.Mock(side_effect=exception.Duplicate)

        query = {"match_all": {}}
        index = "glance"
        doc_type = "metadef"
        fields = []
        offset = 0
        limit = 10

        self.assertRaises(
            webob.exc.HTTPConflict, self.search_controller.search, request,
            query, index, doc_type, fields, offset, limit)

    def test_search_internal_server_error(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.search = mock.Mock(side_effect=Exception)

        query = {"match_all": {}}
        index = "glance"
        doc_type = "metadef"
        fields = []
        offset = 0
        limit = 10

        self.assertRaises(
            webob.exc.HTTPInternalServerError, self.search_controller.search,
            request, query, index, doc_type, fields, offset, limit)

    def test_index_complete(self):
        request = unit_test_utils.get_fake_request()
        self.search_controller.index = mock.Mock(return_value="{}")
        actions = [{'action': 'create', 'index': 'myindex', 'id': 10,
                    'type': 'MyTest', 'data': '{"name": "MyName"}'}]
        default_index = 'glance'
        default_type = 'image'

        self.search_controller.index(
            request, actions, default_index, default_type)
        self.search_controller.index.assert_called_once_with(
            request, actions, default_index, default_type)

    def test_index_repo_complete(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.index = mock.Mock(return_value="{}")
        actions = [{'action': 'create', 'index': 'myindex', 'id': 10,
                    'type': 'MyTest', 'data': '{"name": "MyName"}'}]
        default_index = 'glance'
        default_type = 'image'

        self.search_controller.index(
            request, actions, default_index, default_type)
        repo.index.assert_called_once_with(
            default_index, default_type, actions)

    def test_index_repo_minimal(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.index = mock.Mock(return_value="{}")
        actions = [{'action': 'create', 'index': 'myindex', 'id': 10,
                    'type': 'MyTest', 'data': '{"name": "MyName"}'}]

        self.search_controller.index(request, actions)
        repo.index.assert_called_once_with(None, None, actions)

    def test_index_forbidden(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.index = mock.Mock(side_effect=exception.Forbidden)
        actions = [{'action': 'create', 'index': 'myindex', 'id': 10,
                    'type': 'MyTest', 'data': '{"name": "MyName"}'}]

        self.assertRaises(
            webob.exc.HTTPForbidden, self.search_controller.index,
            request, actions)

    def test_index_not_found(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.index = mock.Mock(side_effect=exception.NotFound)
        actions = [{'action': 'create', 'index': 'myindex', 'id': 10,
                    'type': 'MyTest', 'data': '{"name": "MyName"}'}]

        self.assertRaises(
            webob.exc.HTTPNotFound, self.search_controller.index,
            request, actions)

    def test_index_duplicate(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.index = mock.Mock(side_effect=exception.Duplicate)
        actions = [{'action': 'create', 'index': 'myindex', 'id': 10,
                    'type': 'MyTest', 'data': '{"name": "MyName"}'}]

        self.assertRaises(
            webob.exc.HTTPConflict, self.search_controller.index,
            request, actions)

    def test_index_exception(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.index = mock.Mock(side_effect=Exception)
        actions = [{'action': 'create', 'index': 'myindex', 'id': 10,
                    'type': 'MyTest', 'data': '{"name": "MyName"}'}]

        self.assertRaises(
            webob.exc.HTTPInternalServerError, self.search_controller.index,
            request, actions)

    def test_plugins_info(self):
        request = unit_test_utils.get_fake_request()
        self.search_controller.plugins_info = mock.Mock(return_value="{}")
        self.search_controller.plugins_info(request)
        self.search_controller.plugins_info.assert_called_once_with(request)

    def test_plugins_info_repo(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.plugins_info = mock.Mock(return_value="{}")
        self.search_controller.plugins_info(request)
        repo.plugins_info.assert_called_once_with()

    def test_plugins_info_forbidden(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.plugins_info = mock.Mock(side_effect=exception.Forbidden)

        self.assertRaises(
            webob.exc.HTTPForbidden, self.search_controller.plugins_info,
            request)

    def test_plugins_info_not_found(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.plugins_info = mock.Mock(side_effect=exception.NotFound)

        self.assertRaises(webob.exc.HTTPNotFound,
                          self.search_controller.plugins_info, request)

    def test_plugins_info_internal_server_error(self):
        request = unit_test_utils.get_fake_request()
        repo = searchlight.elasticsearch.CatalogSearchRepo
        repo.plugins_info = mock.Mock(side_effect=Exception)

        self.assertRaises(webob.exc.HTTPInternalServerError,
                          self.search_controller.plugins_info, request)

class TestSearchDeserializer(test_utils.BaseTestCase):

    def setUp(self):
        super(TestSearchDeserializer, self).setUp()
        self.deserializer = search.RequestDeserializer(
            utils.get_search_plugins()
        )

    def test_single_index(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': 'glance',
        })

        output = self.deserializer.search(request)
        self.assertEqual(['glance'], output['index'])

    def test_single_doc_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'type': 'image',
        })

        output = self.deserializer.search(request)
        self.assertEqual(['image'], output['doc_type'])

    def test_empty_request(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({})

        output = self.deserializer.search(request)
        self.assertEqual(['glance'], output['index'])
        self.assertEqual(sorted(['image', 'metadef']),
                         sorted(output['doc_type']))

    def test_empty_request_admin(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({})
        request.context.is_admin = True

        output = self.deserializer.search(request)
        self.assertEqual(['glance'], output['index'])
        self.assertEqual(sorted(['image', 'metadef']),
                         sorted(output['doc_type']))

    def test_invalid_index(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': 'invalid',
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_invalid_doc_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'type': 'invalid',
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_forbidden_schema(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'schema': {},
        })

        self.assertRaises(webob.exc.HTTPForbidden, self.deserializer.search,
                          request)

    def test_forbidden_self(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'self': {},
        })

        self.assertRaises(webob.exc.HTTPForbidden, self.deserializer.search,
                          request)

    def test_fields_restriction(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': ['glance'],
            'type': ['metadef'],
            'query': {'match_all': {}},
            'fields': ['description'],
        })

        output = self.deserializer.search(request)
        self.assertEqual(['glance'], output['index'])
        self.assertEqual(['metadef'], output['doc_type'])
        self.assertEqual(['description'], output['fields'])

    def test_highlight_fields(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': ['glance'],
            'type': ['metadef'],
            'query': {'match_all': {}},
            'highlight': {'fields': {'name': {}}}
        })

        output = self.deserializer.search(request)
        self.assertEqual(['glance'], output['index'])
        self.assertEqual(['metadef'], output['doc_type'])
        self.assertEqual({'name': {}}, output['query']['highlight']['fields'])

    def test_invalid_limit(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': ['glance'],
            'type': ['metadef'],
            'query': {'match_all': {}},
            'limit': 'invalid',
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.search,
                          request)

    def test_negative_limit(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': ['glance'],
            'type': ['metadef'],
            'query': {'match_all': {}},
            'limit': -1,
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.search,
                          request)

    def test_invalid_offset(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': ['glance'],
            'type': ['metadef'],
            'query': {'match_all': {}},
            'offset': 'invalid',
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.search,
                          request)

    def test_negative_offset(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': ['glance'],
            'type': ['metadef'],
            'query': {'match_all': {}},
            'offset': -1,
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.search,
                          request)

    def test_limit_and_offset(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'index': ['glance'],
            'type': ['metadef'],
            'query': {'match_all': {}},
            'limit': 1,
            'offset': 2,
        })

        output = self.deserializer.search(request)
        self.assertEqual(['glance'], output['index'])
        self.assertEqual(['metadef'], output['doc_type'])
        self.assertEqual(1, output['limit'])
        self.assertEqual(2, output['offset'])

class TestIndexDeserializer(test_utils.BaseTestCase):

    def setUp(self):
        super(TestIndexDeserializer, self).setUp()
        self.deserializer = search.RequestDeserializer(
            utils.get_search_plugins()
        )

    def test_empty_request(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({})

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_empty_actions(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'default_index': 'glance',
            'default_type': 'image',
            'actions': [],
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_missing_actions(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'default_index': 'glance',
            'default_type': 'image',
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_invalid_operation_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('invalid', '1')]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_invalid_default_index(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'default_index': 'invalid',
            'actions': [_image_fixture('create', '1')]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_invalid_default_doc_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'default_type': 'invalid',
            'actions': [_image_fixture('create', '1')]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_empty_operation_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('', '1')]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_missing_operation_type(self):
        action = _image_fixture('', '1')
        action.pop('action')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': 'glance',
                '_op_type': 'index',
                '_source': {'disk_format': 'raw', 'name': 'image-1'},
                '_type': 'image'
            }],
            'default_index': None,
            'default_type': None
        }
        self.assertEqual(expected, output)

    def test_create_single(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('create', '1')]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': 'glance',
                '_op_type': 'create',
                '_source': {'disk_format': 'raw', 'name': 'image-1'},
                '_type': 'image'
            }],
            'default_index': None,
            'default_type': None
        }
        self.assertEqual(expected, output)

    def test_create_multiple(self):
        actions = [
            _image_fixture('create', '1'),
            _image_fixture('create', '2', data={'name': 'image-2'}),
        ]

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': actions,
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [
                {
                    '_id': '1',
                    '_index': 'glance',
                    '_op_type': 'create',
                    '_source': {'disk_format': 'raw', 'name': 'image-1'},
                    '_type': 'image'
                },
                {
                    '_id': '2',
                    '_index': 'glance',
                    '_op_type': 'create',
                    '_source': {'disk_format': 'raw', 'name': 'image-2'},
                    '_type': 'image'
                },
            ],
            'default_index': None,
            'default_type': None
        }
        self.assertEqual(expected, output)

    def test_create_missing_data(self):
        action = _image_fixture('create', '1')
        action.pop('data')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_create_with_default_index(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'default_index': 'glance',
            'actions': [_image_fixture('create', '1', index=None)]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': None,
                '_op_type': 'create',
                '_source': {'disk_format': 'raw', 'name': 'image-1'},
                '_type': 'image'
            }],
            'default_index': 'glance',
            'default_type': None
        }
        self.assertEqual(expected, output)

    def test_create_with_default_doc_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'default_type': 'image',
            'actions': [_image_fixture('create', '1', doc_type=None)]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': 'glance',
                '_op_type': 'create',
                '_source': {'disk_format': 'raw', 'name': 'image-1'},
                '_type': None
            }],
            'default_index': None,
            'default_type': 'image'
        }
        self.assertEqual(expected, output)

    def test_create_with_default_index_and_doc_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'default_index': 'glance',
            'default_type': 'image',
            'actions': [_image_fixture('create', '1', index=None,
                                       doc_type=None)]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': None,
                '_op_type': 'create',
                '_source': {'disk_format': 'raw', 'name': 'image-1'},
                '_type': None
            }],
            'default_index': 'glance',
            'default_type': 'image'
        }
        self.assertEqual(expected, output)

    def test_create_missing_id(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('create')]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': None,
                '_index': 'glance',
                '_op_type': 'create',
                '_source': {'disk_format': 'raw', 'name': 'image-1'},
                '_type': 'image'
            }],
            'default_index': None,
            'default_type': None,
        }
        self.assertEqual(expected, output)

    def test_create_empty_id(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('create', '')]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '',
                '_index': 'glance',
                '_op_type': 'create',
                '_source': {'disk_format': 'raw', 'name': 'image-1'},
                '_type': 'image'
            }],
            'default_index': None,
            'default_type': None
        }
        self.assertEqual(expected, output)

    def test_create_invalid_index(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('create', index='invalid')]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_create_invalid_doc_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('create', doc_type='invalid')]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_create_missing_index(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('create', '1', index=None)]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_create_missing_doc_type(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('create', '1', doc_type=None)]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_update_missing_id(self):
        action = _image_fixture('update')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_update_missing_data(self):
        action = _image_fixture('update', '1')
        action.pop('data')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_update_using_data(self):
        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [_image_fixture('update', '1')]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': 'glance',
                '_op_type': 'update',
                '_type': 'image',
                'doc': {'disk_format': 'raw', 'name': 'image-1'}
            }],
            'default_index': None,
            'default_type': None
        }
        self.assertEqual(expected, output)

    def test_update_using_script(self):
        action = _image_fixture('update', '1', script='<sample script>')
        action.pop('data')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': 'glance',
                '_op_type': 'update',
                '_type': 'image',
                'params': {},
                'script': '<sample script>'
            }],
            'default_index': None,
            'default_type': None,
        }
        self.assertEqual(expected, output)

    def test_update_using_script_and_data(self):
        action = _image_fixture('update', '1', script='<sample script>')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': 'glance',
                '_op_type': 'update',
                '_type': 'image',
                'params': {'disk_format': 'raw', 'name': 'image-1'},
                'script': '<sample script>'
            }],
            'default_index': None,
            'default_type': None,
        }
        self.assertEqual(expected, output)

    def test_delete_missing_id(self):
        action = _image_fixture('delete')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        self.assertRaises(webob.exc.HTTPBadRequest, self.deserializer.index,
                          request)

    def test_delete_single(self):
        action = _image_fixture('delete', '1')
        action.pop('data')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action]
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [{
                '_id': '1',
                '_index': 'glance',
                '_op_type': 'delete',
                '_source': {},
                '_type': 'image'
            }],
            'default_index': None,
            'default_type': None
        }
        self.assertEqual(expected, output)

    def test_delete_multiple(self):
        action_1 = _image_fixture('delete', '1')
        action_1.pop('data')
        action_2 = _image_fixture('delete', '2')
        action_2.pop('data')

        request = unit_test_utils.get_fake_request()
        request.body = jsonutils.dumps({
            'actions': [action_1, action_2],
        })

        output = self.deserializer.index(request)
        expected = {
            'actions': [
                {
                    '_id': '1',
                    '_index': 'glance',
                    '_op_type': 'delete',
                    '_source': {},
                    '_type': 'image'
                },
                {
                    '_id': '2',
                    '_index': 'glance',
                    '_op_type': 'delete',
                    '_source': {},
                    '_type': 'image'
                },
            ],
            'default_index': None,
            'default_type': None
        }
        self.assertEqual(expected, output)

class TestResponseSerializer(test_utils.BaseTestCase):

    def setUp(self):
        super(TestResponseSerializer, self).setUp()
        self.serializer = search.ResponseSerializer()

    def test_plugins_info(self):
        expected = {
            "plugins": [
                {
                    "index": "glance",
                    "type": "image"
                },
                {
                    "index": "glance",
                    "type": "metadef"
                }
            ]
        }

        request = webob.Request.blank('/v0.1/search')
        response = webob.Response(request=request)
        result = {
            "plugins": [
                {
                    "index": "glance",
                    "type": "image"
                },
                {
                    "index": "glance",
                    "type": "metadef"
                }
            ]
        }
        self.serializer.search(response, result)
        actual = jsonutils.loads(response.body)
        self.assertEqual(expected, actual)
        self.assertEqual('application/json', response.content_type)

    def test_search(self):
        expected = [{
            'id': '1',
            'name': 'image-1',
            'disk_format': 'raw',
        }]

        request = webob.Request.blank('/v0.1/search')
        response = webob.Response(request=request)
        result = [{
            'id': '1',
            'name': 'image-1',
            'disk_format': 'raw',
        }]
        self.serializer.search(response, result)
        actual = jsonutils.loads(response.body)
        self.assertEqual(expected, actual)
        self.assertEqual('application/json', response.content_type)

    def test_index(self):
        expected = {
            'success': '1',
            'failed': '0',
            'errors': [],
        }

        request = webob.Request.blank('/v0.1/index')
        response = webob.Response(request=request)
        result = {
            'success': '1',
            'failed': '0',
            'errors': [],
        }
        self.serializer.index(response, result)
        actual = jsonutils.loads(response.body)
        self.assertEqual(expected, actual)
        self.assertEqual('application/json', response.content_type)


text:
<?php

namespace App\Controllers;

use App\Model\User;
use Slim\Http\Request;
use Slim\Http\Response;

class DefaultController extends Controller{

    /**
     * Rend la page par defaut
     * @param Request $request
     * @param Response $response
     */
    public function index(Request $request, Response $response){
        $this->render($response, "default/index.twig");
    }
}


text:
using System;
using System.IO;
using GroupDocs.Conversion.Options.Convert;

namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage
{
    /// <summary>
    /// This example demonstrates how to convert VDX file into PPTX format.
    /// For more details about Microsoft Visio XML Drawing File Format (.vdx) to PowerPoint Open XML Presentation (.pptx) conversion please check this documentation article
    /// https://docs.groupdocs.com/conversion/net/convert-vdx-to-pptx
    /// </summary>
    internal static class ConvertVdxToPptx
    {
        public static void Run()
        {
            string outputFolder = Constants.GetOutputDirectoryPath();
            string outputFile = Path.Combine(outputFolder, "vdx-converted-to.pptx");

            // Load the source VDX file
            using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_VDX))
            {
                var options = new PresentationConvertOptions();
                // Save converted PPTX file
                converter.Convert(outputFile, options);
            }

            Console.WriteLine("\nConversion to pptx completed successfully. \nCheck output in {0}", outputFolder);
        }
    }
}


text:
package midmod.pal;

import midmod.rules.Environment;
import midmod.rules.RuleMap;
import midmod.rules.actions.Action;
import midmod.rules.actions.Call;
import midmod.rules.actions.Constant;
import midmod.rules.actions.LoadAsConstant;
import midmod.rules.patterns.Pattern;
import midmod.rules.patterns.Patterns;

import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;

public class MetaEnvironment {
    private MetaEnvironment outer;
    private Map<String, Integer> nameToCaptureAddressMap = new Hashtable<>();
    //private Set<String> nameToCaptureAddressMapClosed = new HashSet<>(); // The captures to bind as rules to the rule map
    private Map<String, Integer> nameToCaptureAddressMapClosed = new Hashtable<>();
    // requiresContext relates to MetaEnvironments that maps to RuleMaps
    private boolean requiresContext; // Should a special context rule be bind to the creation rule map?

    public MetaEnvironment(MetaEnvironment outer) {
        this.outer = outer;
    }

    private Action createActionForInner(MetaEnvironment target, MetaEnvironment current, String name, int distance) {
        Integer index = nameToCaptureAddressMap.get(name);
        if(index != null) {
            //target.nameToDistanceMap.put(name, distance);
            //current.requiresContext = true;
            //nameToCaptureAddressMapClosed.add(name);
            current.nameToCaptureAddressMapClosed.put(name, index);
            // This action could probably be built by composing multiple Call actions
            return new Action() {
                @Override
                public Object perform(RuleMap ruleMap, RuleMap local, Environment captures) {
                    RuleMap context = ruleMap;
                    for(int i = distance; i > 0; i--) {
                        context = (RuleMap) Call.onLocal(context, local, "context");
                    }
                    Object value = Call.onLocal(context, local, name);
                    return value;
                }

                @Override
                public Object toValue() {
                    return Arrays.asList("access", index);
                }
            };
        } else {
            if(outer != null) {
                //requiresContext = true;
                return outer.createActionForInner(target, this, name, distance + 1);
            }

            throw new UnsupportedOperationException("Name " + name + " not declared.");
        }
    }

    /*public Set<String> getNameToCaptureAddressMapClosed() {
        return nameToCaptureAddressMapClosed;
    }*/

    public boolean requiresContext() {
        return requiresContext;
    }

    public Action createActionFor(String name) {
        Integer index = nameToCaptureAddressMap.get(name);
        if(index != null) {
            return new Action() {
                @Override
                public Object perform(RuleMap ruleMap, RuleMap local, Environment captures) {
                    Object val = captures.get(index);
                    return val;
                }

                @Override
                public Object toValue() {
                    return Arrays.asList("access", index);
                }
            };
        }
        if(outer != null) {
            return outer.createActionForInner(this, this, name, 0);
        }

        throw new UnsupportedOperationException("Name " + name + " not declared.");
    }

    public int size() {
        return nameToCaptureAddressMap.size();
    }

    public void put(String name, int index) {
        nameToCaptureAddressMap.put(name, index);
    }

    public int getIndexFor(String name) {
        return nameToCaptureAddressMap.get(name);
    }

    public void setupRuleMap(RuleMap context, RuleMap newRuleMap, Environment captures) {
        //if(requiresContext)
        //    newRuleMap.define(Patterns.equalsObject("context"), new Constant(context));

        nameToCaptureAddressMapClosed.entrySet().forEach(x -> {
            String name = x.getKey();
            int index = x.getValue();
            newRuleMap.define(Patterns.equalsObject(name), new Constant(captures.get(index)));
        });

        /*nameToDistanceMap.entrySet().forEach(x -> {
            String name = x.getKey();
            int distance = x.getValue();
        });*/
    }

    public void addClosedCaptures(Map<Pattern, Action> patternActionMap) {
        nameToCaptureAddressMapClosed.entrySet().forEach(x -> {
            String name = x.getKey();
            int index = x.getValue();
            patternActionMap.put(Patterns.equalsObject(name), new LoadAsConstant(index));
            //newRuleMap.define(Patterns.equalsObject(name), new Constant(captures.get(index)));
        });
    }
}


text:
"use strict";

const path = require("path");
const util = require("util");

const _ = require("lodash");
const async = require("async");
const fs = require("fs-ext");
const log = require("floorine");

var hooks = {};

var Hook = function (base_path, parent) {
  var self = this,
    paths;

  self.parent = parent;
  self.path = base_path;
  self.hook_path = path.join(self.path, "hook.js");
  hooks[self.path] = self;
  // Unused for now, but one day...
  self.children = {};

  log.log(util.format("Loading hooks in %s", self.path));
  /*eslint-disable no-sync */
  paths = fs.readdirSync(self.path);
  /*eslint-enable no-sync */

  self.load();
  _.each(paths, function (p) {
    var stats,
      p_path = path.join(self.path, p);
    /*eslint-disable no-sync */
    stats = fs.lstatSync(p_path);
    /*eslint-enable no-sync */
    if (stats.isDirectory()) {
      self.children[p_path] = new Hook(p_path, self);
    }
  });
  log.log(util.format("Processed hooks in %s", self.path));
};

Hook.prototype.stop = function () {
  var self = this;

  _.each(self.children, function (child, _path) {
    log.log("Stopping %s", _path);
    child.stop();
  });
};

Hook.prototype.load = function () {
  var self = this,
    hook;

  log.log("Loading", self.hook_path);
  try {
    hook = require(self.hook_path);
    if (!_.isFunction(hook)) {
      throw new Error("Not a function: " + hook);
    }
  } catch (e) {
    return log.warn("No hooks found in", self.hook_path, ":", e.toString());
  }
  self.hook = hook;
  log.log("Loaded", self.hook_path);
};

Hook.prototype.handle = function (_path, handle_cb) {
  var self = this;

  if (!self.hook) {
    return handle_cb(util.format("No hook for %s", _path));
  }

  if (_path === self.hook_path) {
    self.load();
    return handle_cb();
  }

  let auto = {
    fd: function (cb) {
      fs.open(_path, "r", cb);
    },
    lock: ["fd", function (cb, res) {
      fs.flock(res.fd, "ex", cb);
    }],
    fstat: ["lock", function (cb, res) {
      fs.fstat(res.fd, cb);
    }],
    read: ["fstat", function (cb, res) {
      let total_bytes_read = 0;
      let size = res.fstat.size;

      let handle_read = function (err, bytes_read, buf) {
        if (err) {
          log.error("Error reading %s: %s", _path, err);
          return cb(err);
        }
        total_bytes_read += bytes_read;
        if (total_bytes_read < size) {
          log.debug(util.format("%s bytes left to read", size - total_bytes_read));
          return fs.read(res.fd, buf, total_bytes_read, size - total_bytes_read, total_bytes_read, handle_read);
        }
        return cb(err, buf);
      };
      handle_read(null, 0, new Buffer(size));
    }],
  };

  async.auto(auto, function (err, result) {
    fs.close(result.fd, function (close_err) {
      if (err || close_err) {
        return handle_cb(err || close_err);
      }
      try {
        let buf = result.read.toString();
        log.debug(_path, "data:", buf);
        let data = JSON.parse(buf);
        return self.hook(_path, data, handle_cb);
      } catch (e) {
        return handle_cb(e);
      }
    });
  });
};

const handle = function (_path, cb) {
  try {
    hooks[path.dirname(_path)].handle(_path, cb);
  } catch (e) {
    cb(e);
  }
};

module.exports = {
  Hook: Hook,
  handle: handle
};


text:
<?php

namespace Tequila\MongoDB\Write\Model;

use Tequila\MongoDB\BulkWrite;
use Tequila\MongoDB\Exception\InvalidArgumentException;
use Tequila\MongoDB\WriteModelInterface;
use function Tequila\MongoDB\ensureValidDocument;

class InsertMany implements WriteModelInterface
{
    /**
     * @var array
     */
    private $documents = [];

    /**
     * @param array $documents
     */
    public function __construct(array $documents)
    {
        foreach ($documents as $position => $document) {
            if (!is_array($document) && !is_object($document)) {
                throw new InvalidArgumentException(
                    sprintf(
                        'Each document must be an array or an object, %s given in $documents[%s].',
                        \Tequila\MongoDB\getType($document),
                        $position
                    )
                );
            }

            try {
                ensureValidDocument($document);
            } catch (InvalidArgumentException $e) {
                throw new InvalidArgumentException(
                    sprintf(
                        'Invalid document at $documents[%s]: %s',
                        $position,
                        $e->getMessage()
                    )
                );
            }
        }

        $this->documents = $documents;
    }

    /**
     * {@inheritdoc}
     */
    public function writeToBulk(BulkWrite $bulk)
    {
        foreach ($this->documents as $document) {
            $bulk->insert($document);
        }
    }
}


text:
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

import pytest
from typepy import RealNumber

from pingparsing import PingTransmitter
from pingparsing._parser import IcmpReplyKey

from .common import ping_parser  # noqa: W0611

@pytest.fixture
def transmitter():
    return PingTransmitter()

class Test_PingTransmitter_ping:
    @pytest.mark.xfail(run=False)
    @pytest.mark.parametrize(["host"], [["localhost"], ["127.0.0.1"], ["::1"]])
    def test_normal_dest(self, transmitter, host):
        transmitter.destination = host
        result = transmitter.ping()

        assert result.returncode == 0
        assert len(result.stdout) > 0

    @pytest.mark.xfail(run=False)
    @pytest.mark.parametrize(["host", "deadline"], [["localhost", 1]])
    def test_normal_deadline(self, transmitter, host, deadline):
        transmitter.destination = host
        transmitter.deadline = deadline
        result = transmitter.ping()

        assert result.returncode == 0
        assert len(result.stdout) > 0

    @pytest.mark.xfail(run=False)
    @pytest.mark.parametrize(["host", "timeout"], [["localhost", 1]])
    def test_normal_timeout(self, transmitter, host, timeout):
        transmitter.destination = host
        transmitter.timeout = timeout
        result = transmitter.ping()

        assert result.returncode == 0
        assert len(result.stdout) > 0

    @pytest.mark.xfail(run=False)
    @pytest.mark.parametrize(
        ["host", "count", "deadline"], [["localhost", 1, None], ["localhost", 1, 1000]]
    )
    def test_normal_count(self, transmitter, host, count, deadline):
        transmitter.destination = host
        transmitter.deadline = deadline
        transmitter.count = count
        result = transmitter.ping()

        assert result.returncode == 0
        assert len(result.stdout) > 0

    @pytest.mark.xfail(run=False)
    @pytest.mark.parametrize(["host", "count"], [["localhost", 3]])
    def test_normal_send_parse(self, transmitter, ping_parser, host, count):
        transmitter.destination = host
        transmitter.count = count
        result = transmitter.ping()

        stats = ping_parser.parse(result.stdout)

        assert stats.packet_transmit >= count
        assert RealNumber(stats.packet_receive).is_type()
        assert RealNumber(stats.packet_loss_rate).is_type()
        assert RealNumber(stats.packet_loss_count).is_type()
        assert RealNumber(stats.packet_duplicate_rate).is_type()
        assert RealNumber(stats.packet_duplicate_count).is_type()
        assert RealNumber(stats.rtt_min).is_type()
        assert RealNumber(stats.rtt_avg).is_type()
        assert RealNumber(stats.rtt_max).is_type()
        assert RealNumber(stats.rtt_mdev).is_type()
        assert IcmpReplyKey.TIMESTAMP not in stats.icmp_replies[0]

    @pytest.mark.xfail(run=False)
    @pytest.mark.parametrize(["host", "count"], [["localhost", 3]])
    def test_normal_send_parse_timestamp(self, transmitter, ping_parser, host, count):
        transmitter.destination = host
        transmitter.count = count
        transmitter.timestamp = True
        result = transmitter.ping()

        stats = ping_parser.parse(result.stdout)

        assert stats.packet_transmit >= count
        assert RealNumber(stats.packet_receive).is_type()
        assert RealNumber(stats.packet_loss_rate).is_type()
        assert RealNumber(stats.packet_loss_count).is_type()
        assert RealNumber(stats.packet_duplicate_rate).is_type()
        assert RealNumber(stats.packet_duplicate_count).is_type()
        assert RealNumber(stats.rtt_min).is_type()
        assert RealNumber(stats.rtt_avg).is_type()
        assert RealNumber(stats.rtt_max).is_type()
        assert RealNumber(stats.rtt_mdev).is_type()
        assert IcmpReplyKey.TIMESTAMP in stats.icmp_replies[0]

    @pytest.mark.parametrize(
        ["dest", "expected"], [["", ValueError], [None, ValueError], [1, ValueError]]
    )
    def test_except_destination(self, transmitter, dest, expected):
        with pytest.raises(expected):
            transmitter.destination = dest

    @pytest.mark.parametrize(
        ["host", "deadline", "expected"],
        [
            ["localhost", 0, ValueError],
            ["localhost", -1, ValueError],
            ["localhost", "a", ValueError],
        ],
    )
    def test_except_deadline(self, transmitter, host, deadline, expected):
        transmitter.destination = host

        with pytest.raises(expected):
            transmitter.deadline = deadline
            transmitter.ping()

    @pytest.mark.parametrize(
        ["host", "timeout", "expected"],
        [
            ["localhost", 0, ValueError],
            ["localhost", -1, ValueError],
            ["localhost", "a", ValueError],
        ],
    )
    def test_except_timeout(self, transmitter, host, timeout, expected):
        transmitter.destination = host

        with pytest.raises(expected):
            transmitter.timeout = timeout
            transmitter.ping()

    @pytest.mark.parametrize(
        ["host", "count", "expected"],
        [
            ["localhost", 0, ValueError],
            ["localhost", -1, ValueError],
            ["localhost", "a", ValueError],
        ],
    )
    def test_except_count(self, transmitter, host, count, expected):
        transmitter.destination = host
        transmitter.count = count
        with pytest.raises(expected):
            transmitter.ping()


text:
namespace CoursesAPI.Services.Models.Entities
{
	/// <summary>
	/// An entity class for a course instance.
	/// </summary>
	public class Course
	{
		/// <summary>
		/// A database-generated ID of the course.
		/// </summary>
		public int    ID          { get; set; }

		/// <summary>
		/// The human-readable ID of a course. Example: "T-514-VEFT"
		/// </summary>
		public string CourseID    { get; set; }

		/// <summary>
		/// The name of the course, in Icelandic.
		/// </summary>
		public string Name        { get; set; }

		/// <summary>
		/// A description of the course.
		/// </summary>
		public string Description { get; set; }
	}
}


text:
<?php

namespace Application\Sonata\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseUser as BaseUser;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

use Gedmo\Mapping\Annotation as Gedmo;
use JMS\Serializer\Annotation\ExclusionPolicy;

/**
 * User
 *
 * @ORM\Table(name="fos_user_user")
 * @ORM\Entity(repositoryClass="Application\Sonata\UserBundle\Repository\UserRepository")
 */
class User extends BaseUser
{

    /**
     * Available properties
     *
     * FOS properties
     *
     * protected $id;
     * protected $username;
     * protected $usernameCanonical;
     * protected $email;
     * protected $emailCanonical;
     * protected $enabled;
     * protected $salt;
     * protected $password;
     * protected $plainPassword;
     * protected $lastLogin;
     * protected $confirmationToken;
     * protected $passwordRequestedAt;
     * protected $groups;
     * protected $locked;
     * protected $expired;
     * protected $expiresAt;
     * protected $roles;
     * protected $credentialsExpired;
     * protected $credentialsExpireAt;
     *
     * Sonata properties
     *
     * protected $createdAt;
     * protected $updatedAt;
     * protected $twoStepVerificationCode;
     * protected $dateOfBirth;
     * protected $firstname;
     * protected $lastname;
     * protected $website;
     * protected $biography;
     * protected $gender; // set the default to unknown
     * protected $locale;
     * protected $timezone;
     * protected $phone;
     * protected $facebookUid;
     * protected $facebookName;
     * protected $facebookData;
     * protected $twitterUid;
     * protected $twitterName;
     * protected $twitterData;
     * protected $gplusUid;
     * protected $gplusName;
     * protected $gplusData;
     * protected $token;
     */

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Many Users have Many Groups.
     * @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\Group", inversedBy="users")
     * @ORM\JoinTable(name="fos_user_user_group")
     */
    protected $groups;

    /**
     * @var string
     * @ORM\Column(name="youtube_uid", type="string", nullable=true)
     */
    protected $youtubeUid;

    /**
     * @var string
     * @ORM\Column(name="youtube_name", type="string", nullable=true)
     */
    protected $youtubeName;

    /**
     * @var array
     * @ORM\Column(name="youtube_data", type="string", nullable=true)
     */
    protected $youtubeData;

    /**
     * @var string
     * @ORM\Column(name="linkedin_uid", type="string", nullable=true)
     */
    protected $linkedinUid;

    /**
     * @var string
     * @ORM\Column(name="linkedin_name", type="string", nullable=true)
     */
    protected $linkedinName;

    /**
     * @var array
     * @ORM\Column(name="linkedin_data", type="string", nullable=true)
     */
    protected $linkedinData;

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

    /**
     * Set youtubeUid
     *
     * @param string $youtubeUid
     * @return User
     */
    public function setYoutubeUid($youtubeUid)
    {
        $this->youtubeUid = $youtubeUid;

        return $this;
    }

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

    /**
     * Set youtubeName
     *
     * @param string $youtubeName
     * @return User
     */
    public function setYoutubeName($youtubeName)
    {
        $this->youtubeName = $youtubeName;

        return $this;
    }

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

    /**
     * Set youtubeData
     *
     * @param string $youtubeData
     * @return User
     */
    public function setYoutubeData($youtubeData)
    {
        $this->youtubeData = $youtubeData;

        return $this;
    }

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

    /**
     * Set linkedinUid
     *
     * @param string $linkedinUid
     * @return User
     */
    public function setLinkedinUid($linkedinUid)
    {
        $this->linkedinUid = $linkedinUid;

        return $this;
    }

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

    /**
     * Set linkedinName
     *
     * @param string $linkedinName
     * @return User
     */
    public function setLinkedinName($linkedinName)
    {
        $this->linkedinName = $linkedinName;

        return $this;
    }

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

    /**
     * Set linkedinData
     *
     * @param string $linkedinData
     * @return User
     */
    public function setLinkedinData($linkedinData)
    {
        $this->linkedinData = $linkedinData;

        return $this;
    }

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


text:
using System;

using Ninject.Extensions.Interception;

namespace Parser.ConsoleClient.FileReaderImplementations
{
    public class LogFilePathDiscoveryStrategyTestingInterceptor : IInterceptor
    {
        private const string MorninWoodDummyParse = @"../../../../../SampleLogs/combat_2017-02-22_22_30_37_978667.txt";
        private const string DrBurnzLiveHealing = @"../../../../../SampleLogs/combat_2017-03-12_21_40_23_745220.txt";
        private const string SampleParse = @"../../../../../SampleLogs/sample.txt";

        public void Intercept(IInvocation invocation)
        {
            try
            {
                // Invoking method for debugging.
                invocation.Proceed();
            }
            catch (Exception)
            {

            }

            // Returning sample data for controlled input.
            invocation.ReturnValue = LogFilePathDiscoveryStrategyTestingInterceptor.DrBurnzLiveHealing;
        }
    }
}


text:
package common

const (
	// Consul dedicated constants

	// OperationalPath is the base path to store the operational details in the kvstore.
	OperationalPath = "cilium-net/operational"

	// ServicesKeyPath is the base path where services are stored in the kvstore.
	ServicesKeyPath = OperationalPath + "/ServicesV2/SHA256SUMServices"
	// ServicePathV1 is the base path for the services stored in the kvstore.
	ServicePathV1 = OperationalPath + "/Services/"

	// Miscellaneous dedicated constants

	// NodeConfigFile is the name of the C header which contains the node's
	// network parameters.
	NodeConfigFile = "node_config.h"
	// CHeaderFileName is the name of the C header file for BPF programs for a
	// particular endpoint.
	CHeaderFileName = "ep_config.h"
	// OldCHeaderFileName is the previous name of the C header file for BPF
	// programs for a particular endpoint. It can be removed once Cilium v1.8
	// is the oldest supported version.
	OldCHeaderFileName = "lxc_config.h"
	// NetdevHeaderFileName is the name of the header file used for bpf_host.c and bpf_overlay.c.
	NetdevHeaderFileName = "netdev_config.h"
	// PreFilterHeaderFileName is the name of the header file used for bpf_xdp.c.
	PreFilterHeaderFileName = "filter_config.h"
	// HostObjFileName is the name of the host object file.
	HostObjFileName = "bpf_host.o"
	// CiliumCHeaderPrefix is the prefix using when printing/writing an endpoint in a
	// base64 form.
	CiliumCHeaderPrefix = "CILIUM_BASE64_"

	// PossibleCPUSysfsPath is used to retrieve the number of CPUs for per-CPU maps.
	PossibleCPUSysfsPath = "/sys/devices/system/cpu/possible"
)


text:
package com.xfggh.blog.req;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

public class UserSaveReq {
    private Long id;

    @NotNull(message = "【用户名】不能为空")
    private String loginName;

    @NotNull(message = "【昵称】不能为空")
    private String username;

    @NotNull(message = "【密码】不能为空")
    // @Length(min = 6, max = 20, message = "【密码】6~20位")
    @Pattern(regexp = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$", message = "【密码】至少包含 数字和英文,长度6-20")
    private String password;

    public Long getId() {
        return id;
    }

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

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", loginName=").append(loginName);
        sb.append(", username=").append(username);
        sb.append(", password=").append(password);
        sb.append("]");
        return sb.toString();
    }
}


text:
layout: post
unique_id: bachata_in_vegas
title: Bachata in Vegas
categories: []
locations:
---

YESTERDAY:
* woke up early
* head to tech rehearsal
* head to a food court for lunch
  * trusty panda express!
* back to hotel for a quick nap
  * finished the other book
* went to a bachata workshop
  * pretty informative!
* head to put on make-up
  * Jackie even styled my hair!
  * get into outfits
* head down for call time
  * found out we are #3 performance of the afternoon!
* went super well I think?
* lots of pictures afterwards
* head to Gordon Ramsay's Burgers for dinner afterwards
  * enjoyed some tator tots
* watch some shows
* second party at teacher's suite

TODAY:
* head to Wicked Spoon with Nikolaus
* two workshops
  * sensual bachata workshop
  * Jen's workshop
* check out a pool party
  * got to sit in a cabana for the ... first time?
* took a nap
* Jackie and I went to have dinner at Eataly
  * surprisingly tasty ribeye steak (little pricy)
  * Jackie liked the cantalope sorbet ... I thought it was ok
* team meeting with Hector
* social dancing

LEARNINGS:
* gym is only open 8 am to 5 pm each day :(


text:
layout: page
title: Rios Technologies Party
date: 2016-05-24
author: Paul Meyers
tags: weekly links, java
status: published
summary: Mauris id magna erat. Nulla facilisi. Morbi.
banner: images/banner/people.jpg
booking:
  startDate: 09/10/2016
  endDate: 09/11/2016
  ctyhocn: COTBAHX
  groupCode: RTP
published: true
---
Duis elementum sit amet purus nec volutpat. Aliquam nisl mauris, dapibus viverra leo non, varius rhoncus turpis. Nunc tincidunt in orci ac sollicitudin. Cras ornare sed libero nec molestie. Morbi eu eros molestie, pulvinar velit ut, mattis ligula. Vestibulum bibendum euismod porttitor. Vestibulum augue ex, luctus quis eros id, bibendum mattis purus. Nam vel mi ut nibh semper venenatis et sit amet tortor. Integer porttitor tempus dolor eu commodo. Sed tempus, mauris sit amet commodo feugiat, justo purus rutrum eros, euismod sollicitudin eros orci in augue. Aliquam dui felis, maximus et nulla sit amet, lacinia imperdiet libero. Proin quis gravida urna. Etiam hendrerit, ante nec iaculis fermentum, enim leo facilisis nisl, vitae egestas risus urna non ligula. Aliquam at nibh mollis, pellentesque sem nec, venenatis est. Donec pellentesque cursus posuere.

* Vivamus ac dui nec odio elementum convallis vitae id dui
* Nullam quis ante at ipsum dictum lobortis in et justo
* Aliquam feugiat ligula faucibus, eleifend ipsum vitae, elementum quam
* Duis nec dolor in lectus auctor varius at in eros.

Vivamus finibus sed nisi at pretium. Ut malesuada tellus nec nisi rutrum aliquet. Sed convallis sapien commodo ante facilisis ullamcorper. Sed gravida dignissim eleifend. Vivamus varius libero ac iaculis suscipit. Nam et enim arcu. Vestibulum et nulla commodo, tincidunt augue sit amet, placerat libero. In finibus turpis non quam sollicitudin, ut aliquet lorem dignissim.


text:
import { isTouch } from './window';

export const events = {
  mouseover: 'mouseover',
  mouseout: 'mouseout',
  mousedown: 'mousedown',
  mouseup: 'mouseup',
  mousemove: 'mousemove',
  click: 'click',
  transitionend: 'transitionend',
  animationstart: 'animationstart',
  animationiteration: 'animationiteration',
  animationend: 'animationend',
};

if (isTouch) {
  events.mouseover = 'touchstart';
  events.mouseout = 'touchend';
  events.mousedown = 'touchstart';
  events.mouseup = 'touchend';
  events.mousemove = 'touchmove';
  events.click = 'click';
}

const platforms = {
  OTransition: {
    transitionend: 'otransitionend',
    animationstart: 'oanimationstart',
    animationiteration: 'oanimationiteration',
    animationend: 'oanimationend',
  },
  MozTransition: {
    transitionend: 'transitionend',
    animationstart: 'moznimationstart',
    animationiteration: 'moznimationiteration',
    animationend: 'moznimationend',
  },
  WebkitTransition: {
    transitionend: 'webkitTransitionEnd',
    animationstart: 'webkitAnimationStart',
    animationiteration: 'webkitAnimationIteration',
    animationend: 'webkitAnimationEnd',
  },
};

if (typeof window !== 'undefined') {
  window.addEventListener('load', function () {
    for (const i in platforms) {
      const data = platforms[i];
      if (document.body.style[i] !== undefined) {
        events.transitionend = data.transitionend;
        events.animationstart = data.animationstart;
        events.animationiteration = data.animationiteration;
        events.animationend = data.animationend;
      }
    }
  });
}

export function createCustomEvent(type, params) {
  let event;
  try {
    event = new CustomEvent(event, params);
  } catch (e) {
    event = document.createEvent('CustomEvent');
    event.initCustomEvent(type, params.bubbles, params.bubbles, params.detail);
  }
  return event;
}

export default class BaseEvent extends Event {
  constructor(type, data, eventInit) {
    super(type, eventInit);
    this.data = data;
  }
}


text:
import mraa
import sys
import time
import socket
import fcntl
import struct

buttonState = 0
buttonPin = 2

while 1:
	time.sleep(.5)
	button = mraa.Gpio(buttonPin)
	button.dir(mraa.DIR_IN)
	buttonState = button.read()
	print buttonState


text:
namespace Framework.Ioc
{
    using System;

    /// <summary>
    /// Used to define the binding info.
    /// </summary>
    /// <typeparam name="T">The service being bound.</typeparam>
    public interface IBindingInfo<in T> : IBindingInfo
    {
        /// <summary>
        /// Indicates that the service should be bound to the specified implementation type.
        /// </summary>
        /// <typeparam name="TImplementation">The implementation type.</typeparam>
        /// <returns><see cref="IBindingInfo{T}"/> object.</returns>
        IBindingInfo<T> To<TImplementation>() where TImplementation : T;

        /// <summary>
        /// Indicates that the service should be bound to the specified implementation type.
        /// </summary>
        /// <returns><see cref="IBindingInfo{T}"/> object.</returns>
        IBindingInfo<T> ToSelf();

        /// <summary>
        /// Indicates that the service should be bound to the specified method.
        /// </summary>
        /// <param name="method">The method to bound.</param>
        /// <returns><see cref="IBindingInfo{T}"/> object.</returns>
        /// <author>Anwar</author>
        /// <date>11/10/2011</date>
        IBindingInfo<T> ToMethod(Func<T> method);

        /// <summary>
        /// Indicates that instances activated via the binding should not be re-used.
        /// </summary>
        /// <returns><see cref="IBindingInfo{T}"/> object.</returns>
        IBindingInfo<T> InTransientScope();

        /// <summary>
        /// Indicates that only a single instance of the binding should be created, and then
        /// should be re-used for all subsequent requests.
        /// </summary>
        /// <returns><see cref="IBindingInfo{T}"/> object.</returns>
        IBindingInfo<T> InSingletonScope();

        /// <summary>
        /// Indicates that instances activated via the binding should be re-used within the same thread.
        /// </summary>
        /// <returns><see cref="IBindingInfo{T}"/> object.</returns>
        IBindingInfo<T> InThreadScope();

        /// -------------------------------------------------------------------------------------------------
        /// <summary>
        /// Indicates that instances activated via the binding should be re-used within the same HTTP
        /// request.
        /// </summary>
        /// <returns>
        /// Binding Info as<see cref="BindingInfo{T}"/>.
        /// </returns>
        /// -------------------------------------------------------------------------------------------------
        IBindingInfo<T> InRequestScope();

        /// -------------------------------------------------------------------------------------------------
        /// <summary>
        /// Indicates that instances activated via the binding should be re-used within the same HTTP
        /// Session.
        /// </summary>
        /// <returns>
        /// Binding Info as<see cref="BindingInfo{T}"/>.
        /// </returns>
        /// -------------------------------------------------------------------------------------------------
        IBindingInfo<T> InSessionScope();
    }
}


text:
list(APPEND WTF_SOURCES
    gobject/GlibUtilities.cpp
    gobject/GOwnPtr.cpp
    gobject/GRefPtr.cpp

    gtk/MainThreadGtk.cpp
)

list(APPEND WTF_LIBRARIES
    pthread
    ${GLIB_LIBRARIES}
    ${GLIB_GIO_LIBRARIES}
    ${GLIB_GOBJECT_LIBRARIES}
)

list(APPEND WTF_INCLUDE_DIRECTORIES
    ${GLIB_INCLUDE_DIRS}
)


text:
cask "radicle-upstream" do
  version "0.2.0"
  sha256 "1fe96cb80dd5d6aae3ffe521cfa245641b5f86aff3ed81361e56f6d8db4a48e3"

  url "https://releases.radicle.xyz/radicle-upstream-#{version}.dmg"
  name "Radicle Upstream"
  desc "Desktop client for Radicle, a p2p stack for code collaboration"
  homepage "https://radicle.xyz/"

  livecheck do
    url "https://github.com/radicle-dev/radicle-upstream"
    strategy :git
  end

  depends_on macos: ">= :mojave"

  app "Radicle Upstream.app"

  zap trash: [
    "~/.radicle",
    "~/Library/Application Support/Radicle Upstream",
    "~/Library/Application Support/xyz.radicle.radicle",
    "~/Library/Application Support/xyz.radicle.radicle-upstream",
    "~/Library/Preferences/xyz.radicle.radicle-upstream.plist",
    "~/Library/Saved Application State/xyz.radicle.radicle-upstream.savedState",
  ]
end


text:
using System.Text;
namespace DynamicSPARQLSpace
{
    public interface IWhereItem
    {
        WhreItemType ItemType { get; }
        StringBuilder AppendToString(StringBuilder sb,
            bool autoQuotation = false,
            bool skipTriplesWithEmptyObject = false,
            bool mindAsterisk = false);
    }

    public enum WhreItemType
    {
        Triple,
        Optional,
        Group,
        Union,
        Filter,
        Bind,
        Minus,
        Exists,
        NotExists,
        Graph,
        None
    }
}


text:
cask "remotion" do
  version "1.90.1"
  sha256 "8ceabe284036de47b69b2b5aef5555fbf78f579467a4ad31419763dc5919c719"

  url "https://updates.remotion.com/installers/Remotion%20#{version}.dmg"
  name "remotion"
  desc "Communication tool for remote teams"
  homepage "https://www.remotion.com/"

  livecheck do
    url "https://updates.remotion.com/latest"
    strategy :header_match
  end

  app "Remotion.app"

  zap trash: [
    "~/Library/Application Support/Remotion",
    "~/Library/Caches/com.remotion.remotion",
    "~/Library/Preferences/com.remotion.remotion.plist",
  ]
end


text:
#pragma once
#include <aws/health/Health_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/health/model/EventTypeCategory.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Health
{
namespace Model
{

  /**
   *
The values to use to filter results from the DescribeEventTypes
   * operation.

See Also:
   AWS
   * API Reference

   */
  class AWS_HEALTH_API EventTypeFilter
  {
  public:
    EventTypeFilter();
    EventTypeFilter(Aws::Utils::Json::JsonView jsonValue);
    EventTypeFilter& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
A list of event type codes.

     */
    inline const Aws::Vector<Aws::String>& GetEventTypeCodes() const{ return m_eventTypeCodes; }

    /**
     *
A list of event type codes.

     */
    inline bool EventTypeCodesHasBeenSet() const { return m_eventTypeCodesHasBeenSet; }

    /**
     *
A list of event type codes.

     */
    inline void SetEventTypeCodes(const Aws::Vector<Aws::String>& value) { m_eventTypeCodesHasBeenSet = true; m_eventTypeCodes = value; }

    /**
     *
A list of event type codes.

     */
    inline void SetEventTypeCodes(Aws::Vector<Aws::String>&& value) { m_eventTypeCodesHasBeenSet = true; m_eventTypeCodes = std::move(value); }

    /**
     *
A list of event type codes.

     */
    inline EventTypeFilter& WithEventTypeCodes(const Aws::Vector<Aws::String>& value) { SetEventTypeCodes(value); return *this;}

    /**
     *
A list of event type codes.

     */
    inline EventTypeFilter& WithEventTypeCodes(Aws::Vector<Aws::String>&& value) { SetEventTypeCodes(std::move(value)); return *this;}

    /**
     *
A list of event type codes.

     */
    inline EventTypeFilter& AddEventTypeCodes(const Aws::String& value) { m_eventTypeCodesHasBeenSet = true; m_eventTypeCodes.push_back(value); return *this; }

    /**
     *
A list of event type codes.

     */
    inline EventTypeFilter& AddEventTypeCodes(Aws::String&& value) { m_eventTypeCodesHasBeenSet = true; m_eventTypeCodes.push_back(std::move(value)); return *this; }

    /**
     *
A list of event type codes.

     */
    inline EventTypeFilter& AddEventTypeCodes(const char* value) { m_eventTypeCodesHasBeenSet = true; m_eventTypeCodes.push_back(value); return *this; }

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline const Aws::Vector<Aws::String>& GetServices() const{ return m_services; }

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline bool ServicesHasBeenSet() const { return m_servicesHasBeenSet; }

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline void SetServices(const Aws::Vector<Aws::String>& value) { m_servicesHasBeenSet = true; m_services = value; }

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline void SetServices(Aws::Vector<Aws::String>&& value) { m_servicesHasBeenSet = true; m_services = std::move(value); }

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline EventTypeFilter& WithServices(const Aws::Vector<Aws::String>& value) { SetServices(value); return *this;}

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline EventTypeFilter& WithServices(Aws::Vector<Aws::String>&& value) { SetServices(std::move(value)); return *this;}

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline EventTypeFilter& AddServices(const Aws::String& value) { m_servicesHasBeenSet = true; m_services.push_back(value); return *this; }

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline EventTypeFilter& AddServices(Aws::String&& value) { m_servicesHasBeenSet = true; m_services.push_back(std::move(value)); return *this; }

    /**
     *
The Amazon Web Services services associated with the event. For example,
     * EC2, RDS.

     */
    inline EventTypeFilter& AddServices(const char* value) { m_servicesHasBeenSet = true; m_services.push_back(value); return *this; }

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline const Aws::Vector<EventTypeCategory>& GetEventTypeCategories() const{ return m_eventTypeCategories; }

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline bool EventTypeCategoriesHasBeenSet() const { return m_eventTypeCategoriesHasBeenSet; }

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline void SetEventTypeCategories(const Aws::Vector<EventTypeCategory>& value) { m_eventTypeCategoriesHasBeenSet = true; m_eventTypeCategories = value; }

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline void SetEventTypeCategories(Aws::Vector<EventTypeCategory>&& value) { m_eventTypeCategoriesHasBeenSet = true; m_eventTypeCategories = std::move(value); }

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline EventTypeFilter& WithEventTypeCategories(const Aws::Vector<EventTypeCategory>& value) { SetEventTypeCategories(value); return *this;}

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline EventTypeFilter& WithEventTypeCategories(Aws::Vector<EventTypeCategory>&& value) { SetEventTypeCategories(std::move(value)); return *this;}

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline EventTypeFilter& AddEventTypeCategories(const EventTypeCategory& value) { m_eventTypeCategoriesHasBeenSet = true; m_eventTypeCategories.push_back(value); return *this; }

    /**
     *
A list of event type category codes. Possible values are issue,
     * accountNotification, or scheduledChange. Currently,
     * the investigation value isn't supported at this time.

     */
    inline EventTypeFilter& AddEventTypeCategories(EventTypeCategory&& value) { m_eventTypeCategoriesHasBeenSet = true; m_eventTypeCategories.push_back(std::move(value)); return *this; }

  private:

    Aws::Vector<Aws::String> m_eventTypeCodes;
    bool m_eventTypeCodesHasBeenSet;

    Aws::Vector<Aws::String> m_services;
    bool m_servicesHasBeenSet;

    Aws::Vector<EventTypeCategory> m_eventTypeCategories;
    bool m_eventTypeCategoriesHasBeenSet;
  };

} // namespace Model
} // namespace Health
} // namespace Aws


text:
package org.systemsbiology.google.visualization.datasource.impls;

import com.google.visualization.datasource.Capabilities;
import com.google.visualization.datasource.DataSourceHelper;
import com.google.visualization.datasource.DataTableGenerator;
import com.google.visualization.datasource.base.DataSourceException;
import com.google.visualization.datasource.datatable.ColumnDescription;
import com.google.visualization.datasource.datatable.DataTable;
import com.google.visualization.datasource.datatable.value.ValueType;
import com.google.visualization.datasource.query.Query;
import com.ibm.icu.util.ULocale;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author hrovira
 */
public abstract class AbstractDataTableGenerator implements DataTableGenerator {
    private static final Logger log = Logger.getLogger(AbstractDataTableGenerator.class.getName());

    private final InputStream inputStream;
    private final ArrayList<ColumnDescription> columnDescriptions = new ArrayList<ColumnDescription>();

    protected AbstractDataTableGenerator(InputStream inputStream, String line, String separator) {
        this.inputStream = inputStream;

        String headerLine = StringUtils.replace(line, "\"", "");
        if (headerLine.contains(separator)) {
            String[] columnHeaders = headerLine.split(separator);
            for (String columnHeader : columnHeaders) {
                columnDescriptions.add(new ColumnDescription(columnHeader, ValueType.TEXT, columnHeader));
            }
        }
    }

    /*
     * DataTableGenerator
     */

    public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException {
        ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request);

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream));
            return generateDataTable(reader, requestLocale, columnDescriptions);
        } catch (IOException e) {
            log.warning("generateDataTable():" + e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.warning("generateDataTable():" + e);
                }
            }
        }
        return null;
    }

    public Capabilities getCapabilities() {
        return Capabilities.NONE;
    }

    /*
     * Protected Methods
     */

    protected abstract DataTable generateDataTable(BufferedReader reader, ULocale requestLocale,
                                                   List<ColumnDescription> columns)
            throws IOException, DataSourceException;
}


text:
package org.apache.aries.blueprint.proxy;

public class ProxyTestClassGeneral extends ProxyTestClassSuper
{

  public String testMethod(String x, int y, Object z)
  {
    somePrivateMethod();
    return x;
  }

  public String testArgs(double a, short b, long c, char d, byte e, boolean f)
  {
    return Character.toString(d);
  }

  protected void testReturnVoid()
  {
  }

  int testReturnInt()
  {
    return 17;
  }

  public Integer testReturnInteger()
  {
    return Integer.valueOf(1);
  }

  private void somePrivateMethod()
  {

  }

  public boolean equals(Object o) {
    return o == this;
  }

  public void testException() {
    throw new RuntimeException();
  }

  public void testInternallyCaughtException() {
    try {
      try {
        throw new RuntimeException();
      } catch (RuntimeException re) {
        // no op
      }
    } catch (Exception e) {

    }
  }
}


text:
using System;
using System.Collections.Generic;
using Orchard;
using CloudBust.Common.Models;

namespace CloudBust.Common.Services {
    public interface IApplinksService : IDependency {
		ApplinksFileRecord Get();
		Tuple<bool, IEnumerable<string>> Save(string text);
	}
}


text:
package escalada.talhakosen.com.escaladaassignment.models;

import android.os.Parcel;
import android.os.Parcelable;

import org.json.JSONException;
import org.json.JSONObject;

// why parcable ? http://prolificinteractive.com/blog/2014/07/18/why-we-love-parcelable
public class ProductDetail extends Base implements Parcelable {
    private int product_id;
    private String name;
    private double price;
    private String image;
    private String description;

    public ProductDetail(JSONObject productDetail) throws JSONException {
        this.product_id = getJsonInt(productDetail, "product_id");
        this.name = getJsonString(productDetail, "name");
        this.price = getJsonDouble(productDetail, "price");
        this.image = getJsonString(productDetail, "image");
        this.description = getJsonString(productDetail, "description");
    }

    public ProductDetail(Parcel in) {
        this.product_id = in.readInt();
        this.name = in.readString();
        this.price = in.readDouble();
        this.image = in.readString();
        this.description = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(product_id);
        dest.writeString(name);
        dest.writeDouble(price);
        dest.writeString(image);
        dest.writeString(description);

    }

    public static final Creator<ProductDetail> CREATOR = new Creator<ProductDetail>() {
        public ProductDetail createFromParcel(final Parcel in) {
            return new ProductDetail(in);
        }

        public ProductDetail[] newArray(int size) {
            return new ProductDetail[size];
        }
    };

    public String getJsonString(JSONObject object, String key) {
        try {
            return object.getString(key);
        } catch (JSONException e) {
            return "";
        }
    }

    public int getJsonInt(JSONObject object, String key) {
        try {
            return object.getInt(key);
        } catch (JSONException e) {
            return 0;
        }
    }

    public Double getJsonDouble(JSONObject object, String key) {
        try {
            return object.getDouble(key);
        } catch (JSONException e) {
            return 0.0;
        }
    }

    public int getProduct_id() {
        return product_id;
    }

    public void setProduct_id(int product_id) {
        this.product_id = product_id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

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

    public String getFormattedPrice(){
        return String.format("%.2f",price/100);
    }
}


text:
#ifndef LIBXYO_WIN_INJECT_VERSION_HPP
#define LIBXYO_WIN_INJECT_VERSION_HPP

#define LIBXYO_WIN_INJECT_VERSION_ABCD                 $VERSION_ABCD
#define LIBXYO_WIN_INJECT_VERSION_STR                 "$VERSION_VERSION"
#define LIBXYO_WIN_INJECT_VERSION_STR_BUILD           "$VERSION_BUILD"
#define LIBXYO_WIN_INJECT_VERSION_STR_DATETIME        "$VERSION_DATETIME"

#ifndef XYO_RC

#ifndef XYO_WIN_INJECT__EXPORT_HPP
#include "xyo-win-inject--export.hpp"
#endif

namespace Lib {
	namespace XYO {
		namespace Win {
			namespace Inject {
				namespace Version {
					XYO_WIN_INJECT_EXPORT const char *version();
					XYO_WIN_INJECT_EXPORT const char *build();
					XYO_WIN_INJECT_EXPORT const char *versionWithBuild();
					XYO_WIN_INJECT_EXPORT const char *datetime();
				};
			};
		};
	};
};

#endif
#endif