text:
using System;
using System.Collections.Generic;       // List<T>
using System.Collections.ObjectModel;   // ReadOnlyCollection<T>
using System.Windows;                   // UIElement
using System.Windows.Media;             // Visual

namespace MS.Internal.Documents
{
    /// <summary>
    /// UIElement layout island.
    /// </summary>
    internal class UIElementIsland : ContainerVisual, IContentHost, IDisposable
    {
        //-------------------------------------------------------------------
        //
        //  Constructors
        //
        //-------------------------------------------------------------------

        #region Constructors

        /// <summary>
        /// Create an instance of a UIElementIsland.
        /// </summary>
        internal UIElementIsland(UIElement child)
        {
            SetFlags(true, VisualFlags.IsLayoutIslandRoot);
            _child = child;

            if (_child != null)
            {
                // Disconnect visual from its old parent, if necessary.
                Visual currentParent = VisualTreeHelper.GetParent(_child) as Visual;
                if (currentParent != null)
                {
                    Invariant.Assert(currentParent is UIElementIsland, "Parent should always be a UIElementIsland.");
                    ((UIElementIsland)currentParent).Dispose();
                }

                // Notify the Visual layer that a new child appeared.
                Children.Add(_child);
            }
        }

        #endregion Constructors

        //-------------------------------------------------------------------
        //
        //  Internal Methods
        //
        //-------------------------------------------------------------------

        #region Internal Methods

        /// <summary>
        /// Do layout of entire UIElement Island.
        /// </summary>
        /// <param name="availableSize">Avalilable slot size of the UIElement Island.</param>
        /// <param name="horizontalAutoSize">Whether horizontal autosizing is enabled.</param>
        /// <param name="verticalAutoSize">Whether vertical autosizing is enabled.</param>
        /// <returns>The size of the UIElement Island.</returns>
        internal Size DoLayout(Size availableSize, bool horizontalAutoSize, bool verticalAutoSize)
        {
            Size islandSize = new Size();
            if (_child != null)
            {
                // Get FlowDirection from logical parent and set it on UIElemntIsland
                // to get layout mirroring provided by the layout system.
                if (_child is FrameworkElement && ((FrameworkElement)_child).Parent != null)
                {
                    SetValue(FrameworkElement.FlowDirectionProperty, ((FrameworkElement)_child).Parent.GetValue(FrameworkElement.FlowDirectionProperty));
                }

                try
                {
                    _layoutInProgress = true;

                    // Measure UIElement
                    _child.Measure(availableSize);

                    // Arrange UIElement
                    islandSize.Width = horizontalAutoSize ? _child.DesiredSize.Width : availableSize.Width;
                    islandSize.Height = verticalAutoSize ? _child.DesiredSize.Height : availableSize.Height;
                    _child.Arrange(new Rect(islandSize));
                }
                finally
                {
                    _layoutInProgress = false;
                }
            }
            return islandSize;
        }

        #endregion Internal Methods

        //-------------------------------------------------------------------
        //
        //  Internal Properties
        //
        //-------------------------------------------------------------------

        #region Internal Properties

        /// <summary>
        /// Root of UIElement island.
        /// </summary>
        internal UIElement Root
        {
            get
            {
                return _child;
            }
        }

        #endregion Internal Properties

        //-------------------------------------------------------------------
        //
        //  Internal Events
        //
        //-------------------------------------------------------------------

        #region Internal Events

        /// <summary>
        /// Fired after DesiredSize for child UIElement has been changed.
        /// </summary>
        internal event DesiredSizeChangedEventHandler DesiredSizeChanged;

        #endregion Internal Events

        //-------------------------------------------------------------------
        //
        //  Private Fields
        //
        //-------------------------------------------------------------------

        #region Private Fields

        private UIElement _child;       // Hosted UIElement root.
        private bool _layoutInProgress; // Whether layout is in progress.

        #endregion Private Fields

        //-------------------------------------------------------------------
        //
        //  IDisposable Members
        //
        //-------------------------------------------------------------------

        #region IDisposable Members

        /// <summary>
        /// <see cref="IDisposable.Dispose"/>
        /// </summary>
        public void Dispose()
        {
            if (_child != null)
            {
                Children.Clear();
                _child = null;
            }
            GC.SuppressFinalize(this);
        }

        #endregion IDisposable Members

        //-------------------------------------------------------------------
        //
        //  IContentHost Members
        //
        //-------------------------------------------------------------------

        #region IContentHost Members

        /// <summary>
        /// <see cref="IContentHost.InputHitTest"/>
        /// </summary>
        IInputElement IContentHost.InputHitTest(Point point)
        {
            // UIElementIsland only hosts UIElements, which can be found by the
            // normal hit-testing logic, so we don't need to provide our own
            // hit-testing implementation.
            return null;
        }

        /// <summary>
        /// <see cref="IContentHost.GetRectangles"/>
        /// </summary>
        ReadOnlyCollection<Rect> IContentHost.GetRectangles(ContentElement child)
        {
            return new ReadOnlyCollection<Rect>(new List<Rect>());
        }

        /// <summary>
        /// <see cref="IContentHost.HostedElements"/>
        /// </summary>
        IEnumerator<IInputElement> IContentHost.HostedElements
        {
            get
            {
                List<IInputElement> hostedElements = new List<IInputElement>();
                if (_child != null)
                {
                    hostedElements.Add(_child);
                }
                return hostedElements.GetEnumerator();
            }
        }

        /// <summary>
        /// <see cref="IContentHost.OnChildDesiredSizeChanged"/>
        /// </summary>
        void IContentHost.OnChildDesiredSizeChanged(UIElement child)
        {
            Invariant.Assert(child == _child);
            if (!_layoutInProgress && DesiredSizeChanged != null)
            {
                DesiredSizeChanged(this, new DesiredSizeChangedEventArgs(child));
            }
        }

        #endregion IContentHost Members
    }

    /// <summary>
    /// DesiredSizeChanged event handler.
    /// </summary>
    internal delegate void DesiredSizeChangedEventHandler(object sender, DesiredSizeChangedEventArgs e);

    /// <summary>
    /// Event arguments for the DesiredSizeChanged event.
    /// </summary>
    internal class DesiredSizeChangedEventArgs : EventArgs
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="child">UIElement for which DesiredSize has been changed.</param>
        internal DesiredSizeChangedEventArgs(UIElement child)
        {
            _child = child;
        }

        /// <summary>
        /// UIElement for which DesiredSize has been changed.
        /// </summary>
        internal UIElement Child
        {
            get { return _child; }
        }

        /// <summary>
        /// UIElement for which DesiredSize has been changed.
        /// </summary>
        private readonly UIElement _child;
    }
}


text:
package net.emaze.dysfunctional.iterations;

import java.util.Iterator;

/**
 * A singleton iterable.
 *
 * @param <T> the element type
 * @author rferranti
 */
public class SingletonIterable<T> implements Iterable<T> {

    private final T element;

    public SingletonIterable(T element) {
        this.element = element;
    }

    @Override
    public Iterator<T> iterator() {
        return new SingletonIterator<T>(element);
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Puppet::Parser::Functions
    newfunction(:search_nodes, :type => :rvalue) do |args|
        require 'puppet/util/mongoquery'

        searchspec = eval(args[0])
        Puppet::Util::MongoQuery.instance.find_node_names(searchspec)
    end
end


text:
<?php
include('config.php');
if(isset($_SESSION['user_id'])){
    header("location: dashboard.php");
}

$error='';
if (isset($_POST['submit'])) {
    if (empty($_POST['username']) || empty($_POST['password'])) {
        $error = "Username or Password is invalid";
    }
    else
    {
        $username = stripslashes($_POST['username']);
        $password = stripslashes($_POST['password']);

        $userfind = Admin::where('username', '=', $username)->where('password', '=', md5($password))->count();

        if ($userfind > 0) {
            $_SESSION['user_id'] = $username;
            header("location: dashboard.php");
        } else {

            $error = "Username or Password is invalid";

        }
    }
}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>FOS-Streaming panel by Tyfix</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link id="bootstrap-style" href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
    <link id="base-style" href="css/style.css" rel="stylesheet">
    <link id="base-style-responsive" href="css/style-responsive.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-ext' rel='stylesheet' type='text/css'>

    <link rel="shortcut icon" href="favicon.ico">

                    <?php
                        if($error != "") {
                            echo "

                                    " . $error . "

";
                        }
                    ?>

FOS-Streaming panel

Login to your account

                <form class="form-horizontal" action="" method="post">

                    <fieldset>

                            <input class="input-large span10" name="username" id="username" type="text" placeholder="type username"/>

                            <input class="input-large span10" name="password" id="password" type="password" placeholder="type password"/>

                            <button type="submit" name="submit" class="btn btn-primary">Login</button>

                </form>


text:
import json

class InfrastructureUpgradeLevel(object):
    name = ''
    upgrade_cost = 0
    no_of_turns_required = 0
    transaction_benefit = 0

    def __init__(
        self,
        name='',
        upgrade_cost=0,
        no_of_turns_required=0,
        transaction_benefit=0
    ):
        self.name = name
        self.upgrade_cost = upgrade_cost
        self.no_of_turns_required = no_of_turns_required
        self.transaction_benefit = transaction_benefit

    def __repr__(self):
        return json.dumps(self.to_dict())

    def to_dict(self):
        return {
            'Name': self.name,
            'UpgradeCost': self.upgrade_cost,
            'NoOfTurnsRequired': self.no_of_turns_required,
            'TransactionBenefit': self.transaction_benefit
        }

    @staticmethod
    def json_factory(input_json):
        result = InfrastructureUpgradeLevel()

        result.name = input_json['Name']
        result.upgrade_cost = input_json['UpgradeCost']
        result.no_of_turns_required = input_json['NoOfTurnsRequired']
        result.transaction_benefit = input_json['TransactionBenefit']

        return result


text:
class Stringer {
    constructor(innerString,innerLength) {
        this.innerString = innerString,
        this.innerLength = innerLength
    }

    increase(length) {
        return this.innerLength += Number(length);
    }

    decrease(length) {
        if(this.innerLength - Number(length) <= 0) {
            this.innerLength = 0;
            return this.innerLength;
        } else {
            return this.innerLength -= Number(length);
        }
    }

    toString() {
        if(this.innerLength == 0) {
            return '...';
        } else if(this.innerString.length > this.innerLength) {
            let neededLength = this.innerString.length - this.innerLength
            let cuttedString = this.innerString.substr(0,neededLength);
            return cuttedString + '...';
        } else {
            return this.innerString;
        }
    }
}

let test = new Stringer('Test', 5);
console.log(test.toString());
//test.decrease(3);
//console.log(test.toString());
test.increase(4);
console.log(test.toString());


text:
<?php
namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\Session\Container;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Model\ViewModel;
use Application\Service\PictureService as PictureService;

class PictureHelper extends AbstractHelper implements ServiceLocatorAwareInterface
{
    protected static $state;
    protected $pictureObject;
    protected $picture;
    protected $username;
    protected $itemId;
    protected $viewmodel;
    protected $renderer;

    /**
     * Set the service locator.
     *
     * @ param ServiceLocatorInterface $serviceLocator
     * @ return CustomHelper
     */
    public function __construct()
    {
    }
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        return $this;
    }
    /**
     * Get the service locator.
     *
     * @ return \Zend\ServiceManager\ServiceLocatorInterface
     */
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }

