text:
package com.graphhopper.routing.weighting;

import com.graphhopper.Repeat;
import com.graphhopper.RepeatRule;
import com.graphhopper.routing.*;
import com.graphhopper.routing.ch.PrepareContractionHierarchies;
import com.graphhopper.routing.lm.PrepareLandmarks;
import com.graphhopper.routing.querygraph.QueryGraph;
import com.graphhopper.routing.util.*;
import com.graphhopper.storage.*;
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.storage.index.LocationIndexTree;
import com.graphhopper.storage.index.QueryResult;
import com.graphhopper.util.CHEdgeIteratorState;
import com.graphhopper.util.EdgeExplorer;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.GHUtility;
import com.graphhopper.util.shapes.BBox;
import com.graphhopper.util.shapes.GHPoint;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.*;

import static com.graphhopper.routing.weighting.Weighting.INFINITE_U_TURN_COSTS;
import static com.graphhopper.util.EdgeIterator.ANY_EDGE;
import static com.graphhopper.util.EdgeIterator.NO_EDGE;
import static com.graphhopper.util.Parameters.Algorithms.ASTAR_BI;
import static com.graphhopper.util.Parameters.Algorithms.DIJKSTRA_BI;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * This test makes sure the different bidirectional routing algorithms correctly implement restrictions of the source/
 * target edges, by comparing with {@link DijkstraBidirectionRef}
 *
 * @author easbar
 * @see RandomizedRoutingTest
 * @see DirectedBidirectionalDijkstraTest
 */
@RunWith(Parameterized.class)
public class DirectedRoutingTest {
    private final Algo algo;
    private final int uTurnCosts;
    private final boolean prepareCH;
    private final boolean prepareLM;
    private Directory dir;
    private GraphHopperStorage graph;
    private CHProfile chProfile;
    private CHGraph chGraph;
    private CarFlagEncoder encoder;
    private TurnCostStorage turnCostStorage;
    private int maxTurnCosts;
    private Weighting weighting;
    private EncodingManager encodingManager;
    private PrepareContractionHierarchies pch;
    private PrepareLandmarks lm;

    @Rule
    public RepeatRule repeatRule = new RepeatRule();

    @Parameterized.Parameters(name = "{0}, u-turn-costs: {1}, prepareCH: {2}, prepareLM: {3}")
    public static Collection<Object[]> params() {
        return Arrays.asList(new Object[][]{
                {Algo.ASTAR, INFINITE_U_TURN_COSTS, false, false},
                {Algo.CH_ASTAR, INFINITE_U_TURN_COSTS, true, false},
                {Algo.CH_DIJKSTRA, INFINITE_U_TURN_COSTS, true, false},
                // todo: yields warnings and fails, see #1665, #1687, #1745
//                {Algo.LM, INFINITE_UTURN_COSTS, false, true}
                {Algo.ASTAR, 40, false, false},
                {Algo.CH_ASTAR, 40, true, false},
                {Algo.CH_DIJKSTRA, 40, true, false},
                // todo: yields warnings and fails, see #1665, 1687, #1745
//                {Algo.LM, 40, false, true}
                // todo: add AlternativeRoute ?
        });
    }

    private enum Algo {
        ASTAR,
        CH_ASTAR,
        CH_DIJKSTRA,
        LM
    }

    public DirectedRoutingTest(Algo algo, int uTurnCosts, boolean prepareCH, boolean prepareLM) {
        this.algo = algo;
        this.uTurnCosts = uTurnCosts;
        this.prepareCH = prepareCH;
        this.prepareLM = prepareLM;
    }

    @Before
    public void init() {
        dir = new RAMDirectory();
        maxTurnCosts = 10;
        // todonow: make this work with speed_both_directions=true!
        encoder = new CarFlagEncoder(5, 5, maxTurnCosts);
        encodingManager = EncodingManager.create(encoder);
        graph = new GraphBuilder(encodingManager).setDir(dir).withTurnCosts(true).build();
        turnCostStorage = graph.getTurnCostStorage();
        weighting = new FastestWeighting(encoder, new DefaultTurnCostProvider(encoder, turnCostStorage, uTurnCosts));
        chProfile = CHProfile.edgeBased(weighting);
        graph.addCHGraph(chProfile);
        graph.create(1000);
    }

    private void preProcessGraph() {
        graph.freeze();
        if (!prepareCH && !prepareLM) {
            return;
        }
        if (prepareCH) {
            pch = PrepareContractionHierarchies.fromGraphHopperStorage(graph, chProfile);
            pch.doWork();
            chGraph = graph.getCHGraph(chProfile);
        }
        if (prepareLM) {
            lm = new PrepareLandmarks(dir, graph, weighting, 16, 8);
            lm.setMaximumWeight(1000);
            lm.doWork();
        }
    }

    private BidirRoutingAlgorithm createAlgo() {
        return createAlgo(prepareCH ? chGraph : graph);
    }

    private BidirRoutingAlgorithm createAlgo(Graph graph) {
        switch (algo) {
            case ASTAR:
                return new AStarBidirection(graph, graph.wrapWeighting(weighting), TraversalMode.EDGE_BASED);
            case CH_DIJKSTRA:
                return (BidirRoutingAlgorithm) pch.getRoutingAlgorithmFactory().createAlgo(graph, AlgorithmOptions.start().weighting(weighting).algorithm(DIJKSTRA_BI).build());
            case CH_ASTAR:
                return (BidirRoutingAlgorithm) pch.getRoutingAlgorithmFactory().createAlgo(graph, AlgorithmOptions.start().weighting(weighting).algorithm(ASTAR_BI).build());
            case LM:
                AStarBidirection astarbi = new AStarBidirection(graph, graph.wrapWeighting(weighting), TraversalMode.EDGE_BASED);
                return (BidirRoutingAlgorithm) lm.getPreparedRoutingAlgorithm(graph, astarbi, AlgorithmOptions.start().build());
            default:
                throw new IllegalArgumentException("unknown algo " + algo);
        }
    }

    @Test
    @Repeat(times = 10)
    public void randomGraph() {
        final long seed = System.nanoTime();
        System.out.println("random Graph seed: " + seed);
        final int numQueries = 50;
        Random rnd = new Random(seed);
        GHUtility.buildRandomGraph(graph, rnd, 100, 2.2, true, true, encoder.getAverageSpeedEnc(), 0.7, 0.8, 0.8);
        GHUtility.addRandomTurnCosts(graph, seed, encodingManager, encoder, maxTurnCosts, turnCostStorage);
//        GHUtility.printGraphForUnitTest(graph, encoder);
        preProcessGraph();
        List<String> strictViolations = new ArrayList<>();
        for (int i = 0; i < numQueries; i++) {
            int source = getRandom(rnd);
            int target = getRandom(rnd);
            int sourceOutEdge = getSourceOutEdge(rnd, source, graph);
            int targetInEdge = getTargetInEdge(rnd, target, graph);
//            System.out.println("source: " + source + ", target: " + target + ", sourceOutEdge: " + sourceOutEdge + ", targetInEdge: " + targetInEdge);
            Path refPath = new DijkstraBidirectionRef(graph, ((Graph) graph).wrapWeighting(weighting), TraversalMode.EDGE_BASED)
                    .calcPath(source, target, sourceOutEdge, targetInEdge);
            Path path = createAlgo()
                    .calcPath(source, target, sourceOutEdge, targetInEdge);
            // do not check nodes, because there can be ambiguity when there are zero weight loops
            strictViolations.addAll(comparePaths(refPath, path, source, target, false));
        }
        // sometimes there are multiple best paths with different distance/time, if this happens too often something
        // is wrong and we fail
        if (strictViolations.size() > Math.max(1, 0.05 * numQueries)) {
            for (String strictViolation : strictViolations) {
                System.out.println("strict violation: " + strictViolation);
            }
            fail("Too many strict violations: " + strictViolations.size() + " / " + numQueries);
        }
    }

    /**
     * Similar to {@link #randomGraph()}, but using the {@link QueryGraph} as it is done in real usage.
     */
    @Test
    @Repeat(times = 10)
    public void randomGraph_withQueryGraph() {
        final long seed = System.nanoTime();
        System.out.println("randomGraph_withQueryGraph seed: " + seed);
        final int numQueries = 50;

        // we may not use an offset when query graph is involved, otherwise traveling via virtual edges will not be
        // the same as taking the direct edge!
        double pOffset = 0;
        Random rnd = new Random(seed);
        GHUtility.buildRandomGraph(graph, rnd, 50, 2.2, true, true, encoder.getAverageSpeedEnc(), 0.7, 0.8, pOffset);
        GHUtility.addRandomTurnCosts(graph, seed, encodingManager, encoder, maxTurnCosts, turnCostStorage);
        // GHUtility.printGraphForUnitTest(graph, encoder);
        preProcessGraph();
        LocationIndexTree index = new LocationIndexTree(graph, dir);
        index.prepareIndex();
        List<String> strictViolations = new ArrayList<>();
        for (int i = 0; i < numQueries; i++) {
            List<GHPoint> points = getRandomPoints(2, index, rnd);

            List<QueryResult> chQueryResults = findQueryResults(index, points);
            List<QueryResult> queryResults = findQueryResults(index, points);

            QueryGraph chQueryGraph = QueryGraph.lookup(prepareCH ? chGraph : graph, chQueryResults);
            QueryGraph queryGraph = QueryGraph.lookup(graph, queryResults);

            int source = queryResults.get(0).getClosestNode();
            int target = queryResults.get(1).getClosestNode();
            Random tmpRnd1 = new Random(seed);
            int sourceOutEdge = getSourceOutEdge(tmpRnd1, source, queryGraph);
            int targetInEdge = getTargetInEdge(tmpRnd1, target, queryGraph);
            Random tmpRnd2 = new Random(seed);
            int chSourceOutEdge = getSourceOutEdge(tmpRnd2, source, chQueryGraph);
            int chTargetInEdge = getTargetInEdge(tmpRnd2, target, chQueryGraph);

            Path refPath = new DijkstraBidirectionRef(queryGraph, ((Graph) queryGraph).wrapWeighting(weighting), TraversalMode.EDGE_BASED)
                    .calcPath(source, target, sourceOutEdge, targetInEdge);
            Path path = createAlgo(chQueryGraph)
                    .calcPath(source, target, chSourceOutEdge, chTargetInEdge);

            // do not check nodes, because there can be ambiguity when there are zero weight loops
            strictViolations.addAll(comparePaths(refPath, path, source, target, false));
        }
        // sometimes there are multiple best paths with different distance/time, if this happens too often something
        // is wrong and we fail
        if (strictViolations.size() > Math.max(1, 0.05 * numQueries)) {
            fail("Too many strict violations: " + strictViolations.size() + " / " + numQueries);
        }
    }

