text:
package org.apache.syncope.core.workflow.java;

import org.apache.syncope.common.lib.request.GroupCR;
import org.apache.syncope.common.lib.request.GroupUR;
import org.apache.syncope.core.persistence.api.dao.GroupDAO;
import org.apache.syncope.core.persistence.api.entity.EntityFactory;
import org.apache.syncope.core.persistence.api.entity.group.Group;
import org.apache.syncope.core.provisioning.api.WorkflowResult;
import org.apache.syncope.core.provisioning.api.data.GroupDataBinder;
import org.apache.syncope.core.workflow.api.GroupWorkflowAdapter;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = { Throwable.class })
public abstract class AbstractGroupWorkflowAdapter extends AbstractWorkflowAdapter implements GroupWorkflowAdapter {

    protected final GroupDataBinder dataBinder;

    protected final GroupDAO groupDAO;

    protected final EntityFactory entityFactory;

    public AbstractGroupWorkflowAdapter(
            final GroupDataBinder dataBinder,
            final GroupDAO groupDAO,
            final EntityFactory entityFactory) {

        this.dataBinder = dataBinder;
        this.groupDAO = groupDAO;
        this.entityFactory = entityFactory;
    }

    @Override
    public String getPrefix() {
        return null;
    }

    protected abstract WorkflowResult<String> doCreate(GroupCR groupCR, String creator, String context);

    @Override
    public WorkflowResult<String> create(final GroupCR groupCR, final String creator, final String context) {
        return doCreate(groupCR, creator, context);
    }

    protected abstract WorkflowResult<GroupUR> doUpdate(Group group, GroupUR groupUR, String updater, String context);

    @Override
    public WorkflowResult<GroupUR> update(final GroupUR groupUR, final String updater, final String context) {
        WorkflowResult<GroupUR> result = doUpdate(groupDAO.authFind(groupUR.getKey()), groupUR, updater, context);

        // re-read to ensure that requester's administration rights are still valid
        groupDAO.authFind(groupUR.getKey());

        return result;
    }

    protected abstract void doDelete(Group group, String eraser, String context);

    @Override
    public void delete(final String groupKey, final String eraser, final String context) {
        doDelete(groupDAO.authFind(groupKey), eraser, context);
    }
}


text:
// ----------------------------------------------------------------------------
// Copyright © Aleksey Nemiro, 2008-2014. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------

namespace Nemiro
{

  public static partial class Convertion
  {

    /// <summary>
    /// Returns a string containing a number formatted as a currency amount. For example: 1 000.45
    /// </summary>
    /// <param name="value">The amount that you want to convert.</param>
    /// <param name="penny">Indicates should be considered a penny or not.</param>
    public static string ToMoneyString(object value, bool penny)
    {
      if (penny)
      {
        return Convertion.ToDecimal(value).ToString("##,###,##0.00");
      }
      else
      {
        return Convertion.ToDecimal(value).ToString("##,###,##0");
      }
    }

    /// <summary>
    /// Returns a string containing a number formatted as a currency amount without penny. For example: 1 000 000
    /// </summary>
    /// <param name="value">The amount that you want to convert.</param>
    public static string ToMoneyString(object value)
    {
      return Convertion.ToMoneyString(value, false);
    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
    switch (arguments.length) {
        case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
        case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
        case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
    }
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var route_recognizer_1 = require('./route_recognizer');
var instruction_1 = require('./instruction');
var collection_1 = require('angular2/src/core/facade/collection');
var async_1 = require('angular2/src/core/facade/async');
var lang_1 = require('angular2/src/core/facade/lang');
var route_config_impl_1 = require('./route_config_impl');
var reflection_1 = require('angular2/src/core/reflection/reflection');
var di_1 = require('angular2/di');
var route_config_nomalizer_1 = require('./route_config_nomalizer');
var url_parser_1 = require('./url_parser');
var _resolveToNull = async_1.PromiseWrapper.resolve(null);
/**
 * The RouteRegistry holds route configurations for each component in an Angular app.
 * It is responsible for creating Instructions from URLs, and generating URLs based on route and
 * parameters.
 */
var RouteRegistry = (function () {
    function RouteRegistry() {
        this._rules = new collection_1.Map();
    }
    /**
     * Given a component and a configuration object, add the route to this registry
     */
    RouteRegistry.prototype.config = function (parentComponent, config) {
        config = route_config_nomalizer_1.normalizeRouteConfig(config);
        // this is here because Dart type guard reasons
        if (config instanceof route_config_impl_1.Route) {
            assertComponentExists(config.component, config.path);
        }
        else if (config instanceof route_config_impl_1.AuxRoute) {
            assertComponentExists(config.component, config.path);
        }
        var recognizer = this._rules.get(parentComponent);
        if (lang_1.isBlank(recognizer)) {
            recognizer = new route_recognizer_1.RouteRecognizer();
            this._rules.set(parentComponent, recognizer);
        }
        var terminal = recognizer.config(config);
        if (config instanceof route_config_impl_1.Route) {
            if (terminal) {
                assertTerminalComponent(config.component, config.path);
            }
            else {
                this.configFromComponent(config.component);
            }
        }
    };
    /**
     * Reads the annotations of a component and configures the registry based on them
     */
    RouteRegistry.prototype.configFromComponent = function (component) {
        var _this = this;
        if (!lang_1.isType(component)) {
            return;
        }
        // Don't read the annotations from a type more than once –
        // this prevents an infinite loop if a component routes recursively.
        if (this._rules.has(component)) {
            return;
        }
        var annotations = reflection_1.reflector.annotations(component);
        if (lang_1.isPresent(annotations)) {
            for (var i = 0; i < annotations.length; i++) {
                var annotation = annotations[i];
                if (annotation instanceof route_config_impl_1.RouteConfig) {
                    collection_1.ListWrapper.forEach(annotation.configs, function (config) { return _this.config(component, config); });
                }
            }
        }
    };
    /**
     * Given a URL and a parent component, return the most specific instruction for navigating
     * the application into the state specified by the url
     */
    RouteRegistry.prototype.recognize = function (url, parentComponent) {
        var parsedUrl = url_parser_1.parser.parse(url);
        return this._recognize(parsedUrl, parentComponent);
    };
    RouteRegistry.prototype._recognize = function (parsedUrl, parentComponent) {
        var _this = this;
        return this._recognizePrimaryRoute(parsedUrl, parentComponent)
            .then(function (instruction) {
            return _this._completeAuxiliaryRouteMatches(instruction, parentComponent);
        });
    };
    RouteRegistry.prototype._recognizePrimaryRoute = function (parsedUrl, parentComponent) {
        var _this = this;
        var componentRecognizer = this._rules.get(parentComponent);
        if (lang_1.isBlank(componentRecognizer)) {
            return async_1.PromiseWrapper.resolve(null);
        }
        // Matches some beginning part of the given URL
        var possibleMatches = componentRecognizer.recognize(parsedUrl);
        var matchPromises = collection_1.ListWrapper.map(possibleMatches, function (candidate) { return _this._completePrimaryRouteMatch(candidate); });
        return async_1.PromiseWrapper.all(matchPromises).then(mostSpecific);
    };
    RouteRegistry.prototype._completePrimaryRouteMatch = function (partialMatch) {
        var _this = this;
        var instruction = partialMatch.instruction;
        return instruction.resolveComponentType().then(function (componentType) {
            _this.configFromComponent(componentType);
            if (lang_1.isBlank(partialMatch.remaining)) {
                if (instruction.terminal) {
                    return new instruction_1.PrimaryInstruction(instruction, null, partialMatch.remainingAux);
                }
                else {
                    return null;
                }
            }
            return _this._recognizePrimaryRoute(partialMatch.remaining, componentType)
                .then(function (childInstruction) {
                if (lang_1.isBlank(childInstruction)) {
                    return null;
                }
                else {
                    return new instruction_1.PrimaryInstruction(instruction, childInstruction, partialMatch.remainingAux);
                }
            });
        });
    };
    RouteRegistry.prototype._completeAuxiliaryRouteMatches = function (instruction, parentComponent) {
        var _this = this;
        if (lang_1.isBlank(instruction)) {
            return _resolveToNull;
        }
        var componentRecognizer = this._rules.get(parentComponent);
        var auxInstructions = {};
        var promises = instruction.auxUrls.map(function (auxSegment) {
            var match = componentRecognizer.recognizeAuxiliary(auxSegment);
            if (lang_1.isBlank(match)) {
                return _resolveToNull;
            }
            return _this._completePrimaryRouteMatch(match).then(function (auxInstruction) {
                if (lang_1.isPresent(auxInstruction)) {
                    return _this._completeAuxiliaryRouteMatches(auxInstruction, parentComponent)
                        .then(function (finishedAuxRoute) {
                        auxInstructions[auxSegment.path] = finishedAuxRoute;
                    });
                }
            });
        });
        return async_1.PromiseWrapper.all(promises).then(function (_) {
            if (lang_1.isBlank(instruction.child)) {
                return new instruction_1.Instruction(instruction.component, null, auxInstructions);
            }
            return _this._completeAuxiliaryRouteMatches(instruction.child, instruction.component.componentType)
                .then(function (completeChild) {
                return new instruction_1.Instruction(instruction.component, completeChild, auxInstructions);
            });
        });
    };
    /**
     * Given a normalized list with component names and params like: `['user', {id: 3 }]`
     * generates a url with a leading slash relative to the provided `parentComponent`.
     */
    RouteRegistry.prototype.generate = function (linkParams, parentComponent) {
        var segments = [];
        var componentCursor = parentComponent;
        for (var i = 0; i < linkParams.length; i += 1) {
            var segment = linkParams[i];
            if (lang_1.isBlank(componentCursor)) {
                throw new lang_1.BaseException("Could not find route named \"" + segment + "\".");
            }
            if (!lang_1.isString(segment)) {
                throw new lang_1.BaseException("Unexpected segment \"" + segment + "\" in link DSL. Expected a string.");
            }
            else if (segment == '' || segment == '.' || segment == '..') {
                throw new lang_1.BaseException("\"" + segment + "/\" is only allowed at the beginning of a link DSL.");
            }
            var params = {};
            if (i + 1 < linkParams.length) {
                var nextSegment = linkParams[i + 1];
                if (lang_1.isStringMap(nextSegment)) {
                    params = nextSegment;
                    i += 1;
                }
            }
            var componentRecognizer = this._rules.get(componentCursor);
            if (lang_1.isBlank(componentRecognizer)) {
                throw new lang_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(componentCursor) + "\" has no route config.");
            }
            var response = componentRecognizer.generate(segment, params);
            if (lang_1.isBlank(response)) {
                throw new lang_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(componentCursor) + "\" has no route named \"" + segment + "\".");
            }
            segments.push(response);
            componentCursor = response.componentType;
        }
        var instruction = this._generateRedirects(componentCursor);
        while (segments.length > 0) {
            instruction = new instruction_1.Instruction(segments.pop(), instruction, {});
        }
        return instruction;
    };
    // if the child includes a redirect like : "/" -> "/something",
    // we want to honor that redirection when creating the link
    RouteRegistry.prototype._generateRedirects = function (componentCursor) {
        if (lang_1.isBlank(componentCursor)) {
            return null;
        }
        var componentRecognizer = this._rules.get(componentCursor);
        if (lang_1.isBlank(componentRecognizer)) {
            return null;
        }
        for (var i = 0; i < componentRecognizer.redirects.length; i += 1) {
            var redirect = componentRecognizer.redirects[i];
            // we only handle redirecting from an empty segment
            if (redirect.segments.length == 1 && redirect.segments[0] == '') {
                var toSegments = url_parser_1.pathSegmentsToUrl(redirect.toSegments);
                var matches = componentRecognizer.recognize(toSegments);
                var primaryInstruction = collection_1.ListWrapper.maximum(matches, function (match) { return match.instruction.specificity; });
                if (lang_1.isPresent(primaryInstruction)) {
                    var child = this._generateRedirects(primaryInstruction.instruction.componentType);
                    return new instruction_1.Instruction(primaryInstruction.instruction, child, {});
                }
                return null;
            }
        }
        return null;
    };
    RouteRegistry = __decorate([
        di_1.Injectable(),
        __metadata('design:paramtypes', [])
    ], RouteRegistry);
    return RouteRegistry;
})();
exports.RouteRegistry = RouteRegistry;
/*
 * Given a list of instructions, returns the most specific instruction
 */
function mostSpecific(instructions) {
    return collection_1.ListWrapper.maximum(instructions, function (instruction) { return instruction.component.specificity; });
}
function assertTerminalComponent(component, path) {
    if (!lang_1.isType(component)) {
        return;
    }
    var annotations = reflection_1.reflector.annotations(component);
    if (lang_1.isPresent(annotations)) {
        for (var i = 0; i < annotations.length; i++) {
            var annotation = annotations[i];
            if (annotation instanceof route_config_impl_1.RouteConfig) {
                throw new lang_1.BaseException("Child routes are not allowed for \"" + path + "\". Use \"...\" on the parent's route path.");
            }
        }
    }
}
function assertComponentExists(component, path) {
    if (!lang_1.isType(component)) {
        throw new lang_1.BaseException("Component for route \"" + path + "\" is not defined, or is not a class.");
    }
}
//# sourceMappingURL=route_registry.js.map


text:
package pl.yourempire.api.object;

import pl.mcplayg.quickrgba.QRGBAImage;

public class Texture
{
    public static final Texture EMPTY = new Texture(new QRGBAImage(64, 64));