	public function setLoggedIn($loggedIn)
	{
		$this->loggedIn = $loggedIn;
	}
	public function setLog($log)
	{
		$this->log = $log;
	}
	public function getLog()
	{
		return $this->log;
	}
    public function setEntityManager($em)
    {
    	$this->em = $em;
    }
    public function getEntityManager()
    {
    	return $this->em;
    }
    public function setViewModel(ViewModel $viewmodel)
    {
        $this->viewmodel = $viewmodel;
    }
    public function getViewModel()
    {
        return $this->viewmodel;
    }
    public function setObject($pictureObject)
    {
        $this->pictureObject = $pictureObject;
        $picture = $pictureObject->getPicture();
        $picture = "thumb_" . $picture;
        $username = $this->getUsername();
        $this->picture = "/uploads/" . $username . "/pix/" . $picture;
    }
    public function setUsername($username)
    {
        $this->username = $username;
    }
    public function getUsername()
    {
        return $this->username;
    }
    public function setItemId($itemId)
    {
        $this->itemId = $itemId;
    }
    public function setRenderer($renderer)
    {
        $this->renderer = $renderer;
    }
    public function getRenderer()
    {
        return $this->renderer;
    }
    public function __invoke()
    {
        $viewRender = $this->getServiceLocator()->get('ViewRenderer');

    	$view = $this->getViewModel();

        //$view->picture = $this->picture;
        $view->picture = "/images/placeholder.jpg";
	$view->width= "50";
	$view->height="50";

	$view->setTemplate('items/picture.phtml');

	return $viewRender->render($view);
    }
}


text:
The objective of this file is to share the intention behind every new branches that are created for RRSchedule. Since each branch
generally represents a "development effort", I think it is useful to describe and explain them.

## Rules and multiple round-robins (branch created on 2011/01/21)

### Rules

The idea behind having "rules" is to allow more flexibility in the schedule generation.

At the moment, we can tell RRSchedule that the games are played (for example) every monday and wednesday at 7:00PM and 9:00PM on four different
playing surfaces. But what if games played on monday are held at 7:00PM while games played on wednesday are held at 7:00PM and 9:00PM?
You just cannot configure it this way at the moment. And what if on monday every playing surfaces are available while only 1 is available on wednesday?
This is why I had the idea of replacing the current "one size fits all" system with a more flexible system.

Thus, we will be able to have rules like:

    Day of week | Game Time | playing surfaces   |
    Monday      | 7:00PM    | Field #1, Field #2 |
    Wednesday   | 7:00PM    | Field #1           |
    Wednesday   | 9:00PM    | Field #1

In the code it might look something like this:

    schedule.rules << Rule.new(:wday => 1, :gt => "7:00PM", :ps => ["Field #1", "Field #2"])
    schedule.rules << Rule.new(:wday => 3, :gt => "7:00PM", :ps => "Field #1")
    schedule.rules << Rule.new(:wday => 3, :gt => "9:00PM", :ps => "Field #1")

    schedule.generate

    ...

### Multiple round-robins

The other development in this branch involves the possibility to create multiple round-robins in the same method call while sharing the same
physical constraints (game times and playing surfaces)

Several sport leagues use a "division" system where teams are seeded in different groups based on their performance. Each group plays
a round-robin *inside* its own division. Suppose a league of 4 divisions containing 8 teams each. A1 will play against A2, A3 and so on but not
against B1, C3 or D6. What we need in this case is 4 different round-robins. However, these 4 round-robins share the same playing surfaces and
game times.

In other words, you will be able to do something like this:

    schedule.teams = [
      [A1,A2,A3,A4,A5,A6,A7,A8],
      [B1,B2,B3,B4,B5,B6,B7,B8],
      [C1,C2,C3,C4,C5,C6,C7,C8],
      [D1,D2,D3,D4,D5,D6,D7,D8]
    ]

    schedule.rules << Rule.new(
      ... #same rules apply for all 32 teams
    )

## Playing locations should be distributed evenly amongst competitors (branch created on 2011/09/23)

At the moment the playing locations are distributed randomly for every matchup. It means that one team
might play a lot more often on a playing field than on another.

The work in this branch will try to fix this issue.

## Optional balancing for Game Times (branch crated on 2011/10/02)

I created this branch to solve a very specific case. When you generate a schedule with multiple divisions, you generally want that all
teams of a given division plays at the same game times. (e.g. Division A plays at 7:00, B plays at 9:00 and so on). However with the new
balancing feature (see 2011/09/23 branch), it is no longer possible to achieve this.

I will add options balanced_gt and balanced_ps, both true by default.


text:
var Transform = require( 'stream' ).Transform;

var MyactStreamTransform = module.exports = function( key ) {
    Transform.call( this, { objectMode: true });

    if ( 'undefined' === typeof key ) key = 'id';
    this.keyProperty = key;
};

MyactStreamTransform.prototype = Object.create( Transform.prototype );

MyactStreamTransform.prototype._transform = function( chunk, encoding, done ) {
    this.push({
        key: chunk[ this.keyProperty ],
        data: chunk
    });

    done();
};


text:
#ifndef V_MAXVALUE_H
#define V_MAXVALUE_H

#include "v_kernel.h"
#include "c_typebase.h"
#include "os_if.h"

#ifdef OSPL_BUILD_CORE
#define OS_API OS_API_EXPORT
#else
#define OS_API OS_API_IMPORT
#endif
/* !!!!!!!!NOTE From here no more includes are allowed!!!!!!! */

OS_API void     v_maxValueInit       (v_maxValue *_this);
OS_API void     v_maxValueReset      (v_maxValue *_this);
OS_API os_timeW v_maxValueGetTime    (v_maxValue *_this);
OS_API c_ulong  v_maxValueGetValue   (v_maxValue *_this);
OS_API void     v_maxValueSetValue   (v_maxValue *_this, c_ulong value);

#undef OS_API

#endif


text: require('select2/dist/js/select2.full');


text:
MongoDB\Driver\Session::startTransaction() throws an error on sharded clusters < 4.2
--SKIPIF--
<?php require __DIR__ . "/../utils/basic-skipif.inc"; ?>
<?php skip_if_not_libmongoc_crypto() ?>
<?php skip_if_not_sharded_cluster_with_replica_set(); ?>
<?php skip_if_server_version('>=', '4.2'); ?>
--FILE--
<?php
require_once __DIR__ . "/../utils/basic.inc";

$manager = create_test_manager();
$session = $manager->startSession();

echo throws(function () use ($session) {
    $session->startTransaction();
}, MongoDB\Driver\Exception\RuntimeException::class), "\n";

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
OK: Got MongoDB\Driver\Exception\RuntimeException
Multi-document transactions are not supported by this server version
===DONE===


text:
<?php

/**
 * @namespace
 */
namespace Bluz\Tests\Validator\Rule;

use \DateTime;
use Bluz\Tests;
use Bluz\Validator\Rule\Date;

/**
 * Class DateTest
 * @package Bluz\Tests\Validator\Rule
 */
class DateTest extends Tests\TestCase
{
    /**
     * @var Date
     */
    protected $validator;

    /**
     * Setup validator instance
     */
    protected function setUp()
    {
        parent::setUp();
        $this->validator = new Date;
    }

    public function testDateWithoutFormatShouldValidate()
    {
        $this->assertTrue($this->validator->validate('today'));
    }

    public function testDateTimeInstancesShouldAlwaysValidate()
    {
        $this->assertTrue($this->validator->validate(new DateTime('today')));
    }

    /**
     * @dataProvider providerForPass
     */
    public function testValidDateShouldPass($format, $date)
    {
        $validator = new Date($format);
        $this->assertTrue($validator->validate($date));
        $this->assertNotEmpty($validator->__toString());
    }

    /**
     * @dataProvider providerForFail
     */
    public function testInvalidateDateShouldFail($format, $date)
    {
        $validator = new Date($format);
        $this->assertFalse($validator->validate($date));
        $this->assertNotEmpty($validator->__toString());
    }

    /**
     * @dataProvider providerForFail
     * @expectedException \Bluz\Validator\Exception\ValidatorException
     */
    public function testInvalidateDateThrowException($format, $date)
    {
        $validator = new Date($format);
        $validator->assert($date);
    }

