text:
import Template from "./template";
import paper from "paper";
import ComponentPort from "../core/componentPort";

export default class PicoInjection extends Template{
    constructor() {
        super();
    }

    __setupDefinitions() {
        this.__unique = {
            position: "Point"
        };

        this.__heritable = {
            componentSpacing: "Float",
            height: "Float",
            width: "Float",
            injectorWidth: "Float",
            injectorLength: "Float",
            dropletWidth: "Float",
            nozzleWidth: "Float",
            nozzleLength: "Float",
            electrodeDistance: "Float",
            electrodeWidth: "Float",
            electrodeLength: "Float",
            rotation: "Float"
        };

        this.__defaults = {
            componentSpacing: 1000,
            height: 250,
            width: 10 * 1000,
            injectorWidth: 2 * 1000,
            injectorLength: 3 * 1000,
            dropletWidth: 0.8 * 1000,
            nozzleWidth: 0.4 * 1000,
            nozzleLength: 0.4 * 1000,
            electrodeDistance: 0.8 * 1000,
            electrodeWidth: 0.8 * 1000,
            electrodeLength: 3 * 1000,
            rotation: 0
        };

        this.__units = {
            componentSpacing: "μm",
            height: "μm",
            width: "μm",
            injectorWidth: "μm",
            injectorLength: "μm",
            dropletWidth: "μm",
            nozzleWidth: "μm",
            nozzleLength: "μm",
            electrodeDistance: "μm",
            electrodeWidth: "μm",
            electrodeLength: "μm",
            rotation: "°"
        };

        this.__minimum = {
            componentSpacing: 0,
            height: 10,
            width: 5 * 1000,
            injectorWidth: 1000,
            injectorLength: 1000,
            dropletWidth: 100,
            nozzleWidth: 80,
            nozzleLength: 80,
            electrodeDistance: 100,
            electrodeWidth: 100,
            electrodeLength: 1000,
            rotation: 0
        };

        this.__maximum = {
            componentSpacing: 10000,
            height: 1200,
            width: 20 * 1000,
            injectorWidth: 4000,
            injectorLength: 5000,
            dropletWidth: 2000,
            nozzleWidth: 1000,
            nozzleLength: 500,
            electrodeDistance: 2000,
            electrodeWidth: 2000,
            electrodeLength: 5000,
            rotation: 360
        };

        this.__placementTool = "componentPositionTool";

        this.__toolParams = {
            cursorPosition: "position"
        };

        this.__featureParams = {
            componentSpacing: "componentSpacing",
            position: "position",
            width: "width",
            injectorWidth: "injectorWidth",
            injectorLength: "injectorLength",
            dropletWidth: "dropletWidth",
            nozzleWidth: "nozzleWidth",
            nozzleLength: "nozzleLength",
            electrodeDistance: "electrodeDistance",
            electrodeWidth: "electrodeWidth",
            electrodeLength: "electrodeLength",
            rotation: "rotation"
        };

        this.__targetParams = {
            componentSpacing: "componentSpacing",
            width: "width",
            injectorWidth: "injectorWidth",
            injectorLength: "injectorLength",
            dropletWidth: "dropletWidth",
            nozzleWidth: "nozzleWidth",
            nozzleLength: "nozzleLength",
            electrodeDistance: "electrodeDistance",
            electrodeWidth: "electrodeWidth",
            electrodeLength: "electrodeLength",
            rotation: "rotation"
        };

        this.__renderKeys = ["FLOW"];

        this.__mint = "PICOINJECTOR";
    }

    getPorts(params) {
        let width = params["width"];
        let injectorLength = params["injectorLength"];
        let dropletWidth = params["dropletWidth"];
        let nozzleLength = params["nozzleLength"];
        let electrodeDistance = params["electrodeDistance"];
        let electrodeWidth = params["electrodeWidth"];
        let electrodeLength = params["electrodeLength"];

        let ports = [];

        // droplet channel
        ports.push(new ComponentPort(-width/2, 0, "1", "FLOW"));
        ports.push(new ComponentPort(width/2, 0, "2", "FLOW"));

        // injector
        ports.push(new ComponentPort(0, - dropletWidth/2 - nozzleLength - injectorLength, "3", "FLOW"));

        return ports;
    }

    render2D(params, key) {
        let rotation = params["rotation"];
        let x = params["position"][0];
        let y = params["position"][1];
        let color = params["color"];
        let width = params["width"];
        let injectorWidth = params["injectorWidth"];
        let injectorLength = params["injectorLength"];
        let dropletWidth = params["dropletWidth"];
        let nozzleWidth = params["nozzleWidth"];
        let nozzleLength = params["nozzleLength"];
        let electrodeDistance = params["electrodeDistance"];
        let electrodeWidth = params["electrodeWidth"];
        let electrodeLength = params["electrodeLength"];
        let serp = new paper.CompoundPath();

        // droplet channel
        let topLeft = new paper.Point(x - width/2, y - dropletWidth/2);
        let bottomRight = new paper.Point(x + width/2, y + dropletWidth/2);

        serp.addChild(new paper.Path.Rectangle(topLeft, bottomRight));

        // nozzle
        topLeft = new paper.Point(x - nozzleWidth/2, y - dropletWidth/2 - nozzleLength);
        bottomRight = new paper.Point(x + nozzleWidth/2, y - dropletWidth/2);

        serp.addChild(new paper.Path.Rectangle(topLeft, bottomRight));

        // injector
        topLeft = new paper.Point(x - injectorWidth/2, y - dropletWidth/2 - nozzleLength - injectorLength);
        bottomRight = new paper.Point(x + injectorWidth/2, y - dropletWidth/2 - nozzleLength);

        serp.addChild(new paper.Path.Rectangle(topLeft, bottomRight));

        // middle electrode
        topLeft = new paper.Point(x - electrodeWidth/2, y + electrodeDistance);
        bottomRight = new paper.Point(x + electrodeWidth/2, y + electrodeDistance + electrodeLength);

        serp.addChild(new paper.Path.Rectangle(topLeft, bottomRight));

        // left electrode
        topLeft = new paper.Point(x - electrodeWidth/2 - 2 * electrodeWidth, y + electrodeDistance);
        bottomRight = new paper.Point(x + electrodeWidth/2 - 2 * electrodeWidth, y + electrodeDistance + electrodeLength);

        serp.addChild(new paper.Path.Rectangle(topLeft, bottomRight));

        // right electrode
        topLeft = new paper.Point(x - electrodeWidth/2 + 2 * electrodeWidth, y + electrodeDistance);
        bottomRight = new paper.Point(x + electrodeWidth/2 + 2 * electrodeWidth, y + electrodeDistance + electrodeLength);

        serp.addChild(new paper.Path.Rectangle(topLeft, bottomRight));

        serp.rotate(rotation, new paper.Point(x, y));

        serp.fillColor = color;
        return serp;
    }

    render2DTarget(key, params) {
        let serp = this.render2D(params, key);

        serp.fillColor.alpha = 0.5;
        return serp;
    }
}


text:
"use strict";

const {CompositeDisposable} = require("atom");
const Options = require("../options.js");

class StrategyManager{

	init(){
		this.fileStrategies = [];
		this.directoryStrategies = [];
		this.disposables = new CompositeDisposable();

		const strategies = [
			require("./strategies/signature-strategy.js"),
			require("./strategies/hashbang-strategy.js"),
			require("./strategies/modeline-strategy.js"),
			require("./strategies/linguist-strategy.js"),
			require("./strategies/usertype-strategy.js"),
			require("./strategies/grammar-strategy.js"),
			require("./strategies/path-strategy.js"),
		];

		for(let i = 0, l = strategies.length; i < l; ++i)
			this.addStrategy(strategies[i]);

		this.fileStrategies = this.fileStrategies.filter(a => a).reverse();
		this.directoryStrategies = this.directoryStrategies.filter(a => a).reverse();
	}

	reset(){
		const strategies = new Set([
			...this.fileStrategies,
			...this.directoryStrategies,
		]);

		strategies.forEach(strategy => strategy.disable());
		this.disposables.dispose();
		this.disposables = null;
	}

	addStrategy(strategy){
		const {priority} = strategy;
		if(strategy.matchesFiles) this.fileStrategies[priority] = strategy;
		if(strategy.matchesDirs)  this.directoryStrategies[priority] = strategy;

		if(!strategy.noSetting)
			this.disposables.add(Options.observe(strategy.name, enabled => {
				enabled ? strategy.enable() : strategy.disable();
			}));

		else if("signature" === strategy.name){
			this.disposables.add(
				Options.observe("hashbangs", enabled => {
					enabled || Options.get("modelines")
						? strategy.enable()
						: strategy.disable();
				}),
				Options.observe("modelines", enabled => {
					enabled || Options.get("hashbangs")
						? strategy.enable()
						: strategy.disable();
				})
			);
		}

		// Strategies without settings are always active
		else strategy.enable();
	}

	query(resource){
		if(null == resource)
			return;

		const strategies = resource.isDirectory
			? this.directoryStrategies
			: this.fileStrategies;

		if(!strategies) return;

		for(let i = 0, l = strategies.length; i < l; ++i){
			const strategy = strategies[i];
			if(!strategy.enabled) continue;
			const shouldStop = strategy.check(resource);
			if(shouldStop)
				break;
		}
	}
}

module.exports = new StrategyManager();

redpajama_set_name: RedPajamaGithub


text:
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements.  See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership.  The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License.  You may obtain a copy of the License at
@REM
@REM    https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied.  See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------

@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM     e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------

@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on"  echo %MAVEN_BATCH_ECHO%

@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")

@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre

@setlocal

set ERROR_CODE=0

@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal

@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome

echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error

:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init

echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error

@REM ==== END VALIDATION ====

:init

@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.

set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir

set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir

:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir

:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"

:endDetectBaseDir

IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig

@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%

:endReadAdditionalConfig

SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain

set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
	IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)

