text:
'use strict';

var request = require('request');
var http = require('http');
var qs = require('querystring');
var token = require('./oauthWebApi');

exports.getKbArticles = function getKbArticles(pageIndexValue, pageSizeValue, callbackSuccess, callbackError) {
  token.getToken(false, function(access_token) {
    var data = {
      pageIndex: pageIndexValue,
      pageSize: pageSizeValue};
    var content = qs.stringify(data);
    var options = {
        hostname: 'api.cnblogs.com',
        port: 80,
        path: '/api/KbArticles?' + content,
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + access_token
          }
    };

    var req = http.request(options, function (res) {
      var str = '';
      // console.log('STATUS: ' + res.statusCode);
      // console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        str += chunk;
      });
      res.on('end', function(){
        // console.log('JSON: ' + str);
        callbackSuccess(JSON.parse(str));
      });
    });

    req.on('error', function (e) {
        callbackError(e);
    });

    req.end();
  }, function(errordata) {
    callbackError(errordata);
  });
}

exports.getKbArticleBody = function getKbArticleBody(kbArticleId, callbackSuccess, callbackError) {
  token.getToken(false, function(access_token) {
    var options = {
      url: 'http://api.cnblogs.com/api/kbarticles/' + kbArticleId + "/body",
      headers: {
        'Authorization': 'Bearer ' + access_token
      }
    };
    request.get(options, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        body = body.substring(1,body.length-1);
        body = body.replace(/\\r/g, "\r");
        body = body.replace(/\\t/g, "\t");
        body = body.replace(/\\n/g, "\n");
        body = body.replace(/\\"/g, "\"");
        // console.log("BODY: " + body);
        callbackSuccess(body);
      } else {
        callbackError(error);
      }
    });
  }, function(errordata) {
    callbackError(errordata);
  });
}


text:
/**
 * How to generate class members.
 */
package de.japkit.test.members;

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace VRGIN.Controls
{
    public class RightController : Controller
    {
        public static RightController Create()
        {
            var rightHand = new GameObject("Right Controller").AddComponent<RightController>();
            rightHand.ToolIndex = 1; // Start with tool 2
            return rightHand;
        }
    }
}


text:
from wedo2.input_output.output_command import OutputCommand
from wedo2.input_output.input_command import InputCommand
from wedo2.bluetooth import bluetooth_helper

CHARACTERISTIC_INPUT_VALUE_UUID = "0x1560"
CHARACTERISTIC_INPUT_FORMAT_UUID = "0x1561"
CHARACTERISTIC_INPUT_COMMAND_UUID = "0x1563"
CHARACTERISTIC_OUTPUT_COMMAND_UUID = "0x1565"

class BluetoothIO:

    def __init__(self, associated_device):
        # Associated device is the pygatt backend object we have connected to
        self.associated_device = associated_device
        self.services = []

    def read_value_for_connect_id(self, connect_id):
        input_command = InputCommand.command_read_value_for_connect_id(connect_id)
        self.write_input_command(input_command.data)
        value = self.read_input_value()
        return value

    def read_input_value(self):
        char_uuid = bluetooth_helper.uuid_with_prefix_custom_base(CHARACTERISTIC_INPUT_VALUE_UUID)
        data = self.associated_device.char_read(char_uuid)
        return data[2:]

    def reset_state_for_connect_id(self, connect_id):
        reset_bytes = bytearray([0x44, 0x11, 0xAA])
        self.write_data(reset_bytes, connect_id)

    def write_input_format(self, input_format, connect_id):
        input_command = InputCommand.command_write_input_format(input_format, connect_id)
        self.write_input_command(input_command.data)

    def read_input_format_for_connect_id(self, connect_id):
        input_command = InputCommand.command_read_input_format_for_connect_id(connect_id)
        self.write_input_command(input_command.data)
        return self.read_input_format()

    def read_input_format(self):
        char_uuid = bluetooth_helper.uuid_with_prefix_custom_base(CHARACTERISTIC_INPUT_FORMAT_UUID)
        data = self.associated_device.char_read(char_uuid)
        return data

    def write_input_command(self, command):
        char_uuid = bluetooth_helper.uuid_with_prefix_custom_base(CHARACTERISTIC_INPUT_COMMAND_UUID)
        self.associated_device.char_write(char_uuid, command)

    def write_motor_power(self, power, offset, connect_id):
        is_positive = power >= 0
        power = abs(power)

        actual_power = ((100.0 - offset) / 100.0) * power + offset
        actual_result_int = round(actual_power)

        if not is_positive:
            actual_result_int = -actual_result_int

        output_command = OutputCommand.command_write_motor_power(actual_result_int, connect_id)
        self.write_output_command(output_command.data)

    def write_piezo_tone_frequency(self, frequency, duration, connect_id):
        output_command = OutputCommand.command_write_piezo_tone_frequency(frequency, duration, connect_id)
        self.write_output_command(output_command.data)

    def write_piezo_tone_stop(self, connect_id):
        output_command = OutputCommand.command_write_piezo_tone_stop_for_connect_id(connect_id)
        self.write_output_command(output_command.data)

    def write_color(self, red, green, blue, connect_id):
        output_command = OutputCommand.command_write_rgb_light(red, green, blue, connect_id)
        self.write_output_command(output_command.data)

    def write_color_index(self, index, connect_id):
        output_command = OutputCommand.command_write_rgb_light_index(index, connect_id)
        self.write_output_command(output_command.data)

    def write_data(self, data, connect_id):
        output_command = OutputCommand.command_with_direct_write_through_data(data, connect_id)
        self.write_output_command(output_command.data)

    def write_output_command(self, command):
        char_uuid = bluetooth_helper.uuid_with_prefix_custom_base(CHARACTERISTIC_OUTPUT_COMMAND_UUID)
        self.associated_device.char_write(char_uuid, command)

    def subscribe_to_char(self, uuid, callback):
        self.associated_device.subscribe(uuid, callback)

    def unsubscribe_from_char(self, uuid):
        self.associated_device.unsubscribe(uuid)