    private QRGBAImage image;
    public Texture(QRGBAImage image)
    {
        if (image == null)
        {
            throw new IllegalArgumentException("Image cannot be null!");
        }
        this.image = image;
    }

    public QRGBAImage getTexture()
    {
        return this.image;
    }

    public void setTexture(QRGBAImage newTexture)
    {
        if (newTexture == null)
        {
            throw new IllegalArgumentException("New texture cannot be null!");
        }
        this.image = newTexture;
    }
}


text:
import World        from './core/World.js';
import GameOfLife   from './cells/GoL';

const SIZE = 100; // cells
const VIEW_SCALE = 8;
const WORLD_FRAME_RATE = 30;

let world = new World({
  size: SIZE,
  spread: 1.0,
  process: 'vertical',
  type: GameOfLife,
  render: 'content',
  scale: VIEW_SCALE
});

window.requestAnimationFrame(render);
window.setInterval(() => { world.evolve() }, 1000 / WORLD_FRAME_RATE);

function render()
{
  world.render();
  window.requestAnimationFrame(render);
}


text:
FROM ruby:2.3.1

RUN mkdir -p /app
WORKDIR /app

COPY . /app/
RUN bundle install

ENTRYPOINT /bin/bash


text:
import * as React from 'react';
import { OverridableComponent, OverrideProps } from '../OverridableComponent';
import { ScopedCssBaselineClasses } from './scopedCssBaselineClasses';

export interface ScopedCssBaselineTypeMap<P = {}, D extends React.ElementType = 'div'> {
  props: P & {
    /**
     * The content of the component.
     */
    children?: React.ReactNode;
    /**
     * Override or extend the styles applied to the component.
     */
    classes?: Partial<ScopedCssBaselineClasses>;
  };
  defaultComponent: D;
}
/**
 *
 * Demos:
 *
 * - [Css Baseline](https://material-ui.com/components/css-baseline/)
 *
 * API:
 *
 * - [ScopedCssBaseline API](https://material-ui.com/api/scoped-css-baseline/)
 */
declare const ScopedCssBaseline: OverridableComponent<ScopedCssBaselineTypeMap>;

export type ScopedCssBaselineProps<
  D extends React.ElementType = ScopedCssBaselineTypeMap['defaultComponent'],
  P = {}
> = OverrideProps<ScopedCssBaselineTypeMap<P, D>, D>;

/**
 *
 * Demos:
 *
 * - [Css Baseline](https://material-ui.com/components/css-baseline/)
 *
 * API:
 *
 * - [ScopedCssBaseline API](https://material-ui.com/api/scoped-css-baseline/)
 */
export default ScopedCssBaseline;


text:
package renderEngine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.TexturedModel;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Matrix4f;

import shaders.StaticShader;
import shaders.TerrainShader;
import terrains.Terrain;
import entities.Camera;
import entities.Entity;
import entities.Light;

public class MasterRenderer {
	private static final float FOV = 70;
	private static final float NEAR_PLANE = 0.1f;
	private static final float FAR_PLANE = 1000f;

	private static final float RED = 0.5f;
	private static final float GREEN = 0.5f;
	private static final float BLUE = 0.5f;

	private Matrix4f projectionMatrix;

	private EntityRenderer renderer;
	private StaticShader shader = new StaticShader();

	private TerrainRenderer terrainRenderer;
	private TerrainShader terrainShader = new TerrainShader();

	private Map<TexturedModel,List<Entity>> entities = new HashMap<TexturedModel,List<Entity>>();
	private List<Terrain> terrains = new ArrayList<Terrain>();

	public MasterRenderer(){
		enableCulling();
		createProjectionMatrix();
		renderer = new EntityRenderer(shader,projectionMatrix);
		terrainRenderer = new TerrainRenderer(terrainShader,projectionMatrix);
	}

	public void render(Light sun, Camera camera){
		prepare();
		shader.start();
		shader.loadSkyColor(RED, GREEN, BLUE);
		shader.loadLight(sun);
		shader.loatViewMatrix(camera);
		renderer.render(entities);
		shader.stop();

		terrainShader.start();
		terrainShader.loadSkyColor(RED, GREEN, BLUE);
		terrainShader.loadLight(sun);
		terrainShader.loadViewMatrix(camera);
		terrainRenderer.render(terrains);
		terrainShader.stop();

		terrains.clear();
		entities.clear();
	}

	public void proccessTerrain(Terrain terrain){
		terrains.add(terrain);
	}

	public void proccessEntity(Entity entity){
		TexturedModel entityModel = entity.getModel();
		List<Entity> batch = entities.get(entityModel);
		if(batch!=null){
			batch.add(entity);
		}
		else{
			List<Entity> newBatch = new ArrayList<Entity>();
			newBatch.add(entity);
			entities.put(entityModel, newBatch);
		}
	}

	public void cleanUp(){
		shader.cleanUp();
		terrainShader.cleanUp();
	}

	public static void enableCulling(){
		GL11.glEnable(GL11.GL_CULL_FACE);
		GL11.glCullFace(GL11.GL_BACK);
	}

	public static void disableCulling(){
		GL11.glDisable(GL11.GL_CULL_FACE);
		GL11.glCullFace(GL11.GL_BACK);
	}

	public void prepare(){
		GL11.glEnable(GL11.GL_DEPTH_TEST);
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT|GL11.GL_DEPTH_BUFFER_BIT);
		GL11.glClearColor(RED,GREEN,BLUE,1);
	}

	private void createProjectionMatrix(){
		float aspectRatio  = (float)Display.getWidth()/(float)Display.getHeight();
		float y_scale = (1f / (float)Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio;
		float x_scale = y_scale/aspectRatio;

		float frustum_length = FAR_PLANE - NEAR_PLANE;

		projectionMatrix = new Matrix4f();
		projectionMatrix.m00 = x_scale;
		projectionMatrix.m11 = y_scale;
		projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustum_length);
		projectionMatrix.m23 = -1;
		projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length);
		projectionMatrix.m33 = 0;
	}
}


text:
package org.elasticsearch.xpack.sql.expression.function.scalar.string;

import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.test.AbstractWireSerializingTestCase;
import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;
import org.elasticsearch.xpack.sql.expression.function.scalar.Processors;
import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor;

import static org.elasticsearch.xpack.sql.tree.Location.EMPTY;
import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l;

public class LocateProcessorTests extends AbstractWireSerializingTestCase<LocateFunctionProcessor> {

    @Override
    protected LocateFunctionProcessor createTestInstance() {
        // the "start" parameter is optional and is treated as null in the constructor
        // when it is not used. Need to take this into account when generating random
        // values for it.
        Integer start = frequently() ? randomInt() : null;
        return new LocateFunctionProcessor(
                new ConstantProcessor(randomRealisticUnicodeOfLengthBetween(0, 128)),
                new ConstantProcessor(randomRealisticUnicodeOfLengthBetween(0, 128)),
                new ConstantProcessor(start));
    }

    @Override
    protected Reader<LocateFunctionProcessor> instanceReader() {
        return LocateFunctionProcessor::new;
    }

    @Override
    protected NamedWriteableRegistry getNamedWriteableRegistry() {
        return new NamedWriteableRegistry(Processors.getNamedWriteables());
    }

    public void testLocateFunctionWithValidInput() {
        assertEquals(4, new Locate(EMPTY, l("bar"), l("foobarbar"), l(null)).makePipe().asProcessor().process(null));
        assertEquals(7, new Locate(EMPTY, l("bar"), l("foobarbar"), l(5)).makePipe().asProcessor().process(null));
    }