    private List<GHPoint> getRandomPoints(int numPoints, LocationIndex index, Random rnd) {
        List<GHPoint> points = new ArrayList<>(numPoints);
        BBox bounds = graph.getBounds();
        final int maxAttempts = 100 * numPoints;
        int attempts = 0;
        while (attempts < maxAttempts && points.size() < numPoints) {
            double lat = rnd.nextDouble() * (bounds.maxLat - bounds.minLat) + bounds.minLat;
            double lon = rnd.nextDouble() * (bounds.maxLon - bounds.minLon) + bounds.minLon;
            QueryResult queryResult = index.findClosest(lat, lon, EdgeFilter.ALL_EDGES);
            if (queryResult.isValid()) {
                points.add(new GHPoint(lat, lon));
            }
            attempts++;
        }
        assertEquals("could not find valid random points after " + attempts + " attempts", numPoints, points.size());
        return points;
    }

    private List<QueryResult> findQueryResults(LocationIndexTree index, List<GHPoint> ghPoints) {
        List<QueryResult> result = new ArrayList<>(ghPoints.size());
        for (GHPoint ghPoint : ghPoints) {
            result.add(index.findClosest(ghPoint.getLat(), ghPoint.getLon(), DefaultEdgeFilter.ALL_EDGES));
        }
        return result;
    }

    private List<String> comparePaths(Path refPath, Path path, int source, int target, boolean checkNodes) {
        List<String> strictViolations = new ArrayList<>();
        double refWeight = refPath.getWeight();
        double weight = path.getWeight();
        if (Math.abs(refWeight - weight) > 1.e-2) {
            System.out.println("expected: " + refPath.calcNodes());
            System.out.println("given:    " + path.calcNodes());
            fail("wrong weight: " + source + "->" + target + ", expected: " + refWeight + ", given: " + weight);
        }
        if (Math.abs(path.getDistance() - refPath.getDistance()) > 1.e-1) {
            strictViolations.add("wrong distance " + source + "->" + target + ", expected: " + refPath.getDistance() + ", given: " + path.getDistance());
        }
        if (Math.abs(path.getTime() - refPath.getTime()) > 50) {
            strictViolations.add("wrong time " + source + "->" + target + ", expected: " + refPath.getTime() + ", given: " + path.getTime());
        }
        if (checkNodes && !refPath.calcNodes().equals(path.calcNodes())) {
            strictViolations.add("wrong nodes " + source + "->" + target + "\nexpected: " + refPath.calcNodes() + "\ngiven:    " + path.calcNodes());
        }
        return strictViolations;
    }

    private int getTargetInEdge(Random rnd, int node, Graph graph) {
        return getAdjEdge(rnd, node, graph);
    }

    private int getSourceOutEdge(Random rnd, int node, Graph graph) {
        return getAdjEdge(rnd, node, graph);
    }

    private int getAdjEdge(Random rnd, int node, Graph graph) {
        // sometimes do not restrict anything
        if (rnd.nextDouble() < 0.05) {
            return ANY_EDGE;
        }
        // sometimes use NO_EDGE
        if (rnd.nextDouble() < 0.05) {
            return NO_EDGE;
        }
        // use all edge explorer, sometimes we will find an edge we can restrict sometimes we do not
        EdgeExplorer explorer = graph.createEdgeExplorer();
        EdgeIterator iter = explorer.setBaseNode(node);
        List<Integer> edgeIds = new ArrayList<>();
        while (iter.next()) {
            if (iter instanceof CHEdgeIteratorState && ((CHEdgeIteratorState) iter).isShortcut()) {
                // skip shortcuts here so we get the same restricted edges for a normal query graph and a
                // query graph that wraps a CH graph (provided that the rnd number generator is in the same
                // state)!
                continue;
            }
            edgeIds.add(iter.getOrigEdgeFirst());
            edgeIds.add(iter.getOrigEdgeLast());
        }
        return edgeIds.isEmpty() ? ANY_EDGE : edgeIds.get(rnd.nextInt(edgeIds.size()));
    }

    private int getRandom(Random rnd) {
        return rnd.nextInt(graph.getNodes());
    }

}


text:
export class Player {

    currency: number;
    personel: number;
    order: number;
    childrenHappiness: number;

}

redpajama_set_name: RedPajamaGithub


text:
function obj = setDegreeFile( obj, file )
% SETDEGREEFILE  Set files for the kernel degree in an
% nlsaDiffusionOperator_batch object
%
% Modified 2016/01/25

if isa( file, 'nlsaFilelist' )
    if ~isCompatible( file, getPartition( obj ) )
        error( 'Incompatible file list' )
    end
    obj.fileD = file;
else
    obj.fileD = setFile( obj.fileD, file );
end


text:
using LinqInfer.Maths;
using NUnit.Framework;

namespace LinqInfer.UnitTests.Maths
{
    [TestFixture]
    public class SoftmaxTests : TestFixtureBase
    {
        [Test]
        public void Apply_ReturnsCorrectTypeAndValues()
        {
            var softmax = new Softmax(3);

            var result = softmax.Apply(ColumnVector1D.Create(0.35, 0.78, 1.12));

            Assert.That(result, Is.InstanceOf<ColumnVector1D>());

            Assert.That(result[0], IsAround(0.2129));
            Assert.That(result[1], IsAround(0.32728));
            Assert.That(result[2], IsAround(0.45981));
        }
    }
}


text:
#pragma once

#include "game/state/stateobject.h"
#include "library/sp.h"
#include "library/vec.h"

namespace OpenApoc
{
class TileObjectDoodad;
class TileMap;
class DoodadType;
class Image;
class GameState;
class VoxelMap;

/* A doodad is a visual only effect (IE doesn't change the game state) for
 * animated sprites, like hit animations/explosions etc. They do not move(?) */
class Doodad : public std::enable_shared_from_this<Doodad>
{
  public:
	Doodad() = default;
	~Doodad() = default;

	Doodad(Vec3<float> position, Vec2<int> imageOffset, bool temporary, int lifetime,
	       sp<Image> image);
	Doodad(Vec3<float> position, StateRef<DoodadType> type);

	sp<Image> getSprite();
	const Vec2<int> &getImageOffset() const { return this->imageOffset; }
	void update(GameState &state, int ticks);
	const Vec3<float> &getPosition() const { return this->position; }

	void setPosition(Vec3<float> position);

	void remove(GameState &state);

	sp<TileObjectDoodad> tileObject;

	Vec3<float> position = {0, 0, 0};
	Vec2<int> imageOffset = {0, 0};
	bool temporary = false;
	int age = 0;
	int lifetime = 0;
	sp<VoxelMap> voxelMap;
	// A doodad is either a single image sprite
	sp<Image> sprite;
	// Or a DoodadType containing an animation
	StateRef<DoodadType> type;
};

} // namespace OpenApoc


text:
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from sklearn.metrics import mean_squared_error

# Fix the number of samples and our seed
NUM_SAMPLES = 200
np.random.seed(42)

# Our "true function"
def f(x):
    return 1.5*x + 0.5

#Construct array of (x,f(x))-pairs where x is sampled randomly from unit interval
data = np.array([[x,f(x) ] for x in np.random.random(NUM_SAMPLES)])

# Create regular grid of x values and the values of f
gridx = np.linspace(0, 1, 200)
gridy = np.array([f(x) for x in gridx])

# Add Gaussian noise with sigma=0.6
normaly = data[:,1]+0.6*np.random.randn(NUM_SAMPLES)

#Plot the messy data
plt.scatter(data[:,0], normaly )
plt.title("Scatter plot of synthetic data with normal errors")
#Plot the true function
plt.plot(gridx, gridy, label = "True function", color = 'Red')
plt.legend(loc = 2)
# Save and clear
plt.savefig("scatter_normal.png")
plt.cla()

# Fit linear regressors to increasingly large intervals of data
lm = LinearRegression()
for i in range(1, NUM_SAMPLES+1):
    # Fit the regressor
    lm.fit(data[:i,0].reshape((i,1)), normaly[:i].reshape((i,1)))
    # Get the predictions on all of the sample points
    predictions = lm.predict(data[:,0].reshape(NUM_SAMPLES,1))

    # Get MSE
    mse = mean_squared_error(predictions, normaly)

    # Plot the messy data
    plt.scatter(data[:,0], normaly)
    plt.title("Linear regression on {} points with normal error".format(i))
    # Plot the true function
    plt.plot(gridx, gridy, label = "True function", color = 'Red')
    # Plot the regression line
    plt.plot(gridx, [lm.coef_[0] * x + lm.intercept_[0]  for x in gridx], label = "Linear regressor line MSE = {:0.4f}".format(mse), color = 'Green')
    plt.legend(loc = 2)
    # Save and clear
    plt.savefig("linreg_normal_{:03d}.png".format(i))
    plt.cla()


text:
using Entitas;

namespace Entitas {
    public partial class Entity {
        public MyFloatComponent myFloat { get { return (MyFloatComponent)GetComponent(VisualDebuggingComponentIds.MyFloat); } }

        public bool hasMyFloat { get { return HasComponent(VisualDebuggingComponentIds.MyFloat); } }

        public Entity AddMyFloat(float newMyFloat) {
            var component = CreateComponent<MyFloatComponent>(VisualDebuggingComponentIds.MyFloat);
            component.myFloat = newMyFloat;
            return AddComponent(VisualDebuggingComponentIds.MyFloat, component);
        }

        public Entity ReplaceMyFloat(float newMyFloat) {
            var component = CreateComponent<MyFloatComponent>(VisualDebuggingComponentIds.MyFloat);
            component.myFloat = newMyFloat;
            ReplaceComponent(VisualDebuggingComponentIds.MyFloat, component);
            return this;
        }

        public Entity RemoveMyFloat() {
            return RemoveComponent(VisualDebuggingComponentIds.MyFloat);
        }
    }
}

    public partial class VisualDebuggingMatcher {
        static IMatcher _matcherMyFloat;

        public static IMatcher MyFloat {
            get {
                if (_matcherMyFloat == null) {
                    var matcher = (Matcher)Matcher.AllOf(VisualDebuggingComponentIds.MyFloat);
                    matcher.componentNames = VisualDebuggingComponentIds.componentNames;
                    _matcherMyFloat = matcher;
                }

                return _matcherMyFloat;
            }
        }
    }