text:
package com.facebook.buck.shell;

import static org.junit.Assert.assertTrue;

import com.facebook.buck.testutil.integration.DebuggableTemporaryFolder;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableSet;

import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;

public class ShTestIntegrationTest {

  @Rule
  public DebuggableTemporaryFolder tmp = new DebuggableTemporaryFolder();

  @Test
  public void args() throws IOException {
    Assume.assumeTrue(
        ImmutableSet.of(Platform.MACOS, Platform.LINUX).contains(Platform.detect()));
    ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(
        this, "sh_test_args", tmp);
    workspace.setUp();
    workspace.runBuckCommand("test", "//foo:test").assertSuccess();
  }

  @Test
  public void timeout() throws IOException {
    Assume.assumeTrue(
        ImmutableSet.of(Platform.MACOS, Platform.LINUX).contains(Platform.detect()));
    ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(
        this, "sh_test_timeout", tmp);
    workspace.setUp();
    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("test", "//:test-spin");
    String stderr = result.getStderr();
    result.assertSpecialExitCode("test should fail", 42);
    assertTrue(stderr, stderr.contains("Timed out running test: //:test-spin"));
  }

  @Test
  public void env() throws IOException {
    Assume.assumeTrue(
        ImmutableSet.of(Platform.MACOS, Platform.LINUX).contains(Platform.detect()));
    ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(
        this, "sh_test_env", tmp);
    workspace.setUp();
    workspace.runBuckCommand("test", "//foo:test").assertSuccess();
  }

}


text:
impjs
=====

Thin wrapper combining pixi.js and PhysicsJS

Example:
```javascript
    var game = imp.createGame( 'example', 400, 300, document.body );

    // Do stuff on game start.
    game.on( 'preload', function( event, game ) {

        game.world.backgroundcolor = 0xEEFFFF;

    } );

    // Do stuff when initialising the physical world.
    game.on( 'load', function( event, game ) {} );

    // Do stuff in our update loop.
    game.on( 'update', function( event, game ) {} );

    // Do stuff before rendering happens
    game.on( 'render', function( event, game ) {} );

    // Start the game.
    game.start();

```


text:
Rails.application.routes.draw do

  mount Occurro::Engine => "/occurro"
end


text:
from unittest import TestCase, main
from os.path import join, abspath, dirname

from biom import load_table
from deblur.workflow import _system_call
from deblur.workflow import sequence_generator
from tempfile import mkdtemp

class TestScript(TestCase):

    def setUp(self):
        self.data_dir = join(dirname(abspath(__file__)), 'data')
        self.seqs_fp = join(self.data_dir, 'seqs_s5.fasta')
        self.orig_fp = join(self.data_dir, 'simset.s3.fasta')
        self.orig_one_seq_fp = join(self.data_dir, 'simset.s5.fasta')
        self.output_dir = mkdtemp()
        self.output_biom = join(self.output_dir, 'all.biom')
        self.output_seqs = join(self.output_dir, 'all.seqs.fa')
        self.trim_length = 150

    def validate_results(self, table_name, orig_fasta_name):
        res_table = load_table(table_name)

        res_seqs = list(res_table.ids(axis='observation'))
        exp_seqs = [item[1] for item in sequence_generator(orig_fasta_name)]
        exp_seqs = list(map(lambda x: x.upper()[:self.trim_length], exp_seqs))
        self.assertListEqual(res_seqs, exp_seqs)

    def test_workflow(self):
        # test default parameters, negative mode, single thread
        cmd = ["deblur", "workflow", "--seqs-fp", self.seqs_fp,
               "--output-dir", self.output_dir,
               "--trim-length", "150", '-w']
        sout, serr, res = _system_call(cmd)
        self.validate_results(self.output_biom, self.orig_one_seq_fp)

        # test default parameters, negative mode, multi thread
        cmd = ["deblur", "workflow", "--seqs-fp", self.seqs_fp,
               "--output-dir", self.output_dir,
               "--trim-length", "150", '-w',
               "-O", "2"]
        sout, serr, res = _system_call(cmd)
        self.validate_results(self.output_biom, self.orig_one_seq_fp)

        # test default parameters, positive mode, single thread
        cmd = ["deblur", "workflow", "--seqs-fp", self.seqs_fp,
               "--output-dir", self.output_dir,
               "--trim-length", "150", '-w']
        sout, serr, res = _system_call(cmd)
        self.validate_results(self.output_biom, self.orig_one_seq_fp)

        # test default parameters, positive mode, multi thread
        cmd = ["deblur", "workflow", "--seqs-fp", self.seqs_fp,
               "--output-dir", self.output_dir,
               "--trim-length", "150", '-w',
               "-O", "2"]
        sout, serr, res = _system_call(cmd)
        self.validate_results(self.output_biom, self.orig_one_seq_fp)

        # test default parameters except min-reads set to 0, negative mode, single thread
        cmd = ["deblur", "workflow", "--seqs-fp", self.seqs_fp,
               "--output-dir", self.output_dir,
               "--trim-length", "150", '-w', '--min-reads', '0']
        sout, serr, res = _system_call(cmd)
        self.validate_results(self.output_biom, self.orig_fp)

if __name__ == "__main__":
    main()


text:
package com.frameworkset.common.tag.pager.tags;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import com.frameworkset.platform.cms.driver.jsp.CMSServletRequest;

/**
 *
PageSizeTag.java

 *
 Description: 获取页面记录数

 *
 bboss workgroup

 *
 Copyright (c) 2009

 *
 * @Date 2011-8-8
 * @author biaoping.yin
 * @version 1.0
 */