    public void testLocateFunctionWithEdgeCasesInputs() {
        assertEquals(4, new Locate(EMPTY, l("bar"), l("foobarbar"), l(null)).makePipe().asProcessor().process(null));
        assertNull(new Locate(EMPTY, l("bar"), l(null), l(3)).makePipe().asProcessor().process(null));
        assertEquals(0, new Locate(EMPTY, l(null), l("foobarbar"), l(null)).makePipe().asProcessor().process(null));
        assertEquals(0, new Locate(EMPTY, l(null), l("foobarbar"), l(null)).makePipe().asProcessor().process(null));

        assertEquals(1, new Locate(EMPTY, l("foo"), l("foobarbar"), l(null)).makePipe().asProcessor().process(null));
        assertEquals(1, new Locate(EMPTY, l('o'), l('o'), l(null)).makePipe().asProcessor().process(null));
        assertEquals(9, new Locate(EMPTY, l('r'), l("foobarbar"), l(9)).makePipe().asProcessor().process(null));
        assertEquals(4, new Locate(EMPTY, l("bar"), l("foobarbar"), l(-3)).makePipe().asProcessor().process(null));
    }

    public void testLocateFunctionValidatingInputs() {
        SqlIllegalArgumentException siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Locate(EMPTY, l(5), l("foobarbar"), l(3)).makePipe().asProcessor().process(null));
        assertEquals("A string/char is required; received [5]", siae.getMessage());
        siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Locate(EMPTY, l("foo"), l(1), l(3)).makePipe().asProcessor().process(null));
        assertEquals("A string/char is required; received [1]", siae.getMessage());
        siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Locate(EMPTY, l("foobarbar"), l("bar"), l('c')).makePipe().asProcessor().process(null));
        assertEquals("A number is required; received [c]", siae.getMessage());
    }
}


text:
package com.stulsoft.poc.pgson.json;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;

import java.io.FileReader;

public class StringInside {
    public static void main(String[] args) {
        System.out.println("==>StringInside::main");
        parse();
    }