    /**
     * @return array
     */
    public function providerForPass()
    {
        return array(
            array('Y-m-d', '2009-09-09'),
            array('d/m/Y', '23/05/1987'),
        );
    }

    /**
     * @return array
     */
    public function providerForFail()
    {
        return array(
            array(null, 'invalid date'),
            array('Y-m-d', '2009-09-00'),
            array('y-m-d', '2009-09-09'),
            array('y-m-d', new \stdClass),
        );
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../std/os/windows/raw/type.HANDLE.html">

Redirecting to ../../../../std/os/windows/raw/type.HANDLE.html...


text:
package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

// ProjectName contains the name of the project
const ProjectName = "dee"

// GOPATH environment variable name.
const GOPATH_ENVIRONMENT_VARIABLE = "GOPATH"

// GOBIN environment variable name
const GOBIN_ENVIRONMENT_VARIBALE = "GOBIN"

// GOOS environment variable name
const GOOS_ENVIRONMENT_VARIBALE = "GOOS"

// GOARCH environment variable name
const GOARCH_ENVIRONMENT_VARIBALE = "GOARCH"

// GO15VENDOREXPERIMENT environment variable name
const GO15VENDOREXPERIMENT_ENVIRONMENT_VARIBALE = "GO15VENDOREXPERIMENT"

var (

	// command line flags
	verboseFlagIsSet      = flag.Bool("v", false, "Verbose mode")
	installFlagIsSet      = flag.Bool("install", false, fmt.Sprintf("Compiles the %s binaries", ProjectName))
	crossCompileFlagIsSet = flag.Bool("crosscompile", false, fmt.Sprintf("Compile %s binaries for all platforms and architectures", ProjectName))
	versionFlagIsSet      = flag.Bool("version", false, "Get the current version number of the repository")
	coverageFlagIsSet     = flag.Bool("coverage", false, "Run the test and create a code coverage report")

	// The GOPATH for the current project
	goPath = getWorkingDirectory()

	// The GOBIN for the current project
	goBin = filepath.Join(goPath, "bin")

	// A list of all supported compilation targets (e.g. "windows/amd64")
	compilationTargets = []compilationTarget{
		compilationTarget{"darwin", "amd64", []string{}},
		compilationTarget{"linux", "amd64", []string{}},
		compilationTarget{"linux", "arm", []string{}},
		compilationTarget{"linux", "arm", []string{"GOARM=5"}},
		compilationTarget{"linux", "arm", []string{"GOARM=6"}},
		compilationTarget{"linux", "arm", []string{"GOARM=7"}},
		compilationTarget{"windows", "amd64", []string{}},
	}

	// The current version number (e.g. "2015-01-11-284c030+")
	version = gitVersion()
)

// Compilation Target Definition
type compilationTarget struct {
	OperatingSystem string
	Architecture    string
	OtherVariables  []string
}

func (target *compilationTarget) String() string {
	return fmt.Sprintf("%s/%s", target.OperatingSystem, target.Architecture)
}

func init() {

	executableName := "make.go"

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s provides functions for compiling %s.\n", executableName, ProjectName)
		fmt.Fprintf(os.Stderr, "\n")
		fmt.Fprintf(os.Stderr, "Version: %s\n", version)
		fmt.Fprintf(os.Stderr, "\n")
		fmt.Fprintf(os.Stderr, "Usage:\n")
		fmt.Fprintf(os.Stderr, "\n")
		fmt.Fprintf(os.Stderr, "  go run %s [options]\n", executableName)
		fmt.Fprintf(os.Stderr, "\n")
		fmt.Fprintf(os.Stderr, "Options:\n")
		fmt.Fprintf(os.Stderr, "\n")
		flag.PrintDefaults()
	}
}

func main() {
	log.SetFlags(0)
	flag.Parse()

	if len(os.Args) < 2 {
		flag.Usage()
		return
	}

	if *verboseFlagIsSet {
		fmt.Printf("Version: %s\n", version)
		fmt.Printf("%s: %s\n", GOPATH_ENVIRONMENT_VARIABLE, goPath)
		fmt.Printf("%s: %s\n", GOBIN_ENVIRONMENT_VARIBALE, goBin)
	}

	if *installFlagIsSet {
		if err := install(); err != nil {
			fmt.Fprintf(os.Stderr, err.Error())
			os.Exit(1)
		}

		return
	}

	if *crossCompileFlagIsSet {
		if err := crossCompile(); err != nil {
			fmt.Fprintf(os.Stderr, err.Error())
			os.Exit(1)
		}

		return
	}

	if *versionFlagIsSet {
		printProjectVersionNumber()
		return
	}

	if *coverageFlagIsSet {
		if err := codecoverage(); err != nil {
			fmt.Fprintf(os.Stderr, err.Error())
			os.Exit(1)
		}

		return
	}

	flag.Usage()
}

// Install all parts of allmark using go install.
func install() error {

	// prepare the environment variables
	environmentVariables := cleanGoEnv()
	environmentVariables = setEnv(environmentVariables, GOBIN_ENVIRONMENT_VARIBALE, goBin)
	environmentVariables = setEnv(environmentVariables, GO15VENDOREXPERIMENT_ENVIRONMENT_VARIBALE, "1")

	return runCommand(os.Stdout, os.Stderr, goPath, environmentVariables, "go", "install", getBuildVersionFlag())

}

// codecoverage runs all tests and creates a code coverage report
func codecoverage() error {

	// prepare the environment variables
	environmentVariables := cleanGoEnv()
	environmentVariables = setEnv(environmentVariables, GOBIN_ENVIRONMENT_VARIBALE, goBin)
	environmentVariables = setEnv(environmentVariables, GO15VENDOREXPERIMENT_ENVIRONMENT_VARIBALE, "1")

	coverageError := runCommand(os.Stdout, os.Stderr, goPath, environmentVariables, "go", "test", "-coverprofile=coverage.out")
	if coverageError != nil {
		return coverageError
	}

	reportError := runCommand(os.Stdout, os.Stderr, goPath, environmentVariables, "go", "tool", "cover", "-html=coverage.out", "-o", "coverage.html")
	if reportError != nil {
		return reportError
	}

	return nil
}

// Cross-compile all parts of allmark for all supported platforms.
func crossCompile() error {

	// prepare the environment variables
	environmentVariables := cleanGoEnv()
	environmentVariables = setEnv(environmentVariables, GOBIN_ENVIRONMENT_VARIBALE, goBin)
	environmentVariables = setEnv(environmentVariables, GO15VENDOREXPERIMENT_ENVIRONMENT_VARIBALE, "1")

	// iterate over all supported compilation targets
	for _, target := range compilationTargets {

		// assemble the target path
		targetFile := filepath.Join(goBin, fmt.Sprintf("%s_%s_%s", ProjectName, target.OperatingSystem, target.Architecture))

		// prepare environment variables for cross-compilation
		crossCompileEnvironemntVariables := environmentVariables
		crossCompileEnvironemntVariables = setEnv(crossCompileEnvironemntVariables, GOOS_ENVIRONMENT_VARIBALE, target.OperatingSystem)
		crossCompileEnvironemntVariables = setEnv(crossCompileEnvironemntVariables, GOARCH_ENVIRONMENT_VARIBALE, target.Architecture)

		// add additional environment variables
		for _, additionalEnvVariable := range target.OtherVariables {
			components := strings.Split(additionalEnvVariable, "=")
			name := components[0]
			value := components[1]

			// append additional environment variables to target file name
			targetFile += fmt.Sprintf("_%s_%s", strings.ToLower(name), strings.ToLower(value))

			crossCompileEnvironemntVariables = setEnv(crossCompileEnvironemntVariables, name, value)
		}

		// build the package for the specified os and arch
		if *verboseFlagIsSet {
			fmt.Printf("Compiling %s for %s\n", ProjectName, target.String())
		}

		// add .exe extension for windows
		if target.OperatingSystem == "windows" {
			targetFile += ".exe"
		}

		err := runCommand(os.Stdout,
			os.Stderr,
			goPath,
			crossCompileEnvironemntVariables,
			"go",
			"build",
			"-o",
			targetFile,
			"-x",
			getBuildVersionFlag())

		if err != nil {
			return err
		}

	}

	return nil
}

// Print the current version number of the project.
func printProjectVersionNumber() {
	fmt.Fprintf(os.Stdout, gitVersion())
}

// getWorkingDirectory returns the current working directory path or fails.
func getWorkingDirectory() string {
	goPath, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get current directory: %v", err)
	}

	return goPath
}

// Execute go in the specified go path with the supplied command arguments.
func runCommand(stdout, stderr io.Writer, workingDirectory string, environmentVariables []string, command string, args ...string) error {

	// Create the command
	cmdName := fmt.Sprintf("%s %s", command, strings.Join(args, " "))
	cmd := exec.Command(command, args...)

	// Set the working directory
	cmd.Dir = workingDirectory

	// set environment variables
	cmd.Env = environmentVariables

	// Capture the output
	cmd.Stdout = stdout
	cmd.Stderr = stderr

	if *verboseFlagIsSet {
		log.Printf("Running %s", cmdName)
	}

	// execute the command
	err := cmd.Run()
	if err != nil {
		return fmt.Errorf("Error running %s: %v", cmdName, err.Error())
	}

	return nil
}

// cleanGoEnv returns a copy of the current environment with GOPATH_ENVIRONMENT_VARIABLE and GOBIN_ENVIRONMENT_VARIBALE removed.
func cleanGoEnv() (clean []string) {
	for _, env := range os.Environ() {
		if strings.HasPrefix(env, GOBIN_ENVIRONMENT_VARIBALE+"=") {
			continue
		}

		clean = append(clean, env)
	}

	return
}

// setEnv sets the given key & value in the provided environment.
// Each value in the env list should be of the form key=value.
func setEnv(env []string, key, value string) []string {
	for i, s := range env {
		if strings.HasPrefix(s, fmt.Sprintf("%s=", key)) {
			env[i] = envPair(key, value)
			return env
		}
	}
	env = append(env, envPair(key, value))
	return env
}