@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
    echo Found %WRAPPER_JAR%
) else (
    echo Couldn't find %WRAPPER_JAR%, downloading it ...
	echo Downloading from: %DOWNLOAD_URL%
    powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
    echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension

%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end

:error
set ERROR_CODE=1

:end
@endlocal & set ERROR_CODE=%ERROR_CODE%

if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost

@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause

if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%

exit /B %ERROR_CODE%


text:
"""
Copyright 2015 Brocade Communications Systems, Inc.

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.
"""

import os
import getpass
import logging
import psutil
import copy

from helpers import cls, getpid
from optparse import OptionParser
from time import sleep

_NAP = 1
# Default for sleep
_SLEEP_DEFAULT = 600

class _setup(object):
    """This class does nothing more than instantiate the setup() class
        and provide bound copies via the get_setup() method.
        Why do this you ask? Me too. It's a Windows issue.
        Pickling the setup instance for each multiprocess goes wrong.
    """

    def __init__(self, **kwargs):
        self.setup = setup(**kwargs)
        return

    def get_setup(self):
        return copy.deepcopy(self.setup)

class setup(object):
    # This is a little unixy. Make Windows happy.
    # _pidfile = "/tmp/icx_collection.pid"
    # _log = "/tmp/clicrud.log"

    _pidfile = "clicrud_collection.pid"
    _log = "clicrud.log"

    def __init__(self, splash):
        # Entry point for __main__
        self._thread_list = []

        # PID List
        self._pid_list = []

        # Parallel mode by default
        self.parallel = True

        # Setup logging
        logging.basicConfig(filename=self._log, level=logging.DEBUG)

        # Deal with init args
        (self._options, self._args) = self.setup_options()
        self._splash = splash

        # Go and get the PID
        self.createPIDfile(self._pidfile, str(getpid()))
        logging.info("Created PID File %s" % self._pidfile)
        self._pid_list.append(os.getpid())

        # Now we deal with user facing splash screen
        if self._splash:
            self.splash_screen()

        if self._options.period is not None:
            self._SLEEP = int(self._options.period)
        else:
            self._SLEEP = _SLEEP_DEFAULT

    def createPIDfile(self, _pidfile, PIDInfo):
        try:
            _f = open(_pidfile, 'w')
            _f.write(PIDInfo)
            _f.close()
        except:
            logging.error("Could not open file for PID")

    def getpasswords(self):

        for thread in self._thread_list:

            if thread._kwargs['password'] == "":
                print "Input password for device %s: " % thread._kwargs['host']
                thread._kwargs['password'] = getpass.getpass()
                if self._splash:
                    self.splash_screen()

            if thread._kwargs['enable'] == "":
                print "Input password for device %s: " % thread._kwargs['host']
                thread._kwargs['enable'] = getpass.getpass()
                if self._splash:
                    self.splash_screen()

    def setup_options(self):
        parser = OptionParser(usage="python icx_diagnose --username=\"name\" \
                                     --hostname=\"192.0.2.1\" \
                                     --method=\"telnet|ssh\" OPTIONAL \
                                     --runonce --password",
                              version="alpha 1.0")

        parser.add_option("-t", "--timeperiod", dest="period",
                          help="Time period between data \
                                collection in seconds",
                          metavar="Time", type="string")

        parser.add_option("-c", "--continuous", dest="loop",
                          help="If continous is set, then this library \
                                will execute in a loop governed by -t",
                          metavar="Continous", action="store_true")

        return parser.parse_args()

    def splash_screen(self):
        cls()
        print 80*"*"
        print "\t\tB R O C A D E\t\t C L I C R U D\t\tv0.1"
        print 80*"*"
        print "Please hit CTRL+C to terminate\n"

    def splash_prepare_to_launch(self):
        if not self.parallel:
            print "In non-parallel mode"
        print "\n------Progress------\n"

    def start_processes(self):
        for _idx, _t in enumerate(self._thread_list):
            _t.start()
            self._pid_list.append(_t.getPID())
            logging.info("Run thread %s with pid %s with kwargs %s" %
                         (_idx+1, _t.getPID(), _t))
            # Uncomment out if we want to block the main thread until
            # at least one pass has completed.
            if not self.parallel:
                _t.ranonce

    def run_processes(self):
        for _idx, _t in enumerate(self._thread_list):
            if _t.is_alive():
                _t.run()
                self._pid_list.append(_t.getPID())
                logging.info("Run thread %s with pid %s with kwargs %s" %
                             (_idx+1, _t.getPID(), _t))

    def main_loop(self, continuous):
        main_loop = True
        free_to_write = True
        _all_ran_once = False
        while main_loop:
            if self.parallel is False:
                try:

                    _SLEEP_ACCUM = 0
                    if continuous:
                        while _SLEEP_ACCUM < self._SLEEP:
                            sleep(_NAP)
                            _SLEEP_ACCUM += _NAP
                    # this is the loop that creates the threads and
                    # joins them together
                    for _idx, _t in enumerate(self._thread_list):
                        # print "Run thread %s with pid %s with kwargs %s" %
                        #      (_idx+1, _t.getPID(), _t)
                        _t.run()
                        while not _t.ranonce:
                            sleep(0.2)

                except KeyboardInterrupt:
                    print "\b\nCtrl C - Stopping server"
                    print "Stopping jobs %s..." % (self._pid_list)
                    # for p in self._thread_list:
                    #    p._t.terminate()
                    # sys.exit(1)
                    main_loop = False

            # PARALLEL OPERATION HERE
            # IF parallel = True
            if self.parallel is True:
                try:

                    # We only want to star the main timing cycle once the job
                    # has run at least once. Else we face overlapping jobs

                    if not _all_ran_once:
                        for _idx, _t in enumerate(self._thread_list):
                            # Wait until we've got our True signal from ranonce
                            _t.ranonce

                        _all_ran_once = True

                    # It is expected that we need to sleep post the run once
                    _SLEEP_ACCUM = 0
                    if continuous:
                        while _SLEEP_ACCUM < self._SLEEP:
                            sleep(_NAP)
                            _SLEEP_ACCUM += _NAP
                    # this is the loop that creates the threads and joins
                    # them together
                    for _idx, _t in enumerate(self._thread_list):
                        # print "Run thread %s with pid %s with kwargs %s"
                        #        % (_idx+1, _t.getPID(), _t)
                        _t.run()

                except KeyboardInterrupt:
                    print "\b\nCtrl C - Stopping server"
                    print "Stopping jobs %s..." % (self._pid_list)
                    # for p in self._thread_list:
                    #    p._t.terminate()
                    # sys.exit(1)
                    main_loop = False

    def start(self, *args):
        for arg in args:
            self._thread_list.append(arg)

        # We only need to do this if we're running a script
        self.getpasswords()

        if not self._options.loop:
            self.splash_prepare_to_launch()
            # Start the multi-processing off!
            self.start_processes()

        # If you only want to use library programming, then don't worry
        # about this.
        if self._options.loop:
            print "Entering periodic refresh loop of : %d seconds" \
                   % (self._SLEEP)
            self.splash_prepare_to_launch()
            # Start the multi-processing off!
            self.start_processes()
            self.main_loop(True)

    def stop(self):
        StopCheck = True
        NumProcs = len(self._thread_list)
        ProcsStopped = 0
        while StopCheck:
            for _idx, _t in enumerate(self._thread_list):
                _qmsg = _t.finq
                if _qmsg == 'completed_run':
                    _t.stop()
                    ProcsStopped += 1
                    logging.info("Stopped thread %s with pid %s with kwargs \
                                 %s" % (_idx+1, _t.getPID(), _t))
                if _qmsg == 'error':
                    _t.stop()
                    logging.info("Error on thread %s with pid %s with kwargs \
                                 %s" % (_idx+1, _t.getPID(), _t))
                    StopCheck = False

                if NumProcs == ProcsStopped:
                    StopCheck = False
            sleep(0.5)

        print "\n\nGoodbye..."
        for pid in self._pid_list:
            p = psutil.Process(pid)
            p.terminate()
        exit(0)


text:
'use strict';

// Regulations controller
angular.module('regulations').controller('RegulationsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Regulations',
	function($scope, $stateParams, $location, Authentication, Regulations) {
		$scope.authentication = Authentication;

		// Create new Regulation
		$scope.create = function() {
			// Create new Regulation object
			var regulation = new Regulations ({
				title: this.title,
				section: this.section,
				number: this.number,
				regText: this.regText
			});

			// Redirect after save
			regulation.$save(function(response) {
				$location.path('regulations/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Regulation
		$scope.remove = function(regulation) {
			if ( regulation ) {
				regulation.$remove();

				for (var i in $scope.regulations) {
					if ($scope.regulations [i] === regulation) {
						$scope.regulations.splice(i, 1);
					}
				}
			} else {
				$scope.regulation.$remove(function() {
					$location.path('regulations');
				});
			}
		};

		// Update existing Regulation
		$scope.update = function() {
			var regulation = $scope.regulation;

			regulation.$update(function() {
				$location.path('regulations/' + regulation._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Regulations
		$scope.find = function() {
			$scope.regulations = Regulations.query();
		};

		// Find existing Regulation
		$scope.findOne = function() {
			$scope.regulation = Regulations.get({
				regulationId: $stateParams.regulationId
			});
		};
	}
]);


text:
namespace blink {

class IdleCallbackDeadline;

class IdleRequestCallback : public GarbageCollectedFinalized<IdleRequestCallback> {
public:
    DEFINE_INLINE_VIRTUAL_TRACE() {}
    virtual ~IdleRequestCallback() {}

    virtual void handleEvent(IdleDeadline*) = 0;
};
}

#endif // IdleRequestCallback_h


text:
exports.getView = function(){
	var filterUsernameScrollView = Ti.UI.createScrollView({
		layout:'vertical',
		backgroundColor:'#8ab3af'
	});

	/////////////////////searchByUsername
	var searchByUsername = Ti.UI.createView({
		height:'40dp',
		backgroundColor:'#8ab3af',
	});

	searchByUsername.add(Ti.UI.createLabel({
		text:'SEARCH BY USERNAME',
		bottom:'2dp',
		left:'10dp',
		color:defaultGreenColor,
		font:{
			fontSize:10,
			fontWeight:'bold'
		}
	}));

	filterUsernameScrollView.add(searchByUsername);

	/////////////////////searchByUsername Content
	var filterUsernameContent = Ti.UI.createView({
		backgroundColor:'#a0cecb',
		height:'90dp',
	});

	var filterUsernameTextField = Ti.UI.createTextField({
		backgroundColor:'white',
		hintText:'enter your location',
		paddingLeft:'5dp',
		color:defaultGreenColor,
		width:'85%',
		height:'25dp',
		borderColor:defaultGreenColor,
		borderWidth:.5
	});

	filterUsernameContent.add(filterUsernameTextField);

	filterUsernameScrollView.add(filterUsernameContent);

	//addbuffer
	filterUsernameScrollView.add(Ti.UI.createView({
		height:'250dp',
		backgroundColor:'transparent',
		width:Ti.UI.FILL
	}));

	//return view
	return filterUsernameScrollView;
};


text:
@interface NUIControlRendererTests : FBSnapshotTestCase
@property (strong, nonatomic) UIControl *sut;
@end

@implementation NUIControlRendererTests

- (void)setUp
{
    [super setUp];

    [NUISettings initWithStylesheet:@"TestTheme.NUI"];

    _sut = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [_sut applyNUI];

    self.recordMode = NO;
}

- (void)tearDown
{
    self.sut = nil;
    [super tearDown];
}

// background-color (Color)
- (void)testSetBackgroundColor
{
    UIColor *color = [UIColor greenColor];
    XCTAssertEqualObjects(_sut.backgroundColor, color, @"NUI should set control background color");
}

// background-image (Image)
- (void)testSetBackgroundImage
{
    _sut.nuiClass = @"ControlWithBackgroundImage";
    [_sut applyNUI];

    FBSnapshotVerifyView(_sut, nil);
}

// border-color (Color)
- (void)testSetBorderColor
{
    UIColor *borderColor = [UIColor colorWithCGColor:_sut.layer.borderColor];
    XCTAssertEqualObjects(borderColor, [UIColor redColor], @"NUI should set control border color");
}

// border-width (Number)
- (void)testSetBorderWidth
{
    XCTAssertEqualObjects(@(_sut.layer.borderWidth), @2, @"NUI should set control border width");
}

// corner-radius (Number)
- (void)testSetCornerRadius
{
    XCTAssertEqualObjects(@(_sut.layer.cornerRadius), @2, @"NUI should set control corner radius");
}

// shadow-color (Color)
- (void)testSetShadowColor
{
    UIColor *shadowColor = [UIColor colorWithCGColor:_sut.layer.shadowColor];
    XCTAssertEqualObjects(shadowColor, [UIColor blackColor], @"NUI should set control shadow color");
}

// shadow-offset (Offset)
- (void)testSetShadowOffset
{
    CGSize offset = CGSizeMake(1, 2);
    XCTAssertTrue(CGSizeEqualToSize(_sut.layer.shadowOffset, offset), @"NUI should set control shadow offset");
}

// shadow-opacity (Number)
- (void)testSetShadowOpacity
{
    XCTAssertEqualWithAccuracy(_sut.layer.shadowOpacity, 0.5, 0.0001, @"NUI should set control shadow opacity");

}

// shadow-radius (Number)
- (void)testSetShadowRadius
{
    XCTAssertEqualObjects(@(_sut.layer.shadowRadius), @2, @"NUI should set control shadow radius");
}

@end


text:
/**
 * Module dependencies
 */

var _ = require('lodash');
var utils = require('./utils');
var hop = utils.object.hasOwnProperty;

/**
 * Expose JoinTables
 */

module.exports = JoinTables;

/**
 * Insert Join/Junction Tables where needed whenever two collections
 * point to each other. Also replaces the references to point to the new join table.
 *
 * @param {Object} collections
 * @return {Object}
 * @api private
 */

function JoinTables(collections) {

  var self = this;
  var joinTables;

  collections = collections || {};
  this.tables = {};

  this.collections = _.cloneDeep(collections);

  // Build Up Join Tables
  for(var collection in collections) {

    // Parse the collection's attributes and create join tables
    // where needed for collections
    joinTables = this.buildJoins(collection);
    this.uniqueTables(joinTables);

    // Mark hasManyThrough tables as junction tables with select all set to true
    this.markCustomJoinTables(collection);
  }

  // Update Collection Attributes to point to the join table
  this.linkAttributes();

  // Remove properties added just for unqueness
  Object.keys(this.tables).forEach(function(table) {
    delete self.tables[table].joinedAttributes;
  });

  return _.extend(this.collections, this.tables);

}

/**
 * Build A Set of Join Tables
 *
 * @param {String} collection
 * @api private
 * @return {Array}
 */

JoinTables.prototype.buildJoins = function(collection) {

  var self = this;
  var tables = [];

  var attributes = this.collections[collection].attributes;
  var collectionAttributes = this.mapCollections(attributes);

  // If there are no collection attributes return an empty array
  if(Object.keys(collectionAttributes).length === 0) return [];

  // For each collection attribute, inspect it to build up a join table if needed.
  collectionAttributes.forEach(function(attribute) {
    var table = self.parseAttribute(collection, attribute);
    if(table) tables.push(self.buildTable(table));
  });

  return tables;

};

/**
 * Find Has Many attributes for a given set of attributes.
 *
 * @param {Object} attributes
 * @return {Object}
 * @api private
 */

JoinTables.prototype.mapCollections = function(attributes) {

  var collectionAttributes = [];

  for(var attribute in attributes) {
    if(!hop(attributes[attribute], 'collection')) continue;
    collectionAttributes.push({ key: attribute, val: attributes[attribute] });
  }

  return collectionAttributes;

};

/**
 * Parse Collection Attributes
 *
 * Check the collection the attribute references to see if this is a one-to-many or many-to-many
 * relationship. If it's a one-to-many we don't need to build up a join table.
 *
 * @param {String} collectionName
 * @param {Object} attribute
 * @return {Object}
 * @api private
 */

JoinTables.prototype.parseAttribute = function(collectionName, attribute) {

  var error = '';
  var attr = attribute.val;

  // Check if this is a hasManyThrough attribute,
  // if so a join table doesn't need to be created
  if(hop(attr, 'through')) return;

  // Normalize `collection` property name to lowercased version
  attr.collection = attr.collection.toLowerCase();

  // Grab the associated collection and ensure it exists
  var child = this.collections[attr.collection];
  if(!child) {
    error = 'Collection ' + collectionName + ' has an attribute named ' + attribute.key + ' that is ' +
            'pointing to a collection named ' + attr.collection + ' which doesn\'t exist. You must ' +
            ' first create the ' + attr.collection + ' collection.';

    throw new Error(error);
  }

  // If the attribute has a `via` key, check if it's a foreign key. If so this is a one-to-many
  // relationship and no join table is needed.
  if(hop(attr, 'via') && hop(child.attributes[attr.via], 'foreignKey')) return;

  // If no via is specified, a name needs to be created for the other column
  // in the join table. Use the attribute key and the associated collection name
  // which will be unique.
  if(!hop(attr, 'via')) attr.via = attribute.key + '_' + attr.collection;

  // Build up an object that can be used to build a join table
  var tableAttributes = {
    column_one: {
      collection: collectionName.toLowerCase(),
      attribute: attribute.key,
      via: attr.via
    },

    column_two: {
      collection: attr.collection,
      attribute: attr.via,
      via: attribute.key
    }
  };

  return tableAttributes;

};

/**
 * Build Collection for a single join
 *
 * @param {Object} columns
 * @return {Object}
 * @api private
 */

JoinTables.prototype.buildTable = function(columns) {

  var table = {};
  var c1 = columns.column_one;
  var c2 = columns.column_two;

  table.identity = this.buildCollectionName(columns).toLowerCase();
  table.tableName = table.identity;
  table.tables = [c1.collection, c2.collection];
  table.joinedAttributes = [];
  table.junctionTable = true;

  // Look for a dominant collection property so the join table can be created on the correct connection.
  table.connection = this.findDominantConnection(columns);
  if(!table.connection) {
    var err = "A 'dominant' property was not supplied for the two collections in a many-to-many relationship. " +
        "One side of the relationship between '" + c1.collection + "' and '" + c2.collection + "' needs a " +
        "'dominant: true' flag set so a join table can be created on the correct connection.";

    throw new Error(err);
  }

  // Set a primary key (should probably be refactored)
  table.attributes = {
    id: {
      primaryKey: true,
      autoIncrement: true,
      type: 'integer'
    }
  };

  // Add each foreign key as an attribute
  table.attributes[c1.collection + '_' + c1.attribute] = this.buildForeignKey(c1, c2);
  table.attributes[c2.collection + '_' + c2.attribute] = this.buildForeignKey(c2, c1);

  table.joinedAttributes.push(c1.collection + '_' + c1.attribute);
  table.joinedAttributes.push(c2.collection + '_' + c2.attribute);

  return table;

};

/**
 * Build a collection name by combining two collection and attribute names.
 *
 * @param {Object} columns
 * @return {String}
 * @api private
 */

JoinTables.prototype.buildCollectionName = function(columns) {

  var c1 = columns.column_one;
  var c2 = columns.column_two;

  if(c1.collection < c2.collection) {
    return c1.collection + '_' + c1.attribute + '__' + c2.collection + '_' + c2.attribute;
  }

  return c2.collection + '_' + c2.attribute + '__' + c1.collection + '_' + c1.attribute;

};

/**
 * Find the dominant collection.
 *
 * @param {Object} columns
 * @return {String}
 * @api private
 */

JoinTables.prototype.findDominantConnection = function(columns) {

  var c1 = this.collections[columns.column_one.collection];
  var c2 = this.collections[columns.column_two.collection];
  var dominantCollection;

  // Don't require a dominant collection on self-referencing associations
  if(columns.column_one.collection === columns.column_two.collection) {
    return c1.connection;
  }

  dominantCollection = this.searchForAttribute(columns.column_one.collection, 'dominant');
  if(dominantCollection) return c1.connection;

  dominantCollection = this.searchForAttribute(columns.column_two.collection, 'dominant');
  if(dominantCollection) return c2.connection;

  // Don't require a dominant collection for models on the same connection.
  if (c1.connection[0] === c2.connection[0]) {
    return c1.connection;
  }

  return false;

};

/**
 * Search Attributes for an attribute property.
 *
 * @param {String} collectionName
 * @param {String} attributeName
 * @param {String} value (optional)
 * @return {String}
 * @api private
 */

JoinTables.prototype.searchForAttribute = function(collectionName, attributeName, value) {

  var collection = this.collections[collectionName];
  var matching;
  var properties;

  Object.keys(collection.attributes).forEach(function(key) {
    properties = collection.attributes[key];
    if(!value && hop(properties, attributeName)) matching = key;
    if(hop(properties, attributeName) && properties[attributeName] === value) matching = key;
  });

  return matching;

};

/**
 * Build a Foreign Key value for an attribute in the join collection
 *
 * @param {Object} column_one
 * @param {Object} column_two
 * @return {Object}
 * @api private
 */

JoinTables.prototype.buildForeignKey = function(column_one, column_two) {

  var primaryKey = this.findPrimaryKey(column_one.collection);
  var columnName = (column_one.collection + '_' + column_one.attribute);
  var viaName = column_two.collection + '_' + column_one.via;

  return {
    columnName: columnName,
    type: primaryKey.attributes.type,
    foreignKey: true,
    references: column_one.collection,
    on: primaryKey.name,
    onKey: primaryKey.name,
    via: viaName,
    groupKey: column_one.collection
  };

};

/**
 * Filter Out Duplicate Join Tables
 *
 * @param {Array} tables
 * @api private
 */

JoinTables.prototype.uniqueTables = function(tables) {

  var self = this;

  tables.forEach(function(table) {
    var add = true;

    // Check if any tables are already joining these attributes together
    Object.keys(self.tables).forEach(function(tableName) {
      var currentTable = self.tables[tableName];
      if(currentTable.joinedAttributes.indexOf(table.joinedAttributes[0]) === -1) return;
      if(currentTable.joinedAttributes.indexOf(table.joinedAttributes[1]) === -1) return;

      add = false;
    });

    if(hop(self.tables, table.identity)) return;
    if(add) self.tables[table.identity] = table;
  });

};

/**
 * Find a collection's primary key attribute
 *
 * @param {String} collection
 * @return {Object}
 * @api private
 */

JoinTables.prototype.findPrimaryKey = function(collection) {

  var primaryKey = null;
  var attribute;
  var error;

  if(!this.collections[collection]) {
    throw new Error('Trying to access a collection ' + collection + ' that is not defined.');
  }

  if(!this.collections[collection].attributes) {
    throw new Error('Collection, ' + collection + ', has no attributes defined.');
  }

  for(var key in this.collections[collection].attributes) {
    attribute = this.collections[collection].attributes[key];

    if(!hop(attribute, 'primaryKey')) continue;

    primaryKey = {
      name: attribute.columnName || key,
      attributes: attribute
    };
  }

  if(!primaryKey) {
    error = 'Trying to create an association on a model that doesn\'t have a Primary Key.';
    throw new Error(error);
  }

  return primaryKey;

};

/**
 * Update Collection Attributes to point to the join table instead of the other collection
 *
 * @api private
 */

JoinTables.prototype.linkAttributes = function() {

  for(var collection in this.collections) {
    var attributes = this.collections[collection].attributes;
    this.updateAttribute(collection, attributes);
  }

};

/**
 * Update An Attribute
 *
 * @param {String} collection
 * @param {Object} attributes
 * @api private
 */

JoinTables.prototype.updateAttribute = function(collection, attributes) {

  for(var attribute in attributes) {
    if(!hop(attributes[attribute], 'collection')) continue;

    var attr = attributes[attribute];
    var parent = collection;
    var child = attr.collection;
    var via = attr.via;

    var joined = this.findJoinTable(parent, child, via);

    if(!joined.join) continue;

    // If the table doesn't know about the other side ignore updating anything
    if(!hop(joined.table.attributes, collection + '_' + attribute)) continue;

    this.collections[collection].attributes[attribute] = {
      collection: joined.table.identity,
      references: joined.table.identity,
      on: joined.table.attributes[collection + '_' + attribute].columnName,
      onKey: joined.table.attributes[collection + '_' + attribute].columnName
    };
  }

};

/**
 * Mark Custom Join Tables as a Junction Table
 *
 * If a collection has an attribute with a `through` property, lookup
 * the collection it points to and mark it as a `junctionTable`.
 *
 * @param {String} collection
 * @api private
 */

JoinTables.prototype.markCustomJoinTables = function(collection) {

  var attributes = this.collections[collection].attributes;

  for(var attribute in attributes) {
    if(!hop(attributes[attribute], 'through')) continue;

    var linkedCollection = attributes[attribute].through;
    this.collections[linkedCollection].junctionTable = true;

    // Build up proper reference on the attribute
    attributes[attribute].collection = linkedCollection;
    attributes[attribute].references = linkedCollection;

    // Find Reference Key
    var reference = this.findReference(collection, linkedCollection);
    attributes[attribute].on = reference;
    attributes[attribute].onKey = reference;

    delete attributes[attribute].through;
  }

};

/**
 * Find Reference attribute name in a set of attributes
 *
 * @param {String} parent
 * @param {String} collection
 * @return {String}
 * @api private
 */

JoinTables.prototype.findReference = function(parent, collection) {

  var attributes = this.collections[collection].attributes;
  var reference;

  for(var attribute in attributes) {
    if(!hop(attributes[attribute], 'foreignKey')) continue;
    if(!hop(attributes[attribute], 'references')) continue;
    if(attributes[attribute].references !== parent) continue;

    reference = attributes[attribute].columnName || attribute;
    break;
  }

  return reference;

};

/**
 * Search for a matching join table
 *
 * @param {String} parent
 * @param {String} child
 * @param {String} via
 * @return {Object}
 * @api private
 */

JoinTables.prototype.findJoinTable = function(parent, child, via) {

  var join = false;
  var tableCollection;

  for(var table in this.tables) {
    var tables = this.tables[table].tables;

    if(tables.indexOf(parent) < 0) continue;
    if(tables.indexOf(child) < 0) continue;

    var column = child + '_' + via;

    if(!hop(this.tables[table].attributes, column)) continue;

    join = true;
    tableCollection = this.tables[table];
    break;
  }

  return { join: join, table: tableCollection };

};


text:
<?php

namespace Tests\Unit\Commands;

use \Tests\Unit\TestCase;
use \Longman\TelegramBot\Telegram;

class CalcCommandTest extends TestCase
{
	/**
	* @var \Longman\TelegramBot\Telegram
	*/
	private $telegram;

	/**
	* @var int
	*/
	private $message_id = 1;

	/**
	* @var int
	*/
	private $chat_id = 2;

	/**
	* setUp
	*/
	protected function setUp()
	{
		$this->telegram = new Telegram('testapikey', 'testbotname');
		$msg = '\/calc 2+2';
		$update = '{"update_id":'.(int)microtime(true).',"message":{"message_id":'.$this->message_id.',"from":{"id":100000,"first_name":"Avtandil","last_name":"Kikabidze","username":"LONGMAN"},"chat":{"id":'.$this->chat_id.',"first_name":"Avtandil","last_name":"Kikabidze","username":"LONGMAN"},"date":1435507990,"text":"'.$msg.'"}}';
		$this->telegram->setCustomUpdate($update);
	}

    /**
     * @test
     */
    public function execute() {
		$result = $this->telegram->handle();
		$this->assertEquals('4', $result['text']);
		$this->assertEquals($this->message_id, $result['reply_to_message_id']);
		$this->assertEquals($this->chat_id, $result['chat_id']);
    }

}


text:
title: Drone Flip, Nailed It!
author: Greg
layout: post
permalink: /2013/10/drone-flip-nailed-it
comments: True
categories:
  - YouTube
tags:
  - YouTube
---

{% include youtube_player.html id='0ZRFk77_AqU' %}


text:
using System;

namespace Beyova
{
    /// <summary>
    /// Interface ITransactionRequest
    /// </summary>
    public interface ITransactionRequest
    {
        /// <summary>
        /// Gets or sets the related party identifier.
        /// </summary>
        /// <value>The related party identifier.</value>
        string RelatedPartyIdentifier { get; set; }

        /// <summary>
        /// Gets or sets the party transaction identifier.
        /// </summary>
        /// <value>The party transaction identifier.</value>
        string PartyTransactionIdentifier { get; set; }

        /// <summary>
        /// Gets or sets the currency.
        /// </summary>
        /// <value>The currency.</value>
        string Currency { get; set; }

        /// <summary>
        /// Gets or sets the amount.
        /// </summary>
        /// <value>The amount.</value>
        decimal? Amount { get; set; }

        /// <summary>
        /// Gets or sets the owner key.
        /// </summary>
        /// <value>
        /// The owner key.
        /// </value>
        Guid? OwnerKey { get; set; }
    }
}


text:
/**
 * Module : Kero yearmonth adapter
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-10 14:11:50
 */

import { YearMonth } from 'tinper-neoui/src/neoui-yearmonth';

var YearMonthAdapter = u.BaseAdapter.extend({
    init: function init() {
        var self = this;
        this.validType = 'yearmonth';
        this.format = this.getOption('format');
        this.comp = new YearMonth({
            el: this.element,
            showFix: this.options.showFix,
            format: this.format
        });

        this.comp.on('valueChange', function (event) {
            self.slice = true;
            self.dataModel.setValue(self.field, event.value);
            self.slice = false;
        });
    },
    modelValueChange: function modelValueChange(value) {
        if (this.slice) return;
        this.comp.setValue(value);
    },
    setEnable: function setEnable(enable) {}
});

if (u.compMgr) u.compMgr.addDataAdapter({
    adapter: YearMonthAdapter,
    name: 'u-yearmonth'
});

export { YearMonthAdapter };


text:
package cn.edu.pku.ss.jddatamining.servlet;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ReadData
 */
@WebServlet("/ReadData")
public class ReadData extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ReadData() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		String type = request.getParameter("type");
		Scanner file;
		String lines;
		int item_count = 0;

		try {
			if (type.equals("cpu_analysis_combo")) {
				file = new Scanner(
						new File(request.getRealPath("\\data\\statistics_base_CPU.txt")));
				ArrayList<String> cpu_type = new ArrayList();
				ArrayList<Integer> cpu_num = new ArrayList();
				ArrayList<Integer> sale_num = new ArrayList();
				ArrayList<Double> average_price = new ArrayList();
				while (file.hasNext()) {
					String[] line;
					lines = file.nextLine();
					line = lines.split(";");
					for (int i = 0; i < line.length; i++) {
						String[] words = line[i].split(",");
						item_count++;
						if(item_count==1)
							continue;//跳过第一行的汉字描述部分。
						cpu_type.add(words[0]);
						cpu_num.add(Integer.parseInt(words[1]));
						sale_num.add(Integer.parseInt(words[2]));
						average_price.add(Double.parseDouble(words[3]));
					}
				}
				request.setAttribute("cpu_type", cpu_type);
				request.setAttribute("cpu_num", cpu_num);
				request.setAttribute("sale_num", sale_num);
				request.setAttribute("average_price", average_price);
				request.getRequestDispatcher("cpu_analysis_combo.jsp").forward(
						request, response);
			}else if(type.equals("statistics_base_brand_combo")|| type.equals("sale_share")){//TXT换行有问题
				String path = request.getRealPath("\\data\\statistics_base_brand.txt");
				file = new Scanner(new File(path));
				ArrayList<String> brand_name = new ArrayList();
				ArrayList<Integer> sale_num = new ArrayList();
				ArrayList<Double> average_price = new ArrayList();
				ArrayList<Double> sale_share = new ArrayList();
				ArrayList<Double> comment_pencentage = new ArrayList();
				while (file.hasNext()) {
					String[] line;
					lines = file.nextLine();
					line = lines.split(";");
					for (int i = 0; i < line.length; i++) {
						String[] words = line[i].split(",");
						item_count++;
						if(item_count==1)
							continue;//跳过第一行的汉字描述部分。
						brand_name.add(words[0]);
						average_price.add(Double.parseDouble(words[2]));
						sale_num.add(Integer.parseInt(words[3]));
						sale_share.add(Double.parseDouble(words[4]));
						comment_pencentage.add(Double.parseDouble(words[5])*100);
					}
				}
				request.setAttribute("brand_name", brand_name);
				request.setAttribute("average_price", average_price);
				request.setAttribute("sale_share", sale_share);
				request.setAttribute("sale_num", sale_num);
				request.setAttribute("comment_pencentage", comment_pencentage);
				if (type.equals("statistics_base_brand_combo")){
					request.getRequestDispatcher("statistics_base_brand_combo.jsp").forward(
							request, response);
				}
				else{
					request.getRequestDispatcher("sale_share.jsp").forward(
							request, response);
				}

			}else if(type.equals("price_range")){
				String path = request.getRealPath("\\data\\statistics_base_price.txt");
				file = new Scanner(new File(path));
				ArrayList<String> range_name      = new ArrayList();
				ArrayList<Integer> range_sale_num = new ArrayList();
				String[][] brand_name      = new String[50][50];
				double[][] brand_share     = new double[50][50];
				int list_num =0;
				double brand_num=0;
				while (file.hasNext()) {
					String[] line;
					lines = file.nextLine();
					line = lines.split(";");
					for (int i = 0; i < line.length; i++) {
						String[] words = line[i].split(",");
						item_count++;
						if(item_count==1)
							continue;//跳过第一行的汉字描述部分。
						range_name.add(words[0]);
						range_sale_num.add(Integer.parseInt(words[1]));
						for(int j=2,count=0;j<words.length;j+=2,count++){
							brand_name[list_num][count]  = words[j];
							brand_share[list_num][count] = Double.parseDouble(words[j+1])*100;
							brand_num++;//品牌数,会重复行数的倍数
						}
						list_num++;//行数
					}
				}
				double temp = brand_num/list_num;
				int intt = (int)temp;
				request.setAttribute("brand_num", intt);
				request.setAttribute("list_num", list_num);
				request.setAttribute("range_name", range_name);
				request.setAttribute("range_sale_num", range_sale_num);
				request.setAttribute("brand_name", brand_name);
				request.setAttribute("brand_share", brand_share);
				request.getRequestDispatcher("price_range.jsp").forward(
						request, response);
			}else if(type.equals("size_analysis_combo")){
				String path = request.getRealPath("\\data\\statistics_base_size.txt");
				file = new Scanner(
						new File(path));
				ArrayList<String> size_name = new ArrayList();
				ArrayList<Integer> sale_num = new ArrayList();
				ArrayList<Integer> type_num = new ArrayList();
				ArrayList<Double> average_price = new ArrayList();

				while (file.hasNext()) {
					String[] line;
					lines = file.nextLine();
					line = lines.split(";");
					for (int i = 0; i < line.length; i++) {
						String[] words = line[i].split(",");
						item_count++;
						if(item_count==1)
							continue;//跳过第一行的汉字描述部分。
						size_name.add(words[0]);
						type_num.add(Integer.parseInt(words[1]));
						sale_num.add(Integer.parseInt(words[2]));
						average_price.add(Double.parseDouble(words[4]));
					}
				}
				request.setAttribute("size_name", size_name);
				request.setAttribute("type_num", type_num);
				request.setAttribute("sale_num", sale_num);
				request.setAttribute("average_price", average_price);
				request.getRequestDispatcher("size_analysis_combo.jsp").forward(
						request, response);
			}else if(type.equals("comment_analyse")){

				request.getRequestDispatcher("analysis_item_1.jsp").forward(
						request, response);
			}else{
					String error_contant="Your input type is not correct.";
					request.setAttribute("error_contant", error_contant);
					request.getRequestDispatcher("error.jsp").forward(
							request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			String error_contant="The format of the data may not correct, please check your input format again.";
			request.setAttribute("error_contant", error_contant);
			request.getRequestDispatcher("error.jsp").forward(
					request, response);
		}finally{

		}

	}

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using SLNetworkComm;
using libsecondlife;

namespace SLeek
{
    public class SleekInstance
    {
        private SecondLife client;
        private SLNetCom netcom;

        private ImageCache imageCache;
        private StateManager state;
        private ConfigManager config;

        private frmMain mainForm;
        private TabsConsole tabsConsole;

        private bool firstInstance;
        private bool otherInstancesOpen = false;

        public SleekInstance(bool firstInstance)
        {
            this.firstInstance = firstInstance;

            client = new SecondLife();
            client.Settings.ALWAYS_REQUEST_OBJECTS = true;
            client.Settings.ALWAYS_DECODE_OBJECTS = true;
            client.Settings.OBJECT_TRACKING = true;
            client.Settings.ENABLE_SIMSTATS = true;
            client.Settings.FETCH_MISSING_INVENTORY = true;
            client.Settings.MULTIPLE_SIMS = true;
            client.Settings.SEND_AGENT_THROTTLE = true;
            client.Settings.SEND_AGENT_UPDATES = true;

            netcom = new SLNetCom(client);

            imageCache = new ImageCache();
            state = new StateManager(this);
            InitializeConfig();

            mainForm = new frmMain(this);
            mainForm.InitializeControls();
            tabsConsole = mainForm.TabConsole;

            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        }

        private void Application_ApplicationExit(object sender, EventArgs e)
        {
            config.SaveCurrentConfig();
        }

        private void InitializeConfig()
        {
            config = new ConfigManager();
            config.ApplyDefault();

            netcom.LoginOptions.FirstName = config.CurrentConfig.FirstName;
            netcom.LoginOptions.LastName = config.CurrentConfig.LastName;
            netcom.LoginOptions.Password = config.CurrentConfig.PasswordMD5;
            netcom.LoginOptions.IsPasswordMD5 = true;
        }

        public SecondLife Client
        {
            get { return client; }
        }

        public SLNetCom Netcom
        {
            get { return netcom; }
        }

        public ImageCache ImageCache
        {
            get { return imageCache; }
        }

        public StateManager State
        {
            get { return state; }
        }

        public ConfigManager Config
        {
            get { return config; }
        }

        public frmMain MainForm
        {
            get { return mainForm; }
        }

        public TabsConsole TabConsole
        {
            get { return tabsConsole; }
        }

        public bool IsFirstInstance
        {
            get { return firstInstance; }
        }

        public bool OtherInstancesOpen
        {
            get { return otherInstancesOpen; }
            set { otherInstancesOpen = value; }
        }
    }
}


text: {% extends "base.html" %}{% block menu_players_active %}active{% endblock %}


text:
import bee
from bee.segments import *
import functools

class gentuple2(object):
    """
    Wraps a tuple or other iterable
    Provide an unresolved tuple
    """

    def __new__(cls, wrapped_tuple):
        class gentuple2(bee.worker):
            def set_parent(self, parent):
                self.parent = parent

            def resolve(self, wrapped):
                return bee.resolve(wrapped, parent=self.parent)

            v_wrapped = variable(("object", "iterable", "tuple"))
            startvalue(v_wrapped, wrapped_tuple)
            value = output("pull", ("object", "iterable", "tuple"))
            connect(v_wrapped, value)

            @modifier
            def m_value(self):
                self.v_wrapped = self.resolve(wrapped_tuple)

            pretrigger(v_wrapped, m_value)

            def get_value(self):
                return self.resolve(wrapped_tuple)

            @staticmethod
            def worker_length():
                class length(bee.worker):
                    v_length = variable("int")

                    @modifier
                    def m_length(self):
                        self.v_length = len(self.resolve(wrapped_tuple))

                    outp = output("pull", "int")
                    connect(v_length, outp)
                    pretrigger(v_length, m_length)

                return length()

            @staticmethod
            def worker_item(index):
                class item(bee.worker):
                    v_item = variable("object")

                    @modifier
                    def m_item(self):
                        self.v_item = self.resolve(wrapped_tuple)[index]

                    outp = output("pull", "object")
                    connect(v_item, outp)
                    pretrigger(v_item, m_item)

                return item()

            @staticmethod
            def worker_getitem():
                class getitem(bee.worker):
                    inp = antenna("pull", "int")
                    b_inp = buffer("pull", "int")
                    trig_inp = triggerfunc(b_inp, "update")
                    connect(inp, b_inp)
                    outp = output("pull", "object")
                    v_outp = variable("object")
                    connect(v_outp, outp)

                    @modifier
                    def m_getitem(self):
                        self.trig_inp()
                        index = self.b_inp
                        item = self.resolve(wrapped_tuple)[index]
                        self.v_outp = item

                    pretrigger(v_outp, m_getitem)

                return getitem()

            @staticmethod
            def worker_slice(start, end):
                class slice(bee.worker):
                    v_slice = variable(("object", "iterable", "tuple"))

                    @modifier
                    def m_slice(self):
                        self.v_slice = self.resolve(wrapped_tuple)[start:end]

                    outp = output("pull", ("object", "iterable", "tuple"))
                    connect(v_slice, outp)
                    pretrigger(v_slice, m_slice)

                return slice()

            @staticmethod
            def worker_getslice():
                class getslice(bee.worker):
                    inp = antenna("pull", ("int", "int"))
                    b_inp = buffer("pull", ("int", "int"))
                    trig_inp = triggerfunc(b_inp, "update")
                    connect(inp, b_inp)
                    outp = output("pull", ("object", "iterable", "tuple"))
                    v_outp = variable(("object", "iterable", "tuple"))
                    connect(v_outp, outp)

                    @modifier
                    def m_getslice(self):
                        self.trig_inp()
                        start, end = self.b_inp
                        slice = self.resolve(wrapped_tuple)[start:end]
                        self.v_outp = slice

                    pretrigger(v_outp, m_getslice)

                return getslice()

        return gentuple2()


text:
The DFC API is a Restful API which has been built to facilitate the ability to Setup/Ammend/Cancel & View Direct Debits with Debit Finance Collections Plc

### Install with Composer
To utilize DFCAPI-Python, install it using pip:

`pip install dfcapi`

After installing the pip package, you can now begin simplifying requests by importing unirest:

`import dfcapi`

## Checking API Credentials

```python
response = dfcapi.checkApiKey('TEST-TEST-TEST-TEST','fee78bd3bf59bfb36238b3f67de0a6ea103de130')
```

<hr>
### Thanks
Thanks go out to:
* [thefosk](https://github.com/thefosk) @ [mashape.com](https://mashape.com) - Unirest Restful Library


text:
layout: page
title: About me
---

I am an open source enthusiast with experience in Web and Android development, CAS and system administration. I love golang and docker.

- Google Summer of Code Intern at PyDy
- Building heroku like PaaS for Institute's Data Center.
- Active developer of Sympy and related projects.
- Secured second place in Angelhack Delhi for Bluemix prize, fifth overall.
- Won IEF Appathon organised at IIT Delhi.
- Developed a community driven app to create and share local interests.
- Was part of an awesome startup, Backpack.

You can see me [resume]({{ site.baseurl }}assets/resume.pdf) or visit my [LinkedIn profile](https://www.linkedin.com/in/sahilshekhawat)


text:
package com.mayloom.vouchserv.dto;

import com.mayloom.vouchserv.man.api.dto.Voucher;

public class ContentEnricherVoucher extends Voucher {

	private int batchNumber;

	/**
	 * @return the batchNumber
	 */
	public int getBatchNumber() {
		return batchNumber;
	}

	/**
	 * @param batchNumber the batchNumber to set
	 */
	public void setBatchNumber(int batchNumber) {
		this.batchNumber = batchNumber;
	}

}


text:
  <sect1>
    <title>Pooling example</title>
    <para>
    The idea is to build an executor backed by a pool of
    <literal>QueuedExecutor</literal>: this will show how Spring.NET
    provides some useful low-level/high-quality reusable threading and
    pooling abstractions.
    This executor will provide parallel executions (in our case
    <literal>grep</literal>-like file scans).  <emphasis>Note: This example
    is not in the 1.0.0 release to its use of classes in the Spring.Threading
    namespace scheduled for release in Spring 1.1. To access ths example
    please get the code from CVS <ulink url="http://opensource.atlassian.com/confluence/spring/display/NET/Project+Structure">(instructions)</ulink> or from the download section of the
    Spring.NET website that contains an .zip with the full CVS tree.</emphasis>
    </para>
    <para>
    Some information on <literal>QueuedExecutor</literal> is helpful to
    better understand the implementation and to possibly disagree with it.
    Keep in mind that the point is to show how to develop your own
    object-pool.
    </para>
    <para>
    A <literal>QueuedExecutor</literal> is an executor where
    <literal>IRunnable</literal> instances are run serialy by a worker
    thread. When you <literal>Execute</literal> with a
    <literal>QueuedExecutor</literal>, your request is queued; at some
    point in the future your request will be taken and executed by the
    worker thread: in case of error the thread is terminated.
    However
    this executor recreates its worker thread as needed.
    </para>
    <para>Last but not least, this executor can be shut down in
    a few different ways (please refer to the Spring.NET SDK documentation).
    Given its simplicity, it is very powerful.
    </para>
    <para>
    The example project <literal>Spring.Examples.Pool</literal> provides
    an implementation of a pooled executor, backed by n instances of
    <literal>Spring.Threading.QueuedExecutor</literal>: please ignore
    the fact that <literal>Spring.Threading</literal> includes already a
    very different implementation of a <literal>PooledExecutor</literal>:
    here we wanto to use a pool of <literal>QueuedExecutor</literal>s.
    </para>
    <para>
    This executor will be used to implement a parallel
    recursive <literal>grep</literal>-like console executable.
    </para>
    <sect2>
    <title>Implementing <literal>Spring.Pool.IPoolableObjectFactory</literal></title>
    <para>
    In order to use the <literal>SimplePool</literal> implementation,
    the first thing to do is to implement the <literal>IPoolableObjectFactory</literal>
    interface. This interface is intended to be implemented by objects
    that can create the type of objects that should be pooled.
    The <literal>SimplePool</literal>
    will call the lifecycle methods on <literal>IPoolableObjectFactory</literal> interface
    (<literal>MakeObject, ActivateObject, ValidateObject, PassivateObject, and DestroyObject</literal>)
    as appropriate when the pool is created, objects are borrowed and returned to the pool, and when
    the pool is destroyed.
    </para>
    <para>
    In our case, as already said, we want to to implement a pool
    of <literal>QueuedExecutor</literal>. Ok, here the declaration:
    <programlisting language="csharp">public class QueuedExecutorPoolableFactory : IPoolableObjectFactory
{</programlisting>
    the first task a factory should do is to create objects:
    <programlisting language="csharp">object IPoolableObjectFactory.MakeObject()
{
    // to actually make this work as a pooled executor
    // use a bounded queue of capacity 1.
    // If we don't do this one of the queued executors
    // will accept all the queued IRunnables as, by default
    // its queue is unbounded, and the PooledExecutor
    // will happen to always run only one thread ...
    return new QueuedExecutor(new BoundedBuffer(1));
}</programlisting>
    and should be also able to destroy them:
    <programlisting language="csharp">void IPoolableObjectFactory.DestroyObject(object o)
{
    // ah, self documenting code:
    // Here you can see that we decided to let the
    // executor process all the currently queued tasks.
    QueuedExecutor executor = o as QueuedExecutor;
    executor.ShutdownAfterProcessingCurrentlyQueuedTasks();
}</programlisting>
    </para>
    <para>
    When an object is taken from the pool, to satisfy a client request,
    may be the object should be activated. We can possibly implement the
    activation like this:
    <programlisting language="csharp">void IPoolableObjectFactory.ActivateObject(object o)
{
    QueuedExecutor executor = o as QueuedExecutor;
    executor.Restart();
}</programlisting>
    even if a <literal>QueuedExecutor</literal> restarts itself as
    needed and so a valid implementation could leave this method empty.
    </para>
    <para>
    After activation, and before the pooled object can be succesfully
    returned to the client, it is validated (should the object be
    invalid, it will be discarded: this can lead to an empty unusable
    pool
    <footnote>
    <para>You may think that we can provide a smarter
    implementation and you are probably right. However, it is not so
    difficult to create a new pool in case the old one became unusable.
    It could not be your preferred choice but surely it leverages
    simplicity and object immutability
    </para>
    </footnote>).
    Here we check that the worker thread exists:
    <programlisting language="csharp">bool IPoolableObjectFactory.ValidateObject(object o)
{
    QueuedExecutor executor = o as QueuedExecutor;
    return executor.Thread != null;
}</programlisting>
    </para>
    <para>
    Passivation, symmetrical to activation, is the process a pooled
    object is subject to when the object is returned to the pool. In our
    case we simply do nothing:
    <programlisting language="csharp">void IPoolableObjectFactory.PassivateObject(object o)
{
}</programlisting>
    </para>
    <para>
    At this point, creating a pool is simply a matter of creating an
    <literal>SimplePool</literal> as in:
    <programlisting language="csharp">pool = new SimplePool(new QueuedExecutorPoolableFactory(), size);</programlisting>
    </para>
    </sect2>
    <sect2>
    <title>Being smart using pooled objects</title>
    <para>
    Taking advantage of the <literal>using</literal> keyword seems
    to be very important in these <literal>c#</literal> days, so we
    implement a very simple helper (<literal>PooledObjectHolder</literal>)
    that can allow us to do things like:
    <programlisting language="csharp">using (PooledObjectHolder holder = PooledObjectHolder.UseFrom(pool))
{
    QueuedExecutor executor = (QueuedExecutor) holder.Pooled;
    executor.Execute(runnable);
}</programlisting>
    without worrying about obtaining and returning an object from/to the
    pool.
    </para>
    <para>
    Here is the implementation:
    <programlisting language="csharp">public class PooledObjectHolder : IDisposable
{
    IObjectPool pool;
    object pooled;

    /// <summary>
    /// Builds a new <see cref="PooledObjectHolder"/>
    /// trying to borrow an object form it
    /// </summary>
    /// <param name="pool"></param>
    private PooledObjectHolder(IObjectPool pool)
    {
        this.pool = pool;
        this.pooled = pool.BorrowObject();
    }

    /// <summary>
    /// Allow to access the borrowed pooled object
    /// </summary>
    public object Pooled
    {
        get
        {
            return pooled;
        }
    }

    /// <summary>
    /// Returns the borrowed object to the pool
    /// </summary>
    public void Dispose()
    {
        pool.ReturnObject(pooled);
    }

    /// <summary>
    /// Creates a new <see cref="PooledObjectHolder"/> for the
    /// given pool.
    /// </summary>
    public static PooledObjectHolder UseFrom(IObjectPool pool)
    {
        return new PooledObjectHolder(pool);
    }
}</programlisting>
    </para>
    <para>
    Please don't forget to destroy all the pooled istances once you have
    finished! How? Well using something like this in
    <literal>PooledQueuedExecutor</literal>:
    <programlisting language="csharp">public void Stop ()
{
    // waits for all the grep-task to have been queued ...
    foreach (ISync sync in syncs)
    {
        sync.Acquire();
    }
    pool.Close();
}</programlisting>
    </para>
    </sect2>
    <sect2>
    <title>Using the executor to do a parallel <literal>grep</literal></title>
    <para>
    The use of the just built executor is quite straigtforward but a
    little tricky if we want to really exploit the pool.
    <programlisting language="csharp">private PooledQueuedExecutor executor;

public ParallelGrep(int size)
{
    executor = new PooledQueuedExecutor(size);
}

public void Recurse(string startPath, string filePattern, string regexPattern)
{
    foreach (string file in Directory.GetFiles(startPath, filePattern))
    {
        executor.Execute(new Grep(file, regexPattern));
    }
    foreach (string directory in Directory.GetDirectories(startPath))
    {
        Recurse(directory, filePattern, regexPattern);
    }
}

public void Stop()
{
    executor.Stop();
}</programlisting>
    </para>
    <para>
      <programlisting language="csharp">public static void Main(string[] args)
{
    if (args.Length < 3)
    {
        Console.Out.WriteLine("usage: {0} regex directory file-pattern [pool-size]", Assembly.GetEntryAssembly().CodeBase);
        Environment.Exit(1);
    }

    string regexPattern = args[0];
    string startPath = args[1];
    string filePattern = args[2];
    int size = 10;
    try
    {
        size = Int32.Parse(args[3]);
    }
    catch
    {
    }
    Console.Out.WriteLine ("pool size {0}", size);

    ParallelGrep grep = new ParallelGrep(size);
    grep.Recurse(startPath, filePattern, regexPattern);
    grep.Stop();
}</programlisting>
    </para>
    </sect2>
  </sect1>


text:
<?php
/**
 * CampaignTest
 *
 * PHP version 5
 *
 * @category Class
 * @package  Dcm
 * @author   http://github.com/swagger-api/swagger-codegen
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * Dolead Campaign Manager API v1.0
 *
 * No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: 1.0
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * 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.
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Please update the test case below to test the model.
 */

namespace Dcm;

/**
 * CampaignTest Class Doc Comment
 *
 * @category    Class */
// * @description Campaign
/**
 * @package     Dcm
 * @author      http://github.com/swagger-api/swagger-codegen
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class CampaignTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Setup before running any test case
     */
    public static function setUpBeforeClass()
    {

    }

    /**
     * Setup before running each test case
     */
    public function setUp()
    {

    }

    /**
     * Clean up after running each test case
     */
    public function tearDown()
    {

    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass()
    {

    }

    /**
     * Test "Campaign"
     */
    public function testCampaign()
    {

    }

    /**
     * Test attribute "account"
     */
    public function testPropertyAccount()
    {

    }

    /**
     * Test attribute "advertiser"
     */
    public function testPropertyAdvertiser()
    {

    }

    /**
     * Test attribute "base_campaign"
     */
    public function testPropertyBaseCampaign()
    {

    }

    /**
     * Test attribute "budget"
     */
    public function testPropertyBudget()
    {

    }

    /**
     * Test attribute "campaign_goal"
     */
    public function testPropertyCampaignGoal()
    {

    }

    /**
     * Test attribute "campaign_goal_value"
     */
    public function testPropertyCampaignGoalValue()
    {

    }

    /**
     * Test attribute "campaign_type"
     */
    public function testPropertyCampaignType()
    {

    }

    /**
     * Test attribute "id"
     */
    public function testPropertyId()
    {

    }

    /**
     * Test attribute "lead_customer_id"
     */
    public function testPropertyLeadCustomerId()
    {

    }

    /**
     * Test attribute "lead_form_ids"
     */
    public function testPropertyLeadFormIds()
    {

    }

    /**
     * Test attribute "name"
     */
    public function testPropertyName()
    {

    }

    /**
     * Test attribute "negative_geo_criterions"
     */
    public function testPropertyNegativeGeoCriterions()
    {

    }

    /**
     * Test attribute "positive_geo_criterions"
     */
    public function testPropertyPositiveGeoCriterions()
    {

    }

    /**
     * Test attribute "publisher_id"
     */
    public function testPropertyPublisherId()
    {

    }

    /**
     * Test attribute "status"
     */
    public function testPropertyStatus()
    {

    }

}


text:
/*
 *Ваши права на использование кода регулируются данной лицензией http://o-s-a.net/doc/license_simple_engine.pdf
*/

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using OsEngine.Entity;

namespace OsEngine.Charts.CandleChart.Indicators
{
    /// <summary>
    /// Индикатор VHF
    /// </summary>
    public class VerticalHorizontalFilter : IIndicatorCandle
    {
        /// <summary>
        /// период N
        /// </summary>
        public int Nperiod;

        /// <summary>
        /// для хранения разницы между максимальной и минимальной цены
        /// </summary>
        private List<decimal> _highlow;

        /// <summary>
        /// конструктор с параметрами. Индикатор будет сохраняться
        /// </summary>
        /// <param name="uniqName">уникальное имя</param>
        /// <param name="canDelete">можно ли пользователю удалить индикатор с графика вручную</param>
        public VerticalHorizontalFilter(string uniqName, bool canDelete)
        {
            Name = uniqName;
            TypeIndicator = IndicatorOneCandleChartType.Line;
            Nperiod = 28;
            ColorBase = Color.DodgerBlue;
            PaintOn = true;
            CanDelete = canDelete;
            Load();
        }

        /// <summary>
        /// конструктор без параметров. Индикатор не будет сохраняться
        /// используется ТОЛЬКО для создания составных индикаторов
        /// не используйте его из слоя создания роботов!
        /// </summary>
        /// <param name="canDelete">можно ли пользователю удалить индикатор с графика вручную</param>
        public VerticalHorizontalFilter(bool canDelete)
        {
            Name = Guid.NewGuid().ToString();

            TypeIndicator = IndicatorOneCandleChartType.Line;
            Nperiod = 28;
            ColorBase = Color.DodgerBlue;
            PaintOn = true;
            CanDelete = canDelete;

        }

        /// <summary>
        /// все значения индикатора
        /// </summary>
        List<List<decimal>> IIndicatorCandle.ValuesToChart
        {
            get
            {
                List<List<decimal>> list = new List<List<decimal>>();
                list.Add(Values);
                return list;
            }
        }

        /// <summary>
        /// цвета для индикатора
        /// </summary>
        List<Color> IIndicatorCandle.Colors
        {
            get
            {
                List<Color> colors = new List<Color>();
                colors.Add(ColorBase);
                return colors;
            }

        }

        /// <summary>
        /// можно ли удалить индикатор с графика. Это нужно для того чтобы у роботов нельзя было удалить
        /// индикаторы которые ему нужны в торговле
        /// </summary>
        public bool CanDelete { get; set; }

        /// <summary>
        /// тип прорисовки индикатора
        /// </summary>
        public IndicatorOneCandleChartType TypeIndicator { get; set; }

        /// <summary>
        /// имя серии данных на которой будет прорисован индикатор
        /// </summary>
        public string NameSeries { get; set; }

        /// <summary>
        /// имя области данных на которой будет прорисовываться индикатор
        /// </summary>
        public string NameArea { get; set; }

        /// <summary>
        /// индикатор
        /// </summary>
        public List<decimal> Values
        { get; set; }

        /// <summary>
        /// уникальное имя индикатора
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// цвет центрально серии данных
        /// </summary>
        public Color ColorBase { get; set; }

        /// <summary>
        /// включена ли прорисовка индикатора
        /// </summary>
        public bool PaintOn { get; set; }

        /// <summary>
        /// сохранить настройки в файл
        /// </summary>
        public void Save()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Name))
                {
                    return;
                }

                using (StreamWriter writer = new StreamWriter(@"Engine\" + Name + @".txt", false))
                {
                    writer.WriteLine(Nperiod);
                    writer.WriteLine(ColorBase.ToArgb());
                    writer.WriteLine(PaintOn);
                    writer.Close();
                }
            }
            catch (Exception)
            {
                // отправить в лог
            }
        }

        /// <summary>
        /// загрузить настройки из файла
        /// </summary>
        public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    Nperiod = Convert.ToInt32(reader.ReadLine());
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.ReadLine();

                    reader.Close();
                }

            }
            catch (Exception)
            {
                // отправить в лог
            }
        }

        /// <summary>
        /// удалить файл с настройками
        /// </summary>
        public void Delete()
        {
            if (File.Exists(@"Engine\" + Name + @".txt"))
            {
                File.Delete(@"Engine\" + Name + @".txt");
            }
        }

        /// <summary>
        /// удалить данные
        /// </summary>
        public void Clear()
        {
            if (Values != null)
            {
                Values.Clear();
            }
            _myCandles = null;
        }

        /// <summary>
        /// показать окно с настройками
        /// </summary>
        public void ShowDialog()
        {
            VerticalHorizontalFilterUi ui = new VerticalHorizontalFilterUi(this);
            ui.ShowDialog();

            if (ui.IsChange && _myCandles != null)
            {
                Reload();
            }
        }

        /// <summary>
        /// перезагрузить индикатор
        /// </summary>
        public void Reload()
        {
            if (_myCandles == null)
            {
                return;
            }
            ProcessAll(_myCandles);

            if (NeadToReloadEvent != null)
            {
                NeadToReloadEvent(this);
            }
        }

        /// <summary>
        /// свечи для рассчёта индикатора
        /// </summary>
        private List<Candle> _myCandles;

        /// <summary>
        /// рассчитать индикатор
        /// </summary>
        /// <param name="candles">свечи</param>
        public void Process(List<Candle> candles)
        {
            _myCandles = candles;

            if (_highlow == null)
            {
                _highlow = new List<decimal>();

            }

            if (Values != null &&
                Values.Count + 1 == candles.Count)
            {
                ProcessOne(candles);
            }
            else if (Values != null &&
                     Values.Count == candles.Count)
            {
                ProcessLast(candles);
            }
            else
            {
                ProcessAll(candles);
            }
        }

        /// <summary>
        /// индикатор нужно перерисовать
        /// </summary>
        public event Action<IIndicatorCandle> NeadToReloadEvent;

        /// <summary>
        /// прогрузить только последнюю свечку
        /// </summary>
        private void ProcessOne(List<Candle> candles)
        {
            if (candles == null)
            {
                return;
            }

            _highlow.Add(GetHighLow(candles, candles.Count - 1));

            if (Values == null)
            {
                Values = new List<decimal>();
                Values.Add(GetValue(candles, candles.Count - 1));
            }
            else
            {
                Values.Add(GetValue(candles, candles.Count - 1));
            }
        }

        /// <summary>
        /// прогрузить с самого начала
        /// </summary>
        private void ProcessAll(List<Candle> candles)
        {
            if (candles == null)
            {
                return;
            }
            Values = new List<decimal>();

            _highlow = new List<decimal>();

            for (int i = 0; i < candles.Count; i++)
            {
                _highlow.Add(GetHighLow(candles, i));
                Values.Add(GetValue(candles, i));
            }
        }

        /// <summary>
        /// перегрузить последнее значение
        /// </summary>
        private void ProcessLast(List<Candle> candles)
        {
            if (candles == null)
            {
                return;
            }

            _highlow[_highlow.Count - 1] = GetHighLow(candles, candles.Count - 1);
            Values[Values.Count - 1] = GetValue(candles, candles.Count - 1);
        }

        /// <summary>
        /// взять значение индикатора по индексу
        /// </summary>
        /// <param name="candles">свечи</param>
        /// <param name="index">индекс</param>
        /// <returns>значение индикатора по индексу</returns>
        private decimal GetValue(List<Candle> candles, int index)
        {

            if (index < Nperiod)
            {
                return 0;
            }
            decimal value;
            decimal sum = 0;

            for (int i = index - Nperiod + 1; i < index+1; i++)
            {
                sum = sum + Math.Abs(candles[i].Close - candles[i - 1].Close);
            }

            if (sum == 0)
            {
                return 0;
            }
            else
            {
                value = _highlow[index] / sum;
            }

            return Math.Round(value,2);
        }

        private decimal GetHighLow(List<Candle> candles, int index)
        {
            if (index < Nperiod)
            {
                return 0;
            }

            decimal maxhigh = 0;
            decimal maxlow = decimal.MaxValue;

            for (int i = index - Nperiod+1; i < index+1; i++)
            {

                if (maxhigh < candles[i].Close)
                {
                    maxhigh = candles[i].Close;
                }

                if (maxlow > candles[i].Close)
                {
                    maxlow = candles[i].Close;
                }
            }
            return (maxhigh - maxlow);
        }

    }
}


text:
Provides a global (brrr) `#content_for` for Cells.

# Installation

	gem 'cells-capture', require: 'cells_capture'

# Usage

Include the module in all your cell classes that require a global (brrr) `#content_for`.

	class BassistCell < Cell::Rails
	  include Cell::Rails::Capture

	  def show
	    render
	  end
	end

In your cell view you use `#content_for`.

	%div
	  - content_for :javascripts
	    $('#pick').append("Yo!")

The captured content is now available globally (brrr) in your controller views or your layouts.

# Limitations

I want to note that I am not a big fan of breaking cells' encapsulation by emitting content into a global variable. However, as many people asked for it I provide this feature to improve the world's happiness factor.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="distributionType" value="DEFAULT_WRAPPED" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleHome" value="/opt/gradle-latest" />
        <option name="gradleJvm" value="#JAVA_HOME" />
        <option name="modules">
          <set>
            <option value="$PROJECT_DIR$" />
            <option value="$PROJECT_DIR$/subproject1" />
          </set>
        </option>
      </GradleProjectSettings>
    </option>
  </component>
</project>


text:
package com.zkhy.presentation.score.form;

public class ScoreDetail {

	/**
	 * 成绩id
	 */
	private int scoreId;

	/**
	 * 试题类型id
	 */
	private int questionTypeId;

	/**
	 * 分数
	 */
	private int points;

	/**
	 * @return the scoreId
	 */
	public int getScoreId() {
		return scoreId;
	}

	/**
	 * @param scoreId the scoreId to set
	 */
	public void setScoreId(int scoreId) {
		this.scoreId = scoreId;
	}

	/**
	 * @return the questionTypeId
	 */
	public int getQuestionTypeId() {
		return questionTypeId;
	}

	/**
	 * @param questionTypeId the questionTypeId to set
	 */
	public void setQuestionTypeId(int questionTypeId) {
		this.questionTypeId = questionTypeId;
	}

	/**
	 * @return the points
	 */
	public int getPoints() {
		return points;
	}

	/**
	 * @param points the points to set
	 */
	public void setPoints(int points) {
		this.points = points;
	}

}


text:
from functools import partial
from kaio import Options

opts = Options()
get = partial(opts.get, section='Database')

class DatabasesMixin(object):

    @staticmethod
    def get_engine(prefix):
        """
        Retrieve the database engine.
        Only change the full engine string if there is no «backends» in it.
        """
        engine = get('{}DATABASE_ENGINE'.format(prefix), 'sqlite3')
        if 'backends' in engine:
            return engine
        return 'django.db.backends.' + engine

    def get_databases(self, prefix=''):
        databases = {
            'default': {
                'ENGINE': self.get_engine(prefix),
                'NAME': get('{}DATABASE_NAME'.format(prefix), '{}db.sqlite'.format(prefix.lower())),
                'USER': get('{}DATABASE_USER'.format(prefix), None),
                'PASSWORD': get('{}DATABASE_PASSWORD'.format(prefix), ''),
                'HOST': get('{}DATABASE_HOST'.format(prefix), ''),
                'PORT': get('{}DATABASE_PORT'.format(prefix), ''),
                'CONN_MAX_AGE': get('{}DATABASE_CONN_MAX_AGE'.format(prefix), 0),
                'TEST': {
                    'NAME': get('{}DATABASE_NAME'.format(prefix), None),
                }
            }
        }

        options = get('DATABASE_OPTIONS_OPTIONS')
        if options:
            databases['default']['OPTIONS'] = {'options': options}

        return databases

    def DATABASES(self):
        return self.get_databases()


text:
package main

import (
	"os/user"
	"testing"

	. "gopkg.in/check.v1"
)

type TestSuite struct{}

var _ = Suite(&TestSuite{})

func Test(t *testing.T) { TestingT(t) }

func (t *TestSuite) TestbinArgs_parse(c *C) {
	const arg0 = "/usr/local/bin/chef-search-stresser"

	var output string
	var err error

	//
	// test that the short-flags work
	//
	args := &binArgs{}
	cli := []string{
		arg0,
		"-q", "role:*",
		"-q", "thing:*",
		"-c", "42",
		"-p",
		"-k", "/tmp/file",
		"-S", "http://localhost:4000/",
		"-N", "fauxhai",
		"-E",
	}

	output, err = args.parse(cli)
	c.Assert(err, IsNil)
	c.Check(output, Equals, "")
	c.Assert(len(args.Queries), Equals, 2)
	c.Check(args.Queries[0], Equals, "role:*")
	c.Check(args.Queries[1], Equals, "thing:*")
	c.Check(args.Concurrency, Equals, uint(42))
	c.Check(args.Partial, Equals, true)
	c.Check(args.Full, Equals, false)
	c.Check(args.PemFile, Equals, "/tmp/file")
	c.Check(args.ChefServer, Equals, "http://localhost:4000/")
	c.Check(args.ClientName, Equals, "fauxhai")
	c.Check(args.PrintErr, Equals, true)
	c.Check(args.DisableSeed, Equals, false)

	args = &binArgs{}
	cli = []string{
		arg0,
		"-q", "role:*",
		"-q", "thing:*",
		"-c", "42",
		"-f",
		"-k", "/tmp/file",
		"-S", "http://localhost:4000/",
		"-N", "fauxhai",
		"-E",
	}

	output, err = args.parse(cli)
	c.Assert(err, IsNil)
	c.Check(output, Equals, "")
	c.Assert(len(args.Queries), Equals, 2)
	c.Check(args.Queries[0], Equals, "role:*")
	c.Check(args.Queries[1], Equals, "thing:*")
	c.Check(args.Concurrency, Equals, uint(42))
	c.Check(args.Partial, Equals, false)
	c.Check(args.Full, Equals, true)
	c.Check(args.PemFile, Equals, "/tmp/file")
	c.Check(args.ChefServer, Equals, "http://localhost:4000/")
	c.Check(args.ClientName, Equals, "fauxhai")
	c.Check(args.PrintErr, Equals, true)
	c.Check(args.DisableSeed, Equals, false)

	//
	// test that long flags work
	//
	args = &binArgs{}
	cli = []string{
		arg0,
		"--query", "role:*",
		"--query", "thing:*",
		"--concurrency", "42",
		"--partial",
		"--client-key", "/tmp/file",
		"--server", "http://localhost:4000/",
		"--name", "fauxhai",
		"--print-errors",
		"--disable-seed",
	}

	output, err = args.parse(cli)
	c.Assert(err, IsNil)
	c.Check(output, Equals, "")
	c.Assert(len(args.Queries), Equals, 2)
	c.Check(args.Queries[0], Equals, "role:*")
	c.Check(args.Queries[1], Equals, "thing:*")
	c.Check(args.Concurrency, Equals, uint(42))
	c.Check(args.Partial, Equals, true)
	c.Check(args.Full, Equals, false)
	c.Check(args.PemFile, Equals, "/tmp/file")
	c.Check(args.ChefServer, Equals, "http://localhost:4000/")
	c.Check(args.ClientName, Equals, "fauxhai")
	c.Check(args.PrintErr, Equals, true)
	c.Check(args.DisableSeed, Equals, true)

	args = &binArgs{}
	cli = []string{
		arg0,
		"--query", "role:*",
		"--query", "thing:*",
		"--concurrency", "42",
		"--full",
		"--client-key", "/tmp/file",
		"--server", "http://localhost:4000/",
		"--name", "fauxhai",
		"--print-errors",
		"--disable-seed",
	}

	output, err = args.parse(cli)
	c.Assert(err, IsNil)
	c.Check(output, Equals, "")
	c.Assert(len(args.Queries), Equals, 2)
	c.Check(args.Queries[0], Equals, "role:*")
	c.Check(args.Queries[1], Equals, "thing:*")
	c.Check(args.Concurrency, Equals, uint(42))
	c.Check(args.Partial, Equals, false)
	c.Check(args.Full, Equals, true)
	c.Check(args.PemFile, Equals, "/tmp/file")
	c.Check(args.ChefServer, Equals, "http://localhost:4000/")
	c.Check(args.ClientName, Equals, "fauxhai")
	c.Check(args.PrintErr, Equals, true)
	c.Check(args.DisableSeed, Equals, true)

	//
	// test that the Queries field is automatically populated
	//
	args = &binArgs{}
	cli = []string{
		arg0,
		"--full",
	}

	output, err = args.parse(cli)
	c.Assert(err, IsNil)
	c.Assert(len(args.Queries), Equals, 2)
	c.Check(args.Queries[0], Equals, "roles:*")
	c.Check(args.Queries[1], Equals, "name:*")

	//
	// test that the ClientName field is automatically populated
	//
	args = &binArgs{}
	cli = []string{
		arg0,
		"--full",
	}

	output, err = args.parse(cli)
	c.Assert(err, IsNil)

	curUser, err := user.Current()
	c.Assert(err, IsNil)
	c.Check(args.ClientName, Equals, curUser.Username)

	//
	// test that setting both --full and --partiail causes an error
	//
	args = &binArgs{}
	cli = []string{
		arg0,
		"--full",
		"--partial",
	}

	output, err = args.parse(cli)
	c.Assert(err, Not(IsNil))
	c.Check(err.Error(), Equals, "unable to run both full and partial search tests at the same time")

	//
	// test that setting neither --full and --partiai causes an error
	//
	args = &binArgs{}
	cli = []string{arg0}

	output, err = args.parse(cli)
	c.Assert(err, Not(IsNil))
	c.Check(err.Error(), Equals, "need to choose one mode of operation: --partial or --full; see --help for more details")
}


text:
import { types as t } from "@babel/core";
import buildOptimizedSequenceExpression from "./buildOptimizedSequenceExpression";

const minimalVisitor = {
  BinaryExpression(path) {
    const { scope, node } = path;
    const { operator, left, right } = node;
    if (operator !== "|>") return;

    const placeholder = scope.generateUidIdentifierBasedOnNode(left);

    const call = t.callExpression(right, [t.cloneNode(placeholder)]);
    path.replaceWith(
      buildOptimizedSequenceExpression({
        placeholder,
        call,
        path,
      }),
    );
  },
};

export default minimalVisitor;


text:
<?php

namespace Esendex\Parser;

use Esendex\Model\Message;
use Esendex\Model\SentMessage;
use Esendex\Model\InboxMessage;

class MessageHeaderXmlParser
{
    public function parse($xml)
    {
        $header = simplexml_load_string($xml);
        return $this->parseHeader($header);
    }

    public function parseHeader($header)
    {
        $direction = $header->direction;
        $result = ($direction == Message::Inbound)
            ? new InboxMessage()
            : new SentMessage();

        $result->id($header["id"]);
        $result->originator($header->from->phonenumber);
        $result->recipient($header->to->phonenumber);
        $result->status($header->status);
        $result->type($header->type);
        $result->direction($direction);
        $result->parts($header->parts);
        $result->bodyUri($header->body["uri"]);
        $result->summary($header->summary);
        $result->lastStatusAt($this->parseDateTime($header->laststatusat));
        if ($direction == Message::Outbound) {
            $result->submittedAt($this->parseDateTime($header->submittedat));
            $result->sentAt($this->parseDateTime($header->sentat));
            $result->deliveredAt($this->parseDateTime($header->deliveredat));
            $result->username($header->username);
        } else {
            $result->receivedAt($this->parseDateTime($header->receivedat));
            $readAt = $header->readat;
            if (substr($readAt, 0, 2) != "00") {
                $result->readAt($this->parseDateTime($readAt));
                $result->readBy($header->readby);
            }
        }

        return $result;
    }

    private function parseDateTime($value)
    {
        $value = (strlen($value) > 20)
            ? substr($value, 0, 19) . "Z"
            : $value;

        return \DateTime::createFromFormat(\DateTime::ISO8601, $value);
    }
}