    private static void parse() {
        System.out.println("==>StringInside::parse");
        try {
            var reader = new FileReader("app/src/main/resources/fileWithStringObject.json");
            JsonObject jsonObject = (JsonObject) JsonParser.parseReader(reader);
            reader.close();
            System.out.printf("%s%n", jsonObject);

            System.out.printf("data is object: %b, is primitive: %b%n",
                    jsonObject.get("data").isJsonObject(),
                    jsonObject.get("data").isJsonPrimitive()
            );

            var dataAsString=jsonObject.get("data").getAsString();
            System.out.printf("dataAsString:%s%n", dataAsString);

            var dataAsJson = (JsonObject)JsonParser.parseString(dataAsString);
            System.out.printf("dataAsJson:%s%n", dataAsJson.toString());
            var b = dataAsJson.getAsJsonPrimitive("b");
            System.out.printf("b:%s%n", b.getAsString());
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }
}


text: echo "Building the theme :P"


text:
'use strict';

// For some reason thinks it's a strict violation.
if (exports !== this) {
  throw new Error('Invalid module context');
}

var moduleStateValue = 'default';

function setModuleStateValue(value) {
  moduleStateValue = value;
}

function getModuleStateValue() {
  return moduleStateValue;
}

exports.getModuleStateValue = getModuleStateValue;
exports.isRealModule = true;
exports.setModuleStateValue = setModuleStateValue;
exports.parent = module.parent;


text:
/******************************************************************************
 *                     Code generated with sympy 0.7.6.1                      *
 *                                                                            *
 *              See http://www.sympy.org/ for more information.               *
 *                                                                            *
 *                       This file is part of 'project'                       *
 ******************************************************************************/

#ifndef PROJECT__ORDER8_SQUARE__H
#define PROJECT__ORDER8_SQUARE__H

void interpolate_order8_square(double epsilon, double eta, double *out_5857460273485771890);
void interpolate_eps_derivative_order8_square(double epsilon, double eta, double *out_3539342882259231955);
void interpolate_eta_derivative_order8_square(double epsilon, double eta, double *out_1604135558802125817);
void closure_mapping_order8_square(int *out_1888811593364008808);
void gll_weights_order8_square(double *out_3995493972137613764);
void gll_coordinates_order8_square(double *out_4420238649482325602);

#endif


text:
import { HighlanderPreview } from './HighlanderPreview';
import { DeploymentStrategyRegistry } from '../../deploymentStrategy.registry';

DeploymentStrategyRegistry.registerStrategy({
  label: 'Highlander',
  description:
    'Destroys <i>all</i> previous server groups in the cluster as soon as new server group passes health checks',
  key: 'highlander',
  AdditionalFieldsComponent: HighlanderPreview,
});


text:
/* globals toolbarSearch, menu, isRtl, fireGlobalEvent, CachedChatSubscription */
import Clipboard from 'clipboard';

Template.body.onRendered(function() {
	new Clipboard('.clipboard');

	$(document.body).on('keydown', function(e) {
		if ((e.keyCode === 80 || e.keyCode === 75) && (e.ctrlKey === true || e.metaKey === true) && e.shiftKey === false) {
			e.preventDefault();
			e.stopPropagation();
			toolbarSearch.focus(true);
		}
		const unread = Session.get('unread');
		if (e.keyCode === 27 && e.shiftKey === true && (unread != null) && unread !== '') {
			e.preventDefault();
			e.stopPropagation();
			return swal({
				title: t('Clear_all_unreads_question'),
				type: 'warning',
				confirmButtonText: t('Yes_clear_all'),
				showCancelButton: true,
				cancelButtonText: t('Cancel'),
				confirmButtonColor: '#DD6B55'
			}, function() {
				const subscriptions = ChatSubscription.find({
					open: true
				}, {
					fields: {
						unread: 1,
						alert: 1,
						rid: 1,
						t: 1,
						name: 1,
						ls: 1
					}
				});

				subscriptions.forEach((subscription) =>{
					if (subscription.alert || subscription.unread > 0) {
						Meteor.call('readMessages', subscription.rid);
					}
				});
			});
		}
	});

	$(document.body).on('keydown', function(e) {
		const target = e.target;
		if (e.ctrlKey === true || e.metaKey === true) {
			return;
		}
		if (!(e.keyCode > 45 && e.keyCode < 91 || e.keyCode === 8)) {
			return;
		}
		if (/input|textarea|select/i.test(target.tagName)) {
			return;
		}
		if (target.id === 'pswp') {
			return;
		}
		const inputMessage = $('textarea.input-message');
		if (inputMessage.length === 0) {
			return;
		}
		return inputMessage.focus();
	});
	$(document.body).on('click', 'a', function(e) {
		const link = e.currentTarget;
		if (link.origin === s.rtrim(Meteor.absoluteUrl(), '/') && /msg=([a-zA-Z0-9]+)/.test(link.search)) {
			e.preventDefault();
			e.stopPropagation();
			if (RocketChat.Layout.isEmbedded()) {
				return fireGlobalEvent('click-message-link', {
					link: link.pathname + link.search
				});
			}
			return FlowRouter.go(link.pathname + link.search, null, FlowRouter.current().queryParams);
		}
	});
	Tracker.autorun(function(c) {
		const w = window;
		const d = document;
		const s = 'script';
		const l = 'dataLayer';
		const i = RocketChat.settings.get('GoogleTagManager_id');
		if (Match.test(i, String) && i.trim() !== '') {
			c.stop();
			return (function(w, d, s, l, i) {
				w[l] = w[l] || [];
				w[l].push({
					'gtm.start': new Date().getTime(),
					event: 'gtm.js'
				});
				const f = d.getElementsByTagName(s)[0];
				const j = d.createElement(s);
				const dl = l !== 'dataLayer' ? `&l=${ l }` : '';
				j.async = true;
				j.src = `//www.googletagmanager.com/gtm.js?id=${ i }${ dl }`;
				return f.parentNode.insertBefore(j, f);
			}(w, d, s, l, i));
		}
	});
	if (Meteor.isCordova) {
		return $(document.body).addClass('is-cordova');
	}
});

Template.main.helpers({
	siteName() {
		return RocketChat.settings.get('Site_Name');
	},
	logged() {
		if (Meteor.userId() != null || (RocketChat.settings.get('Accounts_AllowAnonymousRead') === true && Session.get('forceLogin') !== true)) {
			$('html').addClass('noscroll').removeClass('scroll');
			return true;
		} else {
			$('html').addClass('scroll').removeClass('noscroll');
			return false;
		}
	},
	useIframe() {
		const iframeEnabled = typeof RocketChat.iframeLogin !== 'undefined';
		return iframeEnabled && RocketChat.iframeLogin.reactiveEnabled.get();
	},
	iframeUrl() {
		const iframeEnabled = typeof RocketChat.iframeLogin !== 'undefined';
		return iframeEnabled && RocketChat.iframeLogin.reactiveIframeUrl.get();
	},
	subsReady() {
		const routerReady = FlowRouter.subsReady('userData', 'activeUsers');
		const subscriptionsReady = CachedChatSubscription.ready.get();
		const ready = (Meteor.userId() == null) || (routerReady && subscriptionsReady);
		RocketChat.CachedCollectionManager.syncEnabled = ready;
		return ready;
	},
	hasUsername() {
		return (Meteor.userId() != null && Meteor.user().username != null) || (Meteor.userId() == null && RocketChat.settings.get('Accounts_AllowAnonymousRead') === true);
	},
	requirePasswordChange() {
		const user = Meteor.user();
		return user && user.requirePasswordChange === true;
	},
	CustomScriptLoggedOut() {
		const script = RocketChat.settings.get('Custom_Script_Logged_Out') || '';
		if (script.trim()) {
			eval(script);//eslint-disable-line
		}
	},
	CustomScriptLoggedIn() {
		const script = RocketChat.settings.get('Custom_Script_Logged_In') || '';
		if (script.trim()) {
			eval(script);//eslint-disable-line
		}
	},
	embeddedVersion() {
		if (RocketChat.Layout.isEmbedded()) {
			return 'embedded-view';
		}
	}
});

Template.main.events({
	'click .burger'() {
		if (window.rocketDebug) {
			console.log('room click .burger');
		}
		return menu.toggle();
	},
	'touchstart'(e, t) {
		if (document.body.clientWidth > 780) {
			return;
		}
		t.touchstartX = undefined;
		t.touchstartY = undefined;
		t.movestarted = false;
		t.blockmove = false;
		t.isRtl = isRtl(localStorage.getItem('userLanguage'));
		if ($(e.currentTarget).closest('.main-content').length > 0) {
			t.touchstartX = e.originalEvent.touches[0].clientX;
			t.touchstartY = e.originalEvent.touches[0].clientY;
			t.mainContent = $('.main-content');
			return t.wrapper = $('.messages-box > .wrapper');
		}
	},
	'touchmove'(e, t) {
		if (t.touchstartX != null) {
			const [touch] = e.originalEvent.touches;
			const diffX = touch.clientX - t.touchstartX;
			const diffY = touch.clientY - t.touchstartY;
			const absX = Math.abs(diffX);
			const absY = Math.abs(diffY);
			if (t.movestarted !== true && t.blockmove !== true && absY > 5) {
				t.blockmove = true;
			}
			if (t.blockmove !== true && (t.movestarted === true || absX > 5)) {
				t.movestarted = true;
				if (t.isRtl) {
					if (menu.isOpen()) {
						t.diff = -260 + diffX;
					} else {
						t.diff = diffX;
					}
					if (t.diff < -260) {
						t.diff = -260;
					}
					if (t.diff > 0) {
						t.diff = 0;
					}
				} else {
					if (menu.isOpen()) {
						t.diff = 260 + diffX;
					} else {
						t.diff = diffX;
					}
					if (t.diff > 260) {
						t.diff = 260;
					}
					if (t.diff < 0) {
						t.diff = 0;
					}
				}
				t.mainContent.addClass('notransition');
				t.mainContent.css('transform', `translate(${ t.diff }px)`);
				return t.wrapper.css('overflow', 'hidden');
			}
		}
	},
	'touchend'(e, t) {
		if (t.movestarted === true) {
			t.mainContent.removeClass('notransition');
			t.wrapper.css('overflow', '');
			if (t.isRtl) {
				if (menu.isOpen()) {
					if (t.diff >= -200) {
						return menu.close();
					} else {
						return menu.open();
					}
				} else if (t.diff <= -60) {
					return menu.open();
				} else {
					return menu.close();
				}
			} else if (menu.isOpen()) {
				if (t.diff >= 200) {
					return menu.open();
				} else {
					return menu.close();
				}
			} else if (t.diff >= 60) {
				return menu.open();
			} else {
				return menu.close();
			}
		}
	}
});

Template.main.onRendered(function() {
	if (isRtl(localStorage.getItem('userLanguage'))) {
		$('html').addClass('rtl');
	} else {
		$('html').removeClass('rtl');
	}
	$('#initial-page-loading').remove();
	window.addEventListener('focus', function() {
		return Meteor.setTimeout(function() {
			if (!$(':focus').is('INPUT,TEXTAREA')) {
				return $('.input-message').focus();
			}
		}, 100);
	});
	return Tracker.autorun(function() {
		swal.setDefaults({
			cancelButtonText: t('Cancel')
		});
		const user = Meteor.user();
		const settings = user && user.settings;
		const prefs = settings && settings.preferences;
		if (prefs && prefs.hideUsernames != null) {
			$(document.body).on('mouseleave', 'button.thumb', function() {
				return RocketChat.tooltip.hide();
			});
			return $(document.body).on('mouseenter', 'button.thumb', function(e) {
				const avatarElem = $(e.currentTarget);
				const username = avatarElem.attr('data-username');
				if (username) {
					e.stopPropagation();
					return RocketChat.tooltip.showElement($('<span>').text(username), avatarElem);
				}
			});
		} else {
			$(document.body).off('mouseenter', 'button.thumb');
			return $(document.body).off('mouseleave', 'button.thumb');
		}
	});
});

Meteor.startup(function() {
	return fireGlobalEvent('startup', true);
});


text:
<?php

class I18nTest extends AimeosTestAbstract
{
	public function testGet()
	{
		$aimeos = $this->app->make('\Aimeos\Shop\Base\Aimeos');

		$configMock = $this->getMockBuilder('\Illuminate\Config\Repository')
			->setMethods( array('get', 'has') )->getMock();

		$configMock->expects( $this->once() )->method('has')
			->will( $this->returnValue(true) );

		if( function_exists('apc_store') ) {
			$configMock->expects( $this->exactly(3) )->method('get')
				->will( $this->onConsecutiveCalls( true, 'laravel:', array() ) );
		} else {
			$configMock->expects( $this->once() )->method('get')
				->will( $this->returnValue( array() ) );
		}

		$object = new \Aimeos\Shop\Base\I18n($aimeos, $configMock);
		$list = $object->get( array('en') );

		$this->assertInstanceOf( '\MW_Translation_Interface', $list['en'] );
	}
}


text:
'use strict';

var Duplicate = require('mongoose').model('Duplicate'),
Project = require('mongoose').model('Project'),
Company = require('mongoose').model('Company'),
Concession = require('mongoose').model('Concession'),
Site = require('mongoose').model('Site'),
Link = require('mongoose').model('Link'),
Transfer = require('mongoose').model('Transfer'),
Production = require('mongoose').model('Production'),
async = require('async'),
_ = require("underscore"),
moment = require('moment');

var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;

exports.getDuplicates = function(req, res) {

  var type = String(req.params.type);
  var limit = Number(req.params.limit);
  var skip = Number(req.params.skip);

  var entity, objType, aliases;

  switch(type) {
    case 'company':
    entity = 'company';
    objType = 'Company';
    break;
    case 'project':
    entity = 'project';
    objType = 'Project';
    break;
    default:
    res.send("entity type not found.");
    break;
  }

  if(entity) {
    async.waterfall([
      getDuplicateCount,
      getDuplicateData
    ], function(err, result) {
      if (err && !result) {
        res.send(err);
      }
      else {
        if (req.query && req.query.callback) {
          return res.jsonp("" + req.query.callback + "(" + JSON.stringify(result) + ");");
        }
        else {
          return res.send(result);
        }
      }
    });
  }

  function getDuplicateCount(callback) {
    Duplicate.where({ entity: entity, resolved: false }).count(function(err, duplicate_count) {
      if(err) {
        callback(err);
      }
      else {
        if(!isNaN(duplicate_count) && duplicate_count > 0) {
          callback(null, duplicate_count);
        }
        else {
          callback("no unresolved duplicates found", { data: [], count: 0});
        }
      }
    });
  }

  function getDuplicateData(duplicate_count, callback) {
    Duplicate.find({ entity: entity, resolved: false })
    .populate('original', null, objType)
    .populate('duplicate', null, objType)
    .populate('resolved_by')
    .limit(limit)
    .skip(limit * skip)
    .exec(function(err, duplicates) {
      if(duplicates) {
        callback(null, { data: duplicates, count: duplicate_count });
      }
      else {
        //should never be called
        callback("no duplicates found");
      }
    });
  }

};

exports.resolveDuplicates = function(req, res) {
  var entity,alias, aliases;

  //var user_id = req.user._id;
  var duplicate_id = req.params.id;
  var action = req.params.action;

  async.waterfall([
    getEntity.bind(null, duplicate_id, action),
    getCompanyOrProject,
    addAliasToCompanyOrProject,
    resolveEntity
  ], function (err, result) {
    if (err) {
      res.send(err);
    }
    else {
      res.send(result);
    }
  });

  function getEntity(id, action, callback) {
    if(action!='resolve_all') {
      Duplicate.findOne({_id: id, resolved: false}, function (err, result) {
        if (err) {
          callback(err);
        }
        else if (result && result.entity) {
          callback(null, result, action);
        }
        else {
          callback("no duplicate found with id " + id);
        }
      });
    } else{
      callback(null, {}, action);
    }
  };

  function getCompanyOrProject(result, action, callback) {
    if(action=='setasalias') {

      switch (result.entity) {

        case 'company':
        Company.findOne({_id: result.duplicate}, function (err, company) {
          if(err) {
            callback(err);
          }
          else if(company) {
            alias = {
              alias: company.company_name,
              model: 'company',
              source: company.company_established_source
            };
            callback(null, result, action, alias);
          }
          else {
            callback(err);
          }
        });
        break;

        case 'project':
        Project.findOne({_id: result.duplicate}, function (err, project) {
          if(err) {
            callback(err);
          }
          else if(project) {
            alias = {
              alias: project.proj_name,
              model: 'project',
              source: project.proj_established_source
            };
            callback(null, result, action, alias);
          }
          else {
            callback(err);
          }
        });
        break;

        default:
          break;
      }
    }
    else {
      callback(null, result, action, '');
    }
  };

  function addAliasToCompanyOrProject(result, action, aliases, callback) {

    if(action=='setasalias') {

      switch (result.entity) {

        case 'company':
        Company.findById(result.original)
        .exec(function (err, company) {
          if (err) {
            callback(err);
          }
          else if (company) {
            console.log("pushing alias to company id " + company._id);
            company.company_aliases.push(aliases);
            company.save(function (err) {
            });
            callback(null, result, action);
          }
          else {
            callback(err);
          }
        });
        break;

        case 'project':
        Project.findById(result.original)
        .exec(function (err, project) {
          if (err) {
            callback(err);
          }
          else if (project) {
            console.log("pushing alias to project id " + project._id);
            project.proj_aliases.push(aliases);
            project.save(function (err) {
            });
            callback(null, result, action);
          }
          else {
            callback(err);
          }
        });
        break;
        default:
        break;
      }
    }
    else {
      callback(null, result, action);
    }
  };

  function resolveEntity(obj, action, callback) {

    // currently three action types are allowed: setasalias, resolve, update
    switch (action) {

      case 'setasalias':
        console.log("== reconcile - setasalias");
        if(obj.entity=='company') {
          // HANDLE COMPANY DUPLICATES
          async.series([
            updateAll.bind(null, Link, obj.duplicate, obj.original, obj.entity),
            updateAll.bind(null, Transfer, obj.duplicate, obj.original, obj.entity),
            updateAllCompanyFacts.bind(null, obj.duplicate, obj.original)
          ], function (err, results) {
            if (err) {
              console.log("updating companies. ERROR: " + err);
              callback(err);
            }
            else if (results) {
              Company.findOneAndRemove({_id: obj.duplicate}, function (err, company_to_remove) {
                console.log("looking for duplicate company with id " + obj.duplicate);
                if (err) {
                  callback(err);
                }
                else if (company_to_remove) {
                  console.log("updating companies. DONE.")
                  console.log('setting resolved flag to id ' + obj._id + '.');

                  //TODO search for duplicate id, could be the company name instead
                  Duplicate.find({$or: [{'original': obj.duplicate}, {'duplicate': obj.duplicate}]}, function (err, result) {
                    if (err) {
                      console.log('setting resolved flag to duplicate object with id ' + obj._id + '. ERROR: ' + err);
                      callback(err);
                    }
                    else {
                      _.each(result, function (duplicate) {
                        duplicate.resolved = true;
                        duplicate.resolved_date = Date.now();
                        duplicate.save(function (err) {
                        })
                      });

                      console.log('setting resolved flag to duplicate object with id ' + obj._id + '. DONE.');
                      callback(null, 'company duplicate with id ' + obj._id + ' resolved, all associated links and facts updated');
                    }
                  });
                }
              })
            }
            else {
              console.log("updating companies. ERROR: " + err);
              callback(err);
            }
          })
        }

        if(obj.entity=='project') {
          // HANDLE PROJECT DUPLICATES
          //update links, transfers and facts
          console.log("updating all projects.")
          async.series([
            updateAll.bind(null, Link, obj.duplicate, obj.original._id, obj.entity),
            updateAll.bind(null, Transfer, obj.duplicate, obj.original._id, obj.entity),
            updateAll.bind(null, Production, obj.duplicate, obj.original._id, obj.entity)
            //updateAllProjectFacts.bind(null, obj.duplicate, obj.original._id)
          ], function (err, results) {
            if (err) {
              console.log("updating projects. ERROR: " + err);
              callback(err);
            }
            else if (results) {
                Project.findOneAndRemove({_id: obj.duplicate}, function (err, project_to_remove) {
                console.log("looking for duplicate project with id " + obj.duplicate);
                if (err) {
                  callback(err);
                }
                else if (project_to_remove) {
                  console.log("updating projects. DONE.")
                  console.log('setting resolved flag to duplicate object with id ' + obj._id);
                  Duplicate.find({$or: [{'original': obj.duplicate}, {'duplicate': obj.duplicate}]}, function (err, result) {
                    if (err) {
                      console.log('setting resolved flag to duplicate object with id ' + obj._id + '. ERROR: ' + err);
                      callback(err);
                    }
                    else {
                      _.each(result, function (duplicate) {
                        duplicate.resolved = true;
                        duplicate.resolved_date = Date.now();
                        duplicate.save(function (err) {
                        })
                      });
                      console.log('setting resolved flag to duplicate object with id ' + obj._id + '. DONE.');
                      callback(null, 'project duplicate with id ' + obj._id + ' resolved, all associated links and facts updated');
                    }
                  });
                }
              })
            }
            else {
              console.log("updating projects. ERROR: " + err);
              callback(err);
            }
          });
        }
        break;

      case 'resolve':
        console.log("== reconcile - resolve");
        Duplicate.find({'_id': obj._id}, function (err, result) {
          if (err) {
            callback(err);
          }
          else if(result) {
            _.each(result, function (duplicate) {
              duplicate.resolved = true;
              duplicate.resolved_date = Date.now();
              duplicate.save(function (err) {
              });
            });
            callback(null, 'company duplicate with id ' + obj._id + ' resolved, just deleted');
          }
          else {
            callback(err);
          }
        });
        break;

      case 'resolve_all':
        console.log("== reconcile - resolve_all");
        Duplicate.find({resolved: false}, function (err, result) {
          if (err) {
            callback(err);
          }
          else if(result) {
            _.each(result, function (duplicate) {
              duplicate.resolved = true;
              duplicate.resolved_date = Date.now();
              duplicate.save(function (err) {
              });
            });
            callback(null, 'company duplicate resolved, just deleted');
          }
          else {
            callback(err);
          }
        });
        break;
      case 'update':
        console.log("updating document with duplicate information");
        console.log("removing duplicate object.");
        var entity;
        switch (obj.entity) {
          case 'project':
            entity = Project;
            break;
          case 'company':
            entity = Company;
            break;
          default:
            callback("entity type not found");
            break;
        }
        entity.findOneAndRemove({_id: obj.duplicate}, function (err, entity_to_remove) {
          if (err) {
            console.log("removing duplicate object. ERROR: " + err);
            callback(err);
          }
          else if (entity_to_remove) {
            console.log("removing duplicate object. DONE.");

            //do not overwrite object id
            delete entity_to_remove._id;
            console.log("updating original object with id " + obj._id + ".");
            console.log(entity_to_remove);
            entity.findByIdAndUpdate(obj.original, entity_to_remove, function (err, doc) {
              if (err) {
                console.log("updating original object with id " + obj._id + ". ERROR: " + err);
                callback(err);
              }
              else if (doc) {
                console.log("updating original object with id " + obj._id + ". DONE.");
                console.log("setting resolved flag to id " + obj._id + ".");
                Duplicate.findByIdAndUpdate(obj._id, {
                  resolved: true,
                  resolved_date: Date.now()
                }, function (err, result) {
                  if (err) {
                    console.log("setting resolved flag to id " + obj._id + ". ERROR: " + err);
                    callback(err);
                  }
                  else {
                    console.log("setting resolved flag to id " + obj._id + ". DONE.");
                    callback(null, "entity updated with information");
                  }
                });
              }
              else {
                callback(err);
              }
            });
          }
          else {
            callback(err);
          }
        });
        break;

      default:
        // do nothing here
        callback("no valid action chosen, please chose from [setasalias, resolve, update]");
        break;
    }
  };

  function updateAll(entity, old_company_id, new_company_id, object_entity, callback) {
    console.log("updating entity information (old: " + old_company_id + ", new: " + new_company_id + ")");
    async.waterfall([
      find.bind(null, entity, old_company_id, new_company_id, object_entity),
      update
    ], function (err, results) {
      if (err) {
        console.log("updating entity information (old: " + old_company_id + ", new: " + new_company_id + "). ERROR: " + err);
        callback(err);
      }
      else if (results) {
        console.log("updating entity information (old: " + old_company_id + ", new: " + new_company_id + "). DONE.");
        callback(null, "links updated");
      }
      else {
        console.log("updating entity information (old: " + old_company_id + ", new: " + new_company_id + "). ERROR: " + err);
        callback(err);
      }
      ;
    });
  };

  function find(entity, old_id, new_id, object_entity, callback) {
    console.log('looking for ' + object_entity + ' information with id ' + old_id + '.');
    if(object_entity == 'company') {
      entity.find({ company: old_id }, function (err, results) {
        if (err) {
          console.log('looking for ' + object_entity + ' information with id ' + old_id + '. ERROR: ' + err);
          callback(err);
        }
        else if (results) {
          console.log('looking for ' + object_entity + ' information with id ' + old_id + '. DONE.');
          callback(null, entity, new_id, results, object_entity);
        }
        else {
          console.log('looking for ' + object_entity + ' information with id ' + old_id + '. ERROR: ' + err);
          callback(err);
        }
      });
    }
    if(object_entity == 'project') {
      entity.find({ project: old_id }, function (err, results) {
        if (err) {
          console.log('looking for project information with id ' + old_id + '. ERROR: ' + err);
          callback(err);
        }
        else if (results) {
          console.log('looking for project information with id ' + old_id + '. DONE.');
          callback(null, entity, new_id, results, object_entity);
        }
        else {
          console.log('looking for project information with id ' + old_id + '. ERROR: ' + err);
          callback(err);
        }
      });
    }
  };

  function update(entity, new_id, listOfEntityIds, object_entity, callback) {
    if (listOfEntityIds) {
      console.log('updating ' + object_entity + ' information. ' + listOfEntityIds.length + ' documents.');
      if (listOfEntityIds.length == 0) {
        console.log('updating ' + object_entity + ' information. ' + listOfEntityIds.length + ' documents. DONE.');
        callback(null, "no need to update any element.");
      }
      else {
        async.eachLimit(listOfEntityIds, 5, function (entity_id, callback) {
          if(object_entity == 'company') {
            entity.findByIdAndUpdate(entity_id, { company: new_id }, function (err, results) {
              if (err) {
                callback(err);
              }
              else if (results) {
                callback(null, object_entity + ' link with id ' + entity_id + ' updated successfully');
              }
              else {
                callback(err);
              }
            });
          }
          if(object_entity == 'project') {
            entity.findByIdAndUpdate(entity_id, { project: new_id }, function (err, results) {
              if (err) {
                callback(err);
              }
              else if (results) {
                callback(null, object_entity + ' link with id ' + entity_id + ' updated successfully');
              }
              else {
                callback(err);
              }
            });
          }
        }, function(err) {
          if(err) {
            console.log('updating ' + object_entity + ' information. ' + listOfEntityIds.length + ' documents. ERROR: ' + err);
            callback(err);
          }
          else {
            console.log('updating ' + object_entity + ' information. ' + listOfEntityIds.length + ' documents. DONE.');
            callback(null, 'updating ' + object_entity + ' information. ' + listOfEntityIds.length + ' documents. DONE.');
          }
        });
      }
    }
  };

  // TODO somehow useful to do future implementation with update definition objects
  /*
  var listOfFields = [];
  listOfFields[0] = { entity: Concession, doc: 'concession', fieldsToUpdate: ['concession_operated_by', 'concession_company_share']};
  listOfFields[1] = { entity: Site, doc: 'site', fieldsToUpdate: ['site_operated_by', 'site_company_share']};
  */
  function updateAllCompanyFacts(old_company_id, new_company_id, callback) {
    async.series([
      update_concession_operated_by.bind(null, old_company_id, new_company_id),
      update_concession_company_share.bind(null, old_company_id, new_company_id),
      update_site_operated_by.bind(null, old_company_id, new_company_id),
      update_site_company_share.bind(null, old_company_id, new_company_id)
    ], function (err, results) {
      if (err) {
        callback(err);
      }
      else if (results) {
        callback(null, 'all facts linked to new company id ' + new_company_id);
      }
      else {
        callback(err);
      }
    });
  }
};

exports.test = function(req, res) {
  //testing area
}

function update_concession_operated_by(old_company_id, new_company_id, callback) {
  console.log("updating field 'concession_operated_by'");
  Concession.find({ 'concession_operated_by.company' : old_company_id })
  .exec(function(err, results) {
    if(err) {
      callback(err);
    }
    else if(results && results.length > 0) {
      async.eachLimit(results, 5, function(item, fcallback) {
        for(var index in item.concession_operated_by) {
          Concession.update(
            { _id: item._id },
            { "$set": { "concession_operated_by.company.$.company": new_company_id }},
            function(err, result) {
              if(err) {
                fcallback(err);
              }
              else if(result) {
                fcallback(null, "updated");
              }
              else {
                fcallback(err);
              }
            }
          );
        }
        console.log("updating field 'concession_operated_by'. DONE.");
      }, function(err) {
        callback(err);
      });
    }
    else callback(null, 'nothing to update');
  });
}

function update_concession_company_share(old_company_id, new_company_id, callback) {
  console.log("updating field 'concession_company_share'");
  Concession.find({ 'concession_company_share.company' : old_company_id })
  .populate('concession_company_share')
  .exec(function(err, results) {
    if(err) {
      callback(err);
    }
    else if(results && results.length > 0) {
      async.eachLimit(results, 5, function(item, fcallback) {
        for(var index in item.concession_operated_by.company) {
          Concession.update(
            { _id: item._id },
            { "$set": { "concession_company_share.company.$.company": new_company_id }},
            function(err, result) {
              if(err) {
                fcallback(err);
              }
              else if(result) {
                fcallback(null, "updated");
              }
              else {
                fcallback(err);
              }
            }
          );
        }
        console.log("updating field 'concession_company_share'. DONE.");
      }, function(err) {
        callback(err);
      });
    }
    else callback(null, 'nothing to update');
  });
}

function update_site_operated_by(old_company_id, new_company_id, callback) {
  console.log("updating field 'site_operated_by'");
  Site.find({ 'site_operated_by.company' : old_company_id })
  .populate('site_operated_by')
  .exec(function(err, results) {
    if(err) {
      callback(err);
    }
    else if(results && results.length > 0) {
      async.eachLimit(results, 5, function(item, fcallback) {
        for(var index in item.concession_operated_by.company) {
          Site.update(
            { _id: item._id },
            { "$set": { "site_operated_by.company.$.company": new_company_id }},
            function(err, result) {
              if(err) {
                fcallback(err);
              }
              else if(result) {
                fcallback(null, "updated");
              }
              else {
                fcallback(err);
              }
            }
          );
        }
        console.log("updating field 'site_operated_by'. DONE.");
      }, function(err) {
        callback(err);
      });
    }
    else callback(null, 'nothing to update');
  });
}

function update_site_company_share(old_company_id, new_company_id, callback) {
  console.log("updating field 'site_company_share'.");
  Site.find({ 'site_company_share.company' : old_company_id })
  .populate('site_company_share')
  .exec(function(err, results) {
    if(err) {
      callback(err);
    }
    else if(results && results.length > 0) {
      async.eachLimit(results, 5, function(item, fcallback) {
        for(var index in item.concession_operated_by.company) {
          Site.update(
            { _id: item._id },
            { "$set": { "site_company_share.company.$.company": new_company_id }},
            function(err, result) {
              if(err) {
                fcallback(err);
              }
              else if(result) {
                fcallback(null, "updated");
              }
              else {
                fcallback(err);
              }
            }
          );
        }
        console.log("updating field 'site_company_share'. DONE.");
      }, function(err) {
        callback(err);
      });
    }
    else callback(null, 'nothing to update');
  });
}

exports.getDuplicateByID = function(req, res) {

  async.waterfall([
    getDuplicate
  ], function (err, result) {
    if (err) {
      res.send(err);
    } else {
      if (req.query && req.query.callback) {
        return res.jsonp("" + req.query.callback + "(" + JSON.stringify(result) + ");");
      } else {
        return res.send(result);
      }
    }
  });

  function getDuplicate(callback) {
    Duplicate.findOne({ _id: req.params.id })
    .lean()
    .exec(function(err, duplicate) {
      if(duplicate) {
        callback(null, duplicate);
      } else {
        callback(err);
      }
    });
  }

};

exports.resolveAllDuplicates = function(req, res) {
  var type = req.params.type;

  async.waterfall([
    resolveEntity
  ], function (err, result) {
    if (err) {
      res.send(err);
    }
    else {
      res.send(result);
    }
  });

  function resolveEntity(callback) {
    console.log("== reconcile - resolve_all");
    Duplicate.find({resolved: false, entity:type}, function (err, result) {
          if (err) {
            callback(err);
          }
          else if(result) {
            _.each(result, function (duplicate) {
              duplicate.resolved = true;
              duplicate.resolved_date = Date.now();
              duplicate.save(function (err) {
              });
            });
            callback(null, {'data':'company duplicate resolved, just deleted'});
          }
          else {
            callback(err);
          }
        });
  };

};


text:
package com.leedarson.core.http.retrofit;

import android.util.Log;

import com.leedarson.core.http.retrofit.api.ApiStores;
import com.leedarson.core.http.retrofit.bean.Book;
import com.leedarson.core.http.retrofit.bean.HttpRequest;
import com.leedarson.core.http.retrofit.exception.ApiException;
import com.leedarson.core.http.retrofit.observer.HttpRxObservable;
import com.leedarson.core.http.retrofit.observer.HttpRxObserver;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * Created by hongyongfa on 2017/8/11.
 */

public class HttpManager {
    private HttpManager(){}
    private static class SigletonHolder{
        private static HttpManager INSTANCE=new HttpManager();
    }
    public static HttpManager getInstance(){
        return SigletonHolder.INSTANCE;
    }
    public void getSearcchBooks(String name,String tag,int start,int count){
        Observable<Book> bookObservable=RetrofitHelper.getInstance().getApiStores(ApiStores.class).getSearchBooks(name, tag, start, count);

    }
    public void getSearcchBooks2(LifecycleProvider<ActivityEvent> lifecycle,String name, String tag, int start, int count){
            //构建请求数据
        Map<String, Object> request = HttpRequest.getRequest();

        request.put("q", name);
//        request.put("tag", tag);
        request.put("start",start);
        request.put("count",count);

        HttpRxObserver httpRxObserver = new HttpRxObserver(ApiStores.BOOK_SEARCH + "getInfo") {

            @Override
            protected void onStart(Disposable d) {

            }

            @Override
            protected void onError(ApiException e) {
                Log.e("onError","onError code:" + e.getCode() + " msg:" + e.getMsg());

            }

            @Override
            protected void onSuccess(Object response) {
                Log.e("onSuccess","onSuccess response:" + response.toString());

            }
        };

        HttpRxObservable.getObservable2(RetrofitHelper.getInstance().getApiStores(ApiStores.class).getSearchBooks(request), lifecycle).subscribe(httpRxObserver);

    }
}


text:
#pragma once

#include <vector>
#include <atomic>

#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "hazelcast/util/export.h"
#include "hazelcast/client/member_selectors.h"
#include "hazelcast/client/proxy/ProxyImpl.h"
#include "hazelcast/client/member.h"
#include "hazelcast/client/spi/ClientContext.h"
#include "hazelcast/client/spi/impl/ClientInvocation.h"
#include "hazelcast/util/exception_util.h"
#include "hazelcast/client/spi/impl/ClientExecutionServiceImpl.h"

// CODECs
#include "hazelcast/client/protocol/codec/codecs.h"

#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#pragma warning(push)
#pragma warning(disable : 4251) // for dll export
#endif

namespace hazelcast {
namespace client {
/**
 * Distributed implementation of java.util.concurrent.ExecutorService.
 * IExecutorService provides additional methods like executing tasks
 * on a specific member, on a member who is owner of a specific key,
 * executing a tasks on multiple members.
 *
 */
class HAZELCAST_API iexecutor_service : public proxy::ProxyImpl
{
    friend class spi::ProxyManager;

public:
    static constexpr const char* SERVICE_NAME = "hz:impl:executorService";