// Create an environment variable of the form key=value.
func envPair(key, value string) string {
	return fmt.Sprintf("%s=%s", key, value)
}

// gitVersion returns the git version of the git repo at goPath as a
// string of the form "yyyy-mm-dd-xxxxxxx", with an optional trailing
// '+' if there are any local uncomitted modifications to the tree.
func gitVersion() string {

	// get the latest git hash
	gitHeadCommand := exec.Command("git", "rev-parse", "--short", "HEAD")
	gitHeadCommand.Dir = goPath

	gitHeadCommandOutput, err := gitHeadCommand.Output()
	if err != nil {
		log.Fatalf("Error while retrieving the latest git hash: %v", err)
	}

	gitHash := strings.TrimSpace(string(gitHeadCommandOutput))

	// check if the working directory is dirty
	dirtyFlag := ""
	gitDiffCommand := exec.Command("git", "diff", "--exit-code")
	gitDiffCommand.Dir = goPath
	if err := gitDiffCommand.Run(); err != nil {
		dirtyFlag = "+"
	}

	// get the latest tag
	gitLatestTagCommand := exec.Command("git", "describe", "--abbrev=0", "--tags")
	gitLatestTagCommand.Dir = goPath

	latestTag := "v0.0.0"
	gitLatestTagCommandOutput, _ := gitLatestTagCommand.Output()
	latestTag = strings.TrimSpace(string(gitLatestTagCommandOutput))
	date := getCurrentDateString()

	versionNumber := fmt.Sprintf("%s-%s-%s%s", latestTag, date, gitHash, dirtyFlag)

	return versionNumber
}

// Get the build version flag for the go linker (e.g. -X allmark.io/cmd/allmark 2015-01-11-284c030+).
func getBuildVersionFlag() string {
	return fmt.Sprintf("--ldflags=-X %s.GitInfo=%s", "main", version)
}

// getCurrentDateString returns the current date as a formatted string (e.g. "2006-01-02").
func getCurrentDateString() string {
	return time.Now().Format("2006-01-02")
}


text:
package br.ufc.model;

import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="classificado")
public class Classificado {

	@Id
	@GeneratedValue
	@Column(name="id_classificado")
	private int idClassificado;
	@Column(name="titulo_classificado")
	private String tituloClassificado;
	@Column(name="texto_classificado")
	private String textoClassificado;
	@Column(name="preco_inicial")
	private double precoInicial;
	private String telefone;
	@OneToMany(cascade = CascadeType.ALL, mappedBy="classificado",targetEntity=Oferta.class,fetch=FetchType.EAGER)
	private Collection<Oferta> ofertas;

	public Classificado() {

	}

	public Classificado(int idClassificado, String tituloClassificado,
			String textoClassificado, double precoInicial, String telefone) {

		this.idClassificado = idClassificado;
		this.tituloClassificado = tituloClassificado;
		this.textoClassificado = textoClassificado;
		this.precoInicial = precoInicial;
		this.telefone = telefone;
	}

	public Collection<Oferta> getOfertas() {
		return ofertas;
	}

	public void setOfertas(Collection<Oferta> ofertas) {
		this.ofertas = ofertas;
	}

	public int getIdClassificado() {
		return idClassificado;
	}

	public void setIdClassificado(int idClassificado) {
		this.idClassificado = idClassificado;
	}

	public String getTituloClassificado() {
		return tituloClassificado;
	}

	public void setTituloClassificado(String tituloClassificado) {
		this.tituloClassificado = tituloClassificado;
	}

	public String getTextoClassificado() {
		return textoClassificado;
	}

	public void setTextoClassificado(String textoClassificado) {
		this.textoClassificado = textoClassificado;
	}

	public double getPrecoInicial() {
		return precoInicial;
	}

	public void setPrecoInicial(double precoInicial) {
		this.precoInicial = precoInicial;
	}

	public String getTelefone() {
		return telefone;
	}

	public void setTelefone(String telefone) {
		this.telefone = telefone;
	}

	@Override
	public String toString() {
		return "Classificado [idClassificado=" + idClassificado
				+ ", tituloClassificado=" + tituloClassificado
				+ ", textoClassificado=" + textoClassificado
				+ ", precoInicial=" + precoInicial + ", telefone=" + telefone
				+ "]";
	}

}


text:
package ca.stellardrift.permissionsex.bukkit;

import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;

@ConfigSerializable
final class BukkitConfiguration {

    @Setting
    @Comment("Whether to fall back to checking op status when a permission is unset in PEX")
    private boolean fallbackOp = true;

    boolean fallbackOp() {
        return this.fallbackOp;
    }

}


text:
{% extends "layout.html" %}

{% block css %}
<link href="{{ url_for('static', filename='css/special_all.css') }}" rel='stylesheet' type='text/css'/>
{% endblock %}

{% block content %}

搜索

    <form action="/special_search" method="get">
        <input type="text" name="search" />
    </form>

显示专栏列表

显示所有专栏

            <select id="sort">
        <option id="sort_by_time" value="time">按照时间排序</option>
        <option id="sort_by_favor" value="favor">按照热度排序</option>

    </select>

    {% set special_num = 1 %}
    {% for special in specials_pagination_list.items %}
    {% set special_num = special_num + 1 %}

        {% if special_num%2 == 1 %}

        {% endif %}

			        {{ special.name }}

                {%for au in author(special.special_id)%}
                {{au.nick}}
                {% endfor %}

                {{ special.coin }}

                    {{ special.introduction | safe }}

                {% for article in articles(special.special_id, 1, "time", 5).items %}

                         {{ article.title }}

                    {{ article.coins }}

                      {{ article.time | time_split_2 }}

                {% endfor %}

    {% endfor %}

                       首页

                       上一页

{{ specials_pagination_list.page }} / {{specials_pagination_list.pages }}

下一页

末页

{% endblock %}

{% block js %}

{% endblock %}


text:
This repo supports Starcounter 2.4.0 with Polymer 2 (`master` branch) and Starcounter 2.3.1 with Polymer 1 (`master-2.3` branch).

All changes should be as a PR to the `master` branch.

The branch `master-2.3` does not get updates anymore and is only for reference purposes.

### Build scripts specific prerequisites