text:
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Contributor(s):
 *   Norris Boyd
 *
 * Alternatively, the contents of this file may be used under the terms of
 * the GNU General Public License Version 2 or later (the "GPL"), in which
 * case the provisions of the GPL are applicable instead of those above. If
 * you wish to allow use of your version of this file only under the terms of
 * the GPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replacing
 * them with the notice and other provisions required by the GPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the GPL.
 *
 * ***** END LICENSE BLOCK ***** */

package org.mozilla.javascript;

/**
 * This class implements generator objects. See
 * http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Generators
 *
 * @author Norris Boyd
 */
public final class NativeGenerator extends IdScriptableObject {
    private static final Object GENERATOR_TAG = new Object();

    static NativeGenerator init(ScriptableObject scope, boolean sealed) {
        // Generator
        // Can't use "NativeGenerator().exportAsJSClass" since we don't want
        // to define "Generator" as a constructor in the top-level scope.

        NativeGenerator prototype = new NativeGenerator();
        if (scope != null) {
            prototype.setParentScope(scope);
            prototype.setPrototype(getObjectPrototype(scope));
        }
        prototype.activatePrototypeMap(MAX_PROTOTYPE_ID);
        if (sealed) {
            prototype.sealObject();
        }

        // Need to access Generator prototype when constructing
        // Generator instances, but don't have a generator constructor
        // to use to find the prototype. Use the "associateValue"
        // approach instead.
        if (scope != null) {
            scope.associateValue(GENERATOR_TAG, prototype);
        }

        return prototype;
    }

    /**
     * Only for constructing the prototype object.
     */
    private NativeGenerator() { }

    public NativeGenerator(Scriptable scope, NativeFunction function,
                           Object savedState)
    {
        this.function = function;
        this.savedState = savedState;
        // Set parent and prototype properties. Since we don't have a
        // "Generator" constructor in the top scope, we stash the
        // prototype in the top scope's associated value.
        Scriptable top = ScriptableObject.getTopLevelScope(scope);
        this.setParentScope(top);
        NativeGenerator prototype = (NativeGenerator)
            ScriptableObject.getTopScopeValue(top, GENERATOR_TAG);
        this.setPrototype(prototype);
    }

    public static final int GENERATOR_SEND  = 0,
                            GENERATOR_THROW = 1,
                            GENERATOR_CLOSE = 2;

    public String getClassName() {
        return "Generator";
    }

    /**
     * Close the generator if it is still open.
     */
    public void finalize() throws Throwable {
        if (savedState != null) {
            // This is a little tricky since we are most likely running in
            // a different thread. We need to get a Context to run this, and
            // we must call "doTopCall" since this will likely be the outermost
            // JavaScript frame on this thread.
            Context cx = Context.getCurrentContext();
            ContextFactory factory = cx != null ? cx.getFactory()
                                                : ContextFactory.getGlobal();
            Scriptable scope = ScriptableObject.getTopLevelScope(this);
            factory.call(new CloseGeneratorAction(this));
        }
    }

    private static class CloseGeneratorAction implements ContextAction {
        private NativeGenerator generator;

        CloseGeneratorAction(NativeGenerator generator) {
            this.generator = generator;
        }

        public Object run(Context cx) {
            Scriptable scope = ScriptableObject.getTopLevelScope(generator);
            Callable closeGenerator = new Callable() {
                public Object call(Context cx, Scriptable scope,
                                   Scriptable thisObj, Object[] args) {
                     return ((NativeGenerator)thisObj).resume(cx, scope,
                             GENERATOR_CLOSE, new GeneratorClosedException());
                }
            };
            return ScriptRuntime.doTopCall(closeGenerator, cx, scope,
                                           generator, null);
        }
    }

    protected void initPrototypeId(int id) {
        String s;
        int arity;
        switch (id) {
          case Id_close:          arity=1; s="close";          break;
          case Id_next:           arity=1; s="next";           break;
          case Id_send:           arity=0; s="send";           break;
          case Id_throw:          arity=0; s="throw";          break;
          case Id___iterator__:   arity=1; s="__iterator__";   break;
          default: throw new IllegalArgumentException(String.valueOf(id));
        }
        initPrototypeMethod(GENERATOR_TAG, id, s, arity);
    }

    public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                             Scriptable thisObj, Object[] args)
    {
        if (!f.hasTag(GENERATOR_TAG)) {
            return super.execIdCall(f, cx, scope, thisObj, args);
        }
        int id = f.methodId();

        if (!(thisObj instanceof NativeGenerator))
            throw incompatibleCallError(f);

        NativeGenerator generator = (NativeGenerator) thisObj;

        switch (id) {

          case Id_close:
            // need to run any pending finally clauses
            return generator.resume(cx, scope, GENERATOR_CLOSE,
                                    new GeneratorClosedException());

          case Id_next:
            // arguments to next() are ignored
            generator.firstTime = false;
            return generator.resume(cx, scope, GENERATOR_SEND,
                                    Undefined.instance);

          case Id_send: {
            Object arg = args.length > 0 ? args[0] : Undefined.instance;
            if (generator.firstTime && !arg.equals(Undefined.instance)) {
                throw ScriptRuntime.typeError0("msg.send.newborn");
            }
            return generator.resume(cx, scope, GENERATOR_SEND, arg);
          }

          case Id_throw:
            return generator.resume(cx, scope, GENERATOR_THROW,
                args.length > 0 ? args[0] : Undefined.instance);

          case Id___iterator__:
            return thisObj;

          default:
            throw new IllegalArgumentException(String.valueOf(id));
        }
    }

    private Object resume(Context cx, Scriptable scope, int operation,
                          Object value)
    {
        if (savedState == null) {
            if (operation == GENERATOR_CLOSE)
                return Undefined.instance;
            Object thrown;
            if (operation == GENERATOR_THROW) {
                thrown = value;
            } else {
                thrown = NativeIterator.getStopIterationObject(scope);
            }
            throw new JavaScriptException(thrown, lineSource, lineNumber);
        }
        try {
            synchronized (this) {
              // generator execution is necessarily single-threaded and
              // non-reentrant.
              // See https://bugzilla.mozilla.org/show_bug.cgi?id=349263
              if (locked)
                  throw ScriptRuntime.typeError0("msg.already.exec.gen");
              locked = true;
            }
            return function.resumeGenerator(cx, scope, operation, savedState,
                                            value);
        } catch (GeneratorClosedException e) {
            // On closing a generator in the compile path, the generator
            // throws a special exception. This ensures execution of all pending
            // finalizers and will not get caught by user code.
            return Undefined.instance;
        } catch (RhinoException e) {
            lineNumber = e.lineNumber();
            lineSource = e.lineSource();
            savedState = null;
            throw e;
        } finally {
            synchronized (this) {
              locked = false;
            }
            if (operation == GENERATOR_CLOSE)
                savedState = null;
        }
    }

// #string_id_map#

    protected int findPrototypeId(String s) {
        int id;
// #generated# Last update: 2007-06-14 13:13:03 EDT
        L0: { id = 0; String X = null; int c;
            int s_length = s.length();
            if (s_length==4) {
                c=s.charAt(0);
                if (c=='n') { X="next";id=Id_next; }
                else if (c=='s') { X="send";id=Id_send; }
            }
            else if (s_length==5) {
                c=s.charAt(0);
                if (c=='c') { X="close";id=Id_close; }
                else if (c=='t') { X="throw";id=Id_throw; }
            }
            else if (s_length==12) { X="__iterator__";id=Id___iterator__; }
            if (X!=null && X!=s && !X.equals(s)) id = 0;
            break L0;
        }
// #/generated#
        return id;
    }

    private static final int
        Id_close                 = 1,
        Id_next                  = 2,
        Id_send                  = 3,
        Id_throw                 = 4,
        Id___iterator__          = 5,
        MAX_PROTOTYPE_ID         = 5;

// #/string_id_map#
    private NativeFunction function;
    private Object savedState;
    private String lineSource;
    private int lineNumber;
    private boolean firstTime = true;
    private boolean locked;

    public static class GeneratorClosedException extends RuntimeException {
    }
}


text:
def response(context, flow):

    fp = open('headers','w+')
    fp.write('Server Response Headers:\n')
    fp.write('========================\n')
    for header, value in flow.response.headers.items():
        fp.write(str(header)+': '+str(value)+'\n')
    fp.write('\n')
    fp.close()


text:
package com.intellij.codeInsight.documentation.render;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.ex.util.EditorScrollingPositionKeeper;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.*;

@Service
public final class DocRenderItemUpdater implements Runnable {
  private static final long MAX_UPDATE_DURATION_MS = 50;
  private final Map<RenderedElement, Boolean> myQueue = new HashMap<>();

  static DocRenderItemUpdater getInstance() {
    return ApplicationManager.getApplication().getService(DocRenderItemUpdater.class);
  }

  void updateFoldRegions(@NotNull Collection<CustomFoldRegion> foldRegions, boolean recreateContent) {
    if (foldRegions.isEmpty()) return;
    boolean wasEmpty = myQueue.isEmpty();
    for (CustomFoldRegion foldRegion : foldRegions) {
      myQueue.merge(new FoldRegionWrapper(foldRegion), recreateContent, Boolean::logicalOr);
    }
    if (wasEmpty) processChunk();
  }

  void updateInlays(@NotNull Collection<Inlay<DocRenderer>> inlays, boolean recreateContent) {
    if (inlays.isEmpty()) return;
    boolean wasEmpty = myQueue.isEmpty();
    for (Inlay<DocRenderer> inlay : inlays) {
      myQueue.merge(new InlayWrapper(inlay), recreateContent, Boolean::logicalOr);
    }
    if (wasEmpty) processChunk();
  }

  @Override
  public void run() {
    processChunk();
  }

  private void processChunk() {
    long deadline = System.currentTimeMillis() + MAX_UPDATE_DURATION_MS;
    Map<Editor, EditorScrollingPositionKeeper> keepers = new HashMap<>();
    // This is a heuristic to lessen visual 'jumping' on editor opening. We'd like inlays visible at target opening location to be updated
    // first, and all the rest - later. We're not specifically optimizing for the case when multiple editors are opened simultaneously now,
    // opening several editors in succession should work fine with this logic though (by the time a new editor is opened, 'high-priority'
    // inlays from the previous editor are likely to have been processed already).
    List<RenderedElement> toProcess = new ArrayList<>(myQueue.keySet());
    Object2IntMap<Editor> memoMap = new Object2IntOpenHashMap<>();
    toProcess.sort(Comparator.comparingInt(i -> -Math.abs(i.getOffset() - getVisibleOffset(i.getEditor(), memoMap))));
    do {
      RenderedElement element = toProcess.remove(toProcess.size() - 1);
      boolean updateContent = myQueue.remove(element);
      if (element.isValid()) {
        Editor editor = element.getEditor();
        keepers.computeIfAbsent(editor, e -> {
          EditorScrollingPositionKeeper keeper = new EditorScrollingPositionKeeper(editor);
          keeper.savePosition();
          return keeper;
        });
        element.getRenderer().update(true, updateContent, null);
      }
    }
    while (!toProcess.isEmpty() && System.currentTimeMillis() < deadline);
    keepers.values().forEach(k -> k.restorePosition(false));
    if (!myQueue.isEmpty()) SwingUtilities.invokeLater(this);
  }