    template<typename T>
    class executor_promise
    {
    public:
        executor_promise(spi::ClientContext& context)
          : context_(context)
        {}

        executor_promise(
          boost::future<boost::optional<T>>& future,
          boost::uuids::uuid uuid,
          int partition_id,
          boost::uuids::uuid member,
          spi::ClientContext& context,
          const std::shared_ptr<spi::impl::ClientInvocation>& invocation)
          : shared_future_(future.share())
          , uuid_(uuid)
          , partition_id_(partition_id)
          , member_uuid_(member)
          , context_(context)
          , invocation_(invocation)
        {}

        bool cancel(bool may_interrupt_if_running)
        {
            if (shared_future_.is_ready()) {
                return false;
            }

            try {
                return invoke_cancel_request(may_interrupt_if_running);
            } catch (exception::iexception&) {
                util::exception_util::rethrow(std::current_exception());
            }
            return false;
        }

        boost::shared_future<boost::optional<T>> get_future()
        {
            return shared_future_;
        }

    private:
        boost::shared_future<boost::optional<T>> shared_future_;
        boost::uuids::uuid uuid_;
        int partition_id_;
        boost::uuids::uuid member_uuid_;
        spi::ClientContext& context_;
        std::shared_ptr<spi::impl::ClientInvocation> invocation_;