* Install the latest global .NET Core Cake tool by running `dotnet tool install -g Cake.Tool`.
* Add [nuget.exe](https://www.nuget.org/downloads) to PATH.
* Make sure that the MSBuild version that is used comes from your Visual Studio installation and not from a previous installation of .NET Framework. The easiest way to test this is to run `msbuild /version` which should return a `15.X` version. If it returns something like `4.X`, then you have to either
    * add `C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin` to PATH (check both System AND User).  Make sure it's inserted before any `C:\Windows\Microsoft.NET\Framework\v4.0.30319`
    * or run `C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\Tools\VsDevCmd.bat` which will only set proper environment variable values for the current process.

## How to build and run

### Build and run using CLI

1. Clone this repo to your local machine
2. Build the solution by executing `build.bat` in Windows or `./build.bat` in Git Bash
3. Run it by executing `run.bat` in Windows or `./run.bat` in Git Bash
4. Go to [http://localhost:8080/UniformDocs](http://localhost:8080/UniformDocs)

### Build and run using Visual Studio

1. Clone this repo to your local machine
2. Open the `.sln` file in Visual Studio
3. Build and run it using Debug in Visual Studio (**Debug** > **Start debugging** or <kbd>F5</kbd>)
4. Go to [http://localhost:8080/UniformDocs](http://localhost:8080/UniformDocs)

## Contributing code

To contribute code to this repository, follow the instructions in the [guidelines](https://github.com/Starcounter/CompanyTrack/blob/master/AppsTeam/Guidelines/version_control/contributing_code.md).

## How to release a package

To release the app to the warehouse, follow the instructions in the [guidelines](https://github.com/Starcounter/CompanyTrack/blob/master/AppsTeam/Guidelines/releasing-to-warehouse.md).

## How to deploy to `uniform.starcounter.io`

1. Make sure that the new version of UniformDocs is released to the App Warehouse
2. Connect via RDP to the AWS EC2 instance of hosted UniformDocs (credentials in `N*********.kdbx`)
3. In RDP, wipe out the current data by running `staradmin delete db default`
4. Install the current version of Starcounter 2.4 from http://downloads.starcounter.com/
5. Start Starcounter by running `staradmin start server`
6. Create a new database on port 80 by running `staradmin new db default DefaultUserHttpPort=80`
7. In Administrator, go to the database `default` and install the current version of UniformDocs from App Warehouse
8. Go to https://uniform.starcounter.io/ to verify that the new UniformDocs is correctly deployed

## Testing

### Prepare your environment for cloud Selenium (default)

Before running the steps, you need to:

- Download and install Visual Studio 2017 to run the tests
- Install NUnit 3 Test Adapter in VS (Tools > Extensions and Updates... > Online) in order to see tests in Test Explorer window
- Set `BROWSERSTACK_USERNAME` (this is not the e-mail address!) and `BROWSERSTACK_ACCESS_KEY` envionment variables  (credentials in `N*********.kdbx`). Restart Visual Studio 2017 to acknowledge the changes.
- Get BrowserStackLocal CLI binary from [the download page](https://www.browserstack.com/local-testing#command-line) (CTRL+F "Download the appropriate binary")
- Run `BrowserStackLocal.exe --key %BROWSERSTACK_ACCESS_KEY% --local-identifier %COMPUTERNAME%`

### Prepare your environment for local Selenium

Before running the steps, you need to:

- Download and install Visual Studio 2017 to run the tests
- Install NUnit 3 Test Adapter in VS (Tools > Extensions and Updates... > Online) in order to see tests in Test Explorer window
- Download and install Java, required by Selenium Standalone Server
- Download Selenium Standalone Server and the drivers [Microsoft WebDriver (Edge), Google ChromeDriver (Chrome) and Mozilla GeckoDriver (Firefox)] using [these instructions](https://docs.starcounter.io/cookbook/acceptance-testing-with-selenium).
- Add path to the folder with drivers to system path on your computer
- Start Selenium Remote Driver using `java -jar selenium-server-standalone-3.*.jar -enablePassThrough false`

### Run the test (from Visual Studio)

1. Open `UniformDocs.sln` in Visual Studio and enable Test Explorer (Test > Window > Test Explorer)
2. Start the UniformDocs app
3. Press "Run all" in Test Explorer
   - If you get an error about some packages not installed, right click on the project in Solution Explorer. Choose "Manage NuGet Packages" and click on "Restore".

### Run the test (from command line)

1. Build the solution (`build.bat`)
2. Start the UniformDocs.Test runner (`test.bat`)

To run a specific test, add the param `--test="<testname>"`.

By default, it connects to cloud Selenium (BrowserStack). To connect to a local Selenium, add the param `--params="Server=<Uri>"`, e.g. `--params="Server=http://localhost:4444/wd/hub/`.

To run in a specific browser, add the param `--params="Browsers=<BrowserName>"` (case sensitive). Possible values: `Chrome`, `Firefox`, `Edge` (separated by a comma).

```
test --params="Server=http://192.168.1.49:4444/wd/hub" --params="Browsers=Chrome" --test="UniformDocs.Tests.Test.TextareaPageTest(Chrome).TextareaPage_WriteToTextArea"
```


text:
namespace Akka.Actor
{
    public interface IUntypedActorContext : IActorContext
    {
        void Become(UntypedReceive receive, bool discardOld = true);
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66a.c
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-66a.tmpl.c
*/
/*
 * @description
 * CWE: 134 Uncontrolled Format String
 * BadSource: file Read input from a file
 * GoodSource: Copy a fixed string into data
 * Sinks: fprintf
 *    GoodSink: fwprintf with "%s" as the second argument and data as the third
 *    BadSink : fwprintf with data as the second argument
 * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif

#ifndef OMITBAD

/* bad function declaration */
void CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66b_badSink(wchar_t * dataArray[]);

void CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66_bad()
{
    wchar_t * data;
    wchar_t * dataArray[5];
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    {
        /* Read input from a file */
        size_t dataLen = wcslen(data);
        FILE * pFile;
        /* if there is room in data, attempt to read the input from a file */
        if (100-dataLen > 1)
        {
            pFile = fopen(FILENAME, "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read data from a file */
                if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                {
                    printLine("fgetws() failed");
                    /* Restore NUL terminator if fgetws fails */
                    data[dataLen] = L'\0';
                }
                fclose(pFile);
            }
        }
    }
    /* put data in array */
    dataArray[2] = data;
    CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66b_badSink(dataArray);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66b_goodG2BSink(wchar_t * dataArray[]);

static void goodG2B()
{
    wchar_t * data;
    wchar_t * dataArray[5];
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    /* FIX: Use a fixed string that does not contain a format specifier */
    wcscpy(data, L"fixedstringtest");
    dataArray[2] = data;
    CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66b_goodG2BSink(dataArray);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66b_goodB2GSink(wchar_t * dataArray[]);

static void goodB2G()
{
    wchar_t * data;
    wchar_t * dataArray[5];
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    {
        /* Read input from a file */
        size_t dataLen = wcslen(data);
        FILE * pFile;
        /* if there is room in data, attempt to read the input from a file */
        if (100-dataLen > 1)
        {
            pFile = fopen(FILENAME, "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read data from a file */
                if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                {
                    printLine("fgetws() failed");
                    /* Restore NUL terminator if fgetws fails */
                    data[dataLen] = L'\0';
                }
                fclose(pFile);
            }
        }
    }
    dataArray[2] = data;
    CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66b_goodB2GSink(dataArray);
}

void CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE134_Uncontrolled_Format_String__wchar_t_file_fprintf_66_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
require 'compass/exec/global_options_parser'
require 'compass/exec/project_options_parser'

module Compass::Exec
  class SwitchUI
    include GlobalOptionsParser
    include ProjectOptionsParser
    attr_accessor :args, :options, :opts

    def initialize(args)
      self.args = args
      self.options = {}
      parse!
    end

    def run!
      begin
        perform!
      rescue Exception => e
        raise e if e.is_a? SystemExit
        if e.is_a?(::Compass::Error) || e.is_a?(OptionParser::ParseError)
          $stderr.puts e.message
        else
          ::Compass::Exec::Helpers.report_error(e, @options)
        end
        return 1
      end
      return 0
    end

    protected

    def perform!
      if options[:command]
        do_command(options[:command])
      else
        puts self.opts
      end
    end

    def parse!
      self.opts = OptionParser.new(&method(:set_opts))
      self.opts.parse!(self.args)
      if self.args.size > 0
        self.options[:project_name] = trim_trailing_separator(self.args.shift)
      end
      self.options[:command] ||= self.options[:project_name] ? :create_project : :update_project
      self.options[:framework] ||= :compass
    end

    def trim_trailing_separator(path)
      path[-1..-1] == File::SEPARATOR ? path[0..-2] : path
    end

    def set_opts(opts)
      opts.banner = <<END
Usage: compass [options] [project]

Description:
The compass command line tool will help you create and manage the stylesheets for your project.

To get started on a stand-alone project based on blueprint:

  compass -f blueprint my_compass_project

When you change any sass files, you must recompile your project using --update or --watch.
END
      opts.separator ''
      opts.separator 'Mode Options(only specify one):'

      opts.on('-i', '--install', :NONE, "Create a new compass project.",
                                        "  The default mode when a project is provided.") do
        self.options[:command] = :create_project
      end

      opts.on('-u', '--update', :NONE, 'Update the current project.',
                                       '  This is the default when no project is provided.') do
        self.options[:command] = :update_project
      end

      opts.on('-w', '--watch', :NONE, 'Monitor the current project for changes and update') do
        self.options[:command] = :watch_project
        self.options[:quiet] = true
      end

      opts.on('-p', '--pattern PATTERN', 'Stamp out a pattern into the current project.',
                                         '  Must be used with -f.') do |pattern|
        self.options[:command] = :stamp_pattern
        self.options[:pattern] = pattern
      end

      opts.on('-h', '--help') do
        self.options[:command] = :help
        self.options[:help_command] = :help
      end

      opts.on('--write-configuration', "Write the current configuration to the configuration file.") do
        self.options[:command] = :write_configuration
      end

      opts.on('--list-frameworks', "List compass frameworks available to use.") do
        self.options[:command] = :list_frameworks
      end

      opts.on('--validate', :NONE, 'Validate your project\'s compiled css. Requires Java.') do
        self.options[:command] = :validate_project
      end

      opts.on('--grid-img [DIMENSIONS]', 'Generate a background image to test grid alignment.',
                                         '  Dimension is given as <column_width>+<gutter_width>x<height>.',
                                         '  Defaults to 30+10x20. Height is optional.') do |dimensions|
        self.options[:grid_dimensions] = dimensions || "30+10"
        self.options[:command] = :generate_grid_background
      end

      opts.separator ''
      opts.separator 'Install/Pattern Options:'

      opts.on('-f FRAMEWORK', '--framework FRAMEWORK', 'Use the specified framework. Only one may be specified.') do |framework|
        self.options[:framework] = framework
      end

      opts.on('-n', '--pattern-name NAME', 'The name to use when stamping a pattern.',
                                           '  Must be used in combination with -p.') do |name|
        self.options[:pattern_name] = name
      end

      opts.on("-x", "--syntax SYNTAX", [:sass, :scss], "Specify the syntax to use when generating stylesheets.", "One of sass or scss. Defaults to scss.") do |syntax|
        self.options[:preferred_syntax] = syntax
      end

      opts.on('--rails', "Sets the app type to a rails project (same as --app rails).") do
        self.options[:project_type] = :rails
      end

      opts.on('--app APP_TYPE', 'Specify the kind of application to integrate with.') do |project_type|
        self.options[:project_type] = project_type.to_sym
      end

      opts.separator ''
      opts.separator 'Configuration Options:'

      set_project_options(opts)

      opts.separator ''
      opts.separator 'General Options:'

      set_global_options(opts)

      opts.on('--imports', :NONE, 'Emit an imports suitable for passing to the sass command-line.',
                                  '  Example: sass `compass --imports`',
                                  '  Note: Compass\'s Sass extensions will not be available.') do
        print ::Compass::Frameworks::ALL.map{|f| "-I #{f.stylesheets_directory}"}.join(' ')
        exit
      end

      opts.on('--install-dir', :NONE, 'Emit the location where compass is installed.') do
        puts ::Compass.base_directory
        exit
      end

      opts.on_tail("-v", "--version", "Print version") do
        self.options[:command] = :print_version
      end

      opts.on('--boring', :NONE, 'Turn off colorized output.') do
        self.options[:color_output] = false
      end

    end

    def do_command(command)
      command_class_name = command.to_s.split(/_/).map{|p| p.capitalize}.join('')
      command_class = eval("::Compass::Commands::#{command_class_name}")
      command_class.new(Dir.getwd, options).execute
    end

  end
end


text:
package codegen;

import java.io.PrintStream;

public class Output {
    private static final String INDENT = "  "; // two spaces

    private String indent = "";
    private PrintStream stream;
    private boolean newLine = true;

    public Output(PrintStream s) {
        stream = s;
    }

    public void increaseIndent() {
        indent += INDENT;
    }

    public void decreaseIndent() {
        indent = indent.substring(0, indent.length() - INDENT.length());
    }

    public void setOutputStream(PrintStream s) {
        stream = s;
    }

    public void write(String s) {
        stream.print((newLine ? indent : "") + s);
        newLine = false;
    }

    public void writeLine(String s) {
        stream.println((newLine ? indent : "") + s);
        newLine = true;
    }

    public void writeLine() {
        stream.println();
    }
}


text:
/**
 * @author Victor A. Martynov
 * @version $Revision: 1.3 $
 */

package org.apache.harmony.x.management.console.standalone;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * @author Victor A. Martynov
 * @version $Revision: 1.3 $
 */
class HelpDialog {

	private Shell help_SHELL = null;

	/**
	 * This method initializes error_SHELL
	 *
	 */
	HelpDialog(Shell parent) {

		help_SHELL = new Shell(parent);
		help_SHELL.setText("Help");
		help_SHELL.setSize(500, 500);
		help_SHELL.setImage(Main.resultIcon);

		Text help_TEXT = new Text(help_SHELL, SWT.BORDER);
		help_TEXT.setBounds(0, 0, 500, 470);
		help_TEXT.setText("Help Text");

		Button ok_BUTTON = new Button(help_SHELL, SWT.NONE);

		ok_BUTTON.setBounds(new Rectangle(200, 470, 100, 25));
		ok_BUTTON.setText("OK");

		ok_BUTTON.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				help_SHELL.close();
				help_SHELL.dispose();
				help_SHELL = null;
			}
		});

		help_SHELL.pack();
		help_SHELL.open();
	}
}


text:
/*********************************************************************************************
 * DAGS: Key Encapsulation using Dyadic GS Codes.                             *
 * This code is exclusively intended for submission to the NIST Post=Quantum Cryptography.    *
 * For any other usage , contact the author(s) to ascode_dimmension permission.                             *
 **********************************************************************************************
 */

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdint.h>
#include <assert.h>
#include <libkeccak.a.headers/KangarooTwelve.h>

#include "fichier.h"
#include "util.h"

#define cus_len 4 // I random pick this number to fullfill parameter

/**
 * @brief Method to perform the encapsulation using public key
 * @param pk public key from the scheme
 * @param ct
 * @param ss secret shared
 */
int encapsulation(const unsigned char *pk, unsigned char *ct, unsigned char *ss);


text:
package bioscala.graph

import scala.util.Try
import scala.collection.BitSet
import scala.annotation.tailrec

import bioscala.core._
import bioscala.filehandlers.FASTAFileReader

/*
 * TODO: The tree building implementation is naive (read: O(n**2)). The first node is added optimistically
 *  	 by adding a single edge terminated with a single leaf, and subsequent strings are added by traversing
 *   	 the existing tree and splitting any existing leaves/SuffixTreees to create appropriate new nodes. Ukkonen's
 *       algorithm might be a better choice ("online" and O(n)).
 * TODO: Need to prevent the addition of more suffixes once we've computed the annotations phase
 *  	 since it invalidates them. Or else just recalculate them every time we call LCS, which is what
 *   	 the code currently does. A related change: don't clone on LCS if we've already calculated the
 *       annotations and nothing has changed.
 */

object SuffixTree {

  /**
   * Returns a SuffixTree  representing the sequence strings in the FASTA file fName.
   *
   * NOTE: this currently assumes the FASTA file contains a DNA sequence
   */
  def fromFASTAFile(fName: String): Try[SuffixTree] = {
    val ffr = new FASTAFileReader(fName)
    ffr.enumerateFold(
    	    new SuffixTree(),
    	    (acc: SuffixTree, id: String, c: SequenceCache) => {
    	      	acc.updated(new DNASequence(id, new SequenceSourceCache(c)))
    	    }
    ).result
  }
}

/**
  * Base class for a SuffixTree node.
  */
private abstract class STNode(val path: String) {

  @tailrec
  private[graph] final def addSuffixes(chars: String, id: String, loc: Long): STNode = {
    if (chars.isEmpty) this
    else addSuffix(chars, id, loc).addSuffixes(chars.tail, id, loc + 1)
  }

  /*
   * Add a suffix to the suffix tree.
   *
   * Note: There are two implementations of this method in subclasses which are mutually recursive
   * but the recursion depth will remain shallow since the STBranch implementation is tail recursive.
   *
   */
  def addSuffix(chars: String, id: String, loc: Long): STNode

  /**
   * Return the index of the last matching character in s1 and s2.
   */
  @tailrec
  protected final def extendSuffixMatch(s1: String, s2: String, pos: Int) : Int = {
    if (s1.isEmpty || s2.isEmpty || s1.head != s2.head) pos
    else extendSuffixMatch(s1.tail, s2.tail, pos + 1)
  }

  // Annotations and helpers
  private[graph] def createSourceMap(m: Map[String, Int]) : Map[String, Int]
  private[graph] def createAnnotations(m: Map[String, Int]) : BitSet
  private[graph] def getAnnotations: BitSet
  private[graph] def cloneWithAnnotations(m: Map[String, Int]) : STNode

  // String matching methods (LCS, etc.) and related helpers
  private[graph] def findLCSCandidates(bs: BitSet, path: String, acc: List[String]) : List[String]
  private[graph] def findKMEROccurrences(k: Int, bs: BitSet, path: String, acc: List[(String, Long)]) : List[(String, Long)]
  private[graph] def findPatternMatch(acc: List[(Long, Long)], fsm: FSM[Char], curState: FSM.State, matchLen: Long) : List[(Long, Long)]

  // Helpers
  private[graph] def countDescendants(acc: Long): Long // get count of # of sources in all descendant leaves

  // Visit each leaf and return a flat list of results returned by visitf
  private[graph] def visitAllLeaves[T](acc: List[T], n: STNode, visitf: STLeaf => List[T]) : List[T] = {
	n match {
	  case st: STBranch => st.nodes.foldLeft(acc)((acc, nd) => visitAllLeaves(acc, nd, visitf) ::: acc)
	  case lf: STLeaf => visitf(lf) ::: acc
	}
  }

  // Visit each leaf and aggregate the return values using the combine function
  private[graph] def visitAllLeavesCombine[T](acc: T, n: STNode, visitF: STLeaf => T, combineF: (T, T) => T) : T = {
    n match {
      case st: STBranch => st.nodes.foldLeft(acc)((acc, nd) => combineF(visitAllLeavesCombine(acc, nd, visitF, combineF), acc))
      case lf: STLeaf => combineF(visitF(lf), acc)
    }
  }

  def lcs: List[String] = List()
  def mostFrequentKmers(k: Int): List[(String, Long)] = List()
  def substringsFromPattern[T](alphabet: Alphabet[Char], pattern: String): List[(Long, Long)] = List()

  /**
   * Display/debugging
   */
  private[graph] def showContents(n: Int) : Unit
  private[graph] def countNodes: Long
}

/**
  * SuffixTree leaf node.
  *
  */
private[graph] case class STLeaf(override val path: String, val sources: List[(String, Long)]) extends STNode(path) {

  override def addSuffix(suffix: String, id: String, loc: Long) : STNode = {
    val matchEnd = extendSuffixMatch(suffix, path, 0)
    val (pathPrefix, pathSuffix) = path.splitAt(matchEnd)
    require(pathSuffix.length != 0) // should never matched the entire leaf path due to the unique terminators (i.e. $)
    if (matchEnd == suffix.length)	// entire suffix matches, just add the new source to this leaf
      new STLeaf(path, (id, loc) :: sources)
    else {	// Split this node into a branch with a copy of this leaf as a child,
    		// and delegate the rest of the suffix to the branch
      val branch = new STBranch(pathPrefix, Vector(new STLeaf(pathSuffix, sources)))
      branch.addSuffix(suffix, id, loc)  // pass the entire suffix and let it match in the new branch
    }
  }

    private[graph] def findPatternMatch(acc: List[(Long, Long)], fsm: FSM[Char], curState: FSM.State, matchLen: Long): List[(Long, Long)] = {
    def loop(acc: List[(Long, Long)], fsm: FSM[Char], curState: FSM.State, str: List[Char], matchLen: Long) : List[(Long, Long)] = {
      if (str.isEmpty) acc
      else {
        val candidateEvents = fsm.getValidEvents(curState)
        if (candidateEvents.contains(str.head)) {
		  val nextState = fsm.getNextState(curState, str.head)
		  require(fsm.isValidState(nextState))
		  if (fsm.isAcceptState(nextState)) {
		    val newSources = sources.map(e => (e._2, matchLen + 1))
		    newSources ::: acc
		  }
		  else loop(acc, fsm, nextState, str.tail, matchLen + 1)
        }
		else acc
      }
    }
    loop(acc, fsm, curState, path.toList, matchLen)
  }

  private[graph] def createSourceMap(m: Map[String, Int]) : Map[String, Int] = {
    sources.foldLeft(m)((m: Map[String, Int], v: (String, Long)) =>
     	if (m.contains(v._1)) m else m + (v._1 -> (m.size + 1)))
  }

  private[graph] def getAnnotations: BitSet = BitSet()
  private[graph] def createAnnotations(m: Map[String, Int]) : BitSet =
		  sources.foldLeft(BitSet())((acc: BitSet, source: (String, Long)) => acc | BitSet(m(source._1)))
  private[graph] def cloneWithAnnotations(m: Map[String, Int]): STLeaf = this

  private[graph] def findLCSCandidates(b: BitSet, path: String, acc: List[String]) : List[String] = acc
  private[graph] def findKMEROccurrences(k: Int, bs: BitSet, path: String, acc: List[(String, Long)]) : List[(String, Long)] = acc

  private[graph] def countDescendants(acc: Long): Long = { // get count of # of sources in all descendant leaves
	acc + sources.length
  }

  /**
   * Display/debugging
   */
  private[graph] override val countNodes = 1L
  private[graph] override def showContents(n: Int) = {
    val pad = List[Char]().padTo(n, ' ').mkString
    println(pad + path + " Sources: " + sources.mkString)
  }
}

/**
  * SuffixTree branch node.
  *
  */
private[graph] case class STBranch(
    override val path: 	String,
    val nodes: 			Vector[STNode],
    val annotation: 	BitSet = BitSet()
  ) extends STNode(path)
{
  @tailrec
  final override def addSuffix(suffix: String, id: String, loc: Long): STBranch = {
    if (suffix.isEmpty) this
    else {
      val matchEnd = extendSuffixMatch(suffix, path, 0)
      val (pathPrefix, pathSuffix) = path.splitAt(matchEnd)
      val (newPathFragment, remainingSuffix) = suffix.splitAt(matchEnd)
	  require(newPathFragment.mkString == pathPrefix)
	  if (pathSuffix.length == 0) { // the new suffix matches the whole path fragment, delegate the remainder to children
	    require(pathPrefix == path)
        nodes.find(_.path(0) == remainingSuffix.head) match {
	      case Some(n) => // delegate adding the suffix to the matching node, and replace the old node with the new one
	    				  new STBranch(path, nodes.filter(_ != n) :+ n.addSuffix(remainingSuffix, id, loc))
	      case None	 => // add a brand new leaf for the remainder of the new suffix
	      	  		    new STBranch(path, nodes :+ new STLeaf(remainingSuffix.mkString, List((id, loc))))
	    }
	  }
	  else {
	    // the new suffix matches part of this node, split this node into a new branch that represents
	    // the common path; and delegate the remainder of the new suffix to the branch
	    require(newPathFragment.length != 0 && remainingSuffix.length != 0)
	    val newChild = new STBranch(pathSuffix, nodes)
	    val newParent = new STBranch(pathPrefix.mkString, Vector(newChild))
	    newParent.addSuffix(suffix, id, loc)
	  }
    }
  }

  // TODO: currently this code (and is downstream helpers) assume that there is only one string in the tree and they do not
  // return the string ID, though they should
  private[graph] def findPatternMatch(acc: List[(Long, Long)], fsm: FSM[Char], curState: FSM.State, matchLen: Long): List[(Long, Long)] = {
	def loop(acc: List[(Long, Long)], fsm: FSM[Char], l: List[Char], curState: FSM.State, matchLen: Long) : List[(Long, Long)] = {
	  val candidateEvents = fsm.getValidEvents(curState)
	  if (l.isEmpty) { 	// we've matched this entire path fragment, delegate to child nodes
	    val candidateNodes = nodes.filter(n => candidateEvents.contains(n.path(0)))
	    candidateNodes.foldLeft(acc)((acc, nd) => nd.findPatternMatch(acc, fsm, curState, matchLen))
	  }
	  else {
		if (candidateEvents.contains(l.head)) {
		  val nextState = fsm.getNextState(curState, l.head)
		  if (fsm.isAcceptState(nextState)) {
			val sList = visitAllLeaves(List[(String, Long)](), this, (leaf) => leaf.sources)
			 sList.foldLeft(acc)((acc, pair) => (pair._2, matchLen + 1) :: acc)
		  }
		  else loop(acc, fsm, l.tail, nextState, matchLen + 1)
		}
		else acc
	  }
	}
	loop(acc, fsm, path.toList, curState, matchLen)
  }

  /**
   * Populate a map representing all of the various sources found in the leaves of this tree, with each
   * one assigned to a unique value (used to annotate SuffixTree nodes with the list of sources represented
   * in it's descendant leaves).
   */
  private[graph] def createSourceMap(m: Map[String, Int]) : Map[String, Int] =
    nodes.foldLeft(m)((acc: Map[String, Int], n: STNode) => n.createSourceMap(acc))

  private[graph] def cloneWithAnnotations(m: Map[String, Int]): STNode = {
	val nds = nodes.map(_.cloneWithAnnotations(m))
	val bs = nodes.foldLeft(BitSet())((acc: BitSet, n: STNode) => acc | n.createAnnotations(m))
	new STBranch(path, nds, bs)
  }

  private[graph] def getAnnotations: BitSet = annotation
  private[graph] def createAnnotations(m: Map[String, Int]) : BitSet = {
	  nodes.foldLeft(BitSet())((acc: BitSet, n: STNode) => acc | n.createAnnotations(m))
  }

  /**
   * The current strategy for finding the LCS is to create a new tree with the proper annotations (each branch
   * node/SuffixTree has a list which is the union of all id/source labels seen in any leaf node descendant), then
   * traverse the new tree looking for internal nodes that have an annotation that matches the subset of targets
   * we're looking for (which is usually all of the strings used in the creation of the tree). The path to any
   * such node represents a substring common to all of those sources; the LCS is the longest of these.
   */
  override def lcs: List[String] = {
	val m = createSourceMap(Map())							// collect in a map all of the IDs that appear in any Leaf
	val bs = BitSet() ++ (1 to m.size)						// create a bitset representing all of these IDs
	val st = cloneWithAnnotations(createSourceMap(Map()))	// create a new tree containing the old tree with the annotations
	val candidates = st.findLCSCandidates(bs, "", List())	// find the list of candidate strings based on the annotations
	val mLen = candidates.foldLeft(0L)((acc: Long, s: String) => if (acc > s.length) acc else s.length)
	candidates.filter(_.length == mLen)						// and find the longest ones
  }

  /*
   * Determine if a string (represented by the target suffix tree) contains the motif described
   * by a pattern string, where [XY] in the pattern means either X or Y and {X} means any character
   * except X. Returns the location and length of the substring that matches the pattern.
   */
  override def substringsFromPattern[T](alphabet: Alphabet[Char], pattern: String) : List[(Long, Long)] = {
	val pat = pattern.toVector
	val fsm = FSM.fromPattern(pat, alphabet)
	val st = cloneWithAnnotations(createSourceMap(Map()))	// create a new tree containing the old tree with the annotations
	st.findPatternMatch(List[(Long, Long)](), fsm, 0, 0)
  }

  /*
   * Private helpers
   */
  private[graph] def findLCSCandidates(bs: BitSet, path: String, acc: List[String]) : List[String] = {
	def f(accum: List[String], nd: STNode) = nd.findLCSCandidates(bs, path + nd.path, accum)
	val newlist = if (((bs & annotation) == bs) && path.length > 0) path :: acc else acc
	nodes.foldLeft(newlist)(f)
  }

  /**
   */
  override def mostFrequentKmers(k: Int) : List[(String, Long)] = {		// return value is list of (k-mer, occurrence-count)
	val m = createSourceMap(Map())								// collect in a map all of the IDs that appear in any Leaf
	val bs = BitSet() ++ (1 to m.size)							// create a bitset representing all of these IDs
	val st = cloneWithAnnotations(createSourceMap(Map()))		// create a new tree containing the old tree with the annotations
	val candidates = st.findKMEROccurrences(k, bs, "", List())	// find the list of candidate strings based on the annotations
	val mLen = candidates.foldLeft(0L)((acc: Long, p: (String, Long)) => if (acc > p._2) acc else p._2)
	candidates.filter(_._2 == mLen)								// and find the one with the greatest # of occurrences
  }

  private[graph] def findKMEROccurrences(k: Int, bs: BitSet, path: String, acc: List[(String, Long)]) : List[(String, Long)] = {
	def f(accum: List[(String, Long)], nd: STNode) = {
	val locPath = path + nd.path
	val len = locPath.length
	  if (len < k)						// search deeper nodes
		nd.findKMEROccurrences(k, bs, locPath, accum)
	  else {
		val occurrences = nd.countDescendants(0)
		if (len > k) (locPath.take(k), occurrences) :: accum  	// grab up to k chars
		else (locPath, occurrences) :: accum					// grab the entire path
	  }
	}
	nodes.foldLeft(acc)(f)
  }

  private[graph] def countDescendants(acc: Long): Long = { // get count of # of sources in all descendant leaves
	nodes.foldLeft(acc)((accum: Long, nd: STNode) => nd.countDescendants(accum))
  }

  /**
   * Display/debugging
   */
  override def countNodes: Long = nodes.foldLeft(1L)((acc: Long, nd: STNode) => acc + 1L + nd.countNodes)
  override private[graph] def showContents(n: Int) : Unit = {
    val pad = List[Char]().padTo(n, ' ').mkString
	println(pad + path)
	for (nd <- nodes) {
	  nd.showContents(n + 1)
	}
  }
}

// TODO: implement a suffix array and/or us a packed cache of some kind to store the path strings
// as the current implementation is unrealistic for actual sequences that are large.
/**
 * Generalized Suffix Tree.
 *
 * Naive implementation of a Generalized Suffix Tree for multiple strings. Uses McCreight-style path
 * compression to eliminate internal nodes with a single character path.
 *
 * NOTE:
 *    Each string in the tree must be terminated (by the caller!) with a character that is:
 *
 *  	1) unique (no other string in the tree can be terminated with that character) and:
 *   	2) the character should not be found in the alphabet from which the strings are otherwise
 *         drawn (or put another way, the termination character should not appear anywhere else
 *         in any of the strings)
 *
 * Example usage:
 *
 *  	val st0 = new graph.SuffixTree
 *  	val st1 = st0.updated("GATTACA$", "id1")
 *  	val st2 = st1.updated("TAGACCA#", "id2")
 *   	val lst = st3.LongestCommonSubstring // Longest Common Substring (as a list - there may be more than one)
 *
 */
class SuffixTree protected(private val root: STNode, val terminator: Int) {
  def this() = this(new STBranch("", Vector()), 33) // 33 is the beginning of the ascii range used for auto terminator generation
  def updated(str: String, id: String): SuffixTree = new SuffixTree(root.addSuffixes(str, id, 0), terminator)
  def updated(seq: Sequence): SuffixTree = {
	// TODO: since the sequences in FASTA files don't have unique termination characters (which are required
    // by the suffix tree algorithm), this is a hack to auto-generate a terminator from the ascii range from 33-47
    // After that, it just throws..
    if (terminator > 47)
      throw new java.lang.IllegalStateException("Exceeded limit of auto termination-character-generation hack")
    else
      new SuffixTree(root.addSuffixes(seq.asString(None) + terminator.toChar, seq.id, 0), terminator+1)
  }

  def lcs: List[String] = root.lcs
  def mostFrequentKmers(k: Int): List[(String, Long)] = root.mostFrequentKmers(k)
  def matchPattern[T](alphabet: Alphabet[Char], pattern: String): List[(Long, Long)] = {
    root.substringsFromPattern(alphabet, pattern)
  }

  def display: Unit = root.showContents(0)
}


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 9.5.10
description: >
    [[Delete]] (P)

    11. If booleanTrapResult is false, return false.
flags: [onlyStrict]
features: [Reflect]
---*/

var p = new Proxy({}, {
    deleteProperty: function() {
        return false;
    }
});

assert.sameValue(Reflect.deleteProperty(p, "attr"), false);


text:
import datetime

import pytz
import unittest2

from st2common.util import date as date_utils

class DateUtilsTestCase(unittest2.TestCase):
    def test_get_datetime_utc_now(self):
        date = date_utils.get_datetime_utc_now()
        self.assertEqual(date.tzinfo.tzname(None), 'UTC')

    def test_add_utc_tz(self):
        dt = datetime.datetime.utcnow()
        self.assertIsNone(dt.tzinfo)
        dt = date_utils.add_utc_tz(dt)
        self.assertIsNotNone(dt.tzinfo)
        self.assertEqual(dt.tzinfo.tzname(None), 'UTC')

    def test_convert_to_utc(self):
        date_without_tz = datetime.datetime.utcnow()
        self.assertEqual(date_without_tz.tzinfo, None)
        result = date_utils.convert_to_utc(date_without_tz)
        self.assertEqual(result.tzinfo.tzname(None), 'UTC')

        date_with_pdt_tz = datetime.datetime(2015, 10, 28, 10, 0, 0, 0)
        date_with_pdt_tz = date_with_pdt_tz.replace(tzinfo=pytz.timezone('US/Pacific'))
        self.assertEqual(date_with_pdt_tz.tzinfo.tzname(None), 'US/Pacific')

        result = date_utils.convert_to_utc(date_with_pdt_tz)
        self.assertEqual(str(result), '2015-10-28 17:53:00+00:00')
        self.assertEqual(result.tzinfo.tzname(None), 'UTC')

    def test_parse(self):
        date_str_without_tz = 'January 1st, 2014 10:00:00'
        result = date_utils.parse(value=date_str_without_tz)
        self.assertEqual(str(result), '2014-01-01 10:00:00+00:00')
        self.assertEqual(result.tzinfo.tzname(None), 'UTC')

        # preserve original tz
        date_str_with_tz = 'January 1st, 2014 10:00:00 +07:00'
        result = date_utils.parse(value=date_str_with_tz, preserve_original_tz=True)
        self.assertEqual(str(result), '2014-01-01 10:00:00+07:00')
        self.assertEqual(result.tzinfo.utcoffset(result), datetime.timedelta(hours=7))

        # convert to utc
        date_str_with_tz = 'January 1st, 2014 10:00:00 +07:00'
        result = date_utils.parse(value=date_str_with_tz, preserve_original_tz=False)
        self.assertEqual(str(result), '2014-01-01 03:00:00+00:00')
        self.assertEqual(result.tzinfo.utcoffset(result), datetime.timedelta(hours=0))
        self.assertEqual(result.tzinfo.tzname(None), 'UTC')


text:
/**
 * Do something
 */
export default function demo (input: string): number {

  /* typecheck: ignore statement */
  let foo: string = 123;

  /* typecheck: ignore statement */
  foo = 123;

  return input.length * 2;
}

// typecheck: ignore statement
function badFnLine (input: string = 123): boolean {
  return input;
}

/* typecheck: ignore statement */
function badFnBlock (input: string = 123): boolean  {
  return input;
}


text:
__author__ = 'jamh'

import pandas
import pyspark
from Orange.widgets import widget, gui, settings
from PyQt4.QtGui import QSizePolicy

class OWSparkToPandas(widget.OWWidget):
    priority = 10
    name = "to Pandas"
    description = "Convert Spark dataframe to Pandas"
    icon = "../icons/spark.png"

    inputs = [("DataFrame", pyspark.sql.DataFrame, "get_input", widget.Default)]
    outputs = [("Dataframe", pandas.DataFrame, widget.Dynamic)]
    settingsHandler = settings.DomainContextHandler()

    def __init__(self):
        super().__init__()
        gui.label(self.controlArea, self, "Spark->Pandas:")
        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)

    def get_input(self, obj):
        self.send("Dataframe", obj.toPandas())


text: Aplicativo para gerenciamento de estoque e posologia de remédios.


text:
package io.gravitee.am.service.exception;

/**
 * @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com)
 * @author GraviteeSource Team
 */
public class EntrypointNotFoundException extends AbstractNotFoundException {

    private final String entrypoint;

    public EntrypointNotFoundException(String entrypoint) {
        this.entrypoint = entrypoint;
    }

    @Override
    public String getMessage() {
        return "Entrypoint [" + entrypoint + "] can not be found.";
    }
}


text:
"""
Common functions for tests
"""
__author__ = 'Dan Gunter <dkgunter@lbl.gov>'
__date__ = '10/29/13'

# Stdlib
import json
import logging
import os
import subprocess
import sys
import tempfile
import traceback
import unittest
# Third-party
from mongomock import MongoClient
import pymongo
# Package
from matgendb.query_engine import QueryEngine
from matgendb.builders.incr import CollectionTracker

class MockQueryEngine(QueryEngine):
    """Mock (fake) QueryEngine, unless a real connection works.
    """
    def __init__(self, host="127.0.0.1", port=27017, database="vasp",
                 user=None, password=None, collection="tasks",
                 aliases_config=None, default_properties=None):
        try:
            QueryEngine.__init__(self, host=host, port=port, database=database,
                                 user=user, password=password, collection=collection,
                                 aliases_config=aliases_config,
                                 default_properties=default_properties)
            print("@@ connected to real Mongo")
            return  # actully connected! not mocked..
        except:
            pass
        self.connection = MongoClient(self.host, self.port)
        self.db = self.connection[database]
        self._user, self._password = user, password
        self.host = host
        self.port = port
        self.database_name = database
        # colllection name is now a @property. the setter will set "self.collection" internally
        self.collection_name = collection
        self.set_aliases_and_defaults(aliases_config=aliases_config,
                                      default_properties=default_properties)

# -----------------------------------
# Component test classes / functions
# -----------------------------------

def get_component_logger(name, strm=sys.stdout):
    log = logging.getLogger(name)
    if 'TEST_DEBUG' in os.environ:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    _h = logging.StreamHandler(strm)
    log.addHandler(_h)
    return log

class ComponentTest(unittest.TestCase):
    DB = 'testdb'
    SRC = 'source'
    DST = 'dest'

    MGBUILD_CMD = ["mgbuild", "run"]

    def setUp(self):
        self.db = self.connect(True)
        self.src, self.dst = self.db[self.SRC], self.db[self.DST]
        self.src_conf, self.dst_conf = self.create_configs()

    def mgbuild(self, args):
        try:
            s = subprocess.check_output(self.MGBUILD_CMD + args,
                                        stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as err:
            print("ERROR: {}".format(err.output))
            raise
        return s

    def connect(self, clear=False):
        """Connect to Mongo DB

        :return: pymongo Database
        """
        c = pymongo.MongoClient()
        db = c[self.DB]
        if clear:
            for coll in self.SRC, self.DST:
                db[coll].remove()
                tcoll = coll + '.' + CollectionTracker.TRACKING_NAME
                db[tcoll].remove() # remove tracking as well
        return db

    def get_record(self, i):
        return {
            "number": i,
            "data": [
                1, 2, 3
            ],
            "name": "mp-{:d}".format(i)
        }

    def add_records(self, coll, n):
        for i in range(n):
            coll.insert(self.get_record(i))

    def create_configs(self):
        base = {"host": "localhost",
                "port": 27017,
                "database": self.DB,
                "collection": None}
        files = []
        for coll in (self.SRC, self.DST):
            f = tempfile.NamedTemporaryFile(suffix=".json")
            base['collection'] = coll
            json.dump(base, f)
            f.flush()
            files.append(f)
        return files

    def tearDown(self):
        pass

    def run_command(self, args, options):
        """Run the command-line given by the list
        in `args`, adding the dictionary given by
        options as long-form --{key}=value pairs.
        """
        for key, value in options:
            args.append("--{}".format(key))
            if value:
                args.append(value)
        return subprocess.call(args)


text:
layout: post
title: "Amazon S3 has two types of redirects"
description: ""
categories : development
sub_categories : ""
date: 2015-10-13
tags: []
comments: true
share: true
---

In the time between when I read up on S3 redirects and when I published a post
on what I had learned, Amazon created a second way to redirect parts of S3
websites.

The first way redirects a single URL at a time. These are the redirects I
already knew about, which were introduced last October. They are created by
attaching a special piece of metadata to an S3 object.

The second way was introduced in December, and redirects based on prefix. This
is probably most useful for redirecting entire folders. You can either rewrite
a folder name, preserving the rest of the URL, or redirect the entire folder
to a single URL. This kind of redirect is created by uploading an XML document
containing all of the redirect rules. You can create and upload the XML,
without actually seeing any XML, by descending through boto's hierarchy until
you find boto.s3.bucket.Bucket.configure_website.

출처 : http://nathangrigg.net/2013/02/s3-redirects-again/

스택오버플로우 질문 : http://stackoverflow.com/questions/24521396/map-aws-s3-bucket-to-
no-subdomain-no-www-nothing