public class PageSizeTag extends PagerTagSupport
{

	public int doStartTag(){

		try
		{
			super.doStartTag();
			HttpServletRequest request = this.getHttpServletRequest();
			if(this.pagerContext == null)
			{
				String t_id = "pagerContext." ;

				if(request instanceof CMSServletRequest)
				{
					CMSServletRequest cmsRequest = (CMSServletRequest)request;
					t_id += cmsRequest.getContext().getID() ;
				}
				else if(this.id != null)
				{
					t_id += id;
				}
				else
					t_id += PagerContext.DEFAULT_ID;

				this.pagerContext = (PagerContext)request.getAttribute(t_id);

			}
			JspWriter out = this.getJspWriter();
			out.print(super.pagerContext.getDataSize());
		}
		catch (JspException e1)
		{
			e1.printStackTrace();
		}

		catch (IOException e)
		{
			e.printStackTrace();
		}

		return SKIP_BODY;
	}

	/**
	 *  Description:
	 * @return String
	 * @see com.frameworkset.common.tag.BaseTag#generateContent()
	 */
	public String generateContent()
	{
		return null;
	}

	/**
	 *  Description:
	 * @param output
	 * @see com.frameworkset.common.tag.BaseTag#write(java.io.OutputStream)
	 */
	public void write(OutputStream output)
	{

	}