        bool invoke_cancel_request(bool may_interrupt_if_running)
        {
            invocation_->wait_invoked();

            if (partition_id_ > -1) {
                auto request =
                  protocol::codec::executorservice_cancelonpartition_encode(
                    uuid_, may_interrupt_if_running);
                std::shared_ptr<spi::impl::ClientInvocation> clientInvocation =
                  spi::impl::ClientInvocation::create(
                    context_,
                    request,
                    boost::uuids::to_string(uuid_),
                    partition_id_);
                return clientInvocation->invoke()
                  .get()
                  .get_first_fixed_sized_field<bool>();
            } else {
                auto request =
                  protocol::codec::executorservice_cancelonmember_encode(
                    uuid_, member_uuid_, may_interrupt_if_running);
                std::shared_ptr<spi::impl::ClientInvocation> clientInvocation =
                  spi::impl::ClientInvocation::create(
                    context_,
                    request,
                    boost::uuids::to_string(uuid_),
                    member_uuid_);
                return clientInvocation->invoke()
                  .get()
                  .get_first_fixed_sized_field<bool>();
            }
        }
    };

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws rejected_execution if this task cannot be
     * accepted for execution
     */
    template<typename HazelcastSerializable>
    void execute(const HazelcastSerializable& command)
    {
        submit<HazelcastSerializable, executor_marker>(command);
    }