  private static int getVisibleOffset(Editor editor, Object2IntMap<Editor> memoMap) {
    return memoMap.computeIntIfAbsent(editor, e -> {
      Rectangle visibleArea = e.getScrollingModel().getVisibleAreaOnScrollingFinished();
      if (editor.isDisposed() || visibleArea.height <= 0) {
        return e.getCaretModel().getOffset();
      }
      else {
        int y = visibleArea.y + visibleArea.height / 2;
        int visualLine = e.yToVisualLine(y);
        return e.visualPositionToOffset(new VisualPosition(visualLine, 0));
      }
    });
  }

  // remove after migration to new backend
  private interface RenderedElement {
    Editor getEditor();
    int getOffset();
    boolean isValid();
    DocRenderer getRenderer();
  }

  private static class InlayWrapper implements RenderedElement {
    private final Inlay<DocRenderer> myInlay;

    private InlayWrapper(Inlay<DocRenderer> inlay) { myInlay = inlay; }

    @Override
    public Editor getEditor() {
      return myInlay.getEditor();
    }

    @Override
    public int getOffset() {
      return myInlay.getOffset();
    }

    @Override
    public boolean isValid() {
      return myInlay.isValid();
    }

    @Override
    public DocRenderer getRenderer() {
      return myInlay.getRenderer();
    }
  }

  private static class FoldRegionWrapper implements RenderedElement {
    private final CustomFoldRegion myFoldRegion;

    private FoldRegionWrapper(CustomFoldRegion region) { myFoldRegion = region; }

    @Override
    public Editor getEditor() {
      return myFoldRegion.getEditor();
    }

    @Override
    public int getOffset() {
      return myFoldRegion.getStartOffset();
    }

    @Override
    public boolean isValid() {
      return myFoldRegion.isValid();
    }

    @Override
    public DocRenderer getRenderer() {
      return (DocRenderer)myFoldRegion.getRenderer();
    }
  }
}


text:
layout: post
microblog: true
audio:
photo:
date: 2010-03-11 18:00:00 -0600
guid: http://craigmcclellan.micro.blog/2010/03/12/t10353509106.html
---
I said after seeing Cop Out that Tracy Morgan could be funny reading the phone book. 30 Rock proved that statement true tonight.


text:
package compose

import (
	"github.com/spf13/cobra"
)

// unpauseCommand is the unpause command.
var unpauseCommand = &cobra.Command{
	Use:                "unpause",
	Run:                passthrough,
	SilenceUsage:       true,
	DisableFlagParsing: true,
}

// unpauseConfiguration stores configuration for the unpause command.
var unpauseConfiguration struct {
	// help indicates the presence of the -h/--help flag.
	help bool
}

func init() {
	// Avoid Cobra's built-in help functionality that's triggered when the
	// -h/--help flag is present. We still explicitly register a -h/--help flag
	// below for shell completion support.
	unpauseCommand.SetHelpFunc(commandHelp)

	// Grab a handle for the command line flags.
	flags := unpauseCommand.Flags()

	// Wire up unpause command flags.
	flags.BoolVarP(&unpauseConfiguration.help, "help", "h", false, "")
}


text:
require File.expand_path("../../../../base", __FILE__)

require Vagrant.source_root.join("plugins/communicators/winrm/shell")
require Vagrant.source_root.join("plugins/communicators/winrm/config")

describe VagrantPlugins::CommunicatorWinRM::WinRMShell do
  include_context "unit"

  let(:connection) { double("winrm_connection") }
  let(:shell) { double("winrm_shell") }
  let(:port) { config.transport == :ssl ? 5986 : 5985 }
  let(:config)  {
    VagrantPlugins::CommunicatorWinRM::Config.new.tap do |c|
      c.username = 'username'
      c.password = 'password'
      c.max_tries = 3
      c.retry_delay = 0
      c.basic_auth_only = false
      c.retry_delay = 1
      c.max_tries = 2
      c.finalize!
    end
  }
  let(:output) { WinRM::Output.new.tap { |out| out.exitcode = 0 } }

  before { allow(connection).to receive(:shell).and_yield(shell) }

  subject do
    described_class.new('localhost', port, config).tap do |comm|
      allow(comm).to receive(:new_connection).and_return(connection)
    end
  end

  describe "#upload" do
    let(:fm) { double("file_manager") }
    it "should call file_manager.upload for each passed in path" do
      from = ["/path", "/path/folder", "/path/folder/file.py"]
      to = "/destination"
      size = 80

      allow(WinRM::FS::FileManager).to receive(:new).with(connection)
        .and_return(fm)
      allow(fm).to receive(:upload).and_return(size)

      expect(fm).to receive(:upload).exactly(from.size).times
      expect(subject.upload(from, to)).to eq(size*from.size)
    end

    it "should call file_manager.upload once for a single path" do
      from = "/path/folder/file.py"
      to = "/destination"
      size = 80

      allow(WinRM::FS::FileManager).to receive(:new).with(connection)
        .and_return(fm)
      allow(fm).to receive(:upload).and_return(size)

      expect(fm).to receive(:upload).exactly(1).times
      expect(subject.upload(from, to)).to eq(size)
    end
  end

  describe ".powershell" do
    it "should call winrm powershell" do
      expect(shell).to receive(:run).with("dir").and_return(output)
      expect(subject.powershell("dir").exitcode).to eq(0)
    end

    it "should raise an execution error when an exception occurs" do
      expect(shell).to receive(:run).with("dir").and_raise(
        StandardError.new("Oh no! a 500 SOAP error!"))
      expect { subject.powershell("dir") }.to raise_error(
        VagrantPlugins::CommunicatorWinRM::Errors::ExecutionError)
    end
  end

  describe ".elevated" do
    it "should call winrm elevated" do
      expect(shell).to receive(:run).with("dir").and_return(output)
      expect(shell).to receive(:interactive_logon=).with(false)
      expect(subject.elevated("dir").exitcode).to eq(0)
    end

    it "should set interactive_logon when interactive is true" do
      expect(shell).to receive(:run).with("dir").and_return(output)
      expect(shell).to receive(:interactive_logon=).with(true)
      expect(subject.elevated("dir", { interactive: true }).exitcode).to eq(0)
    end

    it "should raise an execution error when an exception occurs" do
      expect(shell).to receive(:run).with("dir").and_raise(
        StandardError.new("Oh no! a 500 SOAP error!"))
      expect { subject.powershell("dir") }.to raise_error(
        VagrantPlugins::CommunicatorWinRM::Errors::ExecutionError)
    end
  end

  describe ".cmd" do
    it "should call winrm cmd" do
      expect(connection).to receive(:shell).with(:cmd, { })
      expect(shell).to receive(:run).with("dir").and_return(output)
      expect(subject.cmd("dir").exitcode).to eq(0)
    end

    context "when codepage is given" do
      let(:config)  {
        VagrantPlugins::CommunicatorWinRM::Config.new.tap do |c|
          c.codepage = 800
          c.finalize!
        end
      }

      it "creates shell with the given codepage when set" do
        expect(connection).to receive(:shell).with(:cmd, { codepage: 800 })
        expect(shell).to receive(:run).with("dir").and_return(output)
        expect(subject.cmd("dir").exitcode).to eq(0)
      end
    end
  end

  describe ".wql" do
    it "should call winrm wql" do
      expect(connection).to receive(:run_wql).with("select * from Win32_OperatingSystem")
      subject.wql("select * from Win32_OperatingSystem")
    end

    it "should retry when a WinRMAuthorizationError is received" do
      expect(connection).to receive(:run_wql).with("select * from Win32_OperatingSystem").exactly(2).times.and_raise(
        # Note: The initialize for WinRMAuthorizationError may require a status_code as
        # the second argument in a future WinRM release. Currently it doesn't track the
        # status code.
        WinRM::WinRMAuthorizationError.new("Oh no!! Unauthrorized")
      )
      expect { subject.wql("select * from Win32_OperatingSystem") }.to raise_error(
        VagrantPlugins::CommunicatorWinRM::Errors::AuthenticationFailed)
    end
  end

  describe ".endpoint" do
    context 'when transport is :ssl' do
      let(:config)  {
        VagrantPlugins::CommunicatorWinRM::Config.new.tap do |c|
          c.transport = :ssl
          c.finalize!
        end
      }
      it "should create winrm endpoint address using https" do
        expect(subject.send(:endpoint)).to eq("https://localhost:5986/wsman")
      end
    end

    context "when transport is :negotiate" do
      it "should create winrm endpoint address using http" do
        expect(subject.send(:endpoint)).to eq("http://localhost:5985/wsman")
      end
    end

    context "when transport is :plaintext" do
      let(:config)  {
        VagrantPlugins::CommunicatorWinRM::Config.new.tap do |c|
          c.transport = :plaintext
          c.finalize!
        end
      }
      it "should create winrm endpoint address using http" do
        expect(subject.send(:endpoint)).to eq("http://localhost:5985/wsman")
      end
    end
  end

  describe ".endpoint_options" do
    it "should create endpoint options" do
      expect(subject.send(:endpoint_options)).to eq(
        { endpoint: "http://localhost:5985/wsman", operation_timeout: 1800,
          user: "username", password: "password", host: "localhost", port: 5985,
          basic_auth_only: false, no_ssl_peer_verification: false,
          retry_delay: 1, retry_limit: 2, transport: :negotiate })
    end
  end

end


text:
  Soisy-Bouy est
       un village
       localisé dans le département de Seine-et-Marne en Île-de-France. On dénombrait 783 habitants en 2008.

Le parc de logements, à Soisy-Bouy, était réparti en 2011 en un appartements et 344 maisons soit
 un marché relativement équilibré.

À coté de Soisy-Bouy sont localisées les communes de
Jutigny à 4 km, 561 habitants,
Sourdun localisée à 4 km, 1 463 habitants,
Poigny située à 3 km, 447 habitants,
Everly située à 5 km, 606 habitants,
Longueville située à 3 km, 1 634 habitants,
Chalmaison à 4 km, 690 habitants,
 entre autres. De plus, Soisy-Bouy est située à seulement 28 km de Montereau-Fault-Yonne.

