text:
var socketHandler = require('socket.io-events')()
  , cookieParser = require('cookie-parser')
  , store = require('./store')
  , config = require('../config')
  , passportSocketIo = require("passport.socketio");

/**
 * Everything related to the socket business logic
 */
var socket = function (server) {
  var io = require('socket.io')(server);

  // Load user in session
  io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    key:          config.session.name,    // the name of the cookie where express/connect stores its session_id
    secret:       config.session.secret,  // the session_secret to parse the cookie
    store:        store.session,          // we NEED to use a sessionstore. no memorystore please
    fail:         function (data, message, error, accept) {
      if (error) {
        accept(new Error(message));
      } else {
        accept(null, true);
      }
    }
  }));

  // On any socket event we route to the right service
  socketHandler.on(function (socket, args, next) {
    var parts = args[0].split('/');
    return require('../app/service/' + parts[0])[parts[1]](socket, args[1]);
  });

  // Register the socket
  io.use(socketHandler);

  // On connection, do nothing
  io.on('connection', function (socket) {
    socket.emit('user', socket.request.user);
  });

  console.log('Ready to serve socket events!');
}

module.exports = socket;


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.ComponentModel;
using Microsoft.AspNet.WebHooks.Config;

namespace System.Web.Http
{
    /// <summary>
    /// Extension methods for <see cref="HttpConfiguration"/>.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class HttpConfigurationExtensions
    {
        /// <summary>
        /// Initializes support for receiving Stripe WebHooks.
        /// Set the '<c>MS_WebHookReceiverSecret_Stripe</c>' application setting to the application key defined in Stripe.
        /// The corresponding WebHook URI is of the form '<c>https://<host>/api/webhooks/incoming/stripe</c>'.
        /// For details about Stripe WebHooks, see <c>https://stripe.com/docs/webhooks</c>.
        /// </summary>
        /// <param name="config">The current <see cref="HttpConfiguration"/>config.</param>
        public static void InitializeReceiveStripeWebHooks(this HttpConfiguration config)
        {
            WebHooksConfig.Initialize(config);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class Libdap < Formula
  desc "Framework for scientific data networking"
  homepage "https://www.opendap.org/"
  url "https://www.opendap.org/pub/source/libdap-3.19.1.tar.gz"
  sha256 "5215434bacf385ba3f7445494ce400a5ade3995533d8d38bb97fcef1478ad33e"

  bottle do
    sha256 "acb605289bb709760f85304a454047adc51bc7c62f789b1a6e994def60320707" => :high_sierra
    sha256 "643d28d3e211bbca74f1d3a11e3af23128e5da457551d695d6e23fd350bb673c" => :sierra
    sha256 "999d0a4e5235b9c646047e12ebf48c023f073f66ee7cc9952d2873242a66c8b7" => :el_capitan
  end

  head do
    url "https://github.com/OPENDAP/libdap4.git"

    depends_on "automake" => :build
    depends_on "autoconf" => :build
    depends_on "libtool" => :build
  end

  option "without-test", "Skip build-time tests (Not recommended)"

  depends_on "pkg-config" => :build
  depends_on "bison" => :build
  depends_on "libxml2"
  depends_on "openssl"

  needs :cxx11 if MacOS.version < :mavericks

  def install
    # Otherwise, "make check" fails
    ENV.cxx11 if MacOS.version < :mavericks

    args = %W[
      --prefix=#{prefix}
      --disable-dependency-tracking
      --disable-debug
      --with-included-regex
    ]

    # Let's try removing this for OS X > 10.6; old note follows:
    # __Always pass the curl prefix!__
    # Otherwise, configure will fall back to pkg-config and on Leopard
    # and Snow Leopard, the libcurl.pc file that ships with the system
    # is seriously broken---too many arch flags. This will be carried
    # over to `dap-config` and from there the contamination will spread.
    args << "--with-curl=/usr" if MacOS.version <= :snow_leopard

    system "autoreconf", "-fvi" if build.head?
    system "./configure", *args
    system "make"
    system "make", "check" if build.with? "test"
    system "make", "install"

    # Ensure no Cellar versioning of libxml2 path in dap-config entries
    xml2 = Formula["libxml2"]
    inreplace bin/"dap-config", xml2.opt_prefix.realpath, xml2.opt_prefix
  end

  test do
    assert_match version.to_s, shell_output("#{bin}/dap-config --version")
  end
end


text:
require File.join( File.dirname( File.expand_path(__FILE__)), 'smell_detector')
require File.join(File.dirname(File.dirname(File.expand_path(__FILE__))), 'smell_warning')
require File.join(File.dirname(File.dirname(File.expand_path(__FILE__))), 'core', 'smell_configuration')

module Reek
  module Smells

    #
    # A class that publishes a getter or setter for an instance variable
    # invites client classes to become too intimate with its inner workings,
    # and in particular with its representation of state.
    #
    # Currently this detector raises a warning for every +attr+,
    # +attr_reader+, +attr_writer+ and +attr_accessor+ -- including those
    # that are private.
    #
    # TODO:
    # * eliminate private attributes
    # * catch attributes declared "by hand"
    #
    class Attribute < SmellDetector

      SMELL_CLASS = self.name.split(/::/)[-1]
      SMELL_SUBCLASS = SMELL_CLASS

      ATTRIBUTE_KEY = 'attribute'

      def self.contexts      # :nodoc:
        [:class, :module]
      end

      def self.default_config
        super.adopt(Core::SmellConfiguration::ENABLED_KEY => false)
      end

      def initialize(source, config = Attribute.default_config)
        super(source, config)
      end

      #
      # Checks whether the given class declares any attributes.
      #
      # @return [Array<SmellWarning>]
      #
      def examine_context(ctx)
        attributes_in(ctx).map do |attr, line|
          smell = SmellWarning.new(SMELL_CLASS, ctx.full_name, [line],
            "declares the attribute #{attr}",
            @source, SMELL_SUBCLASS,
            {ATTRIBUTE_KEY => attr.to_s})
          smell
        end
      end

    private

      def attributes_in(module_ctx)
        result = Set.new
        attr_defn_methods = [:attr, :attr_reader, :attr_writer, :attr_accessor]
        module_ctx.local_nodes(:call) do |call_node|
          if attr_defn_methods.include?(call_node.method_name)
            call_node.arg_names.each {|arg| result << [arg, call_node.line] }
          end
        end
        result
      end
    end
  end
end


text:
var RX = require("rx");
var MongoWrapper = require("../mongo-wrapper");

function vapor(args, dataSources) {
  dataSources.get("creationMap").set(args.name, args.key, args, "mongo-insert-one");
}

module.exports = function (args, dataSources) {
  var name = args.name;
  var connectString = args.connectionString;
  var collectionName = args.collectionName;
  var dataSource = dataSources.get(args.key);

  var subscription = dataSource.subscribe(function (data) {
    if (data === null || data === undefined) {
      subscription.dispose();
      dataSources.get("dataSinkInstances").remove(args.name);
      return;
    }
    MongoWrapper.connectToMongo(connectString).then(function (db) {
      return MongoWrapper.insertOne(db, collectionName, data);
    });
  }, function (err) {
    console.log(err);
  }, function () {
    dataSources.get("dataSinkInstances").remove(args.name);
  });

  vapor(args, dataSources);
  dataSources.get("dataSinkInstances").set(args.name, subscription);
};

module.exports.vapor = vapor;

module.exports.getArguments = function _callee(prompt, dataSources) {
  var name, fromSource, connectionString, collectionName;
  return regeneratorRuntime.async(function _callee$(_context) {
    while (1) switch (_context.prev = _context.next) {
      case 0:
        _context.next = 2;
        return regeneratorRuntime.awrap(prompt("What name will you give this new instance?\n"));

      case 2:
        name = _context.sent;
        _context.next = 5;
        return regeneratorRuntime.awrap(prompt("What source will this be applied to?\n"));

      case 5:
        fromSource = _context.sent;
        _context.next = 8;
        return regeneratorRuntime.awrap(prompt("Input connection string for mongodb:\n"));

      case 8:
        connectionString = _context.sent;
        _context.next = 11;
        return regeneratorRuntime.awrap(prompt("Input collection this will be inserting:\n"));

      case 11:
        collectionName = _context.sent;
        return _context.abrupt("return", {
          name: name,
          key: fromSource,
          connectionString: connectionString,
          collectionName: collectionName
        });

      case 13:
      case "end":
        return _context.stop();
    }
  }, null, this);
};

module.exports.initialize = function (dataSources) {
  dataSources.get("translations").set("mongo-insert-one", module.exports);
};


text:
<?php
// @codingStandardsIgnoreFile
use Joindin\Api\ContainerFactory;
use Joindin\Api\Request;
use Joindin\Api\Router\ApiRouter;
use Joindin\Api\Router\DefaultRouter;
use Joindin\Api\Router\VersionedRouter;

include __DIR__ . '/../../vendor/autoload.php';
if (!function_exists('apache_request_headers')) {
    include '../inc/nginx-helper.php';
}
if (!ini_get('date.timezone')) {
    date_default_timezone_set('UTC');
}
// Add exception handler
function handle_exception(\Throwable $e)
{
    // pull the correct format before we bail
    global $request, $config;
    $status_code = $e->getCode() ?: 400;
    $status_code = is_numeric($status_code) ? $status_code : 500;
    $request->getView()->setResponseCode($status_code);

    if ($status_code === 401) {
        $request->getView()->setHeader('WWW-Authenticate', 'Bearer realm="api.joind.in');
    }

    error_log(get_class($e) . ': ' . $e->getMessage() . " -- " . $e->getTraceAsString());

    $message = $e->getMessage();
    if ($e instanceof PDOException && (!isset($config['mode']) || $config['mode'] !== "development")) {
        $message = "Database error";
    }
    $request->getView()->render([$message]);
}

set_exception_handler('handle_exception');

// config setup
define('BASEPATH', '.');
include '../config.php';

$container = ContainerFactory::build($config);

if ($config['mode'] == "development") {
    ini_set("html_errors", 0);
}

// database setup
include '../database.php';
$ji_db = new PDO(
    'mysql:host=' . $db['default']['hostname'] .
    ';dbname=' . $db['default']['database'] . ';charset=utf8mb4',
    $db['default']['username'],
    $db['default']['password']
);
$ji_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// collect URL and headers
$request = new Request($config, $_SERVER);

// identify our user if applicable
$headers = array_change_key_case(apache_request_headers(), CASE_LOWER);
if (isset($headers['authorization'])) {
    $request->identifyUser($headers['authorization'], $ji_db);
}

// @TODO This feels just a tad... shonky.
$rules = json_decode(file_get_contents('../config/routes/2.1.json'), true);

$routers = [
    "v2.1" => new VersionedRouter('2.1', $config, $rules),
    '' => new DefaultRouter($config),
];
$router = new ApiRouter($config, $routers, ['2']);

$route = $router->getRoute($request);
$return_data = $route->dispatch($request, $ji_db, $container);
if (is_array($return_data) && isset($request->user_id)) {
    $return_data['meta']['user_uri'] = $request->base . '/' . $request->version . '/users/' . $request->user_id;
}
// Handle output
// TODO sort out headers, caching, etc
$request->getView()->render($return_data);


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<qualifiedTypeNameHistroy>
<fullyQualifiedTypeName name="javax.swing.text.DefaultStyledDocument"/>
<fullyQualifiedTypeName name="javax.swing.text.rtf.RTFEditorKit"/>
<fullyQualifiedTypeName name="javax.swing.text.BadLocationException"/>
<fullyQualifiedTypeName name="java.io.File"/>
<fullyQualifiedTypeName name="javax.swing.text.Document"/>
<fullyQualifiedTypeName name="java.lang.InterruptedException"/>
<fullyQualifiedTypeName name="java.util.Hashtable"/>
<fullyQualifiedTypeName name="org.apache.logging.log4j.LogManager"/>
<fullyQualifiedTypeName name="org.apache.logging.log4j.Logger"/>
<fullyQualifiedTypeName name="java.sql.Driver"/>
<fullyQualifiedTypeName name="java.sql.Connection"/>
<fullyQualifiedTypeName name="java.util.Properties"/>
<fullyQualifiedTypeName name="java.io.InputStream"/>
<fullyQualifiedTypeName name="java.util.Date"/>
<fullyQualifiedTypeName name="java.awt.List"/>
<fullyQualifiedTypeName name="onlinebookstore.entity.Category"/>
<fullyQualifiedTypeName name="java.util.List"/>
<fullyQualifiedTypeName name="javax.swing.JButton"/>
<fullyQualifiedTypeName name="java.awt.BorderLayout"/>
<fullyQualifiedTypeName name="javax.swing.JPanel"/>
<fullyQualifiedTypeName name="java.awt.Color"/>
<fullyQualifiedTypeName name="java.lang.System"/>
<fullyQualifiedTypeName name="java.lang.String"/>
</qualifiedTypeNameHistroy>


text:
/* @flow */

var Implicit = require('ImplicitProvidesModule');
(Implicit.fun(): boolean); // Error: Either Implementation ~> boolean or Declaration ~> boolean

var ExplicitSameName = require('ExplicitProvidesModuleSameName');
(ExplicitSameName.fun(): boolean); // Error: Either Implementation ~> boolean or Declaration ~> boolean

var ExplicitDifferentName = require('ExplicitProvidesModuleDifferentName');
(ExplicitDifferentName.fun(): boolean); // Error: Either Implementation ~> boolean or Declaration ~> boolean


text:
Frequently Asked Questions (FAQ)
================================

The [Frequently Asked Questions][FAQ] are now maintained on the OpenSSL homepage.

  [FAQ]: https://www.openssl.org/docs/faq.html


text:
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */
/*
 * Author: Zion Orent <zorent@ics.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

//Load servo module.
var servoModule = require("jsupm_servo");

//Instantiate ES08A Servo module on GPIO 5
var servo = new servoModule.ES08A(5);

// function to initialize servo
    // timeOffset: how long after hitting "run"
    //		should we start this servo instance
    // timeInterval: how frequently should this instance run after timeOffset
    // angle: the angle for this instance
function startServo(timeOffset, timeInterval, angle)
{
    // Start running this instance after timeOffset milliseconds
    setTimeout(function()
    {
        // run this instance every timeInterval milliseconds
        setInterval(function()
        {
            servo.setAngle(angle);
            console.log("Set angle to " + angle);
        }, timeInterval);
    }, timeOffset);
    // timeOffset tells setTimeout when
    //		to execute the function specified in the first param
    // angle is passed as a param to the specified function
}
// start immediately, run every 3 seconds, go 0 degrees
startServo(0, 3000, 0);

// start in 1 second, run every 3 seconds, go 90 degrees
startServo(1000, 3000, 90);

// start in 2 seconds, run every 3 seconds, go 180 degrees
startServo(2000, 3000, 180);

// Print message when exiting
process.on('SIGINT', function()
{
	console.log("Exiting...");
	process.exit(0);
});


text:
using FM4CC.ExecutionEngine;
using FM4CC.FaultModels.Sine.Parsers;
using FM4CC.TestCase;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;

namespace FM4CC.FaultModels.Sine
{
    internal class WorstCaseScenarioWorker : BackgroundWorker
    {
        internal FM4CCException Exception { get; set; }
        internal IList<DataGridHeatPoint> SelectedRegions {get; set;}
        internal IList<TestCase.FaultModelTesterTestCase> TestCases { get; set; }
        internal Action<string> Logger { get; set; }

        private static System.Timers.Timer aTimer;
        private SineFaultModel fm;
        private bool isRunning;

        internal WorstCaseScenarioWorker()
        {
            this.Exception = null;
            this.WorkerReportsProgress = true;
            this.WorkerSupportsCancellation = true;
            this.DoWork += singleStateWorker_DoWork;
        }

        private void singleStateWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                this.Exception = null;
                isRunning = false;
                if (SelectedRegions == null) throw new FM4CCException("Search regions not set");

                aTimer = new System.Timers.Timer(100);
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                aTimer.Enabled = true;
                aTimer.AutoReset = true;

                fm = e.Argument as SineFaultModel;
                ExecutionInstance currentTestProject = fm.ExecutionInstance;

                string message = null;
                fm.ExecutionEngine.AcquireProcess();

                // Sets up the environment of the execution engine
                fm.ExecutionInstance = currentTestProject;
                fm.SetUpEnvironment();

                e.Result = true;

                int i = 0;
                foreach (DataGridHeatPoint region in SelectedRegions)
                {
                    int requirementIndex = 1;

                    switch (region.Requirement)
                    {
                        case "Stability":
                            requirementIndex = 1;
                            break;
                        case "Precision":
                            requirementIndex = 2;
                            break;
                        case "Smoothness":
                            requirementIndex = 3;
                            break;
                        case "Responsiveness":
                            requirementIndex = 4;
                            break;
                        case "Steadiness":
                            requirementIndex = 5;
                            break;
                    }

                    fm.SetSearchParameters(requirementIndex, region.FrequencyRegion, region.DesiredRegion, region.ContainedHeatPoint, (string)fm.FaultModelConfiguration.GetValue("OptimizationAlgorithm"));

                    isRunning = true;

                    if (Double.IsInfinity(region.ContainedHeatPoint.Intensity))
                    {
                        i++;
                        this.ReportProgress((int)((double)i / SelectedRegions.Count * 100.0));
                        continue;
                    }
                    message = (string)fm.Run("WorstCaseSearch");

                    if (!message.ToLower().Contains("success"))
                    {
                        if (!message.ToLower().Contains("fitting error"))
                        {
                            e.Result = false;
                            this.Exception = new FM4CCException(message);
                            break;
                        }
                        else
                        {
                            string chosenRegressionFunction = fm.ExecutionEngine.GetVariable("ChosenRegressionFunction");
                            double rmse = fm.ExecutionEngine.GetVariable("BestRMSE");
                            double qualityThreshold = fm.ExecutionEngine.GetVariable("RegressionQualityThreshold");
                            string bestRegressionFunction = fm.ExecutionEngine.GetVariable("BestRegressionFunction");
                            // use the worst point found while computing the training set
                            fm.ExecutionEngine.ExecuteCommand("tmpVar = TrainingSet.Input(worstObjectiveFunctions(1,1),:)");
                            double[,] bestPoint = fm.ExecutionEngine.GetVariable("tmpVar");

                            Logger("Sine Fault Model - Accelerated worst case computation for " + region.Requirement + " failed. Unable to fit data to regressed model, falling back to doing simple Simulated Annealing. Best regression function was " + bestRegressionFunction + " (RMSE: " + rmse.ToString() + ", Threshold: " + qualityThreshold.ToString() + ").");
                            fm.SetSearchParameters(requirementIndex, region.FrequencyRegion, region.DesiredRegion, new SineHeatPoint(bestPoint[0,0], bestPoint[0,1], 0.0, 0.0, false), "SimulatedAnnealing");
                            message = (string)fm.Run("WorstCaseSearch");
                        }
                    }
                    else
                    {
                        string chosenRegressionFunction = fm.ExecutionEngine.GetVariable("ChosenRegressionFunction");
                        double rmse = fm.ExecutionEngine.GetVariable("BestRMSE");
                        double qualityThreshold = fm.ExecutionEngine.GetVariable("RegressionQualityThreshold");

                        Logger("Sine Fault Model - Accelerated worst case computation successful for " + region.Requirement + ". Regression function " + chosenRegressionFunction + " selected (RMSE: " + rmse.ToString() + ", Threshold: " + qualityThreshold.ToString() + ").");
                    }
                    i++;
                    this.ReportProgress((int)((double)i / SelectedRegions.Count * 100.0));

                    string worstPointFile = Path.GetDirectoryName(fm.ExecutionInstance.GetValue("SUTPath")) + "\\ControllerTesterResults\\SingleStateSearch\\SingleStateSearch_WorstCase.csv";
                    ProcessWorstCaseResults(region, worstPointFile, fm.ToString());
                }

                aTimer.Enabled = false;

                // Tears down the environment
                fm.TearDownEnvironment(false);

                // Relinquishes control of the execution engine
                fm.ExecutionEngine.RelinquishProcess();
            }
            catch (TargetInvocationException)
            {
                e.Result = false;
            }

        }

        private void ProcessWorstCaseResults(DataGridHeatPoint region, string worstPointFile, string faultModelName)
        {
            FaultModelTesterTestCase testCase = new SineFaultModelTestCase();
            testCase.FaultModel = faultModelName;
            testCase.Name = "Worst " + region.Requirement + " (sine) in region (" +
                String.Format("{0:0.##}", region.FrequencyRegion * region.BaseUnitFrequency) + " to " +
                String.Format("{0:0.##}", (region.FrequencyRegion + 1) * region.BaseUnitFrequency) + ")x(" +
                String.Format("{0:0.##}", region.DesiredRegion * region.BaseUnit) + " to " +
                String.Format("{0:0.##}", (region.DesiredRegion + 1) * region.BaseUnit) + ")";
            testCase.Input = SingleStateSearchParser.Parse(worstPointFile);
            TestCases.Add(testCase);
        }

        private void OnTimedEvent(object sender, ElapsedEventArgs e)
        {
            if (this.CancellationPending)
            {
                if (isRunning)
                {
                    // kill the execution engine and relinquish control
                    aTimer.Enabled = false;
                    fm.ExecutionEngine.Kill();
                    fm.TearDownEnvironment(false);
                    fm.ExecutionEngine.RelinquishProcess();
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BasicallyMe.RobinhoodNet.DataTypes;

namespace RobinhoodDesktop
{
	public partial class LogInForm : Form
	{
		SMS_Code sms_gui = new SMS_Code();
		ChallengeInfo currChallenge;
		public string deviceToken;
		string challengeID = "";
		public LogInForm()
		{
			InitializeComponent();

			// Add logic for when the user interacts with the verify screen
			sms_gui.btn_Verify.MouseUp += (sender, e) =>
			{
				(var success, var challenge) = Broker.Instance.ChallengeResponse(currChallenge.challenge.id, sms_gui.txt_SMS_Code.Text);
				if (success)
				{
					if (challenge.challenge.status == "validated")
					{
						challengeID = challenge.challenge.id;
						GuiPanel.Controls.Remove(sms_gui.smsVerifyPanel);
						ErrorLabel.Text = "Success! You can now sign in!!!";
						GuiPanel.Refresh();
					}
					else
					{
						ErrorLabel.Text = "Error: Invalid pin: " + challenge.challenge.remaining_retries + " retries left";
						GuiPanel.Refresh();
					}
				}
				else
				{
					ErrorLabel.Text = "Error: Invalid pin: " + challenge.challenge.remaining_retries + " retries left";
					GuiPanel.Refresh();
				}
			};
		}

		private void LogIn_Load(object sender, EventArgs e)
		{

		}

		private void panel1_Paint(object sender, PaintEventArgs e)
		{

		}

		private void Login_Click(object sender, EventArgs e)
		{
			(var success, var challenge) = Broker.Instance.SignIn(Username.Text, Password.Text, deviceToken, challengeID);

			if (challenge == null)
			{
				ErrorLabel.Text = "Error: Robinhood appears to have changed their login API, or there is an error with ours";
				GuiPanel.Refresh();
			}
			else if (!success && challenge.challenge.status == "issued")
			{
				currChallenge = challenge;
				GuiPanel.Controls.Add(sms_gui.smsVerifyPanel);
				GuiPanel.Refresh();
			}
			else
			{
				Password.Text = "";
				if (!Broker.Instance.IsSignedIn())
				{
					ErrorLabel.Text = "Error: Invalid username or password";
					GuiPanel.Refresh();
				}
			}
		}
	}
}


text:
package com.sksamuel.elastic4s.search.queries

import com.sksamuel.elastic4s.testkit.DockerTests
import org.scalatest.{Matchers, WordSpec}

import scala.util.Try

class RawQueryTest extends WordSpec with Matchers with DockerTests {

  Try {
    client.execute {
      deleteIndex("rawquerytest")
    }.await
  }

  client.execute {
    bulk(
      indexInto("rawquerytest/paris").fields("landmark" -> "montmarte", "arrondissement" -> "18"),
      indexInto("rawquerytest/paris").fields("landmark" -> "le tower eiffel", "arrondissement" -> "7")
    ).refreshImmediately
  }.await

  "raw query" should {
    "work!" ignore {
      client.execute {
        search("*").types("paris") limit 5 rawQuery {
          """{ "prefix": { "landmark": { "prefix": "montm" } } }"""
        }
      }.await.result.totalHits shouldBe 1
    }
  }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link rel="stylesheet" type="text/css" media="screen" href="__BASEURL__/static/gregor.js/gregor.css" />

  <link rel="stylesheet" type="text/css" media="screen" href="__BASEURL__/static/tailwind.css" />

  <![if !IE]>

  <![endif]>

      <tt id="system_error"></tt>

System trace (for computer programmers purposes)

        close


text:
/**
 * @fileoverview
 * Three-state animated button class
 */

/**
 * @constructor
 * @argument target {Object} animation definition dictionary
 *
 *
 * @class
 *
 *
Note: the classname "Animator" is a bit of a misnomer. It's more of a
 * three-state-button-o-matic. Might be renamed at a later date (runeh)

 *
 * Handle a two or three state button with support for animaton. The button
 * has an initial state, an active state (possibly animated), and optionally
 * a final state. An example is a "connect" button. It starts out passive.
 * When pressed it animates a progress indicator, and when connected, it turns
 * green.
 *
 * The initial state is always the first in the image, that is, positioned
 * at 0px from the top. Hence, one does not need to pass an argument to
 * the constructor to set up the initial state.
 *
 * The animation is configured by passing a dictionary with settings. The
 * dictionary contains the following:
 *
 *

 *
id (required)
The id of the element to operate as a string
 *
delta (required)
The height of a frame of animation in pixels as an int
 *
iterations (required)
The number of frames in the active state as in int
 *
active (optional)
The offset of the first active state frame in the image in pixels as an int. Default: 0
 *
final (optional)
The offset of the final state frame in the image in pixels as an int. Default: 0
 *
x_position (optional)
The vertial offset of the strip of frames in the image in pixels as an int. Default: 0px
 *
time_delta (optional)
The time between each frame in ms as an int. FPS is then equal to 1000/time_delta. Default: 30ms
 *

 *
 *
 */
var Animator = function(target)
{
  var id = target.id;
  var delta = target.delta;
  var iterations = target.iterations;
  var active = target.active || 0;
  var finalState = target.ready || 0;
  var x_position = target.x_position || '0px ';
  var time_delta = target.time_delta || 30;
  var current_count = 0;
  var interval = 0;

  /**
   * Tick function, called every time_delta to update state of animation
   * @private
   */
  var spin = function()
  {
    var ele = document.getElementById(id);
    if( ele )
    {
      ele.style.backgroundPosition = x_position + ( active + ( current_count++ ) * delta ) + 'px';
      if( current_count >= iterations )
      {
        current_count = 0;
      }
    }
  }

  /**
   * Start the animation
   */
  this.setActive = function()
  {
    interval = interval ? interval : setInterval( spin, time_delta );
  }

  /**
   * Stop the animation and place it in its final state. If there is not
   * final state, default to initial state.
   */
  this.setFinal = function()
  {
    interval = interval ? clearInterval(interval) : 0;
    var ele = document.getElementById(id);
    if( ele )
    {
      ele.style.backgroundPosition = x_position + ( finalState ) + 'px';
      current_count = 0;
    }
  }

  /**
   * Stop the animation and place the animation in its initial state
   */
  this.setInitial = function()
  {
    interval = interval ? clearInterval(interval) : 0;
    if( ele = document.getElementById(id) )
    {
      ele.style.backgroundPosition = x_position + ( 0 ) + 'px';
      current_count = 0;
    }
  }

  /**
   * Return the ID of the element the animator is handling
   * @returns {String} the id
   *
   */
  this.getId = function()
  {
    return id;
  }

  this.getState = function()
  {
    var ele = document.getElementById(id);
    return ( interval && 'active'
      || ele && ele.style.backgroundPosition.indexOf(' ' + finalState + 'px') != -1 && 'final'
      || 'initial' );
  }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<model xmlns="http://dev.meisen.net/xsd/dissertation/model"
       xmlns:fxd="http://dev.meisen.net/xsd/dissertation/model/fxd"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://dev.meisen.net/xsd/dissertation/model     http://dev.meisen.net/xsd/dissertation/tidaModel.xsd
                           http://dev.meisen.net/xsd/dissertation/model/fxd http://dev.meisen.net/xsd/dissertation/tidaFixedStructureExtension.xsd"

       id="testModel">

  <config>
    <factories>
      <indexes implementation="net.meisen.dissertation.impl.indexes.IndexFactory" />
    </factories>

    <dataretrievers>
      <dataretriever id="fxd_test">
        <fxd:record>
          <fxd:field name="DOUBLE" type="java.lang.Double" />
        </fxd:record>
      </dataretriever>
    </dataretrievers>
  </config>

  <meta>
    <descriptors>
      <string id="RES" />
    </descriptors>

    <entries>
      <entry descriptor="RES" dataretriever="fxd_test_undefined">
        <fxd:query amount="1" />
      </entry>
    </entries>
  </meta>

  <data />
</model>


text:
"""
storage.py: support for using Banana as if it were pickle

This includes functions for serializing to and from strings, instead of a
network socket. It also has support for serializing 'unsafe' objects,
specifically classes, modules, functions, and instances of arbitrary classes.
These are 'unsafe' because to recreate the object on the deserializing end,
we must be willing to execute code of the sender's choosing (i.e. the
constructor of whatever package.module.class names they send us). It is
unwise to do this unless you are willing to allow your internal state to be
compromised by the author of the serialized data you're unpacking.

This functionality is isolated here because it is never used for data coming
over network connections.
"""

from cStringIO import StringIO
import types
from new import instance, instancemethod
from pickle import whichmodule  # used by FunctionSlicer

from foolscap import slicer, banana, tokens
from foolscap.tokens import BananaError
from twisted.internet.defer import Deferred
from twisted.python import reflect
from foolscap.slicers.dict import OrderedDictSlicer
from foolscap.slicers.root import ScopedRootSlicer, ScopedRootUnslicer

################## Slicers for "unsafe" things

# Extended types, not generally safe. The UnsafeRootSlicer checks for these
# with a separate table.

def getInstanceState(inst):
    """Utility function to default to 'normal' state rules in serialization.
    """
    if hasattr(inst, "__getstate__"):
        state = inst.__getstate__()
    else:
        state = inst.__dict__
    return state

class InstanceSlicer(OrderedDictSlicer):
    opentype = ('instance',)
    trackReferences = True

    def sliceBody(self, streamable, banana):
        yield reflect.qual(self.obj.__class__) # really a second index token
        self.obj = getInstanceState(self.obj)
        for t in OrderedDictSlicer.sliceBody(self, streamable, banana):
            yield t

class ModuleSlicer(slicer.BaseSlicer):
    opentype = ('module',)
    trackReferences = True

    def sliceBody(self, streamable, banana):
        yield self.obj.__name__

class ClassSlicer(slicer.BaseSlicer):
    opentype = ('class',)
    trackReferences = True

    def sliceBody(self, streamable, banana):
        yield reflect.qual(self.obj)

class MethodSlicer(slicer.BaseSlicer):
    opentype = ('method',)
    trackReferences = True

    def sliceBody(self, streamable, banana):
        yield self.obj.im_func.__name__
        yield self.obj.im_self
        yield self.obj.im_class

class FunctionSlicer(slicer.BaseSlicer):
    opentype = ('function',)
    trackReferences = True

    def sliceBody(self, streamable, banana):
        name = self.obj.__name__
        fullname = str(whichmodule(self.obj, self.obj.__name__)) + '.' + name
        yield fullname

UnsafeSlicerTable = {}
UnsafeSlicerTable.update({
    types.InstanceType: InstanceSlicer,
    types.ModuleType: ModuleSlicer,
    types.ClassType: ClassSlicer,
    types.MethodType: MethodSlicer,
    types.FunctionType: FunctionSlicer,
    #types.TypeType: NewstyleClassSlicer,
    # ???: NewstyleInstanceSlicer,  # pickle uses obj.__reduce__ to help
    # http://docs.python.org/lib/node68.html
    })

# the root slicer for storage is exactly like the regular root slicer
class StorageRootSlicer(ScopedRootSlicer):
    pass

# but the "unsafe" one (which handles instances and stuff) uses its own table
class UnsafeStorageRootSlicer(StorageRootSlicer):
    slicerTable = UnsafeSlicerTable

################## Unslicers for "unsafe" things

def setInstanceState(inst, state):
    """Utility function to default to 'normal' state rules in unserialization.
    """
    if hasattr(inst, "__setstate__"):
        inst.__setstate__(state)
    else:
        inst.__dict__ = state
    return inst

class Dummy:
    def __repr__(self):
        return "<Dummy %s>" % self.__dict__
    def __cmp__(self, other):
        if not type(other) == type(self):
            return -1
        return cmp(self.__dict__, other.__dict__)

UnsafeUnslicerRegistry = {}

class InstanceUnslicer(slicer.BaseUnslicer):
    # this is an unsafe unslicer: an attacker could induce you to create
    # instances of arbitrary classes with arbitrary attributes: VERY
    # DANGEROUS!
    opentype = ('instance',)
    unslicerRegistry = UnsafeUnslicerRegistry

    # danger: instances are mutable containers. If an attribute value is not
    # yet available, __dict__ will hold a Deferred until it is. Other
    # objects might be created and use our object before this is fixed.
    # TODO: address this. Note that InstanceUnslicers aren't used in PB
    # (where we have pb.Referenceable and pb.Copyable which have schema
    # constraints and could have different restrictions like not being
    # allowed to participate in reference loops).

    def start(self, count):
        self.d = {}
        self.count = count
        self.classname = None
        self.attrname = None
        self.deferred = Deferred()
        self.protocol.setObject(count, self.deferred)

    def checkToken(self, typebyte, size):
        if self.classname is None:
            if typebyte not in (tokens.STRING, tokens.VOCAB):
                raise BananaError("InstanceUnslicer classname must be string")
        elif self.attrname is None:
            if typebyte not in (tokens.STRING, tokens.VOCAB):
                raise BananaError("InstanceUnslicer keys must be STRINGs")

    def receiveChild(self, obj, ready_deferred=None):
        assert ready_deferred is None
        if self.classname is None:
            self.classname = obj
            self.attrname = None
        elif self.attrname is None:
            self.attrname = obj
        else:
            if isinstance(obj, Deferred):
                # TODO: this is an artificial restriction, and it might
                # be possible to remove it, but I need to think through
                # it carefully first
                raise BananaError("unreferenceable object in attribute")
            if self.d.has_key(self.attrname):
                raise BananaError("duplicate attribute name '%s'" %
                                  self.attrname)
            self.setAttribute(self.attrname, obj)
            self.attrname = None

    def setAttribute(self, name, value):
        self.d[name] = value

    def receiveClose(self):
        # you could attempt to do some value-checking here, but there would
        # probably still be holes

        #obj = Dummy()
        klass = reflect.namedObject(self.classname)
        assert type(klass) == types.ClassType # TODO: new-style classes
        obj = instance(klass, {})

        setInstanceState(obj, self.d)

        self.protocol.setObject(self.count, obj)
        self.deferred.callback(obj)
        return obj, None

    def describe(self):
        if self.classname is None:
            return "<??>"
        me = "<%s>" % self.classname
        if self.attrname is None:
            return "%s.attrname??" % me
        else:
            return "%s.%s" % (me, self.attrname)

class ModuleUnslicer(slicer.LeafUnslicer):
    opentype = ('module',)
    unslicerRegistry = UnsafeUnslicerRegistry

    finished = False

    def checkToken(self, typebyte, size):
        if typebyte not in (tokens.STRING, tokens.VOCAB):
            raise BananaError("ModuleUnslicer only accepts strings")

    def receiveChild(self, obj, ready_deferred=None):
        assert not isinstance(obj, Deferred)
        assert ready_deferred is None
        if self.finished:
            raise BananaError("ModuleUnslicer only accepts one string")
        self.finished = True
        # TODO: taste here!
        mod = __import__(obj, {}, {}, "x")
        self.mod = mod

    def receiveClose(self):
        if not self.finished:
            raise BananaError("ModuleUnslicer requires a string")
        return self.mod, None

class ClassUnslicer(slicer.LeafUnslicer):
    opentype = ('class',)
    unslicerRegistry = UnsafeUnslicerRegistry

    finished = False

    def checkToken(self, typebyte, size):
        if typebyte not in (tokens.STRING, tokens.VOCAB):
            raise BananaError("ClassUnslicer only accepts strings")

    def receiveChild(self, obj, ready_deferred=None):
        assert not isinstance(obj, Deferred)
        assert ready_deferred is None
        if self.finished:
            raise BananaError("ClassUnslicer only accepts one string")
        self.finished = True
        # TODO: taste here!
        self.klass = reflect.namedObject(obj)

    def receiveClose(self):
        if not self.finished:
            raise BananaError("ClassUnslicer requires a string")
        return self.klass, None

class MethodUnslicer(slicer.BaseUnslicer):
    opentype = ('method',)
    unslicerRegistry = UnsafeUnslicerRegistry

    state = 0
    im_func = None
    im_self = None
    im_class = None

    # self.state:
    # 0: expecting a string with the method name
    # 1: expecting an instance (or None for unbound methods)
    # 2: expecting a class

    def checkToken(self, typebyte, size):
        if self.state == 0:
            if typebyte not in (tokens.STRING, tokens.VOCAB):
                raise BananaError("MethodUnslicer methodname must be a string")
        elif self.state == 1:
            if typebyte != tokens.OPEN:
                raise BananaError("MethodUnslicer instance must be OPEN")
        elif self.state == 2:
            if typebyte != tokens.OPEN:
                raise BananaError("MethodUnslicer class must be an OPEN")

    def doOpen(self, opentype):
        # check the opentype
        if self.state == 1:
            if opentype[0] not in ("instance", "none"):
                raise BananaError("MethodUnslicer instance must be " +
                                  "instance or None")
        elif self.state == 2:
            if opentype[0] != "class":
                raise BananaError("MethodUnslicer class must be a class")
        unslicer = self.open(opentype)
        # TODO: apply constraint
        return unslicer

    def receiveChild(self, obj, ready_deferred=None):
        assert not isinstance(obj, Deferred)
        assert ready_deferred is None
        if self.state == 0:
            self.im_func = obj
            self.state = 1
        elif self.state == 1:
            assert type(obj) in (types.InstanceType, types.NoneType)
            self.im_self = obj
            self.state = 2
        elif self.state == 2:
            assert type(obj) == types.ClassType # TODO: new-style classes?
            self.im_class = obj
            self.state = 3
        else:
            raise BananaError("MethodUnslicer only accepts three objects")

    def receiveClose(self):
        if self.state != 3:
            raise BananaError("MethodUnslicer requires three objects")
        if self.im_self is None:
            meth = getattr(self.im_class, self.im_func)
            # getattr gives us an unbound method
            return meth, None
        # TODO: late-available instances
        #if isinstance(self.im_self, NotKnown):
        #    im = _InstanceMethod(self.im_name, self.im_self, self.im_class)
        #    return im
        meth = self.im_class.__dict__[self.im_func]
        # whereas __dict__ gives us a function
        im = instancemethod(meth, self.im_self, self.im_class)
        return im, None

class FunctionUnslicer(slicer.LeafUnslicer):
    opentype = ('function',)
    unslicerRegistry = UnsafeUnslicerRegistry

    finished = False

    def checkToken(self, typebyte, size):
        if typebyte not in (tokens.STRING, tokens.VOCAB):
            raise BananaError("FunctionUnslicer only accepts strings")

    def receiveChild(self, obj, ready_deferred=None):
        assert not isinstance(obj, Deferred)
        assert ready_deferred is None
        if self.finished:
            raise BananaError("FunctionUnslicer only accepts one string")
        self.finished = True
        # TODO: taste here!
        self.func = reflect.namedObject(obj)

    def receiveClose(self):
        if not self.finished:
            raise BananaError("FunctionUnslicer requires a string")
        return self.func, None

# the root unslicer for storage is just like the regular one, but hands
# received objects to the StorageBanana
class StorageRootUnslicer(ScopedRootUnslicer):
    def receiveChild(self, obj, ready_deferred):
        self.protocol.receiveChild(obj, ready_deferred)

# but the "unsafe" one has its own tables
class UnsafeStorageRootUnslicer(StorageRootUnslicer):
    # This version tracks references for the entire lifetime of the
    # protocol. It is most appropriate for single-use purposes, such as a
    # replacement for Pickle.
    topRegistries = [slicer.UnslicerRegistry,
                     slicer.BananaUnslicerRegistry,
                     UnsafeUnslicerRegistry]
    openRegistries = [slicer.UnslicerRegistry,
                      UnsafeUnslicerRegistry]

class StorageBanana(banana.Banana):
    object = None
    violation = None
    disconnectReason = None
    slicerClass = StorageRootSlicer
    unslicerClass = StorageRootUnslicer

    def prepare(self):
        self.d = Deferred()
        return self.d

    def receiveChild(self, obj, ready_deferred):
        if ready_deferred:
            ready_deferred.addBoth(self.d.callback)
            self.d.addCallback(lambda res: obj)
        else:
            self.d.callback(obj)
        del self.d

    def receivedObject(self, obj):
        self.object = obj

    def sendError(self, msg):
        pass

    def reportViolation(self, why):
        self.violation = why

    def reportReceiveError(self, f):
        self.disconnectReason = f
        f.raiseException()

class SerializerTransport:
    def __init__(self, sio):
        self.sio = sio
    def write(self, data):
        self.sio.write(data)
    def loseConnection(self, why="ignored"):
        pass

def serialize(obj, outstream=None, root_class=StorageRootSlicer, banana=None):
    """Serialize an object graph into a sequence of bytes. Returns a Deferred
    that fires with the sequence of bytes."""
    if banana:
        b = banana
    else:
        b = StorageBanana()
        b.slicerClass = root_class
    if outstream is None:
        sio = StringIO()
    else:
        sio = outstream
    b.transport = SerializerTransport(sio)
    b.connectionMade()
    d = b.send(obj)
    def _report_error(res):
        if b.disconnectReason:
            return b.disconnectReason
        if b.violation:
            return b.violation
        return res
    d.addCallback(_report_error)
    if outstream is None:
        d.addCallback(lambda res: sio.getvalue())
    else:
        d.addCallback(lambda res: outstream)
    return d

def unserialize(str_or_instream, banana=None, root_class=StorageRootUnslicer):
    """Unserialize a sequence of bytes back into an object graph."""
    if banana:
        b = banana
    else:
        b = StorageBanana()
        b.unslicerClass = root_class
    b.connectionMade()
    d = b.prepare() # this will fire with the unserialized object
    if isinstance(str_or_instream, str):
        b.dataReceived(str_or_instream)
    else:
        raise RuntimeError("input streams not implemented yet")
    def _report_error(res):
        if b.disconnectReason:
            return b.disconnectReason
        if b.violation:
            return b.violation
        return res # return the unserialized object
    d.addCallback(_report_error)
    return d


text:
{% import "lib/memberHelpers.html" as memberHelper -%}

{% for decorator in doc.decorators %}
@{$ decorator.name $}({$ decorator.arguments $}){% endfor %}
class {$ doc.name $}{$ doc.typeParams | escape $}{$ memberHelper.renderHeritage(doc) $} {
{%- if doc.statics.length %}{% for member in doc.statics %}{% if not member.internal %}
  {$ memberHelper.renderMemberSyntax(member, 1) $}{% endif %}{% endfor %}{% endif -%}
{$ memberHelper.renderMembers(doc) $}
}


text:
#ifndef FEATURECAPTURELASTMOVE_H
#define FEATURECAPTURELASTMOVE_H

#include "MMFeature.h"
#include <memory>

/**
 * @brief The FeatureCaptureLastMove class
 */
class FeatureCaptureLastMove : public MMFeature
{
public:
    FeatureCaptureLastMove();
    void Clear();
    bool LoadFromFile(const string& file_name);
    string Name() const override { return "FeatureCaptureLastMove"; }
    void AddScores(const GoBoard& board , double move_scores[]) const override;
    void AddWinsAndStrength(const GoBoard& board , GoPoint best_move , const double move_scores[] , double total_scores) override;
    void CalcFeatureValue() override;
    void SaveToFile(const string& file_name) const override;
private:
    struct IMP;
    std::auto_ptr<IMP> mpimp;
};

#endif // FEATURECAPTURELASTMOVE_H


text:
<?xml version="1.0"?>
<package format="2">
  <name>grid_map_core</name>
  <version>0.1.0</version>
  <description>Universal grid map library to manage two-dimensional grid maps with multiple data layers.</description>
  <maintainer email="pfankhauser@ethz.ch">Péter Fankhauser</maintainer>
  <license>BSD</license>
  <url type="website">http://github.com/ethz-asl/grid_map</url>
  <url type="bugtracker">http://github.com/ethz-asl/grid_map/issues</url>
  <author email="pfankhauser@ethz.ch">Péter Fankhauser</author>
  <author email="ralf.kaestner@gmail.com">Ralf Kaestner</author>
  <author email="martiwer@student.ethz.ch">Martin Wermelinger</author>
  <buildtool_depend>catkin</buildtool_depend>
</package>


text:
#include "gm.h"

class SkJSCanvas {
public:
    SkJSCanvas(SkCanvas* target);
    ~SkJSCanvas();

    void save();
    void restore();

    double lineWidth;
    void setLineWidth(double);

    void beginPath();
    void moveTo(double x, double y);
    void lineTo(double x, double y);
    void closePath();

    void fill();
    void stroke();

    void fillText(const char text[], double x, double y);

private:
    SkCanvas*   fTarget;
    SkPaint     fFillPaint;
    SkPaint     fStrokePaint;
    SkPath      fPath;
};

SkJSCanvas::SkJSCanvas(SkCanvas* target) : fTarget(target) {
    fFillPaint.setAntiAlias(true);
    sk_tool_utils::set_portable_typeface(&fFillPaint);
    fStrokePaint.setAntiAlias(true);
    fStrokePaint.setStyle(SkPaint::kStroke_Style);
    fStrokePaint.setStrokeWidth(SK_Scalar1);
}

SkJSCanvas::~SkJSCanvas() {}

void SkJSCanvas::save() { fTarget->save(); }
void SkJSCanvas::restore() { fTarget->restore(); }

void SkJSCanvas::beginPath() { fPath.reset(); }
void SkJSCanvas::moveTo(double x, double y) {
    fPath.moveTo(SkDoubleToScalar(x), SkDoubleToScalar(y));
}

void SkJSCanvas::lineTo(double x, double y) {
    fPath.lineTo(SkDoubleToScalar(x), SkDoubleToScalar(y));
}

void SkJSCanvas::closePath() { fPath.close(); }

void SkJSCanvas::fill() {
    fTarget->drawPath(fPath, fFillPaint);
}

void SkJSCanvas::stroke() {
    fStrokePaint.setStrokeWidth(SkDoubleToScalar(lineWidth));
    fTarget->drawPath(fPath, fStrokePaint);
}

void SkJSCanvas::fillText(const char text[], double x, double y) {
    fTarget->drawText(text, strlen(text),
                      SkDoubleToScalar(x), SkDoubleToScalar(y), fFillPaint);
}

///////////////////////////////////////////////////////////////////////////////

static void dump(const SkPath& path) {
    const SkRect& r = path.getBounds();
    SkDebugf("isEmpty %d, bounds [%g %g %g %g]\n", path.isEmpty(),
             r.fLeft, r.fTop, r.fRight, r.fBottom);
}

static void test_stroke(SkCanvas* canvas) {
    if (true) {
        SkPath path;
        dump(path);
        path.reset(); path.moveTo(0, 0);
        dump(path);
        path.reset(); path.moveTo(100, 100);
        dump(path);
        path.reset(); path.moveTo(0, 0); path.moveTo(100, 100);
        dump(path);
        path.reset(); path.moveTo(0, 0); path.lineTo(100, 100);
        dump(path);
        path.reset(); path.moveTo(0, 0); path.lineTo(100, 100); path.moveTo(200, 200);
        dump(path);
    }

#if 0
    // TEST 1 - The rectangle as it's expected to look
    var canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    var ctx = canvas.getContext("2d");
#else
    SkJSCanvas ctx(canvas);
#endif

    ctx.save();
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(10, 100);
    ctx.lineTo(150, 100);
    ctx.lineTo(150, 15);
    ctx.lineTo(10, 15);
    ctx.closePath();

    // no extra moveTo here
    // ctx.moveTo(175, 125);

    ctx.stroke();
    ctx.restore();

    ctx.fillText("As Expected", 10, 10);

#if 0
    // TEST 2 - Includes an extra moveTo call before stroke; the rectangle appears larger
    canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    ctx = canvas.getContext("2d");
#else
    canvas->translate(200, 0);
#endif

    ctx.save();
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(10, 100);
    ctx.lineTo(150, 100);
    ctx.lineTo(150, 15);
    ctx.lineTo(10, 15);
    ctx.closePath();

    ctx.moveTo(175, 125);

    ctx.stroke();
    ctx.restore();

    ctx.fillText("Larger Rectangle", 10, 10);

#if 0
    // TEST 3 - Identical to test 2 except the line width is 1
    canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    ctx = canvas.getContext("2d");
#else
    canvas->translate(200, 0);
#endif

    ctx.save();
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(10, 100);
    ctx.lineTo(150, 100);
    ctx.lineTo(150, 15);
    ctx.lineTo(10, 15);
    ctx.closePath();

    ctx.moveTo(175, 125);

    ctx.stroke();
    ctx.restore();

    ctx.fillText("As Expected - line width 1", 10, 10);
}

class Poly2PolyGM : public skiagm::GM {
public:
    Poly2PolyGM() {}

protected:
    uint32_t onGetFlags() const SK_OVERRIDE {
        return kSkipTiled_Flag;
    }

    SkString onShortName() SK_OVERRIDE {
        return SkString("poly2poly");
    }

    SkISize onISize() SK_OVERRIDE {
        return SkISize::Make(835, 840);
    }

    static void doDraw(SkCanvas* canvas, SkPaint* paint, const int isrc[],
                       const int idst[], int count) {
        SkMatrix matrix;
        SkPoint src[4], dst[4];

        for (int i = 0; i < count; i++) {
            src[i].set(SkIntToScalar(isrc[2*i+0]), SkIntToScalar(isrc[2*i+1]));
            dst[i].set(SkIntToScalar(idst[2*i+0]), SkIntToScalar(idst[2*i+1]));
        }

        canvas->save();
        matrix.setPolyToPoly(src, dst, count);
        canvas->concat(matrix);

        paint->setColor(SK_ColorGRAY);
        paint->setStyle(SkPaint::kStroke_Style);
        const SkScalar D = SkIntToScalar(64);
        canvas->drawRectCoords(0, 0, D, D, *paint);
        canvas->drawLine(0, 0, D, D, *paint);
        canvas->drawLine(0, D, D, 0, *paint);

        SkPaint::FontMetrics fm;
        paint->getFontMetrics(&fm);
        paint->setColor(SK_ColorRED);
        paint->setStyle(SkPaint::kFill_Style);
        SkScalar x = D/2;
        SkScalar y = D/2 - (fm.fAscent + fm.fDescent)/2;
        SkString str;
        str.appendS32(count);
        canvas->drawText(str.c_str(), str.size(), x, y, *paint);

        canvas->restore();
    }

    void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        if (false) { test_stroke(canvas); return; }

        SkPaint paint;
        paint.setAntiAlias(true);
        sk_tool_utils::set_portable_typeface(&paint);
        paint.setStrokeWidth(SkIntToScalar(4));
        paint.setTextSize(SkIntToScalar(40));
        paint.setTextAlign(SkPaint::kCenter_Align);

        canvas->save();
        canvas->translate(SkIntToScalar(10), SkIntToScalar(10));
        // translate (1 point)
        const int src1[] = { 0, 0 };
        const int dst1[] = { 5, 5 };
        doDraw(canvas, &paint, src1, dst1, 1);
        canvas->restore();

        canvas->save();
        canvas->translate(SkIntToScalar(160), SkIntToScalar(10));
        // rotate/uniform-scale (2 points)
        const int src2[] = { 32, 32, 64, 32 };
        const int dst2[] = { 32, 32, 64, 48 };
        doDraw(canvas, &paint, src2, dst2, 2);
        canvas->restore();

        canvas->save();
        canvas->translate(SkIntToScalar(10), SkIntToScalar(110));
        // rotate/skew (3 points)
        const int src3[] = { 0, 0, 64, 0, 0, 64 };
        const int dst3[] = { 0, 0, 96, 0, 24, 64 };
        doDraw(canvas, &paint, src3, dst3, 3);
        canvas->restore();

        canvas->save();
        canvas->translate(SkIntToScalar(160), SkIntToScalar(110));
        // perspective (4 points)
        const int src4[] = { 0, 0, 64, 0, 64, 64, 0, 64 };
        const int dst4[] = { 0, 0, 96, 0, 64, 96, 0, 64 };
        doDraw(canvas, &paint, src4, dst4, 4);
        canvas->restore();
    }

private:
    typedef skiagm::GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

DEF_GM( return new Poly2PolyGM; )


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Bombardia bertioides Ces.

### Remarks
null


text:
package com.tx.example.nlp;

/**
 * action 常量.
 *
 * <p>
 * action 值因厂商、系统版本等因素不尽相同, 安装 NLP 前一定要确认我们的 action 定义跟系统当前的 action 一致, 否则
 * framework location service 可能无法绑定到我们的 service
 *
 */
public class Actions {

	/**
	 * Android 2.3, Android 4.0, Android 4.1 上通常使用的 action
	 */
	public static class V {
		public static final String GEOCODE = "com.google.android.location.GeocodeProvider";
		public static final String LOCATION = "com.google.android.location.NetworkLocationProvider";

		public static final String GEOCODE2 = "com.android.location.service.GeocodeProvider";
		public static final String LOCATION2 = "com.android.location.service.NetworkLocationProvider";

	}

	/**
	 * Android 4.2 上通常使用的 action
	 */
	public static class V2 {
		public static final String LOCATION = "com.android.location.service.v2.NetworkLocationProvider";
	}

	// TODO 其他的 action, 如小米系统

	public static class V3 {
		public static final String LOCATION = "com.android.location.service.v3.NetworkLocationProvider";
	}
}


text:
#ifndef TENSORFLOW_JAVA_SRC_MAIN_NATIVE_OPERATION_JNI_H_
#define TENSORFLOW_JAVA_SRC_MAIN_NATIVE_OPERATION_JNI_H_

#include <jni.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Class:     org_tensorflow_Operation
 * Method:    name
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_org_tensorflow_Operation_name(JNIEnv *, jclass,
                                                             jlong);

/*
 * Class:     org_tensorflow_Operation
 * Method:    type
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_org_tensorflow_Operation_type(JNIEnv *, jclass,
                                                             jlong);

/*
 * Class:     org_tensorflow_Operation
 * Method:    numOutputs
 * Signature: (J)I
 */
JNIEXPORT jint JNICALL Java_org_tensorflow_Operation_numOutputs(JNIEnv *,
                                                                jclass, jlong);

/*
 * Class:     org_tensorflow_Operation
 * Method:    outputListLength
 * Signature: (JLjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_org_tensorflow_Operation_outputListLength(JNIEnv *,
                                                                      jclass,
                                                                      jlong,
                                                                      jstring);

/*
 * Class:     org_tensorflow_Operation
 * Method:    shape
 * Signature: (JJI)[J
 */
JNIEXPORT jlongArray JNICALL Java_org_tensorflow_Operation_shape(JNIEnv *,
                                                                 jclass, jlong,
                                                                 jlong, jint);

/*
 * Class:     org_tensorflow_Operation
 * Method:    dtype
 * Signature: (JJI)I
 */
JNIEXPORT jint JNICALL Java_org_tensorflow_Operation_dtype(JNIEnv *, jclass,
                                                           jlong, jlong, jint);

/*
 * Class:     org_tensorflow_Operation
 * Method:    inputListLength
 * Signature: (JLjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_org_tensorflow_Operation_inputListLength(JNIEnv *,
                                                                      jclass,
                                                                      jlong,
                                                                      jstring);

#ifdef __cplusplus
}  // extern "C"
#endif  // __cplusplus
#endif  // TENSORFLOW_JAVA_SRC_MAIN_NATIVE_OPERATION_JNI_H_


text:
namespace XtraReportSerialization {

    public class defaultXtraReport1 : DReporting.Services.BaseXtraReport {
        private DevExpress.XtraReports.UI.TopMarginBand TopMargin1;
        private DevExpress.XtraReports.UI.DetailBand Detail1;
        private DevExpress.XtraReports.UI.XRTable table2;
        private DevExpress.XtraReports.UI.XRTableRow tableRow2;
        private DevExpress.XtraReports.UI.XRTableCell tableCell5;
        private DevExpress.XtraReports.UI.XRTableCell tableCell6;
        private DevExpress.XtraReports.UI.XRTableCell tableCell7;
        private DevExpress.XtraReports.UI.XRTableCell tableCell8;
        private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin1;
        private DevExpress.DataAccess.ObjectBinding.ObjectDataSource Api_Data_Provider2;
        private System.Resources.ResourceManager _resources;
        private string _resourceString;
        public defaultXtraReport1() {
            this._resourceString = DevExpress.XtraReports.Serialization.XRResourceManager.GetResourceFor("XtraReportSerialization.defaultXtraReport1");
            this.InitializeComponent();
        }
        private System.Resources.ResourceManager resources {
            get {
                if (_resources == null) {
                    this._resources = new DevExpress.XtraReports.Serialization.XRResourceManager(this._resourceString);
                }
                return this._resources;
            }
        }
        private void InitializeComponent() {
            DevExpress.DataAccess.ObjectBinding.ObjectConstructorInfo objectConstructorInfo1 = new DevExpress.DataAccess.ObjectBinding.ObjectConstructorInfo();
            DevExpress.DataAccess.ObjectBinding.Parameter parameter1 = new DevExpress.DataAccess.ObjectBinding.Parameter();
            DevExpress.DataAccess.ObjectBinding.Parameter parameter2 = new DevExpress.DataAccess.ObjectBinding.Parameter();
            DevExpress.DataAccess.ObjectBinding.Parameter parameter3 = new DevExpress.DataAccess.ObjectBinding.Parameter();
            this.TopMargin1 = new DevExpress.XtraReports.UI.TopMarginBand();
            this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
            this.BottomMargin1 = new DevExpress.XtraReports.UI.BottomMarginBand();
            this.table2 = new DevExpress.XtraReports.UI.XRTable();
            this.tableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
            this.tableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
            this.tableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
            this.tableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
            this.tableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
            this.Api_Data_Provider2 = new DevExpress.DataAccess.ObjectBinding.ObjectDataSource();
            ((System.ComponentModel.ISupportInitialize)(this.table2)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.Api_Data_Provider2)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
            //
            // TopMargin1
            //
            this.TopMargin1.HeightF = 117F;
            this.TopMargin1.Name = "TopMargin1";
            this.TopMargin1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
            //
            // Detail1
            //
            this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
                        this.table2});
            this.Detail1.HeightF = 100F;
            this.Detail1.Name = "Detail1";
            this.Detail1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
            //
            // BottomMargin1
            //
            this.BottomMargin1.HeightF = 100F;
            this.BottomMargin1.Name = "BottomMargin1";
            this.BottomMargin1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
            //
            // table2
            //
            this.table2.LocationFloat = new DevExpress.Utils.PointFloat(0F, 46.54F);
            this.table2.Name = "table2";
            this.table2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
                        this.tableRow2});
            this.table2.SizeF = new System.Drawing.SizeF(650F, 23F);
            //
            // tableRow2
            //
            this.tableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
                        this.tableCell5,
                        this.tableCell6,
                        this.tableCell7,
                        this.tableCell8});
            this.tableRow2.Name = "tableRow2";
            this.tableRow2.Weight = 1D;
            //
            // tableCell5
            //
            this.tableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
                        new DevExpress.XtraReports.UI.XRBinding("Text", null, "Booking.BookingID")});
            this.tableCell5.Name = "tableCell5";
            this.tableCell5.Text = "tableCell5";
            this.tableCell5.Weight = 1D;
            //
            // tableCell6
            //
            this.tableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
                        new DevExpress.XtraReports.UI.XRBinding("Text", null, "Booking.CheckInDate")});
            this.tableCell6.Name = "tableCell6";
            this.tableCell6.Text = "tableCell6";
            this.tableCell6.Weight = 1D;
            //
            // tableCell7
            //
            this.tableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
                        new DevExpress.XtraReports.UI.XRBinding("Text", null, "Booking.CheckOutDate")});
            this.tableCell7.Name = "tableCell7";
            this.tableCell7.Text = "tableCell7";
            this.tableCell7.Weight = 1D;
            //
            // tableCell8
            //
            this.tableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
                        new DevExpress.XtraReports.UI.XRBinding("Text", null, "Booking.ContactName")});
            this.tableCell8.Name = "tableCell8";
            this.tableCell8.Text = "tableCell8";
            this.tableCell8.Weight = 1D;
            //
            // Api_Data_Provider2
            //
            parameter1.Name = "designMode";
            parameter1.Type = typeof(bool);
            parameter1.ValueInfo = "True";
            parameter2.Name = "search";
            parameter2.Type = typeof(DevExpress.DataAccess.Expression);
            parameter2.Value = new DevExpress.DataAccess.Expression("[Parameters.search]", typeof(string));
            parameter3.Name = "contactName";
            parameter3.Type = typeof(string);
            objectConstructorInfo1.Parameters.AddRange(new DevExpress.DataAccess.ObjectBinding.Parameter[] {
                        parameter1,
                        parameter2,
                        parameter3});
            this.Api_Data_Provider2.Constructor = objectConstructorInfo1;
            this.Api_Data_Provider2.DataMember = "GetApiData";
            this.Api_Data_Provider2.DataSource = typeof(DReporting.Web.ReportDatas.DynamicApiData);
            this.Api_Data_Provider2.Name = "Api_Data_Provider2";
            //
            // defaultXtraReport1
            //
            this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
                        this.TopMargin1,
                        this.Detail1,
                        this.BottomMargin1});
            this.DataMember = "Booking";
            this.DataSource = this.Api_Data_Provider2;
            this.DisplayName = "Api Data Provider - Bookings";
            this.Extensions.Add("DataSerializationExtension", "DevExpress.XtraReports.Web.ReportDesigner.DefaultDataSerializer");
            this.Margins = new System.Drawing.Printing.Margins(100, 100, 117, 100);
            this.Name = "defaultXtraReport1";
            this.PageHeight = 1100;
            this.PageWidth = 850;
            this.Version = "17.1";
            ((System.ComponentModel.ISupportInitialize)(this.table2)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.Api_Data_Provider2)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
        }
    }
}


text:
module Main where

import CArgs

import Parcial2.App
import Parcial2.Examples.Data

import System.Environment

-----------------------------------------------------------------------------

appName = "ga-labyrinth-example-1"
appDescr' = [ "Searches the shortest path in the labyrinth example with Genetic Algorithm." ]

args0 = CArgs{
    positionalArguments = Positional "Population Size" int [] :. Nil
  , optionalArguments = optionalArguments appArgs
  }

main = do cargs <- parseArgs args0 <$> getArgs
          let params = readParams (optionalValues cargs)
              pop = case positionalValues cargs of
                Right (pop' :. Nil) -> posValue pop'

          withHelp appName appDescr' args0 cargs
            $ printAppResult =<< runApp labyrinth params pop

    where labyrinth = labyrinth2D labyrinthExample


text:
package com.headstartech.scheelite;

/**
 * Exception wrapping any exception thrown from {@link State}, {@link Action} or {@link Guard}.
 */
public class ExecutionException extends Exception {

    public ExecutionException(Throwable cause) {
        super(cause);
    }

    public ExecutionException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
<?php

namespace Proxies\__CG__\BackOffice\AdminBundle\Entity;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class Mouvement extends \BackOffice\AdminBundle\Entity\Mouvement implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function getDate()
    {
        $this->__load();
        return parent::getDate();
    }

    public function getNature()
    {
        $this->__load();
        return parent::getNature();
    }

    public function getUnite()
    {
        $this->__load();
        return parent::getUnite();
    }

    public function getNombre()
    {
        $this->__load();
        return parent::getNombre();
    }

    public function getQtedispo()
    {
        $this->__load();
        return parent::getQtedispo();
    }

    public function getQtedemande()
    {
        $this->__load();
        return parent::getQtedemande();
    }

    public function getQteStock()
    {
        $this->__load();
        return parent::getQteStock();
    }

    public function setId($id)
    {
        $this->__load();
        return parent::setId($id);
    }

    public function setDate(\DateTime $date)
    {
        $this->__load();
        return parent::setDate($date);
    }

    public function setNature($nature)
    {
        $this->__load();
        return parent::setNature($nature);
    }

    public function setUnite($unite)
    {
        $this->__load();
        return parent::setUnite($unite);
    }

    public function setNombre($nombre)
    {
        $this->__load();
        return parent::setNombre($nombre);
    }

    public function setQtedispo($qtedispo)
    {
        $this->__load();
        return parent::setQtedispo($qtedispo);
    }

    public function setQtedemande($qtedemande)
    {
        $this->__load();
        return parent::setQtedemande($qtedemande);
    }

    public function setQteStock($qteStock)
    {
        $this->__load();
        return parent::setQteStock($qteStock);
    }

    public function setIdstock(\BackOffice\AdminBundle\Entity\Stock $idstock = NULL)
    {
        $this->__load();
        return parent::setIdstock($idstock);
    }

    public function getIdstock()
    {
        $this->__load();
        return parent::getIdstock();
    }

    public function __sleep()
    {
        return array('__isInitialized__', 'id', 'date', 'nature', 'unite', 'nombre', 'qtedispo', 'qtedemande', 'qteStock', 'idstock');
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}


text:
import { SORTABLE_ENUM } from "./sort"
import { SEARCHABLE_ENUM } from "./filter"
import {
  SchemaComposer,
  InterfaceTypeComposer,
  ObjectTypeComposer,
} from "graphql-compose"
import { IGatsbyResolverContext } from "../type-definitions"
import { Node } from "../../.."

export const NodeInterfaceFields = [`id`, `parent`, `children`, `internal`]

const getOrCreateNodeInterface = <TSource, TArgs>(
  schemaComposer: SchemaComposer<IGatsbyResolverContext<TSource, TArgs>>
): InterfaceTypeComposer => {
  // TODO: why is `mediaType` on Internal? Applies only to File!?
  // `fieldOwners` is an object
  // Should we drop ignoreType?
  const internalTC = schemaComposer.getOrCreateOTC(`Internal`, tc => {
    tc.addFields({
      content: `String`,
      contentDigest: `String!`,
      description: `String`,
      fieldOwners: [`String`],
      ignoreType: `Boolean`,
      mediaType: `String`,
      owner: `String!`,
      type: `String!`,
      contentFilePath: `String`,
    })
    // TODO: Can be removed with graphql-compose 5.11
    tc.getInputTypeComposer()
  })

  const nodeInterfaceTC = schemaComposer.getOrCreateIFTC(`Node`, tc => {
    tc.setDescription(`Node Interface`)
    tc.addFields({
      id: `ID!`,
      parent: {
        type: `Node`,
        resolve: (source, _args, context): Node | null => {
          const { path } = context
          return context.nodeModel.getNodeById({ id: source.parent }, { path })
        },
        extensions: {
          searchable: SEARCHABLE_ENUM.SEARCHABLE,
          sortable: SORTABLE_ENUM.SORTABLE,
          needsResolve: true,
        },
      },
      children: {
        type: `[Node!]!`,
        resolve: (source, _args, context): Array<Node> => {
          const { path } = context
          return context.nodeModel.getNodesByIds(
            { ids: source.children },
            { path }
          )
        },
        extensions: {
          searchable: SEARCHABLE_ENUM.SEARCHABLE,
          sortable: SORTABLE_ENUM.SORTABLE,
          needsResolve: true,
        },
      },
      internal: internalTC.getTypeNonNull(),
    })

    const nodeInputTC = tc.getInputTypeComposer()
    nodeInputTC.extendField(`id`, { type: `String` })
  })

  return nodeInterfaceTC
}

export const addNodeInterfaceFields = <TSource = any, TArgs = any>({
  schemaComposer,
  typeComposer,
}: {
  schemaComposer: SchemaComposer<IGatsbyResolverContext<TSource, TArgs>>
  typeComposer: ObjectTypeComposer
}): void => {
  const nodeInterfaceTC = getOrCreateNodeInterface(schemaComposer)
  typeComposer.addFields(nodeInterfaceTC.getFields())
  nodeInterfaceTC.setResolveType(node => node.internal.type)
  schemaComposer.addSchemaMustHaveType(typeComposer)
}

export const addNodeInterface = <TSource = any, TArgs = any>({
  schemaComposer,
  typeComposer,
}: {
  schemaComposer: SchemaComposer<IGatsbyResolverContext<TSource, TArgs>>
  typeComposer: ObjectTypeComposer
}): void => {
  const nodeInterfaceTC = getOrCreateNodeInterface(schemaComposer)
  typeComposer.addInterface(nodeInterfaceTC)
  addNodeInterfaceFields({ schemaComposer, typeComposer })
}

export const getNodeInterface = <TSource = any, TContext = any, TArgs = any>({
  schemaComposer,
}: {
  schemaComposer: SchemaComposer<IGatsbyResolverContext<TSource, TArgs>>
}): InterfaceTypeComposer<TSource, TContext> =>
  getOrCreateNodeInterface(schemaComposer)


text:
package chav1961.purelib.cdb;

import com.sun.jdi.event.Event;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.event.ThreadStartEvent;
import com.sun.jdi.event.ThreadDeathEvent;
import com.sun.jdi.request.ThreadStartRequest;
import com.sun.jdi.request.ThreadDeathRequest;

import chav1961.purelib.cdb.ThreadWatcher.ThreadEventProcessor.EventType;

public class ThreadWatcher extends AbstractDebugWatcher {

	@FunctionalInterface
	public static interface ThreadEventProcessor  {
		public enum EventType {
			START,
			TERMINATE;
		}

		void process(final EventType event, ThreadReference thread);
	}

	private final ThreadEventProcessor	proc;
	private ThreadStartRequest	tsr = null;
	private ThreadDeathRequest	tdr = null;

	public ThreadWatcher(final ThreadEventProcessor proc) {
		if (proc == null) {
			throw new NullPointerException("Thread event processor can't be null");
		}
		else {
			this.proc = proc;
		}
	}

	@Override
	<T extends Event> void processEvent(T event) {
		if (isStarted() && !isSuspended()) {
			if (event instanceof ThreadStartEvent) {
				proc.process(EventType.START, ((ThreadStartEvent)event).thread());
			}
			else if (event instanceof ThreadDeathEvent) {
				proc.process(EventType.TERMINATE, ((ThreadDeathEvent)event).thread());
			}
		}
	}

	@Override
	void prepareEventRequests(final VirtualMachine vm) {
		tsr = vm.eventRequestManager().createThreadStartRequest();
		tdr = vm.eventRequestManager().createThreadDeathRequest();
	}

	@Override
	void enableEventRequests(final VirtualMachine vm) {
		tsr.enable();
		tdr.enable();
	}

	@Override
	void disableEventRequests(final VirtualMachine vm) {
		tsr.disable();
		tdr.disable();
	}

	@Override
	void unprepareEventRequests(final VirtualMachine vm) {
		vm.eventRequestManager().deleteEventRequest(tsr);
		vm.eventRequestManager().deleteEventRequest(tdr);
	}
}


text:
describe('Controller', function(){

	var controller;
	var grid;
	var view;
	var score = new Score(0);
	var endgame = new EndGame();
	var modegame = new ModeGame('4x4');

	var lines = 4;
	var cols = 4;

	beforeEach(function(){
		grid = new Grid(lines,cols);
		var frames = [];
		var count = 0;
		for(var i=0;i<lines;i++){
			for(var j=0;j<cols;j++){
				var frame = new Frame(count,j,i,'',grid);
				frames[count] = frame;
				count++;
			}
		}

		grid.frames = frames;
		view = new View(grid,endgame,modegame);
		controller = new Controller(grid,view,score);
	});

	it('should load two frames in the grid', function(){
		controller.load(false);
		var framesPainted = grid.getFramesNoEmpty();
		expect(2).toEqual(framesPainted.length);
	});

	it('should return two frames for posibly move after load', function(){
		controller.load(false);
		var framesToMove = controller.move();
		expect(2).toEqual(framesToMove.length);
	});

	it('should return zero frames for posibly move before load', function(){
		var framesToMove = controller.move();
		expect(0).toEqual(framesToMove.length);
	});

	it('should add one frame to the grid', function(){
		controller.addFrame();
		var framesPainted = grid.getFramesNoEmpty();
		expect(1).toEqual(framesPainted.length);
	});

	it('should move two frames to the right position for the way "right"', function(){
		controller.load(false);
		var framesToMove = controller.move();

		var firstPosition = framesToMove[0].line*4 + 3;
		var secondPosition = framesToMove[1].line*4 + 3;

		var framesToPaint = controller.dirToMove('right',framesToMove);
		view.rePaint(framesToMove,framesToPaint);

		var framesPainted = grid.getFramesNoEmpty();

		var first = framesPainted[0].pos;
		expect(firstPosition).toEqual(first);

		//Is posible that the frames move to the same position due to they stay in same line become in a frame with value '4'
		if(framesPainted.length==2){
			var second = framesPainted[1].pos;
			expect(secondPosition).toEqual(second);
		}else{
			expect('4').toEqual(framesPainted[0].val);
		}
	});

	it('should not return any frame for paint when all frames stay in finals position', function(){
		grid.setValueFrame(3,'2');
		grid.setValueFrame(7,'2');
		grid.setValueFrame(11,'2');
		grid.setValueFrame(15,'2');

		var framesToMove = controller.move();

		var framesToPaint = controller.dirToMove('right', framesToMove);

		expect(0).toEqual(framesToPaint.length);

	});
});


text:
import pickle
import multiprocessing
import logging
import sys

import pandas as pd
import numpy as np

from __future__ import print_function

from sklearn.cross_validation import StratifiedKFold
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.metrics import f1_score, accuracy_score, recall_score, \
    precision_score, confusion_matrix

logging.basicConfig(filename='sentiment-timik.log', level=logging.DEBUG)
log = logging.getLogger()
log.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)

# mpl = pd.read_pickle('lemmatized-messages-table-positive.pkl-2015-11-25_11-15-46')
# mnl = pd.read_pickle('lemmatized-messages-table-negative.pkl-2015-11-25_18-59-07')
# mol = pd.read_pickle('lemmatized-messages-table-other.pkl-2015-11-26_08-07-44')

# m_pos = pd.read_pickle('messages-table-positive.pkl')
# m_neg = pd.read_pickle('messages-table-negative.pkl')
# m_oth = pd.read_pickle('messages-table-other.pkl')

# m_pos[m_pos.messageId == 19806260]

# m_neg = m_neg[m_neg.message.str.contains('(;|:)( |-)?(\(|{|\[)', row.message, flags=re.IGNORECASE)]
# m_neg.to_pickle('messages-table-negative.pkl')

# def get_emoticons_from_messages(df, reg_exp, sent):
#     try:
#         emoticon_col = []
#         [emoticon_col.append(re.search(reg_exp, row.message, flags=re.IGNORECASE).group()) for row_index, row in df.iterrows()]
#         df['emoticons_raw'] = emoticon_col
#         df['emoticons'] = df.apply(lambda x: ''.join(x.emoticons_raw.split()), axis=1)
#         print('Unique emoticons: ', df.emoticons.unique())
#         df['sentiment'] = [sent for x in xrange(df.shape[0])]
#         df.to_pickle('messages-table-emoticons-{}.pkl'.format(sent))
#     except AttributeError as err:
#         print(str(err), row.message, row)
#         raise Exception
#     return df

# m_pos = get_emoticons_from_messages(m_pos, '(;|:)( |-)?(\)|}|]|D)', 'positive')
# m_neg = get_emoticons_from_messages(m_neg, '(;|:)( |-)?(\(|{|\[)', 'negative')
# m_oth = get_emoticons_from_messages(m_oth, '(;|;)( |-)?(p|X|\*|\||8)', 'other')

# m_pos.to_pickle('messages-sentiment-positive.pkl')
# m_neg.to_pickle('messages-sentiment-negative.pkl')

# cols = ['messageId', 'message', 'fromId', 'toId', 'date', 'emoticons', 'sentiment']
# m_sent = pd.concat([m_pos[cols], m_neg[cols]])
# m_sent.to_pickle('messages_sentiment.pkl')
# m_sent

# for x in ['positive', 'negative']:
#     print(x)
#     df = m_sent[m_sent.sentiment == x]
#     avg_chars = np.mean(df.message.apply(lambda x: len(x)))
#     print('AVG chars in message: {}'.format(avg_chars))
#     avg_word = np.mean(df.message.apply(lambda x: len(x.strip().split(' '))))
#     print('AVG words in message: {}'.format(avg_word))

# emoticons_positive = m_pos.emoticons.unique()
# print('Positive emoticons: {}'.format(emoticons_positive))
# emoticons_negative = m_neg.emoticons.unique()
# print('Negative emoticons: {}'.format(emoticons_negative))

# In[21]:

# m_sent.groupby('sentiment').describe()

# In[18]:

# df.emoticons.unique()

# In[20]:

# df.groupby(['emoticons']).count()

# # Sentiment analysis based on characters

# In[27]:

def superv_sent(docs, y, result_queue, ngram_range=(1, 1), analyzer='char_wb',
                n_folds=10):
    logging.info('Analyzer: {}'.format(analyzer))
    logging.info('ngram_range: {}'.format(ngram_range))
    vectorizer = CountVectorizer(analyzer=analyzer, ngram_range=ngram_range,
                                 encoding="ISO-8859-1")
    X = vectorizer.fit_transform(docs)

    log.info('#{} features'.format(X.shape[1]))

    result = {}
    result['char_wb'] = analyzer
    result['ngram_range'] = ngram_range
    result['#docs'] = X.shape[0]
    result['#features'] = X.shape[1]

    for clf_name, classifier in all_clfs.iteritems():
        logging.info('Clf: {}'.format(clf_name))
        output = {'acc': [], 'prec': [], 'rec': [], 'f1': [], 'conf_matrix': []}
        counter = 0
        for train_index, test_index in kf:
            counter += 1
            logging.info('CV: {} {} {} {}'.format(counter, clf_name, analyzer,
                                                  ngram_range))
            X_train, X_test = X[train_index], X[test_index]
            y_train, y_test = y[train_index], y[test_index]

            clf = classifier.fit(X_train, y_train)
            pred = clf.predict(X_test)

            output['acc'].append(accuracy_score(y_test, pred))
            # output['prec'].append(precision_score(y_test, pred, average='macro'))
            # output['f1'].append(f1_score(y_test, pred, average='macro'))
            # output['rec'].append(recall_score(y_test, pred, average='macro'))
            output['prec'].append(precision_score(y_test, pred))
            output['f1'].append(f1_score(y_test, pred))
            output['rec'].append(recall_score(y_test, pred))

            output['conf_matrix'].append(confusion_matrix(y_test, pred))

            log.info('Accuracy {} {} {}: {}'.format(clf_name, analyzer,
                                                    ngram_range,
                                                    accuracy_score(y_test,
                                                                   pred)))
            log.info('F-measure {} {} {}: {}'.format(clf_name, analyzer,
                                                     ngram_range,
                                                     f1_score(y_test, pred)))

        result[clf_name] = output

    result_queue.put(result)

if __name__ == "__main__":
    messages = pd.read_pickle('/datasets/polish/timik/messages_sentiment.pkl')
    n_folds = 5

    # remove emoticons from messages
    messages['message'] = messages.message.str.replace('(;|:)( |-)?(\)|}|]|D)',
                                                       '')
    messages['message'] = messages.message.str.replace('(;|:)( |-)?(\(|{|\[)',
                                                       '')

    ###############################################################################

    all_clfs = {
        # 'BernoulliNB': BernoulliNB(),
        # 'GaussianNB': GaussianNB(),
        # 'MultinomialNB': MultinomialNB(),
        # 'DecisionTreeClassifier': DecisionTreeClassifier(),
        # 'AdaBoostClassifier': AdaBoostClassifier(),
        # 'RandomForestClassifier': RandomForestClassifier(),
        'LogisticRegression': LogisticRegression(),
        # 'Perceptron': Perceptron(),
        # 'BernoulliRBM': BernoulliRBM(),
        # 'SVC': SVC(),
        'LinearSVC': LinearSVC(),
        # 'SVR': SVR(),
        # 'NuSVC': NuSVC(),
        # 'NuSVR': NuSVR(),
        # 'OneClassSVM': OneClassSVM(),
        # 'ExtraTreeClassifier': ExtraTreeClassifier()
    }

    n = messages[messages.sentiment == 'negative'].shape[0]
    messages[messages.sentiment == 'positive'].head(n)
    messages = pd.concat([messages[messages.sentiment == 'negative'],
                          messages[messages.sentiment == 'positive'].head(n)])

    docs = messages.message
    # labels for messages
    y = np.asarray(
        messages.sentiment.apply(lambda x: 1 if x in ['positive'] else 2))

    kf = StratifiedKFold(y, n_folds=n_folds, shuffle=True)
    results = []

    params = [{'ngram_range': (1, 1), 'analyzer': 'char_wb'},
              {'ngram_range': (1, 2), 'analyzer': 'char_wb'},
              {'ngram_range': (2, 2), 'analyzer': 'char_wb'},
              {'ngram_range': (2, 3), 'analyzer': 'char_wb'},
              {'ngram_range': (1, 1), 'analyzer': 'word'}]
    # params.append({'ngram_range': (1, 4), 'analyzer': 'char_wb'})
    # params.append({'ngram_range': (2, 4), 'analyzer': 'char_wb'})
    # params.append({'ngram_range': (3, 4), 'analyzer': 'char_wb'})
    # params.append({'ngram_range': (1, 2), 'analyzer': 'word'})
    # params.append({'ngram_range': (1, 3), 'analyzer': 'word'})
    # params.append({'ngram_range': (2, 3), 'analyzer': 'word'})

    result_queue = multiprocessing.Queue()
    jobs = []

    for param in params:
        log.info('Add process for {}'.format(param))
        p = multiprocessing.Process(target=superv_sent,
                                    args=(
                                    docs, y, result_queue, param['ngram_range'],
                                    param['analyzer'], n_folds))
        p.start()
        jobs.append(p)

    [results.append(result_queue.get()) for j in jobs]
    logging.info('Waiting for all processes')
    [j.join() for j in jobs]
    logging.info('All processes joined')

    # with open('message-output.pkl') as f:
    with open('message-output-1-2-3.pkl', 'w') as f:
        pickle.dump(results, f)


text:
<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="checks")
 * @ORM\HasLifecycleCallbacks()
 */
class Check
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="integer")
     */
    protected $persons;

    /**
     * @ORM\ManyToOne(targetEntity="UserBundle\Entity\User")
     * @ORM\JoinColumn(name="author_id", referencedColumnName="id")
     **/
    protected $author;

    /**
     * created Time/Date
     *
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    public $createdAt;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    protected $discount;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $free;

    /**
     * @ORM\OneToMany(targetEntity="CheckItem", mappedBy="check")
     **/
    protected $checkItems;

    /**
     * @ORM\ManyToOne(targetEntity="Shift", inversedBy="checks")
     * @ORM\JoinColumn(name="shift_id", referencedColumnName="id")
     **/
    protected $shift;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->checkItems = new \Doctrine\Common\Collections\ArrayCollection();
        $this->createdAt = new \DateTime();
    }

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