    /**
     * Executes a task on a randomly selected member.
     *
     * @param command        the task that is executed on a randomly selected
     * member
     * @param memberSelector memberSelector
     * @throws rejected_execution if no member is selected
     */
    template<typename HazelcastSerializable>
    void execute(const HazelcastSerializable& command,
                 const member_selector& member_selector)
    {
        std::vector<member> members = select_members(member_selector);
        int selectedMember = rand() % (int)members.size();
        execute_on_member<HazelcastSerializable>(command,
                                                 members[selectedMember]);
    }

    /**
     * Executes a task on the owner of the specified key.
     *
     * @param command a task executed on the owner of the specified key
     * @param key     the specified key
     */
    template<typename HazelcastSerializable, typename K>
    void execute_on_key_owner(const HazelcastSerializable& command,
                              const K& key)
    {
        submit_to_key_owner<HazelcastSerializable, K>(command, key);
    }

    /**
     * Executes a task on the specified member.
     *
     * @param command the task executed on the specified member
     * @param member  the specified member
     */
    template<typename HazelcastSerializable>
    void execute_on_member(const HazelcastSerializable& command,
                           const member& member)
    {
        submit_to_member<HazelcastSerializable, executor_marker>(command,
                                                                 member);
    }

    /**
     * Executes a task on each of the specified members.
     *
     * @param command the task executed on the specified members
     * @param members the specified members
     */
    template<typename HazelcastSerializable>
    void execute_on_members(const HazelcastSerializable& command,
                            const std::vector<member>& members)
    {
        for (std::vector<member>::const_iterator it = members.begin();
             it != members.end();
             ++it) {
            submit_to_member<HazelcastSerializable, executor_marker>(command,
                                                                     *it);
        }
    }

    /**
     * Executes a task on each of the selected members.
     *
     * @param command        a task executed on each of the selected members
     * @param memberSelector memberSelector
     * @throws rejected_execution if no member is selected
     */
    template<typename HazelcastSerializable>
    void execute_on_members(const HazelcastSerializable& command,
                            const member_selector& member_selector)
    {
        std::vector<member> members = select_members(member_selector);
        execute_on_members<HazelcastSerializable>(command, members);
    }

    /**
     * Executes a task on all of the known cluster members.
     *
     * @param command a task executed  on all of the known cluster members
     */
    template<typename HazelcastSerializable>
    void execute_on_all_members(const HazelcastSerializable& command)
    {
        std::vector<member> memberList =
          get_context().get_client_cluster_service().get_member_list();
        for (std::vector<member>::const_iterator it = memberList.begin();
             it != memberList.end();
             ++it) {
            submit_to_member<HazelcastSerializable, executor_marker>(command,
                                                                     *it);
        }
    }

    /**
     * Submits a task to the owner of the specified key and returns a
     * executor_promise representing that task.
     *
     * @param task task submitted to the owner of the specified key
     * @param key  the specified key
     * @param <T>  the result type of callable
     * @return a executor_promise representing pending completion of the task
     */
    template<typename HazelcastSerializable, typename T, typename K>
    executor_promise<T> submit_to_key_owner(const HazelcastSerializable& task,
                                            const K& key)
    {
        return submit_to_key_owner_internal<HazelcastSerializable, T, K>(
          task, key, false);
    }

    /**
     * Submits a task to the specified member and returns a executor_promise
     * representing that task.
     *
     * @param task   the task submitted to the specified member
     * @param member the specified member
     * @param <T>    the result type of callable
     * @return a executor_promise representing pending completion of the task
     */
    template<typename HazelcastSerializable, typename T>
    executor_promise<T> submit_to_member(const HazelcastSerializable& task,
                                         const member& member)
    {
        return submit_to_target_internal<HazelcastSerializable, T>(
          task, member, false);
    }

    /**
     * Submits a task to given members and returns
     * map of Member-executor_promise pairs representing pending completion of
     * the task on each member
     *
     * @param task    the task submitted to given members
     * @param members the given members
     * @param <T>     the result type of callable
     * @return map of Member-executor_promise pairs representing pending
     * completion of the task on each member
     */
    template<typename HazelcastSerializable, typename T>
    std::unordered_map<member, executor_promise<T>> submit_to_members(
      const HazelcastSerializable& task,
      const std::vector<member>& members)
    {
        std::unordered_map<member, executor_promise<T>> futureMap;
        for (auto& member : members) {
            auto f = submit_to_target_internal<HazelcastSerializable, T>(
              task, member, true);
            // no need to check if emplace is success since member is unique
            futureMap.emplace(member, std::move(f));
        }
        return futureMap;
    }

    /**
     * Submits a task to selected members and returns a
     * map of Member-executor_promise pairs representing pending completion of
     * the task on each member.
     *
     * @param task           the task submitted to selected members
     * @param memberSelector memberSelector
     * @param <T>            the result type of callable
     * @return map of Member-executor_promise pairs representing pending
     * completion of the task on each member
     * @throws rejected_execution if no member is selected
     */
    template<typename HazelcastSerializable, typename T>
    std::unordered_map<member, executor_promise<T>> submit_to_members(
      const HazelcastSerializable& task,
      const member_selector& member_selector)
    {
        std::vector<member> members = select_members(member_selector);
        return submit_to_members<HazelcastSerializable, T>(task, members);
    }

    /**
     * Submits task to all cluster members and returns a
     * map of Member-executor_promise pairs representing pending completion of
     * the task on each member.
     *
     * @param task the task submitted to all cluster members
     * @param <T>  the result type of callable
     * @return map of Member-executor_promise pairs representing pending
     * completion of the task on each member
     */
    template<typename HazelcastSerializable, typename T>
    std::unordered_map<member, executor_promise<T>> submit_to_all_members(
      const HazelcastSerializable& task)
    {
        std::unordered_map<member, executor_promise<T>> futureMap;
        for (const auto& m :
             get_context().get_client_cluster_service().get_member_list()) {
            auto f = submit_to_target_internal<HazelcastSerializable, T>(
              task, m, true);
            // no need to check if emplace is success since member is unique
            futureMap.emplace(m, std::move(f));
        }
        return futureMap;
    }

    /**
     * Submits a task for execution and returns a executor_promise
     * representing that task. The executor_promise's {@code
     * executor_promise::get} method will return the given result upon
     * successful completion.
     *
     * @param task the task to submit
     * @param result the result to return
     * @param <T> the type of the result
     * @return a executor_promise representing pending completion of the task
     * @throws rejected_execution if the task cannot be
     *         scheduled for execution
     * @throws null_pointer if the task is null
     */
    template<typename HazelcastSerializable, typename T>
    executor_promise<T> submit(const HazelcastSerializable& task)
    {
        serialization::pimpl::data task_data =
          to_data<HazelcastSerializable>(task);

        if (task_data.has_partition_hash()) {
            int partitionId = get_partition_id(task_data);

            return submit_to_partition_internal<T>(
              task_data, false, partitionId);
        } else {
            return submit_to_random_internal<T>(task_data, false);
        }
    }

    /**
     * Submits a task to a randomly selected member and returns a
     * executor_promise representing that task.
     *
     * @param task           task submitted to a randomly selected member
     * @param memberSelector memberSelector
     * @param <T>            the result type of callable
     * @return a executor_promise representing pending completion of the task
     * @throws rejected_execution if no member is selected
     */
    template<typename HazelcastSerializable, typename T>
    executor_promise<T> submit(const HazelcastSerializable& task,
                               const member_selector& member_selector)
    {
        std::vector<member> members = select_members(member_selector);
        int selectedMember = rand() % (int)members.size();
        return submit_to_member<HazelcastSerializable, T>(
          task, members[selectedMember]);
    }

    /**
     * Initiates an orderly shutdown in which previously submitted
     * tasks are executed, but no new tasks will be accepted.
     * Invocation has no additional effect if already shut down.
     *
     * <p>This method does not wait for previously submitted tasks to
     * complete execution.
     *
     */
    void shutdown();

    /**
     * Returns {@code true} if this executor has been shut down.
     *
     * @return {@code true} if this executor has been shut down
     */
    boost::future<bool> is_shutdown();

    /**
     * Returns {@code true} if all tasks have completed following shut down.
     * Note that {@code isTerminated} is never {@code true} unless
     * either {@code shutdown}.
     *
     * @return {@code true} if all tasks have completed following shut down
     */
    boost::future<bool> is_terminated();

private:
    iexecutor_service(const std::string& name, spi::ClientContext* context);

    struct executor_marker
    {};

    std::vector<member> select_members(const member_selector& member_selector);

    template<typename T>
    executor_promise<T> submit_to_partition_internal(
      const serialization::pimpl::data& task_data,
      bool prevent_sync,
      int partition_id)
    {
        auto uuid = context_.random_uuid();

        auto f = invoke_on_partition_internal(task_data, partition_id, uuid);

        return check_sync<T>(f, uuid, partition_id, prevent_sync);
    }

    std::pair<boost::future<protocol::ClientMessage>,
              std::shared_ptr<spi::impl::ClientInvocation>>
    invoke_on_partition_internal(const serialization::pimpl::data& task_data,
                                 int partition_id,
                                 boost::uuids::uuid uuid)
    {
        return invoke_on_partition_owner(
          protocol::codec::executorservice_submittopartition_encode(
            name_, uuid, task_data),
          partition_id);
    }

    template<typename HazelcastSerializable, typename T, typename K>
    executor_promise<T> submit_to_key_owner_internal(
      const HazelcastSerializable& task,
      const K& key,
      bool prevent_sync)
    {

        serialization::pimpl::data dataKey = to_data<K>(key);

        int partitionId = get_partition_id(dataKey);

        return submit_to_partition_internal<T>(
          to_data<HazelcastSerializable>(task), prevent_sync, partitionId);
    }

    template<typename T>
    executor_promise<T> submit_to_random_internal(
      const serialization::pimpl::data& task_data,
      bool prevent_sync)
    {

        int partitionId = random_partition_id();

        return submit_to_partition_internal<T>(
          task_data, prevent_sync, partitionId);
    }

    template<typename HazelcastSerializable, typename T>
    executor_promise<T> submit_to_target_internal(
      const HazelcastSerializable& task,
      const member& member,
      bool prevent_sync)
    {
        boost::uuids::uuid uuid = context_.random_uuid();

        auto f =
          invoke_on_target_internal<HazelcastSerializable>(task, member, uuid);

        return check_sync<T>(f, uuid, -1, member, prevent_sync);
    }