La ville offre quelques  équipements sportifs, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.

À Soisy-Bouy, la valorisation moyenne à l'achat d'un appartement se situe à 3 413 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 518 € du m². À la location la valorisation moyenne se situe à 0 € du m² par mois.

Si vous pensez demenager à Soisy-Bouy, vous pourrez facilement trouver une maison à acheter.


text:
var doc = require('dynamodb-doc');
var dynamo = new doc.DynamoDB();

exports.handler = function(event, context) {

  var updateRequest = {
    TableName: "supersimplesequences",
    Key: {
      sequencename: event.sequenceName
    },
    AttributeUpdates: {
      sequencevalue: {}
    },
    ReturnValues: "ALL_NEW"
  };

  var take = 1;
  if ( event.sequenceValue ) {
    updateRequest.AttributeUpdates.sequencevalue.Action = "PUT";
    updateRequest.AttributeUpdates.sequencevalue.Value = Number(event.sequenceValue);
  } else {
    take = (Number(event.take)>0) ? Number(event.take) : take;
    updateRequest.AttributeUpdates.sequencevalue.Action = "ADD";
    updateRequest.AttributeUpdates.sequencevalue.Value = take;
  }

  dynamo.updateItem(updateRequest, function(error, timer_result) {
    if (error) {
      context.fail("500: error retrieving sequence: "+error);
      return;
    }
    var lastNumber = Number(timer_result.Attributes.sequencevalue);
    var firstNumber = lastNumber - take +1;
    var result = {
      firstNumber: firstNumber,
      lastNumber: lastNumber
    };
    context.succeed(result);
  });

};


text:
import numpy as np
import nibabel as nb
import os
import sys
import nighresjava
from ..io import load_volume, save_volume
from ..utils import _output_dir_4saving, _fname_4saving, \
                    _check_topology_lut_dir, _check_available_memory

def intensity_based_skullstripping(main_image, extra_image=None,
                            noise_model='exponential', skip_zero_values=True,
                            iterate=False, dilate_mask=0, dynamic_range=0.8,
                            topology_lut_dir=None,
                            save_data=False, overwrite=False, output_dir=None,
                            file_name=None):
    """ Intensity-based skull stripping

    Estimate a brain mask for a dataset with good brain/background intensity
    separation (e.g. PD-weighted). An extra image can be used to ensure high
    intensities are preserved (e.g. T1 map, T2-weighted data or a probability
    map for a ROI).

    Parameters
    ----------
    main_image: niimg
        Main Intensity Image
    extra_image: niimg, optional
        Extra image with high intensity at brain boundary
    noise_model: {'exponential','half-normal','exp+log-normal','half+log-normal'}
        Background noise model (default is 'exponential')
    skip_zero_values: bool
        Ignores voxels with zero value (default is True)
    iterate: bool
        Whether to iterate the estimation (may be unstable in some cases,
        default is False)
    dilate_mask: int
         Additional dilation (or erosion, if negative) of the brain mask
         (default is 0)
    dynamic_range: float
         Dynamic range for the foreground / background differences in [0,1]
         (default is 0.8)
    topology_lut_dir: str, optional
        Path to directory in which topology files are stored (default is stored
        in TOPOLOGY_LUT_DIR)
    save_data: bool
        Save output data to file (default is False)
    overwrite: bool
        Overwrite existing results (default is False)
    output_dir: str, optional
        Path to desired output directory, will be created if it doesn't exist
    file_name: str, optional
        Desired base name for output files with file extension
        (suffixes will be added)

    Returns
    ----------
    dict
        Dictionary collecting outputs under the following keys
        (suffix of output files in brackets)

        * brain_mask (niimg): Binary brain mask (_istrip-mask)
        * brain_proba (niimg): Probability brain map (_istrip-proba)
        * main_masked (niimg): Masked main image (_istrip-main)
        * extra_masked (niimg): Masked extra map (_istrip-extra)

    Notes
    ----------
    Original Java module by Pierre-Louis Bazin. Details on the algorithm can
    be found in [1]_

    References
    ----------
    .. [1] Bazin et al. (2014). A computational framework for ultra-high
       resolution cortical segmentation at 7 Tesla.
       DOI: 10.1016/j.neuroimage.2013.03.077
    """

    print('\nIntensity-based Skull Stripping')

    # check topology lut dir and set default if not given
    topology_lut_dir = _check_topology_lut_dir(topology_lut_dir)

    # make sure that saving related parameters are correct
    if save_data:
        output_dir = _output_dir_4saving(output_dir, main_image)

        mask_file = os.path.join(output_dir,
                        _fname_4saving(module=__name__,file_name=file_name,
                                   rootfile=main_image,
                                   suffix='istrip-mask'))
        proba_file = os.path.join(output_dir,
                        _fname_4saving(module=__name__,file_name=file_name,
                                   rootfile=main_image,
                                   suffix='istrip-proba'))
        main_file = os.path.join(output_dir,
                    _fname_4saving(module=__name__,file_name=file_name,
                                  rootfile=main_image,
                                  suffix='istrip-main'))

        if extra_image is not None:
            extra_file = os.path.join(output_dir,
                        _fname_4saving(module=__name__,file_name=file_name,
                                        rootfile=extra_image,
                                        suffix='istrip-extra'))
        else:
            extra_file = None

        if overwrite is False \
            and os.path.isfile(mask_file) \
            and os.path.isfile(proba_file) \
            and os.path.isfile(main_file) :

            print("skip computation (use existing results)")
            output = {'brain_mask': mask_file,
                    'brain_proba': proba_file,
                    'main_masked': main_file}
            if extra_file is not None:
                if os.path.isfile(extra_file) :
                    output['extra_masked'] = extra_file
            return output

    # start virtual machine, if not already running
    try:
        mem = _check_available_memory()
        nighresjava.initVM(initialheap=mem['init'], maxheap=mem['max'])
    except ValueError:
        pass

    # create skulltripping instance
    algo = nighresjava.BrainIntensityBasedSkullStripping()

    # get dimensions and resolution from second inversion image
    main_img = load_volume(main_image)
    main_data = main_img.get_data()
    main_affine = main_img.affine
    main_hdr = main_img.header
    resolution = [x.item() for x in main_hdr.get_zooms()]
    dimensions = main_data.shape
    algo.setDimensions(dimensions[0], dimensions[1], dimensions[2])
    algo.setResolutions(resolution[0], resolution[1], resolution[2])
    algo.setMainIntensityImage(nighresjava.JArray('float')(
                                    (main_data.flatten('F')).astype(float)))

    # pass other inputs
    if extra_image is not None:
        extra_img = load_volume(extra_image)
        extra_data = extra_img.get_data()
        extra_affine = extra_img.affine
        extra_hdr = extra_img.header
        algo.setExtraIntensityImage(nighresjava.JArray('float')(
                                    (extra_data.flatten('F')).astype(float)))

    algo.setBackgroundNoiseModel(noise_model)
    algo.setIterativeEstimation(iterate)
    algo.setSkipZeroValues(skip_zero_values)
    algo.setAdditionalMaskDilation(dilate_mask)
    algo.setTopologyLUTdirectory(topology_lut_dir)
    algo.setDynamicRange(dynamic_range)

    # execute skull stripping
    try:
        algo.execute()

    except:
        # if the Java module fails, reraise the error it throws
        print("\n The underlying Java code did not execute cleanly: ")
        print(sys.exc_info()[0])
        raise
        return

    # collect outputs and potentially save
    main_masked_data = np.reshape(np.array(
                                algo.getMaskedMainImage(),
                                dtype=np.float32), dimensions, 'F')
    main_hdr['cal_max'] = np.nanmax(main_masked_data)
    main_masked = nb.Nifti1Image(main_masked_data, main_affine, main_hdr)

    mask_data = np.reshape(np.array(algo.getBrainMaskImage(),
                                    dtype=np.uint32), dimensions, 'F')
    main_hdr['cal_max'] = np.nanmax(mask_data)
    mask = nb.Nifti1Image(mask_data, main_affine, main_hdr)

    proba_data = np.reshape(np.array(
                                algo.getForegroundProbabilityImage(),
                                dtype=np.float32), dimensions, 'F')
    main_hdr['cal_max'] = np.nanmax(proba_data)
    proba = nb.Nifti1Image(proba_data, main_affine, main_hdr)

    if extra_image is not None:
        extra_data = np.reshape(np.array(
                                algo.getMaskedExtraImage(),
                                dtype=np.float32), dimensions, 'F')
        extra_hdr['cal_max'] = np.nanmax(extra_data)
        extra_masked = nb.Nifti1Image(extra_data, extra_affine, extra_hdr)

    if save_data:
        save_volume(main_file, main_masked)
        save_volume(mask_file, mask)
        save_volume(proba_file, proba)
        outputs = {'brain_mask': mask_file, 'brain_proba': proba_file, 'main_masked': main_file}
        if extra_image is not None:
            save_volume(extra_file, extra_masked)
            outputs['extra_masked'] = extra_file
    else:
        outputs = {'brain_mask': mask, 'brain_proba': proba, 'main_masked': main_masked}
        if extra_image is not None:
            outputs['extra_masked'] = extra_masked

    return outputs


text:
module("baidu.ui.Button.Button$poll");

test("Timer is undefined and duration is 250", function() {
	var div_test = te.dom[0];
	var num = 0;
	var options = {
		content : "按钮",
		poll : true,
		onmousedown : function(){
			num++;
		}
	};
	var button = new baidu.ui.Button(options);
	ok(!!button.__listeners['onmousedown'], 'The mousedown event is on');
	button.render(div_test.id);
	ua.mousedown(button.getBody());
	stop();
	setTimeout(function(){
		ua.mouseup(button.getBody());
		equal(num, 3, 'Dispatch mousedown event 3 times');
		start();
	}, 250);
	te.obj.push(button);
});

test("Timer is 4 and duration is 250", function() {
	var div_test = te.dom[0];
	var num = 0;
	var options = {
		content : "按钮",
		poll : {time : 4},
		onmousedown : function(){
			num++;
		}
	};
	var button = new baidu.ui.Button(options);
	ok(!!button.__listeners['onmousedown'], 'The mousedown event is on');
	button.render(div_test.id);
	ua.mousedown(button.getBody());
	stop();
	setTimeout(function(){
		ua.mouseup(button.getBody());
		equal(num, 1, 'Dispatch mousedown event once');
		start();
	}, 250);
	te.obj.push(button);
});