	@Override
	public void doFinally() {
		this.pagerContext = null;
		super.doFinally();
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Module: Selenium::WebDriver::ProfileHelper::ClassMethods

    — Documentation by YARD 0.8.7.3

</title>

  <link rel="stylesheet" href="../../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../../css/common.css" type="text/css" charset="utf-8" />

    Index (C) »
    Selenium » WebDriver » ProfileHelper
     »
    ClassMethods

(no frames)

      Class List

      Method List

      File List

Module: Selenium::WebDriver::ProfileHelper::ClassMethods

  Private

Defined in:

rb/lib/selenium/webdriver/common/profile_helper.rb

  This module is part of a private API.
  You should avoid using this module if possible, as it may be removed or be changed in the future.

      Instance Method Summary
      (collapse)

      - (Object) from_json(json)

  private

Instance Method Details

    - (<tt>Object</tt>) from_json(json)

  This method is part of a private API.
  You should avoid using this method if possible, as it may be removed or be changed in the future.

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

# File 'rb/lib/selenium/webdriver/common/profile_helper.rb', line 48

def from_json(json)
  data = WebDriver.json_load(json).fetch('zip')

  # can't use Tempfile here since it doesn't support File::BINARY mode on 1.8
  # can't use Dir.mktmpdir(&blk) because of http://jira.codehaus.org/browse/JRUBY-4082
  tmp_dir = Dir.mktmpdir
  begin
    zip_path = File.join(tmp_dir, "webdriver-profile-duplicate-#{json.hash}.zip")
    File.open(zip_path, "wb") { |zip_file| zip_file << Base64.decode64(data) }

    new Zipper.unzip(zip_path)
  ensure
    FileUtils.rm_rf tmp_dir
  end
end

  Generated on Mon Feb 17 23:05:56 2014 by
  yard
  0.8.7.3 (ruby-2.1.0).


text:
"use strict";

oak.Statable = function () {

}.inherit(oak.Evented, {

  states: {},

  // setState
  // --------
  // setting a state will look for an on handler in the states object
  // E.g. setState("loading") will call the states.onLoading function if it's
  // defined.
  setState: function (state) {
    var args = oak._arrProto.slice.call(arguments, 1);
    var offCallback, offEvent, onCallback, onEvent,
        newState = state;

    if (typeof this.currentState === "undefined" || newState !== this.currentState) {
      onCallback = this.states["on" + newState.replace(/^\w/, function (s) { return s.toUpperCase(); })];
      onEvent = "on:" + newState;
      if (typeof this.currentState !== "undefined") {
        offCallback = this.states["off" + this.currentState.replace(/^\w/, function (s) { return s.toUpperCase(); })];
        offEvent = "off:" + this.currentState;
      }

      this.currentState = newState;
      if (typeof offCallback !== "undefined") {
        offCallback.apply(this);
        this.trigger(offEvent, args);
      }
      if (typeof onCallback !== "undefined") {
        onCallback.apply(this, args);
        this.trigger(onEvent, args);
      }
    }
  }
});


text:
#ifndef __PROJECT_EULER_PROBLEM291_H__
#define __PROJECT_EULER_PROBLEM291_H__
/*
 * ProjectEuler/include/c/ProjectEuler/Problem291.h
 *
 * Panaitopol Primes
 * =================
 * Published on Friday, 7th May 2010, 09:00 pm
 *
 * A prime number p is called a Panaitopol prime if  for some positive integers
 * x and y.     Find how many Panaitopol primes are less than 51015.
 */

#  ifdef __cplusplus
extern "C" {
#  endif

#  ifdef __cplusplus
}
#  endif

#endif  /* __PROJECT_EULER_PROBLEM291_H__ */


text:
/*
 * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen.
 */
package com.solidfire.element.api;

import com.solidfire.gson.Gson;
import com.solidfire.core.client.Attributes;
import com.solidfire.gson.annotations.SerializedName;
import com.solidfire.core.annotation.Since;
import com.solidfire.core.javautil.Optional;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;

/**
 * ListVolumeStatsRequest
 * ListVolumeStats returns high-level activity measurements for a single volume, list of volumes, or all volumes (if you omit the volumeIDs parameter). Measurement values are cumulative from the creation of the volume.
 **/

public class ListVolumeStatsRequest implements Serializable {

    public static final long serialVersionUID = -3771841461014731507L;
    @SerializedName("volumeIDs") private Optional<Long[]> volumeIDs;
    // empty constructor
    @Since("7.0")
    public ListVolumeStatsRequest() {}

    // parameterized constructor
    @Since("7.0")
    public ListVolumeStatsRequest(
        Optional<Long[]> volumeIDs
    )
    {
        this.volumeIDs = (volumeIDs == null) ? Optional.<Long[]>empty() : volumeIDs;
    }

    /**
     * A list of volume IDs of volumes from which to retrieve activity information.
     **/
    public Optional<Long[]> getVolumeIDs() { return this.volumeIDs; }

    public void setVolumeIDs(Optional<Long[]> volumeIDs) {
        this.volumeIDs = (volumeIDs == null) ? Optional.<Long[]>empty() : volumeIDs;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ListVolumeStatsRequest that = (ListVolumeStatsRequest) o;

        return
            Objects.equals(volumeIDs, that.volumeIDs);
    }

    @Override
    public int hashCode() {
        return Objects.hash( volumeIDs );
    }

    public java.util.Map<String, Object> toMap() {
        java.util.Map<String, Object> map = new HashMap<>();
        map.put("volumeIDs", volumeIDs);
        return map;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        Gson gson = new Gson();
        sb.append( "{ " );

        if(null != volumeIDs && volumeIDs.isPresent()){
            sb.append(" volumeIDs : ").append(gson.toJson(volumeIDs)).append(",");
        }
        else{
            sb.append(" volumeIDs : ").append("null").append(",");
        }
        sb.append( " }" );

        if(sb.lastIndexOf(", }") != -1)
            sb.deleteCharAt(sb.lastIndexOf(", }"));

        return sb.toString();
    }

    public static Builder builder() {
        return new Builder();
    }

    public final Builder asBuilder() {
        return new Builder().buildFrom(this);
    }

    public static class Builder {
        private Optional<Long[]> volumeIDs;

        private Builder() { }

        public ListVolumeStatsRequest build() {
            return new ListVolumeStatsRequest (
                         this.volumeIDs);
        }

        private ListVolumeStatsRequest.Builder buildFrom(final ListVolumeStatsRequest req) {
            this.volumeIDs = req.volumeIDs;

            return this;
        }

        public ListVolumeStatsRequest.Builder optionalVolumeIDs(final Long[] volumeIDs) {
            this.volumeIDs = (volumeIDs == null) ? Optional.<Long[]>empty() : Optional.of(volumeIDs);
            return this;
        }

    }
}


text:
package com.s24.redjob.channel.command;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Command to shutdown queue workers.
 */
@JsonTypeName
public class ShutdownQueueWorker {
   /**
    * Constructor to shutdown all workers.
    */
   @JsonCreator
   public ShutdownQueueWorker() { }
}


text:
module Battle
  class Game
    attr_reader :name, :email, :id, :coords, :status, :ships, :prize,
      :response, :nuke_status, :sunk

    STATUSES = %w[start victory defeat]

    def initialize(name = nil, email = nil, id: nil)
      @name = name
      @email = email
      @id = id
      @coords = [nil, nil]
      @status = id ? 'start': 'init'
      @ships = []
      @response = {}
      Battle.ships.each { |name| @ships << Ship.new(name) }
    end

    def register!
      raise PlayerNameNotSpecified if name.nil? || name.empty?
      raise PlayerEmailNotSpecified if email.nil? || email.empty?

      do_request REGISTER_URL, "name" => name, "email" => email
      handle_register

      response
    end

    def nuke(x, y)
      raise GameNotStartedYetError if init?
      raise GameAlreadyFinishedError if finished?

      do_request NUKE_URL, id: id, x: x, y: y
      handle_nuke

      response
    end

    def init?
      status == "init"
    end

    def finished?
      status == "lost" || status == "victory"
    end

    private
    STATUSES.each do |status|
      define_method status do
        @status = status
      end
    end

    def do_request(url, data)
      options = { content_type: :json, accept: :json }
      @response = JSON.parse RestClient.post(url, data.to_json, options)
    end

    def sink_ship(name)
      @sunk = name
      return if name.nil?
      ships.delete ships.find { |ship| ship.is? name }
    end

    def has_ships?
      !ships.empty?
    end

    def won?
      !response["prize"].nil? || !has_ships?
    end

    def handle_nuke
      sink_ship response['sunk']
      handle_nuke_status
      handle_defeat
      handle_victory
      assign_coordinates
    end

    def handle_victory
      if won?
        victory
        @prize = response['prize']
      end
    end

    def handle_nuke_status
      @nuke_status = response['status']
    end

    def handle_defeat
      defeat if response["game_status"] == "lost"
    end

    def handle_register
      @id = response["id"]
      assign_coordinates
      start
    end

    def assign_coordinates
      @coords = [response["x"], response["y"]]
    end
  end
end


text:
/**
 * Created by i68066 on 11/9/15.
 */
context = document.getElementById('canvasInAPerfectWorld').getContext('2d');
var canvasDiv = document.getElementById('canvasDiv');
var canvasWidth = '490px';
var canvasHeight = '220px';
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
    canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");
$('#canvas').mousedown (function (e) {
   var mouseX = e.pageX - this.offsetLeft;
    var mouseY = e.pageY - this.offsetTop;
    paint - true;
    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
    redraw();
});
$('#canvas').mousemove(function(e) {
   if (paint) {
       addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
       redraw;
   }
});
$('#canvas').mouseleave(function(e) {
   paint = false;
});

var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;

function addClick (x,y, dragging) {
    clickX.push(x);
    clickY.push(y);
    clickDrag.push(dragging);
}

function redraw () {
    context.clearRect(0, 0, context.canvas.width, context.canvas.height);
    context.strokeStyle = "#df4b26";
    context.lineJoin = "round";
    context.lineWidth = 5;

    for (var i = 0; i < clickX.length; i++) {
        contex.beginPath();
        if (clickDrag[i] && i) {
            context.moveTo(clickX[i-1], clickY[i-1]);
        }
        else {
            context.moveTo(clickX[i]-1, clickY[i]);
        }
        context.lineTo(clickX[i], clickY[i]);
        context.closePath();
        context.stroke();
    }
}


text:
<?php

namespace Symfony\Component\CssSelector\Exception;

/**
 * ParseException is thrown when a CSS selector syntax is not valid.
 *
 * This component is a port of the Python lxml library,
 * which is copyright Infrae and distributed under the BSD license.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class ParseException extends \Exception
{
}


text:
<!DOCTYPE html>

<title>oogl.js Test 01</title>

			<canvas id="canvas" width="800" height="600">

Sorry, no browser support. See here please.

			</canvas>

made with oogl.js - source code - demo index


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BudgetPal
{
    static class ErrorStrings
    {
        public static string NameExists             = "The name already exists. Object name must be unique.";
        public static string InvalidName            = "The specified name is invalid. Name cannot be empty.";
        public static string NullObject             = "The object cannot be null.";
        public static string PeriodTypeMismatch     = "The period types do not match.";
        public static string ObjectTypeMismatch     = "The objects are of differents types";
        public static string CannotDeleteObject     = "Cannot delete object with references.";
        public static string InvalidModelObject     = "The specified object value is invalid.";
        public static string DuplicateObject        = "The object already exists.";
        public static string BudgetExists           = "A budget of the same period already exists.";
        public static string InvalidTransactObject  = "The given transaction object is invalid.";
    }
}


text:
package com.cinnober.msgcodec.io;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;

/**
 * An output stream wrapoer for a byte sink.
 *
 * @author mikael.brannstrom
 */
public class ByteSinkOutputStream extends OutputStream {
    private final ByteSink sink;

    /**
     * Create a new byte sink output stream.
     * @param sink the wrapped byte sink to write to, not null.
     */
    public ByteSinkOutputStream(ByteSink sink) {
        this.sink = Objects.requireNonNull(sink);
    }

    @Override
    public void write(int b) throws IOException {
        sink.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        sink.write(b, off, len);
    }

    @Override
    public void write(byte[] b) throws IOException {
        sink.write(b);
    }
}


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

package app.metatron.discovery.prep.parser.preparation.rule;

import app.metatron.discovery.prep.parser.preparation.rule.expr.Expression;

public class Merge implements Rule, Rule.Factory {

  /**
   * Merge target columns (multiple)
   */
  Expression col;

  /**
   * Concatenator
   */
  String with;

  /**
   * New column name
   */
  String as;

  public Merge() {
  }

  public Merge(Expression col, String with, String as) {
    this.col = col;
    this.with = with;
    this.as = as;
  }

  public Expression getCol() {
    return col;
  }

  public void setCol(Expression col) {
    this.col = col;
  }

  public String getWith() {
    return with;
  }

  public void setWith(String with) {
    this.with = with;
  }

  public String getAs() {
    return as;
  }

  public void setAs(String as) {
    this.as = as;
  }

  @Override
  public String getName() {
    return "merge";
  }

  @Override
  public Rule get() {
    return new Merge();
  }

  @Override
  public String toString() {
    return "Merge{" +
            "col=" + col +
            ", with=" + with +
            ", as='" + as + '\'' +
            '}';
  }
}


text:
require 'spec_helper'
require 'timecop'
require_relative 'obligation_shared'
require_relative 'observable_shared'

module Concurrent

  describe ScheduledTask do
    context 'behavior' do

      # obligation

      let!(:fulfilled_value) { 10 }
      let!(:rejected_reason) { StandardError.new('mojo jojo') }

      let(:pending_subject) do
        ScheduledTask.new(1){ fulfilled_value }.execute
      end

      let(:fulfilled_subject) do
        latch = Concurrent::CountDownLatch.new(1)
        task = ScheduledTask.new(0.1){ latch.count_down; fulfilled_value }.execute
        latch.wait(1)
        sleep(0.1)
        task
      end

      let(:rejected_subject) do
        latch = Concurrent::CountDownLatch.new(1)
        task = ScheduledTask.new(0.1){ latch.count_down; raise rejected_reason }.execute
        latch.wait(1)
        sleep(0.1)
        task
      end

      it_should_behave_like :obligation

      # dereferenceable

      specify{ expect(ScheduledTask.ancestors).to include(Dereferenceable) }

      # observable

      subject{ ScheduledTask.new(0.1){ nil } }

      def trigger_observable(observable)
        observable.execute
        sleep(0.2)
      end

      it_should_behave_like :observable
    end

    context '#initialize' do

      it 'accepts a number of seconds (from now) as the schedule time' do
        Timecop.freeze do
          now = Time.now
          task = ScheduledTask.new(60){ nil }.execute
          expect(task.schedule_time.to_i).to eq now.to_i + 60
        end
      end

      it 'accepts a time object as the schedule time' do
        schedule = Time.now + (60*10)
        task = ScheduledTask.new(schedule){ nil }.execute
        expect(task.schedule_time).to eq schedule
      end

      it 'raises an exception when seconds is less than zero' do
        expect {
          ScheduledTask.new(-1){ nil }
        }.to raise_error(ArgumentError)
      end

      it 'raises an exception when schedule time is in the past' do
        expect {
          ScheduledTask.new(Time.now - 60){ nil }
        }.to raise_error(ArgumentError)
      end

      it 'raises an exception when no block given' do
        expect {
          ScheduledTask.new(1)
        }.to raise_error(ArgumentError)
      end

      it 'sets the initial state to :unscheduled' do
        task = ScheduledTask.new(1){ nil }
        expect(task).to be_unscheduled
      end

      it 'sets the #schedule_time to nil prior to execution' do
        task = ScheduledTask.new(1){ nil }
        expect(task.schedule_time).to be_nil
      end
    end

    context 'instance #execute' do

      it 'does nothing unless the state is :unscheduled' do
        expect(Thread).not_to receive(:new).with(any_args)
        task = ScheduledTask.new(1){ nil }
        task.instance_variable_set(:@state, :pending)
        task.execute
        task.instance_variable_set(:@state, :rejected)
        task.execute
        task.instance_variable_set(:@state, :fulfilled)
        task.execute
      end

      it 'calculates the #schedule_time on execution' do
        Timecop.freeze do
          now = Time.now
          task = ScheduledTask.new(5){ nil }
          Timecop.travel(10)
          task.execute
          expect(task.schedule_time.to_i).to eq now.to_i + 15
        end
      end

      it 'raises an exception if expected schedule time is in the past' do
        Timecop.freeze do
          schedule = Time.now + (10)
          task = ScheduledTask.new(schedule){ nil }
          Timecop.travel(60)
          expect {
            task.execute
          }.to raise_error(ArgumentError)
        end
      end

      it 'sets the sate to :pending' do
        task = ScheduledTask.new(1){ nil }
        task.execute
        expect(task).to be_pending
      end

      it 'returns self' do
        task = ScheduledTask.new(1){ nil }
        expect(task.execute).to eq task
      end
    end

    context 'class #execute' do

      it 'creates a new ScheduledTask' do
        task = ScheduledTask.execute(1){ nil }
        expect(task).to be_a(ScheduledTask)
      end

      it 'passes the block to the new ScheduledTask' do
        @expected = false
        task = ScheduledTask.execute(0.1){ @expected = true }
        task.value(1)
        expect(@expected).to be_truthy
      end

      it 'calls #execute on the new ScheduledTask' do
        task = ScheduledTask.new(0.1){ nil }
        allow(ScheduledTask).to receive(:new).with(any_args).and_return(task)
        expect(task).to receive(:execute).with(no_args)
        ScheduledTask.execute(0.1){ nil }
      end
    end

    context '#cancel' do

      it 'returns false if the task has already been performed' do
        task = ScheduledTask.new(0.1){ 42 }.execute
        task.value(1)
        expect(task.cancel).to be_falsey
      end

      it 'returns false if the task is already in progress' do
        latch = Concurrent::CountDownLatch.new(1)
        task = ScheduledTask.new(0.1) {
          latch.count_down
          sleep(1)
        }.execute
        latch.wait(1)
        expect(task.cancel).to be_falsey
      end

      it 'cancels the task if it has not yet scheduled' do
        latch = Concurrent::CountDownLatch.new(1)
        task = ScheduledTask.new(0.1){ latch.count_down }
        task.cancel
        task.execute
        expect(latch.wait(0.3)).to be_falsey
      end

      it 'cancels the task if it has not yet started' do
        latch = Concurrent::CountDownLatch.new(1)
        task = ScheduledTask.new(0.3){ latch.count_down }.execute
        sleep(0.1)
        task.cancel
        expect(latch.wait(0.5)).to be_falsey
      end

      it 'returns true on success' do
        task = ScheduledTask.new(10){ nil }.execute
        sleep(0.1)
        expect(task.cancel).to be_truthy
      end

      it 'sets the state to :cancelled when cancelled' do
        task = ScheduledTask.new(10){ 42 }.execute
        sleep(0.1)
        task.cancel
        expect(task).to be_cancelled
      end
    end

    context 'execution' do

      it 'sets the state to :in_progress when the task is running' do
        latch = Concurrent::CountDownLatch.new(1)
        task = ScheduledTask.new(0.1) {
          latch.count_down
          sleep(1)
        }.execute
        latch.wait(1)
        expect(task).to be_in_progress
      end
    end

    context 'observation' do

      let(:clazz) do
        Class.new do
          attr_reader :value
          attr_reader :reason
          attr_reader :count
          attr_reader :latch
          def initialize
            @latch = Concurrent::CountDownLatch.new(1)
          end
          def update(time, value, reason)
            @count = @count.to_i + 1
            @value = value
            @reason = reason
            @latch.count_down
          end
        end
      end

      let(:observer) { clazz.new }

      it 'returns true for an observer added while :unscheduled' do
        task = ScheduledTask.new(0.1){ 42 }
        expect(task.add_observer(observer)).to be_truthy
      end

      it 'returns true for an observer added while :pending' do
        task = ScheduledTask.new(0.1){ 42 }.execute
        expect(task.add_observer(observer)).to be_truthy
      end

      it 'returns true for an observer added while :in_progress' do
        task = ScheduledTask.new(0.1){ sleep(1); 42 }.execute
        sleep(0.2)
        expect(task.add_observer(observer)).to be_truthy
      end

      it 'returns false for an observer added once :cancelled' do
        task = ScheduledTask.new(1){ 42 }
        task.cancel
        expect(task.add_observer(observer)).to be_falsey
      end

      it 'returns false for an observer added once :fulfilled' do
        task = ScheduledTask.new(0.1){ 42 }.execute
        task.value(1)
        expect(task.add_observer(observer)).to be_falsey
      end

      it 'returns false for an observer added once :rejected' do
        task = ScheduledTask.new(0.1){ raise StandardError }.execute
        task.value(0.2)
        expect(task.add_observer(observer)).to be_falsey
      end

      it 'notifies all observers on fulfillment' do
        task = ScheduledTask.new(0.1){ 42 }.execute
        task.add_observer(observer)
        observer.latch.wait(1)
        expect(observer.value).to eq(42)
        expect(observer.reason).to be_nil
      end

      it 'notifies all observers on rejection' do
        task = ScheduledTask.new(0.1){ raise StandardError }.execute
        task.add_observer(observer)
        observer.latch.wait(1)
        expect(observer.value).to be_nil
        expect(observer.reason).to be_a(StandardError)
      end

      it 'does not notify an observer added after fulfillment' do
        expect(observer).not_to receive(:update).with(any_args)
        task = ScheduledTask.new(0.1){ 42 }.execute
        task.value(1)
        task.add_observer(observer)
        sleep(0.1)
      end

      it 'does not notify an observer added after rejection' do
        expect(observer).not_to receive(:update).with(any_args)
        task = ScheduledTask.new(0.1){ raise StandardError }.execute
        task.value(1)
        task.add_observer(observer)
        sleep(0.1)
      end

      it 'does not notify an observer added after cancellation' do
        expect(observer).not_to receive(:update).with(any_args)
        task = ScheduledTask.new(0.1){ 42 }.execute
        task.cancel
        task.add_observer(observer)
        task.value(1)
      end
    end
  end
end


text:
"""
Json Utils

Licensed under MIT
Copyright (c) 2011 Isaac Muse <isaacmuse@gmail.com>

https://gist.github.com/facelessuser/5750103
"""

import re
from .comments import Comments

JSON_PATTERN = re.compile(
    r"""
          (
                (?P<square_comma>
                    ,                        # trailing comma
                    (?P<square_ws>[\s\r\n]*) # white space
                    (?P<square_bracket>\])   # bracket
                )
              | (?P<curly_comma>
                    ,                        # trailing comma
                    (?P<curly_ws>[\s\r\n]*)  # white space
                    (?P<curly_bracket>\})    # bracket
                )
          )
        | (?P<code>
                "(?:\\.|[^"\\])*"            # double quoted string
              | '(?:\\.|[^'\\])*'            # single quoted string
              | .[^,"']*                     # everything else
          )
    """,
    re.MULTILINE | re.DOTALL | re.VERBOSE
)

def strip_dangling_commas(text, preserve_lines=False):
    regex = JSON_PATTERN

    def remove_comma(g, preserve_lines):
        if preserve_lines:
            # ,] -> ] else ,} -> }
            if g["square_comma"] is not None:
                return g["square_ws"] + g["square_bracket"]
            else:
                return g["curly_ws"] + g["curly_bracket"]
        else:
            # ,] -> ] else ,} -> }
            return g["square_bracket"] if g["square_comma"] else g["curly_bracket"]

    def evaluate(m, preserve_lines):
        g = m.groupdict()
        return remove_comma(g, preserve_lines) if g["code"] is None else g["code"]

    return ''.join(map(lambda m: evaluate(m, preserve_lines), regex.finditer(text)))

def strip_comments(text, preserve_lines=False):
    return Comments('json', preserve_lines).strip(text)

def sanitize_json(text, preserve_lines=False):
    return strip_dangling_commas(Comments('json', preserve_lines).strip(text), preserve_lines)


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of VariablesController
 *
 * @author Ea Design
 */
class EaDesign_PdfGenerator_Adminhtml_VariableController extends Mage_Adminhtml_Controller_Action
{
    /**
     * WYSIWYG Plugin Action
     *
     */
    public function wysiwygPluginAction()
    {
        $customVariables = Mage::getModel('eadesign/variables_process')->getVariablesOptionArray(true);
        $this->getResponse()->setBody(Zend_Json::encode($customVariables));
    }
}

?>


text:
require 'test_helper'

class AttributionsTest < ActionController::TestCase
  # use SopsController, because attributions don't have their own controller
  tests SopsController

  fixtures :all

  include AuthenticatedTestHelper
  include SharingFormTestHelper
  def setup
    login_as(:owner_of_my_first_sop)
  end

  def test_should_create_attribution_when_creating_new_sop
    # create a SOP and verify that both SOP and attribution get created
    assert !users(:owner_of_my_first_sop).person.projects.empty?
    assert users(:owner_of_my_first_sop).person.projects.include?(projects(:myexperiment_project))
    assert_difference ['Sop.count', 'Relationship.count'] do
      post :create, :sop => {:data => fixture_file_upload('files/little_file.txt'), :title => "test_attributions",:project_ids=>[projects(:myexperiment_project).id]}, :sharing => valid_sharing, :attributions => ActiveSupport::JSON.encode([["Sop", 1]])
    end
    assert_redirected_to sop_path(assigns(:sop))
  end

  def test_shouldnt_create_duplicated_attribution
    # create a SOP and verify that both SOP and attribution get created
    # (two identical attributions will be posted, but only one needs to be created)
    assert_difference ['Sop.count', 'Relationship.count'] do
      post :create, :sop => {:data => fixture_file_upload('files/little_file.txt'), :title => "test_attributions",:project_ids=>[projects(:myexperiment_project).id]}, :sharing => valid_sharing, :attributions => ActiveSupport::JSON.encode([["Sop", 1], ["Sop", 1]])
    end
    assert_redirected_to sop_path(assigns(:sop))
  end

  def test_should_remove_attribution_on_update
    # create a SOP / attribution first
    assert_difference ['Sop.count', 'Relationship.count'] do
      post :create, :sop => {:data => fixture_file_upload('files/little_file.txt'), :title => "test_attributions",:project_ids=>[projects(:myexperiment_project).id]}, :sharing => valid_sharing, :attributions => ActiveSupport::JSON.encode([["Sop", 1]])
    end
    assert_redirected_to sop_path(assigns(:sop))

    # update the SOP, but supply no data about attributions - these should be removed
    assert_no_difference('Sop.count') do
      assert_difference('Relationship.count', -1) do
        put :update, :id => assigns(:sop).id, :sop => {:title => "edited_title",:project_ids=>[projects(:myexperiment_project).id]}, :sharing => valid_sharing,:attributions=>nil # NB! no attributions supplied - should remove if any existed for the sop
      end
    end
    assert_redirected_to sop_path(assigns(:sop))
  end

  def test_attributions_will_get_destroyed_when_master_sop_is_destroyed
    # create a SOP and verify that both SOP and attributions get created
    assert_difference('Sop.count') do
      assert_difference('Relationship.count', +2) do
        post :create, :sop => {:data => fixture_file_upload('files/little_file.txt'), :title => "test_attributions",:project_ids=>[projects(:myexperiment_project).id]}, :sharing => valid_sharing, :attributions => ActiveSupport::JSON.encode([["Sop", 111], ["Sop", 222]])
      end
    end
    assert_redirected_to sop_path(assigns(:sop))

    # destroy the new sop and verify that the attributions get destroyed too
    sop_instance = Sop.find(assigns(:sop).id)
    assert_difference('Sop.count', -1) do
      assert_difference('Relationship.count', -2) do
        User.current_user = sop_instance.contributor
        sop_instance.destroy
      end
    end

    # double-check to see that no attributions for this sop remain
    destroyed_sop_attributions = Relationship.where :subject_id => sop_instance.id,
                                                    :subject_type => sop_instance.class.name,
                                                    :predicate => Relationship::ATTRIBUTED_TO
    assert_equal [], destroyed_sop_attributions
  end

  def test_attributions_are_getting_properly_synchronized
    # create a SOP / attributions first
    assert_difference('Sop.count') do
      assert_difference('Relationship.count', +2) do
        post :create, :sop => {:data => fixture_file_upload('files/little_file.txt'), :title => "test_attributions",:project_ids=>[projects(:myexperiment_project).id]}, :sharing => valid_sharing, :attributions => ActiveSupport::JSON.encode([["Sop", 1], ["Sop", 2]])
      end
    end
    assert_redirected_to sop_path(assigns(:sop))

    # store IDs of created attribution for further checks
    sop_id = assigns(:sop).id
    sop_instance = Sop.find(sop_id)

    assert_equal 2, sop_instance.attributions.length
    if sop_instance.attributions[0].other_object_id == 1
      attr_to_sop_one = sop_instance.attributions[0]
      attr_to_sop_two = sop_instance.attributions[1]
    else
      attr_to_sop_one = sop_instance.attributions[1]
      attr_to_sop_two = sop_instance.attributions[0]
    end

    # update the SOP: attributions data will add a new attribution, remove one old and keep one old unchanged -
    # this leaves the total number of attributions unchaged
    assert_no_difference ['Sop.count', 'Relationship.count'] do
      put :update, :id => assigns(:sop).id, :sop => {:title => "edited_title"}, :sharing => valid_sharing, :attributions => ActiveSupport::JSON.encode([["Sop", 44], ["Sop", 2]])
    end
    assert_redirected_to sop_path(assigns(:sop))

    # verify it's still the same SOP
    assert_equal sop_id, assigns(:sop).id

    # --- Verify that synchronisation was performed correctly ---

    # attribution that was supposed to be deleted was really destroyed
    deleted_attr_to_sop_one = Relationship.where({ :subject_id => attr_to_sop_one.subject_id, :subject_type => attr_to_sop_one.subject_type,
                                                                         :predicate => attr_to_sop_one.predicate, :other_object_id => attr_to_sop_one.other_object_id,
                                                                         :other_object_type => attr_to_sop_one.other_object_type } ).first
    assert_equal nil, deleted_attr_to_sop_one

    # attribution that was supposed to stay unchanged should preserve its ID -
    # this will then indicate that it was identified to be existing and was properly
    # handled by keeping intact instead of removing and re-creating new record with the
    # same attribution data
    remaining_attr_to_sop_two = Relationship.where({ :subject_id => attr_to_sop_two.subject_id, :subject_type => attr_to_sop_two.subject_type,
                                                                           :predicate => attr_to_sop_two.predicate, :other_object_id => attr_to_sop_two.other_object_id,
                                                                           :other_object_type => attr_to_sop_two.other_object_type } ).first
    assert_equal attr_to_sop_two.id, remaining_attr_to_sop_two.id

    # make sure that new attribution was created correctly
    # (we have already checked that the total number of attributions after running the test
    #  is correct - one removed, one added, one left unchanged: total - unchanged)
    new_attr = Relationship.where({ :subject_id => sop_id, :subject_type => sop_instance.class.name,
                                                          :predicate => Relationship::ATTRIBUTED_TO, :other_object_id => 44,
                                                          :other_object_type => "Sop" } ).first
    assert (!new_attr.nil?), "new attribution shouldn't be nil - nil means that it wasn't created"
  end

  test "should display attributions" do
    u = Factory :user
    login_as(u)
    sop1 = Factory :sop,:policy=>(Factory :public_policy),:contributor=>u
    sop2 = Factory :sop,:policy=>(Factory :public_policy),:contributor=>u
    sop3 = Factory :sop,:policy=>(Factory :public_policy),:contributor=>u
    Relationship.create :subject=>sop1,:other_object=>sop2,:predicate=>Relationship::ATTRIBUTED_TO
    sop1.reload
    sop2.reload
    assert_equal [sop2],sop1.attributions.collect{|r| r.other_object}
    assert_equal [sop2],sop1.attributions_objects

    get :show,:id=>sop1
    assert_response :success
    assert_select "div.contribution_section_box" do
      assert_select "p.heading",:text=>/Attributions/
      assert_select "ul.list" do
        assert_select "li" do
          assert_select "a[href=?]",sop_path(sop2),:text=>/#{sop2.title}/
        end
      end
    end

    get :show,:id=>sop3
    assert_response :success
    assert_select "div.contribution_section_box" do
      assert_select "p.heading",:text=>/Attributions/
      assert_select "p.none_text",:text=>"None"
    end
  end

end