    template<typename HazelcastSerializable>
    std::pair<boost::future<protocol::ClientMessage>,
              std::shared_ptr<spi::impl::ClientInvocation>>
    invoke_on_target_internal(const HazelcastSerializable& task,
                              const member& member,
                              boost::uuids::uuid uuid)
    {
        return invoke_on_target(
          protocol::codec::executorservice_submittomember_encode(
            name_, uuid, to_data(task), member.get_uuid()),
          member.get_uuid());
    }

    std::pair<boost::future<protocol::ClientMessage>,
              std::shared_ptr<spi::impl::ClientInvocation>>
    invoke_on_partition_owner(protocol::ClientMessage&& request,
                              int partition_id);

    std::pair<boost::future<protocol::ClientMessage>,
              std::shared_ptr<spi::impl::ClientInvocation>>
    invoke_on_target(protocol::ClientMessage&& request,
                     boost::uuids::uuid target);

    template<typename T>
    executor_promise<T> check_sync(
      std::pair<boost::future<protocol::ClientMessage>,
                std::shared_ptr<spi::impl::ClientInvocation>>& future_pair,
      boost::uuids::uuid uuid,
      int partition_id,
      bool prevent_sync)
    {
        return check_sync<T>(
          future_pair, uuid, partition_id, member(), prevent_sync);
    }

    template<typename T>
    typename std::enable_if<!std::is_same<executor_marker, T>::value,
                            executor_promise<T>>::type
    check_sync(
      std::pair<boost::future<protocol::ClientMessage>,
                std::shared_ptr<spi::impl::ClientInvocation>>& future_pair,
      boost::uuids::uuid uuid,
      int partition_id,
      const member& member,
      bool prevent_sync)
    {
        bool sync = is_sync_computation(prevent_sync);
        auto objectFuture = to_object<T>(
          decode<serialization::pimpl::data>(std::move(future_pair.first)));
        if (sync) {
            objectFuture.wait();
        }

        return executor_promise<T>(objectFuture,
                                   uuid,
                                   partition_id,
                                   member.get_uuid(),
                                   get_context(),
                                   future_pair.second);
    }

    template<typename T>
    typename std::enable_if<std::is_same<executor_marker, T>::value,
                            executor_promise<T>>::type
    check_sync(
      std::pair<boost::future<protocol::ClientMessage>,
                std::shared_ptr<spi::impl::ClientInvocation>>& future_pair,
      boost::uuids::uuid uuid,
      int partition_id,
      const member& member,
      bool prevent_sync)
    {
        bool sync = is_sync_computation(prevent_sync);
        if (sync) {
            future_pair.first.get();
        }

        return executor_promise<T>(get_context());
    }

    bool is_sync_computation(bool prevent_sync);

    address get_member_address(const member& member);

    int random_partition_id();

    static const int32_t MIN_TIME_RESOLUTION_OF_CONSECUTIVE_SUBMITS = 10;
    static const int32_t MAX_CONSECUTIVE_SUBMITS = 100;

    std::atomic<int32_t> consecutive_submits_;
    std::atomic<int64_t> last_submit_time_;
};
} // namespace client
} // namespace hazelcast

#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#pragma warning(pop)
#endif


text:
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

class LinkList:
    def __init__(self):
        self.head = None

    def push(self, val):
        node = Node(val)
        if self.head:
            node.next = self.head
            self.head = node
        else:
            self.head = node

    def printList(self):
        p = self.head
        while p:
            print p.val,
            p = p.next
        print

def mergeSort(head):
    if not head:
        return
    if not head.next:
        return

    slow = head
    fast = head.next
    while fast:
        fast = fast.next
        if fast:
            slow = slow.next
            fast = fast.next
    # 2 3 20 5 10 15
    frontHalf = head
    backHalf = slow.next
    slow.next = None
    mergeSort(frontHalf)
    mergeSort(backHalf)
    head = sortedMerge(frontHalf, backHalf)
    return head

def sortedMerge(a, b):
    if not a:
        return b
    elif not b:
        return a
    temp = None
    if a.val <= b.val:
        temp = a
        a.next = sortedMerge(temp.next, b)
        return a
    else:
        temp = b
        b.next = sortedMerge(a, temp.next)
        return b

ll = LinkList()
ll.push(15)
ll.push(10)
ll.push(5)
ll.push(20)
ll.push(3)
ll.push(2)

ll.printList()

ll.head = mergeSort(ll.head)

ll.printList()


text:
'use strict';
var events = require('events');
var util = require('util');
var duplexer = require('duplexer');
var spawn = require('child_process').spawn;
var split = require('split');
var through = require('through2');
var parser = require('./parser');
var slug = require('to-slug-case');
var shellescape = require('shell-escape');

function parseOpts(options) {
    var flags = [], opts = options || {}, val;
    for (var key in opts) {
        val = opts[key];
        val = val === true ? '' : ('=' + shellescape([val]));

        flags.push('--' + slug(key) + val);
    }

    return flags;
}

module.exports = function(opts) {
    var proc   = spawn('aspell', ['-a'].concat(parseOpts(opts)));
    var stream = duplexer(proc.stdin, proc.stdout);

    proc.stdout
        .pipe(split())
        .pipe(through(function(chunk, enc, cb) {
            var result = parser(chunk.toString());
            stream.emit(result.type, result);
            cb();
        }));

    util.inherits(stream, events.EventEmitter);
    return stream;
};


text:
package hype.extended.colorist;

import hype.H;
import hype.interfaces.HColorist;
import hype.HDrawable;
import hype.HColors;
import hype.HMath;
import processing.core.PVector;

import java.util.ArrayList;

public class HColorField implements HColorist {
	private ArrayList<HColorPoint> colorPoints;
	private float maxDist;
	private boolean appliesFill, appliesStroke, appliesAlpha;

	public HColorField() {
		this(H.app().width, H.app().height);
	}

	public HColorField(float xBound, float yBound) {
		this( (float) Math.sqrt(xBound*xBound + yBound*yBound) );
	}

	public HColorField(float maximumDistance) {
		colorPoints = new ArrayList<HColorField.HColorPoint>();
		maxDist = maximumDistance;
		fillAndStroke();
	}

	public HColorField addPoint(PVector loc, int clr, float radius) {
		return addPoint(loc.x,loc.y, clr, radius);
	}

	public HColorField addPoint(float x, float y, int clr, float radius) {
		HColorPoint pt = new HColorPoint();
		pt.x = x;
		pt.y = y;
		pt.radius = radius;
		pt.clr = clr;
		colorPoints.add(pt);
		return this;
	}

	public int getColor(float x, float y, int baseColor) {
		int[] baseClrs = HColors.explode(baseColor);
		int[] maxClrs = new int[4];

		int initJ;
		if(appliesAlpha) {
			initJ = 0;
		} else { // make the loop skip alpha and use baseClrs' alpha instead
			initJ = 1;
			maxClrs[0] = baseClrs[0];
		}

		for(int i=0; i< colorPoints.size(); ++i) {
			HColorPoint pt = colorPoints.get(i);

			int[] ptClrs = HColors.explode(pt.clr);

			// Get the adjusted distance between the two points.
			float distLimit = maxDist * pt.radius;
			float dist = HMath.dist(x,y, pt.x,pt.y);
			if(dist > distLimit)
				dist = distLimit;

			// Compute the color based on the distance from the color point.
			for(int j=initJ; j<4; ++j) {
				int newClrVal = Math.round(
					HMath.map(dist, 0,distLimit, ptClrs[j], baseClrs[j]));

				if(newClrVal > maxClrs[j])
					maxClrs[j] = newClrVal;
			}
		}
		return HColors.merge(maxClrs[0],maxClrs[1],maxClrs[2],maxClrs[3]);
	}

	public HColorField appliesAlpha(boolean b) {
		appliesAlpha = b;
		return this;
	}

	public boolean appliesAlpha() {
		return appliesAlpha;
	}

	@Override
	public HColorField fillOnly() {
		appliesFill = true;
		appliesStroke = false;
		return this;
	}

	@Override
	public HColorField strokeOnly() {
		appliesFill = false;
		appliesStroke = true;
		return this;
	}

	@Override
	public HColorField fillAndStroke() {
		appliesFill = appliesStroke = true;
		return this;
	}

	@Override
	public boolean appliesFill() {
		return appliesFill;
	}

	@Override
	public boolean appliesStroke() {
		return appliesStroke;
	}

	@Override
	public HDrawable applyColor(HDrawable drawable) {
		float x = drawable.x();
		float y = drawable.y();

		if(appliesFill) {
			int baseFill = drawable.fill();
			drawable.fill( getColor(x,y, baseFill) );
		}
		if(appliesStroke) {
			int baseStroke = drawable.stroke();
			drawable.stroke( getColor(x,y, baseStroke) );
		}
		return drawable;
	}

	public static class HColorPoint {
		public float x, y, radius;
		public int clr;
	}
}


text:
package com.btmura.android.reddit.app;

interface ThingActionModeController extends ActionModeController {

  boolean isSwipeable(int position);

  void swipe(int position);

  void vote(int position, int action);
}


text:
package com.manning.hsia.dvdstore.test;

import java.lang.reflect.Proxy;
import java.util.List;

import org.hibernate.Transaction;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.testng.annotations.Test;

import com.manning.hsia.dvdstore.action.ItemAction;
import com.manning.hsia.dvdstore.action.ItemActionImpl;
import com.manning.hsia.dvdstore.model.Item;
import com.manning.hsia.dvdstore.util.SessionInvocationHandler;
import com.manning.hsia.dvdstore.util.TestCase;

public class ItemActionTest extends TestCase {

	@Test(groups="ch06")
	public void testIdentity() {
		ItemAction identity = getItemAction();
		identity.loadItem(1);
	}

	private ItemAction getItemAction() {
		ItemAction action = new ItemActionImpl();
		return (ItemAction) Proxy.newProxyInstance(
					this.getClass().getClassLoader(),
					new Class[] { ItemAction.class },
					new SessionInvocationHandler(action, factory) );
	}

	@Test(groups="ch06")
	public void testSimpleQuery() {
		ItemAction identity = getItemAction();
		assert 2 == identity.findByTitle("batman").size() :
			"Wrong numbr of matching results. Found " + identity.findByTitle("batman").size();
	}

	@Override
	public void postSetUp() throws Exception {
		FullTextSession session = Search.getFullTextSession( factory.openSession() );
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			//manual indexing solution OK for small amounts of data
			List results = session.createCriteria( Item.class ).list();
			for (Object entity : results) {
			    session.index( entity ); //index each element
			}
			//commit the index changes
			tx.commit();
		}
		finally {
			session.close();
		}
	}

}