test("Timer is 4 and duration is 650", function() {
	var div_test = te.dom[0];
	var num = 0;
	var options = {
		content : "按钮",
		poll : {time : 4},
		onmousedown : function(){
			num++;
		}
	};
	var button = new baidu.ui.Button(options);
	ok(!!button.__listeners['onmousedown'], 'The mousedown event is on');
	button.render(div_test.id);
	ua.mousedown(button.getBody());
	stop();
	setTimeout(function(){
		ua.mouseup(button.getBody());
		//TODO
		equal(num, 3, 'Dispatch mousedown event 3 times' +
				'(注意:在IE下可能得不到正确结果,原因为如果mousedown的时间拉得太长(如1650),会导致计算不精确)');
		start();
	}, 650);
	te.obj.push(button);
});

test("Test when the button disposed, whether the poll event is canceled", function() {
	var div_test = te.dom[0];
	var options = {
		content : "按钮",
		poll : true
	};
	var button = new baidu.ui.Button(options);
	button.render(div_test.id);
	ua.mousedown(button.getBody());
	stop();
	setTimeout(function(){
		ua.mouseup(button.getBody());
		button.dispose();
		start();
		equals(button.poll, undefined, 'The poll event is canceled PUBLICGE-338');
	}, 250);
});


text:
package com.microsoft.azure.management.logic.v2016_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The Edifact delimiter override settings.
 */
public class EdifactDelimiterOverride {
    /**
     * The message id.
     */
    @JsonProperty(value = "messageId")
    private String messageId;

    /**
     * The message version.
     */
    @JsonProperty(value = "messageVersion")
    private String messageVersion;

    /**
     * The message release.
     */
    @JsonProperty(value = "messageRelease")
    private String messageRelease;

    /**
     * The data element separator.
     */
    @JsonProperty(value = "dataElementSeparator", required = true)
    private int dataElementSeparator;

    /**
     * The component separator.
     */
    @JsonProperty(value = "componentSeparator", required = true)
    private int componentSeparator;

    /**
     * The segment terminator.
     */
    @JsonProperty(value = "segmentTerminator", required = true)
    private int segmentTerminator;

    /**
     * The repetition separator.
     */
    @JsonProperty(value = "repetitionSeparator", required = true)
    private int repetitionSeparator;

    /**
     * The segment terminator suffix. Possible values include: 'NotSpecified',
     * 'None', 'CR', 'LF', 'CRLF'.
     */
    @JsonProperty(value = "segmentTerminatorSuffix", required = true)
    private SegmentTerminatorSuffix segmentTerminatorSuffix;

    /**
     * The decimal point indicator. Possible values include: 'NotSpecified',
     * 'Comma', 'Decimal'.
     */
    @JsonProperty(value = "decimalPointIndicator", required = true)
    private EdifactDecimalIndicator decimalPointIndicator;

    /**
     * The release indicator.
     */
    @JsonProperty(value = "releaseIndicator", required = true)
    private int releaseIndicator;

    /**
     * The message association assigned code.
     */
    @JsonProperty(value = "messageAssociationAssignedCode")
    private String messageAssociationAssignedCode;

    /**
     * The target namespace on which this delimiter settings has to be applied.
     */
    @JsonProperty(value = "targetNamespace")
    private String targetNamespace;

    /**
     * Get the message id.
     *
     * @return the messageId value
     */
    public String messageId() {
        return this.messageId;
    }

    /**
     * Set the message id.
     *
     * @param messageId the messageId value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withMessageId(String messageId) {
        this.messageId = messageId;
        return this;
    }

    /**
     * Get the message version.
     *
     * @return the messageVersion value
     */
    public String messageVersion() {
        return this.messageVersion;
    }

    /**
     * Set the message version.
     *
     * @param messageVersion the messageVersion value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withMessageVersion(String messageVersion) {
        this.messageVersion = messageVersion;
        return this;
    }

    /**
     * Get the message release.
     *
     * @return the messageRelease value
     */
    public String messageRelease() {
        return this.messageRelease;
    }

    /**
     * Set the message release.
     *
     * @param messageRelease the messageRelease value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withMessageRelease(String messageRelease) {
        this.messageRelease = messageRelease;
        return this;
    }

    /**
     * Get the data element separator.
     *
     * @return the dataElementSeparator value
     */
    public int dataElementSeparator() {
        return this.dataElementSeparator;
    }

    /**
     * Set the data element separator.
     *
     * @param dataElementSeparator the dataElementSeparator value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withDataElementSeparator(int dataElementSeparator) {
        this.dataElementSeparator = dataElementSeparator;
        return this;
    }

    /**
     * Get the component separator.
     *
     * @return the componentSeparator value
     */
    public int componentSeparator() {
        return this.componentSeparator;
    }

    /**
     * Set the component separator.
     *
     * @param componentSeparator the componentSeparator value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withComponentSeparator(int componentSeparator) {
        this.componentSeparator = componentSeparator;
        return this;
    }

    /**
     * Get the segment terminator.
     *
     * @return the segmentTerminator value
     */
    public int segmentTerminator() {
        return this.segmentTerminator;
    }

    /**
     * Set the segment terminator.
     *
     * @param segmentTerminator the segmentTerminator value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withSegmentTerminator(int segmentTerminator) {
        this.segmentTerminator = segmentTerminator;
        return this;
    }

    /**
     * Get the repetition separator.
     *
     * @return the repetitionSeparator value
     */
    public int repetitionSeparator() {
        return this.repetitionSeparator;
    }

    /**
     * Set the repetition separator.
     *
     * @param repetitionSeparator the repetitionSeparator value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withRepetitionSeparator(int repetitionSeparator) {
        this.repetitionSeparator = repetitionSeparator;
        return this;
    }

    /**
     * Get the segment terminator suffix. Possible values include: 'NotSpecified', 'None', 'CR', 'LF', 'CRLF'.
     *
     * @return the segmentTerminatorSuffix value
     */
    public SegmentTerminatorSuffix segmentTerminatorSuffix() {
        return this.segmentTerminatorSuffix;
    }

    /**
     * Set the segment terminator suffix. Possible values include: 'NotSpecified', 'None', 'CR', 'LF', 'CRLF'.
     *
     * @param segmentTerminatorSuffix the segmentTerminatorSuffix value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withSegmentTerminatorSuffix(SegmentTerminatorSuffix segmentTerminatorSuffix) {
        this.segmentTerminatorSuffix = segmentTerminatorSuffix;
        return this;
    }

    /**
     * Get the decimal point indicator. Possible values include: 'NotSpecified', 'Comma', 'Decimal'.
     *
     * @return the decimalPointIndicator value
     */
    public EdifactDecimalIndicator decimalPointIndicator() {
        return this.decimalPointIndicator;
    }

    /**
     * Set the decimal point indicator. Possible values include: 'NotSpecified', 'Comma', 'Decimal'.
     *
     * @param decimalPointIndicator the decimalPointIndicator value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withDecimalPointIndicator(EdifactDecimalIndicator decimalPointIndicator) {
        this.decimalPointIndicator = decimalPointIndicator;
        return this;
    }

    /**
     * Get the release indicator.
     *
     * @return the releaseIndicator value
     */
    public int releaseIndicator() {
        return this.releaseIndicator;
    }

    /**
     * Set the release indicator.
     *
     * @param releaseIndicator the releaseIndicator value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withReleaseIndicator(int releaseIndicator) {
        this.releaseIndicator = releaseIndicator;
        return this;
    }

    /**
     * Get the message association assigned code.
     *
     * @return the messageAssociationAssignedCode value
     */
    public String messageAssociationAssignedCode() {
        return this.messageAssociationAssignedCode;
    }

    /**
     * Set the message association assigned code.
     *
     * @param messageAssociationAssignedCode the messageAssociationAssignedCode value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withMessageAssociationAssignedCode(String messageAssociationAssignedCode) {
        this.messageAssociationAssignedCode = messageAssociationAssignedCode;
        return this;
    }

    /**
     * Get the target namespace on which this delimiter settings has to be applied.
     *
     * @return the targetNamespace value
     */
    public String targetNamespace() {
        return this.targetNamespace;
    }

    /**
     * Set the target namespace on which this delimiter settings has to be applied.
     *
     * @param targetNamespace the targetNamespace value to set
     * @return the EdifactDelimiterOverride object itself.
     */
    public EdifactDelimiterOverride withTargetNamespace(String targetNamespace) {
        this.targetNamespace = targetNamespace;
        return this;
    }

}


text:
@protocol IVGDMConnectionTimeoutDelegate<NSObject>
- (void) connectionTimeout:(NSURLConnection *) connection;
@end

@interface IVGDMConnectionTimeoutManager : NSObject

@property (nonatomic,assign) id<IVGDMConnectionTimeoutDelegate> delegate;

- (void) startMonitoringConnection:(NSURLConnection *) connection
                        forTimeout:(NSTimeInterval) timeout;
- (void) stopMonitoringConnection:(NSURLConnection *) connection;
- (void) keepAlive:(NSURLConnection *) connection;

@end


text:
class PageLinkPageAttribute < ActiveRecord::Base

  belongs_to :page_attribute
  belongs_to :link_to_page, :class_name  => 'Page', :foreign_key => 'link_to_page_id'

  include IsAPageAttribute

  def page_url
    if @page_url.nil?
      if link_to_page.nil?
        return nil
      end
      @page_url = link_to_page.url;
    end
    @page_url
  end

  def page_url=(val)
    @page_url = val
    if( val.nil? || val.to_s == "" )
      self.link_to_page = nil;
    else
      self.link_to_page = Page.find_by_url(self.page_url.to_s, false)
    end
  end

end


text:
function _pyeval(input_file, output_file)
% _PYEVAL: Load a request from an input file, execute the request, and save
%         the response to the output file.
%
%   This allows you to run any Octave code. req should be a struct with the
%   following fields:
%       dname: The name of a directory to add to the runtime path before attempting to run the code.
%       func_name: The name of a function to invoke.
%       func_args: An array of arguments to send to the function.
%       nout: An int specifying how many output arguments are expected.
%       ref_indices: The indices of in the func_args that should
%         be replaced by the value represented by their name.
%       store_as: Optional name to store the return value in the base
%         workspace, instead of returing a value.
%
%   Should save a file containing the result object.
%
% Based on Max Jaderberg's web_feval

sentinel = { '__no_value__' };
result = { sentinel };
err = '';