    /**
     * Set persons
     *
     * @param integer $persons
     *
     * @return Check
     */
    public function setPersons($persons)
    {
        $this->persons = $persons;

        return $this;
    }

    /**
     * Get persons
     *
     * @return integer
     */
    public function getPersons()
    {
        return $this->persons;
    }

    /**
     * Set createdAt
     *
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set discount
     *
     * @param string $discount
     *
     * @return Check
     */
    public function setDiscount($discount)
    {
        $this->discount = $discount;

        return $this;
    }

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

    /**
     * Set free
     *
     * @param boolean $free
     *
     * @return Check
     */
    public function setFree($free)
    {
        $this->free = $free;

        return $this;
    }

    /**
     * Get free
     *
     * @return boolean
     */
    public function getFree()
    {
        return $this->free;
    }

    /**
     * Set author
     *
     * @param \UserBundle\Entity\User $author
     *
     * @return Check
     */
    public function setAuthor(\UserBundle\Entity\User $author = null)
    {
        $this->author = $author;

        return $this;
    }

    /**
     * Get author
     *
     * @return \UserBundle\Entity\User
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Add checkItem
     *
     * @param \AppBundle\Entity\CheckItem $checkItem
     *
     * @return Check
     */
    public function addCheckItem(\AppBundle\Entity\CheckItem $checkItem)
    {
        $this->checkItems[] = $checkItem;

        return $this;
    }

    /**
     * Remove checkItem
     *
     * @param \AppBundle\Entity\CheckItem $checkItem
     */
    public function removeCheckItem(\AppBundle\Entity\CheckItem $checkItem)
    {
        $this->checkItems->removeElement($checkItem);
    }

    /**
     * Get checkItems
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCheckItems()
    {
        return $this->checkItems;
    }

    /**
     * Set shift
     *
     * @param \AppBundle\Entity\Shift $shift
     *
     * @return Check
     */
    public function setShift(\AppBundle\Entity\Shift $shift = null)
    {
        $this->shift = $shift;

        return $this;
    }

    /**
     * Get shift
     *
     * @return \AppBundle\Entity\Shift
     */
    public function getShift()
    {
        return $this->shift;
    }
}