try
    % Store the simple response in case we don't make it through the script.
    save('-v6', '-mat-binary', output_file, 'result', 'err');

    req = load(input_file);

    % Add function path to current path.
    if req.dname
        addpath(req.dname);
    end

    % Replace the names at the specified indices with their values.
    for idx=1:length(req.ref_indices)
      ref_index = req.ref_indices(idx);
      var_name = req.func_args{ref_index};
      req.func_args{ref_index} = evalin('base', var_name);
    end

    assignin('base', 'ans', sentinel);

    % Use the `ans` response if no output arguments are expected.
    if req.nout == 0

        if length(req.func_args)
          feval(req.func_name, req.func_args{:});
        else
          feval(req.func_name)
        end

        result = get_ans(sentinel);

    elseif length(req.func_args)
      try
        [result{1:req.nout}] = feval(req.func_name, req.func_args{:});
      catch ME
        if (strcmp(ME.message, 'element number 1 undefined in return list') != 1 ||
            length(ME.stack) != 1)
          rethrow(ME);
        else
          result = get_ans(sentinel);
        end

      end

    else
      try
        [result{1:req.nout}] = feval(req.func_name);
      catch ME
          rethrow(ME);
        if (strcmp(ME.message, 'element number 1 undefined in return list') != 1 ||
            length(ME.stack) != 1)
          rethrow(ME);
        end
      end
    end

    if req.store_as
      assignin('base', req.store_as, result{1});
      result = { sentinel };
    end

    if ((strcmp(get(0, 'defaultfigurevisible'), 'on') == 1) &&
        length(get(0, 'children')))
      drawnow('expose');
    end

catch ME
    err = ME;
end

% Save the output to a file.
try
  save('-v6', '-mat-binary', output_file, 'result', 'err');
catch ME
  result = { sentinel };
  err = ME;
  save('-v6', '-mat-binary', output_file, 'result', 'err');
end

end  % function

function result = get_ans(sentinel)
    try
      [result{1}] = evalin('base', 'ans');
    catch
      result = { sentinel };
    end
end


text:
package io.jeo.android.graphics;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LineString;

/**
 * Samples a LineString object at arbitrary positions along the line string.
 *

 * This sampler is stateful and maintains a current distance from the start of the line that is
 * moved along with calls to the {@link #advance(double)} method. The {@link #sample()} method is
 * used to obtain the coordinate at the current position.
 *

 * @author Justin Deoliveira, OpenGeo
 */
public class LineSampler {

    /** default comparison tolerance */
    final static double DEFAULT_TOL = 1e-7;

    /** the line coordinates */
    Coordinate[] line;

    /** index of current and next coordinate */
    int p, q;

    /** percentage between current coordinates */
    float f;

    /** comparison tolerance */
    double tol = DEFAULT_TOL;

    public LineSampler(LineString line) {
        this(line.getCoordinates());
    }

    public LineSampler(Coordinate[] line) {
        this.line = line;
        p = 0; q = 1;
        f = 0;
    }

    /**
     * Sets the tolerance to use when comparing distances.
     *

     * The default tolerance is <tt>1e-7</tt>.
     *

     */
    public void setTolerance(double tol) {
        this.tol = tol;
    }

    /**
     * Advances the position of the sampler along by the specified distance.
     */
    public LineSampler advance(double dist) {
        while (dist > 0 && p < line.length-1) {
            double len = lenToNext();
            if (len == -1) {
                //no more
                break;
            }

            double remain = dist - len;
            if (remain > tol) {
                // advance to next and keep going
                dist -= len;
                p++;
                q++;
                f = 0;
            }
            else {
                // were here, readjust f
                f = (float) ((lenFromPrev() + dist) / line[p].distance(line[q]));
                break;
            }
        }

        return this;
    }

    /**
     * Samples the coordinate at the current position.
     *

     * If the current position is past the end of the line string this method returns
     * null.
     *

     */
    public Coordinate sample() {
        if (p == line.length-1) {
            return null;
        }

        Coordinate c1 = line[p];
        Coordinate c2 = line[q];

        double x = (c2.x - c1.x) * f + c1.x;
        double y = (c2.y - c1.y) * f + c1.y;

        return new Coordinate(x,y);
    }

    double lenToNext() {
        if (p == line.length-1) {
            return -1;
        }

        double d = line[p].distance(line[q]);
        return d - d * f;
    }

    double lenFromPrev() {
        if (p == line.length-1) {
            return 0-1;
        }

        double d = line[p].distance(line[q]);
        return d * f;
    }
}


text:
module Dml
  ##
  # Repository module
  #
  module Repository
  end
end

require 'dml/repository/base'


text:
/*
 * File         : BasicType.java
 * Author       : Sang Lim, Sung-Hoon Ko, Xinying Li, Bryan Carpenter,
 *                Aamir Shafi
 * Created      : Fri Sep 10 12:22:15 BST 2004
 * Revision     : $Revision: 1.13 $
 * Updated      : $Date: 2005/08/12 19:12:08 $
 */

package mpi;

import java.nio.ByteBuffer;

import mpjbuf.BufferFactory;
import mpjbuf.NIOBuffer;

public class BasicType
    extends Datatype {

  int type;

  BasicType(int type) {

    // It is an error if type < 0 or type > Datatype.OBJECT.
    // But since this constructor should not be called from user
    // code we do not check for this condition.

    this.type = type;

    if (type == LB || type == UB) {
      baseType = UNDEFINED;
      size = 0;
      byteSize = 0;
    }
    else {

      baseType = type;

      switch (type) {

        case UNDEFINED:
          size = 0;
          byteSize = 0;
          break;

        case NULL:
          size = 0;
          byteSize = 0;
          break;

        case BYTE:
          bufferType = mpjbuf.Type.BYTE;
          byteSize = 1;
          break;

        case CHAR:
          bufferType = mpjbuf.Type.CHAR;
          byteSize = 2;
          break;

        case SHORT:
          bufferType = mpjbuf.Type.SHORT;
          byteSize = 2;
          break;

        case BOOLEAN:
          bufferType = mpjbuf.Type.BOOLEAN;
          byteSize = 1;
          break;

        case INT:
          bufferType = mpjbuf.Type.INT;
          byteSize = 4;
          break;

        case LONG:
          bufferType = mpjbuf.Type.LONG;
          byteSize = 8;
          break;

        case FLOAT:
          bufferType = mpjbuf.Type.FLOAT;
          byteSize = 4;
          break;

        case DOUBLE:
          bufferType = mpjbuf.Type.DOUBLE;
          byteSize = 8;
          break;

        case PACKED: //is this right ?

          size = 0;
          byteSize = 0;
          break;

        case OBJECT: //remember, object type is not copied onto static buffer.
          bufferType = mpjbuf.Type.OBJECT;
          size = 0;
          byteSize = 0;
          break;

        default:
          break;
      }

      size = 1;
    }

    computeBounds();

  }

  private void computeBounds() {

    // Compute `ub' and `lb', which define the `extent' of the new type.
    // Also defines `ubSet', `lbSet' for this type.

    switch (type) {
      case LB:
        lb = 0;
        ub = 0;
        lbSet = true;
        ubSet = false;

        break;

      case UB:
        lb = 0;
        ub = 0;
        lbSet = false;
        ubSet = true;

        break;

      default: // **** what about PACKED? ****

        lb = 0;
        ub = 1;
        lbSet = false;
        ubSet = false;

        break;
    }

    extent = ub - lb;
  }

  @Override
  public mpjbuf.Buffer createWriteBuffer(ByteBuffer slicedBuffer, int messageSize) {
    return new mpjbuf.Buffer(new NIOBuffer(messageSize, slicedBuffer),
		    MPI.BSEND_OVERHEAD, messageSize );
  }

  @Override
  public mpjbuf.Buffer createWriteBuffer(int count) throws MPIException {
    int capacity = packedSize(count) + MPI.SEND_OVERHEAD ;
    int offset = MPI.SEND_OVERHEAD ;
    mpjbuf.RawBuffer rawBuffer = BufferFactory.create(capacity);
    mpjbuf.Buffer wBuffer = new mpjbuf.Buffer (rawBuffer, offset, capacity) ;

    try {
      wBuffer.putSectionHeader(this.bufferType); // need conversion
    }
    catch (Exception e) {
      throw new MPIException(e);
    }

    return wBuffer;
  }

  @Override
mpjbuf.Buffer createReadBuffer(int count) {

    int capacity = packedSize(count) + MPI.RECV_OVERHEAD ;
    int offset = MPI.RECV_OVERHEAD ;
    mpjbuf.RawBuffer rawBuffer = BufferFactory.create(capacity);
    mpjbuf.Buffer mpjbuf = new mpjbuf.Buffer(rawBuffer, offset, capacity) ;
    return mpjbuf;

  }

  @Override
int packedSize(int count) {
    int dataSize = count * byteSize;
    int totalSize = 0;
    int sectionHeader = 8; //what about multiple sections.
    totalSize = sectionHeader + dataSize;
    int padding = 0;

    if (totalSize % 8 != 0)
      padding = totalSize % 8;

    return totalSize + padding;
  }

  @Override
void setPacker() {
    packer = SimplePackerFactory.create(1, baseType);
  }

}

// Things to do:
//


text:
@font-face {
	font-family: 'icomoon';
	src:url('../../fonts/icomoon.eot?-1pcdel');
	src:url('../../fonts/icomoon.eot?#iefix-1pcdel') format('embedded-opentype'),
		url('../../fonts/icomoon.ttf?-1pcdel') format('truetype'),
		url('../../fonts/icomoon.woff?-1pcdel') format('woff'),
		url('../../fonts/icomoon.svg?-1pcdel#icomoon') format('svg');
	font-weight: normal;
	font-style: normal;
}

[class*="icon-"] {
	font-family: 'icomoon';
	speak: none;
	font-style: normal;
	font-weight: normal;
	font-variant: normal;
	text-transform: none;
	line-height: 1;

	/* Better Font Rendering =========== */
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-user:before {
	content: "\e600";
}


text:
'use strict';

// =============================================================================
// var declaration
// =============================================================================
var mongoose = require('mongoose'),
	Performance = mongoose.model('Performance');

// =============================================================================
// helper function declaration
// =============================================================================
var findPerformance = function(req, res) {
	var currentYear = (new Date()).getFullYear();

	Performance.find({resource: req.user._id, year: currentYear}).exec(function(err, performanceList) {
		if (err) {
			return res.send(400, {message: 'Something error'});
		} else {
			res.jsonp({
				year: currentYear,
				performanceList: performanceList
			});
		}
	});
};

// =============================================================================
// exported function declaration
// =============================================================================
exports.do = function(req, res) {
	findPerformance(req, res);
};


text:
namespace arangodb {
class EndpointUnixDomain final : public Endpoint {
 public:
  //////////////////////////////////////////////////////////////////////////////
  /// @brief creates an endpoint
  //////////////////////////////////////////////////////////////////////////////

  EndpointUnixDomain(EndpointType, int, std::string const&);

  //////////////////////////////////////////////////////////////////////////////
  /// @brief destroys an endpoint
  //////////////////////////////////////////////////////////////////////////////

  ~EndpointUnixDomain();

 public:
  //////////////////////////////////////////////////////////////////////////////
  /// @brief connect the endpoint
  //////////////////////////////////////////////////////////////////////////////

  TRI_socket_t connect(double, double) override;

  //////////////////////////////////////////////////////////////////////////////
  /// @brief disconnect the endpoint
  //////////////////////////////////////////////////////////////////////////////

  void disconnect() override;

  //////////////////////////////////////////////////////////////////////////////
  /// @brief init an incoming connection
  //////////////////////////////////////////////////////////////////////////////

  bool initIncoming(TRI_socket_t) override;

  int domain() const override { return AF_UNIX; }
  int port() const override { return 0; }
  std::string host() const override { return "localhost"; }
  std::string hostAndPort() const override { return "localhost"; }
  std::string path() { return _path; }

 private:
  std::string const _path;
};
}

#endif

#endif


text:
import gzip
import os
import re
import tarfile
import sys

import six.moves import urllib

import tensorflow as tf

# Special vocab. symbols
_PAD = b"_PAD"
_GO  = b"_GO"
_EOS = b"_EOS"
_UNK = b"_UNK"
_START_VOCAB = [_PAD, _GO, _EOS, _UNK]

PAD_ID = 0
GO_ID  = 1
EOS_ID = 2
UNK_ID = 3

# Regular expressions for tokenization
_WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
_DIGIT_RE   = re.compile(br"\d")

# URLs for WMT data
_WMT_ENFR_TRAIN_URL = "http://www.statmt.org/wmt10/training-giga-fren.tar"
_WMT_ENFR_DEV_URL   = "http://www.statmt.org/wmt15/dev-v2.tgz"

def download(directory, filename, url):
    if not os.path.exists(directory):
        print("Creating dir. {}".format(directory))
        os.mkdir(directory)
    filepath = os.path.join(directory, filename)
    if not os.path.exists(filepath):
        def _progress(count, block_size, total_size):
            sys.stdout.write('\r >> Downloading %s %.1f%%' %(filename,
                                                             float(count * block_size) / float(total_size) * 100.0))
            sys.stdout.flush()
        filepath, _ = urllib.requst.urlretrieve(_WMT_ENFR_TRAIN_URL, filepath, _progress)
        print()
        print("Successfully downloading", filename, os.stat(filepath).st_size, "bytes.")
    return filepath

def gunzip_file(gz_path, new_path, remove=True):
    print("Unpacking %s to %s" % (gz_path, new_path))
    with gzip.open(gz_path, "rb") as gz_file:
        with open(new_path, "wb") as new_file:
            for line in gz_file:
                new_file.write(line)

    if remove:
        os.remove(gz_path)

def get_train_set(directory):
    train_path = os.path.join(directory, "giga-fren.release2.fixed")
    if not (gfile.Exists(train_path + ".fr") and gfile.Exists(train_path + ".en")):
        corpus_file = download(directory, "training-giga-fren.tar",
                               _WMT_ENFR_TRAIN_URL)
        print("Extracting tar file %s" % corpus_file)
        with tarfile.open(corpus_file, "r") as corpus_tar:
            corpus_tar.extractall(directory)
        gunzip_file(train_path + ".fr.gz", train_path + ".fr")
        gunzip_file(train_path + ".en.gz", train_path + ".en")
    return train_path

def basic_tokenizer(sentence):
    words = []
    for space_separated_fragment in sentence.strip().split():
        words.extend(_WORD_SPLIT.split(space_separated_fragment))
    return [w for w in words if w]

def create_vocab(vocab_path, data_path, max_vocab_size,
                 tokenizer=None, nomalize_digits=True):
    if not gfile.Exists(vocab_path):
        print("Creating vocabulary %s from data %s" % (vocab_path, data_path))
        vocab = {}
        with gfile.GFile(data_path, mode="rb") as f:
            counter = 0
            for line in f:
                line = tf.compat.as_bytes(line)
                tokens = tokenizer(line) if tokenizer else basic_tokenizer(line)
                for w in tokens:
                    word = _DEGIT_RE.sub(b"0", w) if normalize_digis else w
                    if word in vocab:
                        vocab[word] += 1
                    else:
                        vocab[word] = 1
            vocab_list = _START_VOCAB + sorted(vocab, key=vocab.get, reverse=True)
            if len(vocab_list) > max_vocab_size:
                vocab_list = vocab_list[:max_vocab+_size]
            with gfiel.GFile(vocab_path, mode="wb") as vocab_f:
                for w in vocab_list:
                    vocab_f.write(w + b"\n")

def init_vocab(vocab_path):
    if gfile.Exists(vocab_path):
        rev_vocab = []
        with gfile.GFile(vocab_path, mode="rb") as f:
            rev_vocab.extend(f.readlines())
        rev_vocab = [tf.compat.as_bytes(line.strip()) for line in rev_vocab]
        vocab = dict([ (x,y) for (y, x) in enumerate(rev_vocab)])
        return vocab, rev_vocab
    else:
        raise ValueError("vocab file %s not found.", vocab_path)

def sentence_to_token_ids(sentence, vocab,
                          tokenizer=None, normalize_digits=True):
    if tokenizer:
        words = tokenizer(sentence)
    else:
        words = basic_tokenizer(sentence)
    if not normalize_digits:
        return [vocab.get(w, UNK_ID) for w in words]
    return [vocaburary.get(_DEGIT_RE.sub(b"0", w), UNK_ID) for w in words]

def data_to_token_ids(data_path, target_path, vocab_path,
                      tokenizer=None, normalize_digits=True):
    if not gfile.Exists(target_path):
        print("Tokenizing data in %s" % data_path)
        vocab, _ = initialize_vocab(vocab_path)
        with gfile.GFile(data_path, mode="rb") as data_file:
            with gfile.GFile(target_path, mode="w") as tokens_file:
                for line in data_file:
                    token_ids = sentence_to_token_ids(tf.compat.as_bytes(line), vocab,
                                                                         tokenizer,
                                                                         normalize_digis)
                    tokens_file.write(" ".join([str(tok) for tok in token_ids]) + "\n")

def prepare_wmt_data(data_dir, en_vocab_size, fr_vocab_size, tokenizer=None):
    train_path = get_wmt_enfr_train_set(data_dir)
    dev_path   = get_wmt_enfr_dev_set(data_dir)

    from_train_path = train_path + ".en"
    to_train_path   = train_path + ".fr"
    from_dev_path   = dev_path   + ".en"
    to_dev_path     = dev_path   + ".fr"

    return prepare_data(data_dir, from_train_path, to_train_path,
                        from_dev_path, to_dev_path,
                        en_vocab_size, fr_vocab_size, tokenizer)

def prepare_data(data_dir, from_train_path, to_train_path,
                 from_dev_path, to_dev_path,
                 from_vocab_size, to_vocab_size, tokenizer=None):
    to_vocab_path   = os.path.join(data_dir, "vocab%d.to" % to_vocab_size)
    from_vocab_path = os.path.join(data_dir, "vocab%d.from" % from_vocab_size)
    create_vocab(to_vocab_path, to_train_path, to_vocab_size, tokenizer)
    create_vocab(from_vocab_path, from_train_path, from_vocab_size, tokenizer)

    to_train_ids_path   = to_train_path + (".ids%d" % to_vocab_size)
    from_train_ids_path = from_train_path + (".ids%d" % from_vocab_size)
    data_to_token_ids(to_train_path, to_train_ids_path, to_vocab_size, tokenizer)
    data_to_token_ids(from_train_path, form_train_ids_path, from_vocab_size, tokenizer)

    return (from_train_ids_path, to_train_ids_path,
            from_dev_ids_path, to_dev_ids_path,
            from_vocab_path, to_vocab_path)


text:
"""
@author: Pranay Pradhananga, Damian Katsigiannis
@filename: GoSubLayout.py
@title: GoSubLayout
@description: This is the main program for the Scratchbasic application.
              It consists of four major layout panel: Main Layout, Command Panel Layout, Workspace Layout, Output Layout
              MainLayout is the base layout that instantiates Command Panel, Workspace and Output layout in order
              Each Expression Layout PRINT, LET, IF/GOTO, GOTO is a subclass of Expression Layout
              Such design consideration allows one to add a new expression by simply extending Expression Layout
              This program reuses existing Dumbasic program written in Python to compute the expressions and operations
              An instance of Interpreter class is used to integrate with Dumbasic program
"""

import kivy
from Layouts.Expressions.ExpressionLayout import ExpressionLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget

kivy.require('1.0.6') # current kivy version !

class GoSubLayout(ExpressionLayout):
    """
    Goto Layout represents Gosub expression. It extends the Expression Layout
    """
    def __init__(self, line,  **kwargs):
        super(GoSubLayout, self).__init__(line, 'GOSUB', **kwargs)

        self.cols = 4
        self.padding = 4
        self.height = 40
        self.width = 350

        self.txt_value = TextInput(multiline = False, size_hint =(.3,1))

    """
    Add the widgets to the layout
    """
    def draw(self):
        super(GoSubLayout, self).draw()
        self.add_widget(self.txt_value)

    """
    Get the expression list
    """
    def get_expression(self):
        super(GoSubLayout, self).get_expression()

        line_number = self.txt_value.text
        if line_number.isdigit():
            return [self.name, line_number]
        else:
            return ["Error", "Line number is not valid"]


text:
#include <zephyr.h>

#if CONFIG_JASONTEK_SYNCDEMO
	#include "syncdemo.h"
        K_THREAD_DEFINE(threadA_id, STACKSIZE, threadA, NULL, NULL, NULL,	PRIORITY, 0, K_NO_WAIT);
#else
	#if CONFIG_JASONTEK_SHELLDEMO
		#include "shelldemo.h"
		#define  demo_main  shelldemo_main
	#elif CONFIG_JASONTEK_BTNDEMO
		#include "btndemo.h"
		#define  demo_main  button_main
	#elif CONFIG_JASONTEK_PHILDEMO
		#include "phildemo.h"
		#define  demo_main  phildemo_main
	#elif CONFIG_JASONTEK_PWMDEMO
		#include "pwmdemo.h"
		#define  demo_main  fadedemo_main
	#endif
void main(void)
{
	demo_main();
}
#endif