text:
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import classnames from 'classnames'
import divider from '../divider/divider'
const prefixCls = divider.prefixCls

class Textarea extends Component {

    constructor(props) {
        super(props)
        this.state = {
            Changeed: false
        }
    }

    handleChange(e) {
        const { onChange } = this.props;
        this.setState({ clicked: true })
        clearTimeout(this.timeout);
        this.timeout = window.setTimeout(() => this.setState({ clicked: false }), 500)
        if (onChange) {
            onChange(e.target.value, e)
        }
    }

    render() {
        const { type, size, loading, className, htmlType, children, icon, ghost, ...others, } = this.props;
        let getClass = classnames(`${prefixCls}-input`, className, {
            [`${prefixCls}-input-${type}`]: type,
            [`${prefixCls}-input-${size}`]: size,
            [`${prefixCls}-input-${ghost}`]: ghost,
            [`${prefixCls}-input-${loading}`]: loading,
            [`${prefixCls}-input-clicked`]: this.state.clicked,
        })
        return (
            <textarea
                type={type || 'text'}
                className={getClass}
                onChange={(e) => {
                    this.handleChange(e)
                }}
                {...others}
            ></textarea>
        )
    }

}

export default Textarea


text:
require 'net/http'
require 'json'
require 'gruff'
require 'octokit'

projects = settings.projects || []

SCHEDULER.every '1h' do
    client = Octokit::Client.new(:access_token => settings.github['token'])
    user = client.user
    user.login
    languages_url = URI("https://api.github.com/repos/" + projects.first['repo'] + "/languages")
    ruby = python = javascript = css = shell = 0
    #Get data for each language
    Net::HTTP.start(languages_url.host, languages_url.port, :use_ssl => (languages_url.scheme == 'https')) do |http|
        response = http.request(Net::HTTP::Get.new(languages_url.request_uri))
        data = JSON.parse(response.body)
        ruby = ruby + (data['Ruby']).to_i
        python = python + (data['Python']).to_i
        javascript = javascript + (data['JavaScript']).to_i
        css = css + (data['CSS']).to_i
        shell = shell + (data['Shell']).to_i
        end

    #Begin constructing actual g
    #First let's try making a dataset
    @dataset = [
        [:Ruby, [ruby]],
        [:Python, [python]],
        [:JavaScript, [javascript]],
        [:CSS, [css]],
        [:Shell, [shell]]
    ]
    g = Gruff::Pie.new
    g.title = nil
    g.theme = {
    :colors =>['#A11C03', '#9DB61E', '#2C3E50', '#F39C12'],
    :marker_color => '#000',
    :background_colors => ['#00B0C6', '#00B0C6']
    }
    #g.hide_legend = true
    @dataset.each do |data|
        g.data(data[0], data[1])
    end
    g.write("assets/images/piechart.png")
    send_event('languages', {})
    projects.rotate!
end

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
Section: email-forgot-password
Language: Czech
Translator: SierraHawk <sierrahawk@outlook.com>
*/

$translations = array(
    'email' => 'Žádost o vyřízení nového hesla pro "{$user}"

Vaše nové heslo je {$newData}

Potvrďte prosím tuto změnu kliknutím na následující odkaz:

{$mailLink}

Pokud jste to nebyly vy, kdo požádal o nové heslo na webových stránkách db4free.net, ignorujte prosím tento e-mail!

S přáním pěkného dne,

Tým db4free.net
http://www.db4free.net',
);
?>


text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-b299888d-9431-4d05-aa33-4e871dfeb3b7" version="1.1.1" timestamp="2014-08-22T15:28:00+00:00">
    <stix:STIX_Header>
        <stix:Title>Notes: Modeling as misuse and Integrity/Authenticity. There was no data breached from Mississippi state office. The defendants would provide stolen or purchased birth certificates and SSN cards to acquire licenses for illegals.</stix:Title>
    </stix:STIX_Header>
    <stix:Incidents>
        <stix:Incident id="example:incident-1f4f67e6-03e0-4cb3-932a-02275742c0a5" timestamp="2014-08-22T15:28:00+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>2 state employees are charged with identity theft. Using access to driver's license bureau, they sold authentic birth certificates and Social Security cards to receive Mississippi driver's licenses and state IDs.</incident:Title>
            <incident:External_ID source="VERIS">333BA6BD-3191-46F4-99F4-82F5ADF5C6D1</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="month">2013-11-01T00:00:00</incident:Initial_Compromise>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Spitler</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">MIssissippi Department of Public Safety</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>US</xal:NameElement>
      </xal:Country>
      <xal:AdministrativeArea xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>MS</xal:NameElement>
      </xal:AdministrativeArea>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Desktop</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property>
                            <incident:Description_Of_Effect>Fraudulent transaction; Notes:Issuance of driver's license to illegal immigrants with stolen identities. </incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Impact_Assessment>
                <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification>
            </incident:Impact_Assessment>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-616c9a6c-b6b2-4348-b8f7-61b6ef563c51" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-6b51fb70-a6af-4693-b372-1eb8884b1181" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Unknown</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://www.knoe.com/story/26331823/2-ex-state-workers-plead-guilty-to-id-theft-charge</stixCommon:Reference>
                    <stixCommon:Reference>http://www.wtok.com/home/headlines/2-public-safety-employees-arrested-247560671.html#.Uw-BYns3IcM.facebook</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-616c9a6c-b6b2-4348-b8f7-61b6ef563c51" timestamp="2014-12-22T16:24:29.375000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>Unknown</xal:NameElement>
      </xal:Country>
    </xpil:Address>
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>MX</xal:NameElement>
      </xal:Country>
    </xpil:Address>
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>US</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </ta:Identity>
            <ta:Type timestamp="2014-12-22T16:24:29.375000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Type>
            <ta:Type timestamp="2014-12-22T16:24:29.375000+00:00">
                <stixCommon:Value>Unaffiliated</stixCommon:Value>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:24:29.375000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:MotivationVocab-1.1">Financial or Economic</stixCommon:Value>
            </ta:Motivation>
        </stix:Threat_Actor>
        <stix:Threat_Actor id="example:threatactor-6b51fb70-a6af-4693-b372-1eb8884b1181" timestamp="2014-12-22T16:24:29.375000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Type timestamp="2014-12-22T16:24:29.375000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:ThreatActorTypeVocab-1.0">Insider Threat</stixCommon:Value>
                <stixCommon:Description>End-user</stixCommon:Description>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:24:29.375000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:MotivationVocab-1.1">Financial or Economic</stixCommon:Value>
            </ta:Motivation>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
function render_visualize_times() {
    google_visualization_load(render_visualize_times_loaded);
}

function render_visualize_times_loaded() {
    row_selector($('#rowPrefixDrop'), {startRow: $('#startRow'), stopRow: $('#stopRow')});
    function drawYears(hist) {
        var data = google.visualization.arrayToDataTable([['Year', 'Count']].concat(hist));
        new google.visualization.ColumnChart(document.getElementById('histYear')).draw(data, {title:"Histogram (Year)", width:600, height:400, vAxis: {title: "Count"}, hAxis: {title: "Year"}});
    }
    function drawMonths(hist) {
        var data = google.visualization.arrayToDataTable([['Month', 'Count']].concat(hist));
        new google.visualization.ColumnChart(document.getElementById('histMonth')).draw(data, {title:"Histogram (Month)", width:600, height:400, vAxis: {title: "Count"}, hAxis: {title: "Month"}});
    }
    function drawHours(hist) {
        var data = google.visualization.arrayToDataTable([['Hour', 'Count']].concat(hist));
        new google.visualization.ColumnChart(document.getElementById('histHour')).draw(data, {title:"Histogram (Hour)", width:600, height:400, vAxis: {title: "Count"}, hAxis: {title: "Hour"}});
    }
    function drawDays(hist) {
        var data = google.visualization.arrayToDataTable([['Day', 'Count']].concat(hist));
        new google.visualization.ColumnChart(document.getElementById('histDay')).draw(data, {title:"Histogram (Day)", width:600, height:400, vAxis: {title: "Count"}, hAxis: {title: "Day"}});
    }
    function dataToHist(data) {
        var hist = {};
        _.each(data, function (x) {
            var y = 0;
            if (_.has(hist, x)) {
                y = hist[x];
            }
            hist[x] = y + 1;
        });
        return hist;
    }
    function dataToListHist(data) {
        return _.map(_.pairs(dataToHist(data)), function (x) {return [Number(x[0]), x[1]]}).sort();
    }
    $('#runButton').click(function () {
        var timeColumn = 'meta:dateupload';
        images = new PicarusRows([], {'table': 'images'});
        function time_success(row, columns) {
            columns.row = row;
            images.add(new PicarusRow(columns));
        }
        function time_done() {
            years = [];
            months = [];
            hours = [];
            days = [];
            // TODO: FInish visual
            images.each(function (x) {
                var curTime = Number(x.get(timeColumn));
                var curDate = new Date(0);
                curDate.setUTCSeconds(curTime);
                years.push(curDate.getFullYear());
                months.push(curDate.getMonth());
                hours.push(curDate.getHours());
                days.push(curDate.getDay());
            });
            drawYears(dataToListHist(years));
            drawMonths(dataToListHist(months));
            drawHours(dataToListHist(hours));
            drawDays(dataToListHist(days));
        }
        PICARUS.scanner("images", unescape($('#startRow').val()), unescape($('#stopRow').val()), {success: time_success, done: time_done, columns: [timeColumn]});
    })
}


text:
<?xml version="1.0"?>
<!-- initial phpunit configuration file, that you can modify for your project needs -->
<phpunit cacheTokens="true"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         stopOnError="true"
         stopOnFailure="true"
         stopOnIncomplete="false"
         stopOnSkipped="false"
         strict="false"
         verbose="false"
         bootstrap="app/code/community/EcomDev/PHPUnit/bootstrap.php">
    <listeners>
        <listener file="app/code/community/EcomDev/PHPUnit/Test/Listener.php" class="EcomDev_PHPUnit_Test_Listener" />
    </listeners>
    <testsuite name="Magento Test Suite">
        <file>app/code/community/EcomDev/PHPUnit/Test/Suite.php</file>
    </testsuite>
    <filter>
        <blacklist>
            <!-- Exclude Magento Core files from code coverage -->
            <directory suffix=".php">app/code/core</directory>
            <!-- Exclude EcomDev_PHPUnit classes from code coverage -->
            <directory suffix=".php">app/code/community/EcomDev/PHPUnitTest</directory>
            <directory suffix=".php">lib/Spyc</directory>
            <directory suffix=".php">lib/vfsStream</directory>
            <!-- Exclude Mage.php file from code coverage -->
            <file>app/Mage.php</file>
            <!-- Exclude template files -->
            <directory suffix=".phtml">app/design</directory>
            <!-- Exclude Varien & Zend libraries -->
            <directory suffix=".php">lib/Varien</directory>
            <directory suffix=".php">lib/Zend</directory>
            <directory suffix=".php">../../vendor/</directory>
        </blacklist>
    </filter>
</phpunit>


text:
Controls:

A - Block.
D - Attack.
Arrow Keys - Move.
F - Special Attack.
P - Fullscreen.
Esc - Exit Fullscreen.

Normal Mode.
Recommended for 99.9% of players.
Best experiance.

Extreme Mode. (Original Mode)
Only play once you have beaten Normal Mode.
Only for advanced players.
Far more enemies, traps and no extra reward.
Just imposibly hard.

Choose a mode.

 click to run normal mode

 click to run original mode


text:
package io.crate.analyze;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import io.crate.sql.tree.*;

import java.util.Locale;
import java.util.Set;

public class SubscriptVisitor extends AstVisitor<Void, SubscriptContext> {

    private static final Long MAX_VALUE = Integer.MAX_VALUE + 1L;
    private static final Set<Class<?>> SUBSCRIPT_NAME_CLASSES = ImmutableSet.<Class<?>>of(
            SubscriptExpression.class,
            QualifiedNameReference.class,
            FunctionCall.class,
            ArrayLiteral.class
    );
    private static final Set<Class<?>> SUBSCRIPT_INDEX_CLASSES = ImmutableSet.<Class<?>>of(
            StringLiteral.class,
            LongLiteral.class,
            NegativeExpression.class,
            ParameterExpression.class
    );

    @Override
    protected Void visitSubscriptExpression(SubscriptExpression node, SubscriptContext context) {
        Preconditions.checkArgument(
                node.index() == null
                        || SUBSCRIPT_INDEX_CLASSES.contains(node.index().getClass()),
                "index of subscript has to be a string or long literal or parameter. " +
                "Any other index expression is not supported"
        );
        Preconditions.checkArgument(
                SUBSCRIPT_NAME_CLASSES.contains(node.name().getClass()),
                "An expression of type %s cannot have an index accessor ([])",
                node.name().getClass().getSimpleName()
        );
        if (node.index() != null) {
            node.index().accept(this, context);
        }
        node.name().accept(this, context);
        return null;
    }

    @Override
    protected Void visitQualifiedNameReference(QualifiedNameReference node, SubscriptContext context) {
        context.qName(node.getName());
        return null;
    }

    @Override
    protected Void visitStringLiteral(StringLiteral node, SubscriptContext context) {
        validateNestedArrayAccess(context);
        context.add(node.getValue());
        return null;
    }

    @Override
    public Void visitParameterExpression(ParameterExpression node, SubscriptContext context) {
        throw new UnsupportedOperationException("Parameter substitution is not supported in subscript");
    }

    @Override
    public Void visitArrayLiteral(ArrayLiteral node, SubscriptContext context) {
        Preconditions.checkArgument(
                context.index() != null,
                "Array literals can only be accessed via numeric index.");
        context.expression(node);
        return null;
    }

    @Override
    protected Void visitLongLiteral(LongLiteral node, SubscriptContext context) {
        validateNestedArrayAccess(context);
        long value = node.getValue();

        if (value < 1 || value > MAX_VALUE) {
            throw new UnsupportedOperationException(
                    String.format(Locale.ENGLISH, "Array index must be in range 1 to %s",
                            MAX_VALUE));
        }
        context.index((int) value);
        return null;
    }

    @Override
    protected Void visitNegativeExpression(NegativeExpression node, SubscriptContext context) {
        throw new UnsupportedOperationException(
                String.format(Locale.ENGLISH, "Array index must be in range 1 to %s",
                        MAX_VALUE));
    }

    @Override
    protected Void visitFunctionCall(FunctionCall node, SubscriptContext context) {
        context.expression(node);
        return null;
    }

    @Override
    protected Void visitExpression(Expression node, SubscriptContext context) {
        throw new UnsupportedOperationException(String.format(
                "Expression of type %s is not supported within a subscript expression",
                node.getClass()));
    }

    private void validateNestedArrayAccess(SubscriptContext context) {
        if (context.index() != null) {
            throw new UnsupportedOperationException("Nested array access is not supported");
        }
    }
}


text:
'use strict';

var _templateObject = _taggedTemplateLiteral(['\n      color: ', ';\n    '], ['\n      color: ', ';\n    ']),
    _templateObject2 = _taggedTemplateLiteral(['\n      background: ', ';\n    '], ['\n      background: ', ';\n    ']),
    _templateObject3 = _taggedTemplateLiteral(['\n      color: ', ';\n      z-index: ', 'px;\n    '], ['\n      color: ', ';\n      z-index: ', 'px;\n    ']);

var _mochaJsdom = require('mocha-jsdom');

var _mochaJsdom2 = _interopRequireDefault(_mochaJsdom);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _enzyme = require('enzyme');

var _utils = require('./utils');

var _ThemeProvider = require('../models/ThemeProvider');

var _ThemeProvider2 = _interopRequireDefault(_ThemeProvider);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

var styled = void 0;

describe('theming', function () {
  beforeEach(function () {
    styled = (0, _utils.resetStyled)();
  });

  it('should inject props.theme into a styled component', function () {
    var Comp = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });
    var theme = { color: 'black' };
    (0, _enzyme.render)(_react2.default.createElement(
      _ThemeProvider2.default,
      { theme: theme },
      _react2.default.createElement(Comp, null)
    ));
    (0, _utils.expectCSSMatches)('.a { color: ' + theme.color + '; }');
  });

  it('should inject props.theme into a styled component multiple levels deep', function () {
    var Comp = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });
    var theme = { color: 'black' };
    (0, _enzyme.render)(_react2.default.createElement(
      _ThemeProvider2.default,
      { theme: theme },
      _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(Comp, null)
        )
      )
    ));
    (0, _utils.expectCSSMatches)('.a { color: ' + theme.color + '; }');
  });

  it('should properly allow a component to fallback to its default props when a theme is not provided', function () {
    var Comp1 = styled.div(_templateObject, function (props) {
      return props.theme.test.color;
    });

    Comp1.defaultProps = {
      theme: {
        test: {
          color: "purple"
        }
      }
    };
    (0, _enzyme.render)(_react2.default.createElement(
      'div',
      null,
      _react2.default.createElement(Comp1, null)
    ));
    (0, _utils.expectCSSMatches)('.a { color: purple; }');
  });

  it('should properly set the theme with an empty object when no teme is provided and no defaults are set', function () {
    var Comp1 = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });
    (0, _enzyme.render)(_react2.default.createElement(
      'div',
      null,
      _react2.default.createElement(Comp1, null)
    ));
    (0, _utils.expectCSSMatches)('.a { color: ; }');
  });

  it('should only inject props.theme into styled components within its child component tree', function () {
    var Comp1 = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });
    var Comp2 = styled.div(_templateObject2, function (props) {
      return props.theme.color;
    });

    var theme = { color: 'black' };
    (0, _enzyme.render)(_react2.default.createElement(
      'div',
      null,
      _react2.default.createElement(
        _ThemeProvider2.default,
        { theme: theme },
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(Comp1, null)
        )
      ),
      _react2.default.createElement(Comp2, null)
    ));
    (0, _utils.expectCSSMatches)('.a { color: ' + theme.color + '; } .b { background: ; }');
  });

  it('should inject props.theme into all styled components within the child component tree', function () {
    var Comp1 = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });
    var Comp2 = styled.div(_templateObject2, function (props) {
      return props.theme.color;
    });
    var theme = { color: 'black' };
    (0, _enzyme.render)(_react2.default.createElement(
      _ThemeProvider2.default,
      { theme: theme },
      _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(Comp1, null)
        ),
        _react2.default.createElement(Comp2, null)
      )
    ));
    (0, _utils.expectCSSMatches)('.a { color: ' + theme.color + '; } .b { background: ' + theme.color + '; }');
  });

  it('should inject new CSS when the theme changes', function () {
    var Comp = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });
    var originalTheme = { color: 'black' };
    var newTheme = { color: 'blue' };
    var theme = originalTheme;
    // Force render the component
    var renderComp = function renderComp() {
      (0, _enzyme.render)(_react2.default.createElement(
        _ThemeProvider2.default,
        { theme: theme },
        _react2.default.createElement(Comp, null)
      ));
    };
    renderComp();
    var initialCSS = (0, _utils.expectCSSMatches)('.a { color: ' + theme.color + '; }');
    // Change the theme
    theme = newTheme;
    renderComp();
    (0, _utils.expectCSSMatches)(initialCSS + '.b { color: ' + newTheme.color + '; }');
  });
});

describe('theming (jsdom)', function () {
  (0, _mochaJsdom2.default)();

  beforeEach(function () {
    styled = (0, _utils.resetStyled)();
  });

  it('should properly render with the same theme from default props on re-render', function () {
    var Comp1 = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });

    Comp1.defaultProps = {
      theme: {
        color: "purple"
      }
    };
    var wrapper = (0, _enzyme.mount)(_react2.default.createElement(Comp1, null));
    (0, _utils.expectCSSMatches)('.a { color: purple; }');

    wrapper.update();
    (0, _utils.expectCSSMatches)('.a { color: purple; }');
  });

  it('should properly update style if theme is changed', function () {
    var Comp1 = styled.div(_templateObject, function (props) {
      return props.theme.color;
    });

    Comp1.defaultProps = {
      theme: {
        color: "purple"
      }
    };
    var wrapper = (0, _enzyme.mount)(_react2.default.createElement(Comp1, null));
    (0, _utils.expectCSSMatches)('.a { color: purple; }');

    wrapper.setProps({ theme: { color: 'pink' } });
    (0, _utils.expectCSSMatches)('.a { color: purple; }.b { color: pink; }');
  });

  it('should properly update style if props used in styles is changed', function () {
    var Comp1 = styled.div(_templateObject3, function (props) {
      return props.theme.color;
    }, function (props) {
      return props.zIndex;
    });

    Comp1.defaultProps = {
      theme: {
        color: "purple"
      },
      zIndex: 0
    };
    var wrapper = (0, _enzyme.mount)(_react2.default.createElement(Comp1, null));
    var expectedStyles = '.a { color: purple; z-index: 0px; }';
    (0, _utils.expectCSSMatches)(expectedStyles);

    wrapper.setProps({ theme: { color: 'pink' } });
    expectedStyles = expectedStyles + '.b { color: pink; z-index: 0px; }';
    (0, _utils.expectCSSMatches)(expectedStyles);

    wrapper.setProps({ zIndex: 1 });
    (0, _utils.expectCSSMatches)(expectedStyles + '.c { color: pink; z-index: 1px; }');
  });
});


text:
import { module } from 'angular';

import { ApplicationDataSourceRegistry } from 'core/application/service/ApplicationDataSourceRegistry';
import { DELIVERY_KEY } from 'core/application/nav/defaultCategories';
import { EntityTagsReader } from 'core/entityTag/EntityTagsReader';
import { EXECUTION_SERVICE } from './service/execution.service';
import { PipelineConfigService } from './config/services/PipelineConfigService';
import { SETTINGS } from 'core/config/settings';
import { CLUSTER_SERVICE } from 'core/cluster/cluster.service';

export const CORE_PIPELINE_PIPELINE_DATASOURCE = 'spinnaker.core.pipeline.dataSource';
export const name = CORE_PIPELINE_PIPELINE_DATASOURCE; // for backwards compatibility
module(CORE_PIPELINE_PIPELINE_DATASOURCE, [EXECUTION_SERVICE, CLUSTER_SERVICE]).run([
  '$q',
  'executionService',
  'clusterService',
  function ($q, executionService, clusterService) {
    const addExecutions = (application, executions) => {
      executionService.transformExecutions(application, executions, application.executions.data);
      return $q.when(executionService.addExecutionsToApplication(application, executions));
    };

    const loadExecutions = (application) => {
      return executionService.getExecutions(application.name, application);
    };

    const loadPipelineConfigs = (application) => {
      const pipelineLoader = PipelineConfigService.getPipelinesForApplication(application.name);
      const strategyLoader = PipelineConfigService.getStrategiesForApplication(application.name);
      return $q
        .all([pipelineLoader, strategyLoader])
        .then(([pipelineConfigs, strategyConfigs]) => ({ pipelineConfigs, strategyConfigs }));
    };

    const addPipelineConfigs = (application, data) => {
      application.strategyConfigs = { data: data.strategyConfigs };
      return $q.when(data.pipelineConfigs);
    };

    const loadRunningExecutions = (application) => {
      return executionService.getRunningExecutions(application.name);
    };

    const addRunningExecutions = (application, data) => {
      executionService.transformExecutions(application, data);
      return $q.when(data);
    };

    const runningExecutionsLoaded = (application) => {
      clusterService.addExecutionsToServerGroups(application);
      executionService.mergeRunningExecutionsIntoExecutions(application);
      application.getDataSource('serverGroups').dataUpdated();
    };

    const executionsLoaded = (application) => {
      addExecutionTags(application);
      executionService.removeCompletedExecutionsFromRunningData(application);
    };

    const addExecutionTags = (application) => {
      EntityTagsReader.addTagsToExecutions(application);
    };

    const addPipelineTags = (application) => {
      EntityTagsReader.addTagsToPipelines(application);
    };

    if (SETTINGS.feature.pipelines !== false) {
      ApplicationDataSourceRegistry.registerDataSource({
        optional: true,
        primary: true,
        icon: 'fa fa-xs fa-fw fa-list',
        iconName: 'spMenuPipelines',
        key: 'executions',
        label: 'Pipelines',
        category: DELIVERY_KEY,
        sref: '.pipelines.executions',
        activeState: '**.pipelines.**',
        loader: loadExecutions,
        onLoad: addExecutions,
        afterLoad: executionsLoaded,
        lazy: true,
        badge: 'runningExecutions',
        description: 'Orchestrated deployment management',
        defaultData: [],
      });

      ApplicationDataSourceRegistry.registerDataSource({
        key: 'pipelineConfigs',
        loader: loadPipelineConfigs,
        onLoad: addPipelineConfigs,
        afterLoad: addPipelineTags,
        lazy: true,
        visible: false,
        defaultData: [],
      });

      ApplicationDataSourceRegistry.registerDataSource({
        key: 'runningExecutions',
        visible: false,
        loader: loadRunningExecutions,
        onLoad: addRunningExecutions,
        afterLoad: runningExecutionsLoaded,
        defaultData: [],
      });
    }
  },
]);


text:
//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// 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.
//
'use strict';

var should = require('should');
var utils = require('../../../../lib/util/utils');
var CLITest = require('../../../framework/arm-cli-test');
var testPrefix = 'arm-cli-powerbiembedded-tests';

var requiredEnvironment = [
  { name: 'AZURE_POWERBIEMBEDDED_TEST_LOCATION', defaultValue: 'southcentralus' },
  { name: 'AZURE_POWERBIEMBEDDED_TEST_SKU', defaultValue: 'S1' },
  { name: 'AZURE_POWERBIEMBEDDED_TEST_TIER', defaultValue: 'Standard' },
];
var resourceGroupPrefix = "azureXplatCliTestResourceGroup";
var createdResourceGroups = [];
var workspaceCollectionPrefix = "azureXplatCliTestWorkspaceCollection";
var createdWorkspaceCollections = [];

var suite;

describe('arm', function () {
  describe('powerbiembedded', function () {
    var resourceGroupName;
    var workspaceCollection;
    var workspaceCollectionName;
    var accountLcation;
    var accountSku;
    var accountTier;

    before(function (done) {
      suite = new CLITest(this, testPrefix, requiredEnvironment);

      // set defaults from environment variables
      accountLcation = process.env.AZURE_POWERBIEMBEDDED_TEST_LOCATION || "southcentralus";
      accountSku = process.env.AZURE_POWERBIEMBEDDED_TEST_SKU;
      accountTier = process.env.AZURE_POWERBIEMBEDDED_TEST_TIER;

      suite.setupSuite(function () {
        resourceGroupName = suite.generateId(resourceGroupPrefix, createdResourceGroups);
        if (!suite.isPlayback()) {
          suite.execute('group create %s %s --json', resourceGroupName, accountLcation, function (result) {
            result.exitStatus.should.equal(0);

            done();
          });
        } else {
          done();
        }
      });
    });

    after(function (done) {
      if (!suite.isPlayback()) {
        suite.execute('group delete %s --quiet --json', resourceGroupName, function () {
          suite.teardownSuite(done);
        });
      }
      else {
        suite.teardownSuite(done);
      }
    });

    beforeEach(function (done) {
      suite.setupTest(done);
    });

    afterEach(function (done) {
      suite.teardownTest(done);
    });

    it('can create a workspace collection in resource group', function (done) {
      workspaceCollectionName = suite.generateId(workspaceCollectionPrefix, createdWorkspaceCollections);

      suite.execute('powerbi create %s %s %s --json', resourceGroupName, workspaceCollectionName, accountLcation, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });

    it('can create a workspace collection in resource group with tags', function (done) {
      var newWorkspaceCollectionName = suite.generateId(workspaceCollectionPrefix, createdWorkspaceCollections);
      var tagsString = "tag1=value1;tag2=value2";

      suite.execute('powerbi create %s %s %s --tags %s --json', resourceGroupName, newWorkspaceCollectionName, accountLcation, tagsString, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });

    /**
     * Skip until update operation is fixed.
     */
    it.skip('should update the workspace collection with new tags', function (done) {
      var tagsString = "newTag=newValue;tag1=updatedValue;tag2=";

      suite.execute('powerbi update %s %s --tags %s --json', resourceGroupName, workspaceCollectionName, tagsString, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });

    it('should list workspace collections within subscription', function (done) {
      suite.execute('powerbi list --json', function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });

    it('should list workspace collections within subscription and within resource group', function (done) {
      suite.execute('powerbi list %s --json', resourceGroupName, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });

    it('should return primary and secondary access keys', function (done) {
      suite.execute('powerbi keys list %s %s --json', resourceGroupName, workspaceCollectionName, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    })

    it('should regenerate one of the keys for the workspace collection', function (done) {
      suite.execute('powerbi keys renew %s %s --primary --json', resourceGroupName, workspaceCollectionName, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });

    it('should list the workspaces within the workspace collection', function (done) {
      suite.execute('powerbi workspaces list %s %s', resourceGroupName, workspaceCollectionName, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });

    /**
     * Skip until delete operation is fixed and working in the client repo.
     */
    it.skip('should delete workspace collection', function (done) {
      suite.execute('powerbi delete %s %s', resourceGroupName, workspaceCollectionName, function (result) {
        result.exitStatus.should.equal(0);

        done();
      });
    });
  });
});


text:
ddp-srp
=======

[![Build Status](https://travis-ci.org/oortcloud/ddp-srp.svg)](https://travis-ci.org/oortcloud/ddp-srp)

Library for Secure Remote Password (SRP) exchanges.

###`SRP.generateVerifier(password, options)`

Generate a new SRP verifier. Password is the plaintext password.

`options` is optional and can include:

- `identity`: `String`. The SRP username to user. Mostly this is passed in for testing.  Random UUID if not provided.
- `salt`: `String`. A salt to use.  Mostly this is passed in for testing.  Random UUID if not provided.
- SRP parameters (see _defaults and paramsFromOptions below)

###`SRP.Client`

Generate a new SRP client object. Password is the plaintext password.

`options` is optional and can include:

- `a`: client's private ephemeral value. `String` or BigInteger. Normally, this is picked randomly, but it can be passed in for testing.
- SRP parameters (see _defaults and paramsFromOptions below)

###`SRP.Client.startExchange()`

Initiate an SRP exchange.

returns `{ A: 'client public ephemeral key. hex encoded integer.' }`

###`SRP.Client.prototype.respondToChallenge(challenge)`

Respond to the server's challenge with a proof of password.

challenge is an object with

- `B`: server public ephemeral key. hex encoded integer.
- `identity`: user's identity (SRP username).
- `salt`: user's salt.

returns `{ M: 'client proof of password. hex encoded integer.' }`

throws an error if it got an invalid challenge.

###`SRP.Client.verifyConfirmation(confirmation)`

Verify server's confirmation message.

confirmation is an object with
- `HAMK`: server's proof of password.

returns true or false.

###`SRP.Server(verifier, options)`

Generate a new SRP server object.

options is optional and can include:

- `b`: server's private ephemeral value. `String` or `BigInteger`. Normally, this is picked randomly, but it can be passed in for testing.
- SRP parameters (see _defaults and paramsFromOptions below)

###`SRP.Server.issueChallenge(request)`

Issue a challenge to the client.

Takes a request from the client containing:

- `A`: hex encoded int.

Returns a challenge with:

- `B`: server public ephemeral key. hex encoded integer.
- `identity`: user's identity (SRP username).
- `salt`: user's salt.

Throws an error if issued a bad request.

###`SRP.Server.verifyResponse(response)`

Verify a response from the client and return confirmation.

Takes a challenge response from the client containing:

- `M`: client proof of password. hex encoded int.

Returns a confirmation if the client's proof is good:

- `HAMK`: server proof of password. hex encoded integer.
 OR `null` if the client's proof doesn't match.

###`_defaults`

```js
/**
 * Default parameter values for SRP.
 *
 */
var _defaults = {
  hash: function (x) { return SHA256(x).toLowerCase(); },
  N: new BigInteger("EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3", 16),
  g: new BigInteger("2")
};
_defaults.k = new BigInteger(
  _defaults.hash(
    _defaults.N.toString(16) +
      _defaults.g.toString(16)),
  16);
```

###`paramsFromOptions`

```js
/**
 * Process an options hash to create SRP parameters.
 *
 * Options can include:
 * - hash: Function. Defaults to SHA256.
 * - N: String or BigInteger. Defaults to 1024 bit value from RFC 5054
 * - g: String or BigInteger. Defaults to 2.
 * - k: String or BigInteger. Defaults to hash(N, g)
 */
var paramsFromOptions = function (options) {
  if (!options) // fast path
    return _defaults;

  var ret = _.extend({}, _defaults);

  _.each(['N', 'g', 'k'], function (p) {
    if (options[p]) {
      if (typeof options[p] === "string")
        ret[p] = new BigInteger(options[p], 16);
      else if (options[p] instanceof BigInteger)
        ret[p] = options[p];
      else
        throw new Error("Invalid parameter: " + p);
    }
  });

  if (options.hash)
    ret.hash = function (x) { return options.hash(x).toLowerCase(); };

  if (!options.k && (options.N || options.g || options.hash)) {
    ret.k = ret.hash(ret.N.toString(16) + ret.g.toString(16));
  }

  return ret;
};
```


text:
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'phpWhois\\' => array($baseDir . '/src'),
    'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'),
    'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
);


text:
"""
This file contains the main module code for buck python test programs.

By default, this is the main module for all python_test() rules.  However,
rules can also specify their own custom main_module.  If you write your own
main module, you can import this module as tools.test.stubs.fbpyunit, to access
any of its code to help implement your main module.
"""

from __future__ import print_function

import json
import optparse
import os
import sys
import time
import re
import unittest
import traceback
import contextlib

class TestStatus(object):

    ABORTED = 'FAILURE'
    PASSED = 'SUCCESS'
    FAILED = 'FAILURE'
    EXPECTED_FAILURE = 'SUCCESS'
    UNEXPECTED_SUCCESS = 'FAILURE'
    SKIPPED = 'SUCCESS'

class TeeStream(object):

    def __init__(self, *streams):
        self._streams = streams

    def write(self, data):
        for stream in self._streams:
            stream.write(data)

    def flush(self):
        for stream in self._streams:
            stream.flush()

    def isatty(self):
        return False

class CallbackStream(object):

    def __init__(self, callback):
        self._callback = callback

    def write(self, data):
        self._callback(data)

    def flush(self):
        pass

    def isatty(self):
        return False

class FbJsonTestResult(unittest._TextTestResult):
    """
    Our own TestResult class that outputs data in a format that can be easily
    parsed by fbmake's test runner.
    """

    def __init__(self, stream, descriptions, verbosity):
        super(FbJsonTestResult, self).__init__(stream, descriptions, verbosity)
        self._results = []
        self._current_test = None
        self._saved_stdout = sys.stdout
        self._saved_stderr = sys.stderr

    def getResults(self):
        return self._results

    def startTest(self, test):
        super(FbJsonTestResult, self).startTest(test)

        sys.stdout = TeeStream(CallbackStream(self.addStdout), sys.stdout)
        sys.stderr = TeeStream(CallbackStream(self.addStderr), sys.stderr)

        self._current_test = test
        self._test_start_time = time.time()
        self._current_status = TestStatus.ABORTED
        self._messages = []
        self._stacktrace = None
        self._stdout = ''
        self._stderr = ''

    def stopTest(self, test):
        sys.stdout = self._saved_stdout
        sys.stderr = self._saved_stderr

        super(FbJsonTestResult, self).stopTest(test)

        self._results.append({
            'testCaseName': test._testMethodName,
            'testCase': '{0}.{1}'.format(
                test.__class__.__module__,
                test.__class__.__name__),
            'type': self._current_status,
            'time': int((time.time() - self._test_start_time) * 1000),
            'message': os.linesep.join(self._messages),
            'stacktrace': self._stacktrace,
            'stdOut': self._stdout,
            'stdErr': self._stderr,
        })

        self._current_test = None

    @contextlib.contextmanager
    def _withTest(self, test):
        self.startTest(test)
        yield
        self.stopTest(test)

    def _setStatus(self, test, status, message=None, stacktrace=None):
        assert test == self._current_test
        self._current_status = status
        self._stacktrace = stacktrace
        if message is not None:
            if message.endswith(os.linesep):
                message = message[:-1]
            self._messages.append(message)

    def setStatus(self, test, status, message=None, stacktrace=None):
        # addError() may be called outside of a test if one of the shared
        # fixtures (setUpClass/tearDownClass/setUpModule/tearDownModule)
        # throws an error.
        #
        # In this case, create a fake test result to record the error.
        if self._current_test is None:
            with self._withTest(test):
                self._setStatus(test, status, message, stacktrace)
        else:
            self._setStatus(test, status, message, stacktrace)

    def setException(self, test, status, excinfo):
        exctype, value, tb = excinfo
        self.setStatus(
            test, status,
            '{0}: {1}'.format(exctype.__name__, value),
            ''.join(traceback.format_tb(tb)))

    def addSuccess(self, test):
        super(FbJsonTestResult, self).addSuccess(test)
        self.setStatus(test, TestStatus.PASSED)

    def addError(self, test, err):
        super(FbJsonTestResult, self).addError(test, err)
        self.setException(test, TestStatus.ABORTED, err)

    def addFailure(self, test, err):
        super(FbJsonTestResult, self).addFailure(test, err)
        self.setException(test, TestStatus.FAILED, err)

    def addSkip(self, test, reason):
        super(FbJsonTestResult, self).addSkip(test, reason)
        self.setStatus(test, TestStatus.SKIPPED, 'Skipped: %s' % (reason,))

    def addExpectedFailure(self, test, err):
        super(FbJsonTestResult, self).addExpectedFailure(test, err)
        self.setException(test, TestStatus.EXPECTED_FAILURE, err)

    def addUnexpectedSuccess(self, test):
        super(FbJsonTestResult, self).addUnexpectedSuccess(test)
        self.setStatus(test, TestStatus.UNEXPECTED_SUCCESS,
                       'Unexpected success')

    def addStdout(self, val):
        self._stdout += val

    def addStderr(self, val):
        self._stderr += val

class FbJsonTestRunner(unittest.TextTestRunner):

    def _makeResult(self):
        return FbJsonTestResult(
            self.stream,
            self.descriptions,
            self.verbosity)

class RegexTestLoader(unittest.TestLoader):

    def __init__(self, regex=None):
        super(unittest.TestLoader, self).__init__()
        self.regex = regex

    def getTestCaseNames(self, testCaseClass):
        """
        Return a sorted sequence of method names found within testCaseClass
        """

        testFnNames = super(RegexTestLoader, self).getTestCaseNames(
            testCaseClass)
        matched = []
        for attrname in testFnNames:
            fullname = '{0}.{1}#{2}'.format(
                testCaseClass.__class__.__module__,
                testCaseClass.__class__.__name__,
                attrname)
            if self.regex is None or re.search(self.regex, fullname):
                matched.append(attrname)
        return matched

class Loader(object):

    def __init__(self, modules, regex=None):
        self.modules = modules
        self.regex = regex

    def load_all(self):
        loader = RegexTestLoader(self.regex)
        test_suite = unittest.TestSuite()
        for module_name in self.modules:
            __import__(module_name, level=0)
            module = sys.modules[module_name]
            module_suite = loader.loadTestsFromModule(module)
            test_suite.addTest(module_suite)
        return test_suite

    def load_args(self, args):
        loader = RegexTestLoader(self.regex)

        suites = []
        for arg in args:
            suite = loader.loadTestsFromName(arg)
            # loadTestsFromName() can only process names that refer to
            # individual test functions or modules.  It can't process package
            # names.  If there were no module/function matches, check to see if
            # this looks like a package name.
            if suite.countTestCases() != 0:
                suites.append(suite)
                continue

            # Load all modules whose name is <arg>.<something>
            prefix = arg + '.'
            for module in self.modules:
                if module.startswith(prefix):
                    suite = loader.loadTestsFromName(module)
                    suites.append(suite)

        return loader.suiteClass(suites)

class MainProgram(object):
    '''
    This class implements the main program.  It can be subclassed by
    users who wish to customize some parts of the main program.
    (Adding additional command line options, customizing test loading, etc.)
    '''
    DEFAULT_VERBOSITY = 2

    def __init__(self, argv):
        self.init_option_parser()
        self.parse_options(argv)

    def init_option_parser(self):
        usage = '%prog [options] [TEST] ...'
        op = optparse.OptionParser(usage=usage, add_help_option=False)
        self.option_parser = op

        op.add_option(
            '-o', '--output',
            help='Write results to a file in a JSON format to be read by Buck')
        op.add_option(
            '-l', '--list-tests', action='store_true', dest='list',
            default=False, help='List tests and exit')
        op.add_option(
            '-q', '--quiet', action='count', default=0,
            help='Decrease the verbosity (may be specified multiple times)')
        op.add_option(
            '-v', '--verbosity',
            action='count', default=self.DEFAULT_VERBOSITY,
            help='Increase the verbosity (may be specified multiple times)')
        op.add_option(
            '-r', '--regex', default=None,
            help='Regex to apply to tests, to only run those tests')
        op.add_option(
            '-?', '--help', action='help',
            help='Show this help message and exit')

    def parse_options(self, argv):
        self.options, self.test_args = self.option_parser.parse_args(argv[1:])
        self.options.verbosity -= self.options.quiet

    def create_loader(self):
        import __test_modules__
        return Loader(__test_modules__.TEST_MODULES, self.options.regex)

    def load_tests(self):
        loader = self.create_loader()
        if self.test_args:
            return loader.load_args(self.test_args)
        else:
            return loader.load_all()

    def get_test_names(self, test_suite):
        names = []

        for test in test_suite:
            if isinstance(test, unittest.TestSuite):
                names.extend(self.get_test_names(test))
            else:
                names.append(str(test))

        return names

    def run(self):
        test_suite = self.load_tests()

        if self.options.list:
            for test in self.get_test_names(test_suite):
                print(test)
            return 0
        else:
            result = self.run_tests(test_suite)
            if self.options.output is not None:
                with open(self.options.output, 'w') as f:
                    json.dump(result.getResults(), f, indent=4, sort_keys=True)
            return 0
            #return 0 if result.wasSuccessful() else 1

    def run_tests(self, test_suite):
        # Install a signal handler to catch Ctrl-C and display the results
        # (but only if running >2.6).
        if sys.version_info[0] > 2 or sys.version_info[1] > 6:
            unittest.installHandler()

        # Run the tests
        runner = FbJsonTestRunner(verbosity=self.options.verbosity)
        result = runner.run(test_suite)

        return result

def main(argv):
    return MainProgram(sys.argv).run()

if __name__ == '__main__':
    sys.exit(main(sys.argv))


text:
/* global module, __dirname, require */
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: path.resolve(__dirname, 'app', 'app.js'),
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.css$/,
      loader: 'style!css'
    }, {
      test: /\.js$/,
      exclude: /node_modules/,
      loaders: ['ng-annotate', 'babel?presets[]=es2015']
      // query: {
      //   cacheDirectory: true
      // }
    },
    {
      test: /\.html$/,
      loader: 'ngtemplate?relativeTo=' + (path.resolve(__dirname, 'app')) + '/!html',
      exclude: path.resolve(__dirname, 'app', 'public', 'index.html')
    }
  ]},
  plugins: [new HtmlWebpackPlugin({
    template: path.resolve(__dirname, 'app', 'public', 'index.html'),
    hash: true
  })],
  devServer: {},
  devtool: 'eval'
};


text:
package com.github.weisj.darklaf.ui.internalframe;

import java.awt.*;

import javax.swing.*;

import com.github.weisj.darklaf.ui.util.DarkUIUtil;

public class InternalFrameMenuBar extends JComponent {

    protected Color borderColor;
    protected JMenuBar menuBar;

    public InternalFrameMenuBar() {
        setBackground(UIManager.getColor("InternalFrameMenuBar.background"));
        borderColor = UIManager.getColor("InternalFrameMenuBar.borderColor");
    }

    public void setActiveJMenuBar(final JMenuBar menuBar) {
        if (menuBar != null) {
            add(menuBar);
        } else if (this.menuBar != null) {
            remove(this.menuBar);
        }
        this.menuBar = menuBar;
        getParent().doLayout();
        doLayout();
        repaint();
    }

    @Override
    protected void paintComponent(final Graphics g) {
        super.paintComponent(g);
        if (menuBar != null) {
            g.setColor(getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(borderColor);
            g.fillRect(0, getHeight() - 1, getWidth(), 1);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return DarkUIUtil.getPreferredSize(menuBar);
    }

    @Override
    public void doLayout() {
        if (menuBar != null) {
            menuBar.setBounds(0, 0, DarkUIUtil.getPreferredSize(menuBar).width, getHeight());
            menuBar.doLayout();
        }
    }
}


text:
<?php
/**
 * @author Sam Street <samstreet.dev@gmail.com>
 */

namespace Trackmate\Controller;

use Slim\Http\Request;
use Slim\Http\Response;
use NilPortugues\Api\Problem\ApiProblemResponse;
use Trackmate\Service\HalService;
use Trackmate\Service\User\UserAuthenticationService;
use Exception;

/**
 * Class AuthController
 *
 * @package Trackmate\Controller
 */
class AuthController extends BaseController
{
    /**
     * Authenticate a user
     *
     * @param Request $request
     * @param Response $response
     */
    public function authenticate(Request $request, Response $response)
    {

        return ApiProblemResponse::json(
            403,
            "Invalid Credentials",
            "Authentication Error",
            "error.authentication"
        );

    }

    public function refresh(Request $request, Response $response)
    {

    }
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var router_1 = require("@angular/router");
var index_1 = require("../core/services/index");
var user_1 = require("../core/models/user");
var RegisterComponent = (function () {
    function RegisterComponent(router, userService) {
        this.router = router;
        this.userService = userService;
        this.loading = false;
        this.model = new user_1.User();
    }
    RegisterComponent.prototype.register = function () {
        var _this = this;
        this.loading = true;
        this.userService.register(this.model)
            .subscribe(function (data) {
            _this.router.navigateByUrl('/');
        }, function (error) {
            console.log(error);
            _this.loading = false;
        });
    };
    return RegisterComponent;
}());
RegisterComponent = __decorate([
    core_1.Component({
        moduleId: module.id,
        templateUrl: 'register.component.html'
    }),
    __metadata("design:paramtypes", [router_1.Router,
        index_1.UserService])
], RegisterComponent);
exports.RegisterComponent = RegisterComponent;
//# sourceMappingURL=register.component.js.map


text:
const VARIANT_INTERPRETER_BROWSER_CANCER_CNV_SETTINGS = {
    menu: {
        // add all filters and let variant-interpreter-browser-cancer handle the visibility based on callers
        // filters: []

        sections: [ // sections and subsections, structure and order is respected
            {
                title: "Sample And File",
                filters: ["sample-genotype", "variant-file", "variant-file-info-filter"],
            },
            {
                title: "Genomic",
                collapsed: true,
                filters: ["region", "feature", "biotype", "type"]
            },
            {
                title: "Clinical",
                collapsed: true,
                filters: ["diseasePanels"]
            },
            {
                title: "Phenotype",
                collapsed: true,
                filters: ["go", "hpo"]
            },
        ]
    },
    table: {
        // merge criterium: spread operator
        toolbar: {
            showColumns: true,
            showExport: true,
            showDownload: false
            // columns list for the dropdown will be added in grid components based on settings.table.columns
        }
        // merge criterium: uses this array as filter for internal 1D/2D array. It handles row/col span
        // It is supported either columns[] or hiddenColumns[].
        // columns: ["id"]
    }
    // merge criterium: uses this array as filter for internal 1D array.
    // details: []
};


text:
/*
 * Autocomplete control.
 *
 * Requires: juis.core-1.x
 *           rich-field-1.x
 */

juis.autocomplete = (function() {
  /* Properties */
  var _currentField;

  /* Constructor Helpers */

  // First run setup
  function _setup(field, target) {
    var dataSource = document.querySelector("#" + target);
    var dataValues = dataSource.querySelectorAll("li");

    if (_isCombo(field)) {
      field.dataset.showOnActive = "true";

/*      //append manual activation button
      var activator = document.createElement("button");
      activator.id = field.id + "-activator";
      activator.dataset.target = target;
      activator.innerText = "\u25bc";
      activator.classList.add("g-rf__activator");
      activator.type = "button";*/

//      field.parentElement.parentElement.insertBefore(activator, field.parentElement.nextSibling);
    }

    //loop through values
    for (var i=0; i < dataValues.length; i++) {
      //assign value to any elements that don't have one
      if (!dataValues[i].dataset.originalValue) {
        dataValues[i].dataset.originalValue = dataValues[i].textContent;
      }

      //store search value
      dataValues[i].dataset.searchValue = dataValues[i].textContent.toLowerCase();
    }

    //clone the source and attach it to the to the original
    //dataSource.clone = dataSource.cloneNode(true);
  }

  // Event binding
  function _bind(field, target) {
    //initialise events
    field.addEventListener("focus", _setPicker);
    field.addEventListener("input", _applyFilter);
    field.addEventListener("keydown", _handleKeyboardEvents);

    var dataList = document.querySelector("#" + target);
    var dataValues = dataList.querySelectorAll("li");

    for (i=0; i < dataValues.length; i++) {
      //add select event
      dataValues[i].addEventListener("click", _clickNode);
    }

    // toggle/hide show
    if (_isCombo(field)) {
      //var activator = document.querySelector("#" + field.id + "-activator");
      //activator.addEventListener("click", _clickComboActivator);
    }
  }

  /* Event Listeners */

  function _applyFilter(event) {
    var target = event.target.dataset.target;
    var dataList = document.querySelector("#" + target);

    _reset(dataList);

    //don't filter for less than two characters
    var filterValue = this.value.toLowerCase();
    if (filterValue.length < 2) {
      _clearFilters(dataList);
      return;
    }

    //select non-matching elements
    var selected = dataList.querySelectorAll("li:not([data-search-value*='" + filterValue + "'])");

    //hide non-matching nodes
    for (var i=0; i < selected.length; i++) {
      juis.setVisibility(selected[i]);
    }

    //select matching elements
    var matches = dataList.querySelectorAll("li[data-search-value*='" + filterValue + "']");

    //highlight matching text
    for (i=0; i < matches.length; i++) {
      matches[i].innerHTML = matches[i].dataset.originalValue.replace(new RegExp(juis.sanitiseRegEx(filterValue), "gi"), "<mark>$&</mark>");
    }
  }

  //set picker value
  function _clickNode(event) {
    _setValue(event.target.textContent);
  }

  //select node by keyboard
  function _selectNode(event) {
    var selectedNode = document.querySelector("#" + event.target.dataset.target + " [aria-selected='true']");

    _setValue(selectedNode.textContent);
  }

  //set target picker
  function _setPicker(event) {
    _currentField = event.target;
  }

/*  function _clickComboActivator(event) {
    var target = document.querySelector("#" + event.target.dataset.target);

    //if the control is hidden
    if (!juis.richField.isActive(target)) {
      //focus on the field
      event.target.parentElement.querySelector(".g-ac").focus();
      //prevent click event from going any further
      event.stopPropagation();
    } else {
      //control will hide itself

      //focus on self
      event.target.focus();
    }
  }*/

  function _handleKeyboardEvents(event) {
    //ignore keys if modifiers are active
    if (juis.keyModiferActive(event)) {
      return;
    }

    var code = event.key || event.charCode || event.keyCode;

    switch(code) {
      case "ArrowDown":
      case "Down":
      case 40:
        _go(event.target, "down");
        event.preventDefault();
        break;
      case "ArrowUp":
      case "Up":
      case 38:
        _go(event.target, "up");
        event.preventDefault();
        break;
      case "Enter":
      case "13":
        //handle return to select
        _selectNode(event);
        break;
      default:
    }
  }

  function _toggleChild() {
    // toggle child expanded state
    var child = this.parentNode.querySelector("[role='group']");
    juis.setExpandedState(child, child.hasAttribute("aria-expanded") && child.getAttribute("aria-expanded") === "true");
  }

  /* Methods */

  function _isCombo(field) {
    return field.classList.contains("g-ac__combo");
  }

  //reset the source to it's original layout
  function _reset(source) {
    //select items
    var items = source.querySelectorAll("li");

    //show everything by default (reset)
    for (var i=0; i < items.length; i++) {
      juis.setVisibility(items[i], true);
    }

    //Deselect any selected nodes
    var selected = source.querySelector("[aria-selected='true']");
    if (!selected) {
      return;
    }
    selected.setAttribute("aria-selected", "false");
  }

  //clear marks, collapse
  function _clearFilters(source) {
    //clear highlights
    var highlights = source.querySelectorAll("mark");
    for (var i=0; i < highlights.length; i++) {
      highlights[i].outerHTML = highlights[i].outerHTML.replace(/<.*>(.*)<.*>/, "$1");
    }
  }

  function _setValue(value) {
    if (!_currentField) {
      throw new Error("Autocomplete failed to set target");
    }

    //set value
    _currentField.value = value;

    //return focus to the picker
    _currentField.focus();

    //select tree
    var tree = document.querySelector("#" + _currentField.dataset.target);

    //hide tree
    juis.richField.hide(tree);

    //reset positioning, clear filters,
    _reset(tree);
    _clearFilters(tree);
  }

  //handles keyboard navigation
  function _go(field, direction){
    //get selected node
    var tree = document.querySelector("#" + field.dataset.target);
    var selectedNode = tree.querySelector("[aria-selected='true']");

    //if no selected node
    if (!selectedNode)
    {
      //if down, select first visible
      if (direction !== "down") {
        return;
      }

      var firstNode = tree.querySelector("li:not([aria-hidden='true'])");
      if (!firstNode) {//if none are visible, exit
        return;
      }

      //set highlight
      firstNode.setAttribute("aria-selected", "true");
      return;
    }

    //if filter has been applied, ignore in/out
    switch (direction) {
      case "in":
        // if selected node has collapsed children, expand them
        var childTree = selectedNode.querySelector("[role='group']");
        if (childTree && childTree.getAttribute("aria-expanded") === "false") {
          childTree.setAttribute("aria-expanded", "true");
        }
        break;
      case "out":
        // if selected node has expanded children, collapse them
        childTree = selectedNode.querySelector("[role='group']");
        if (childTree && childTree.getAttribute("aria-expanded") === "true") {
          childTree.setAttribute("aria-expanded", "false");
          return;
        }

        //if a parent group exists, collapse the group
        var parentRole = selectedNode.parentNode.getAttribute("role");
        if (parentRole && parentRole === "group") {
          selectedNode.parentNode.setAttribute("aria-expanded", "false");

          //clear child selection
          selectedNode.setAttribute("aria-selected", "false");

          //select the parent node
          selectedNode.parentNode.parentNode.setAttribute("aria-selected", "true");
        }
        break;
      case "up":
      case "down":
        //fetch visible nodes
        var visibleNodes = tree.querySelectorAll("[aria-expanded='true'] > li:not([aria-hidden='true'])");
        var selectedNodeIndex;
        //loop through nodes and find the currently selected node
        for (var i=0; i < visibleNodes.length; i++) {
          //keep looking until we find the selected node in the list
          if (visibleNodes[i] !== selectedNode) {
            continue;
          }

          selectedNodeIndex = i;
          break;
        }

        //if we're at the first and want to go up
        //or we're at the last and want to go down
        if (selectedNodeIndex === 0 && direction === "up" ||
          selectedNodeIndex === (visibleNodes.length - 1) && direction === "down") {
          //do nothing
          return;
        }
        selectedNode.setAttribute("aria-selected", "false");
        //select previous/next node
        selectedNodeIndex = selectedNodeIndex + (direction === "down" ? 1 : -1);
        //if there are no selectable nodes
        if (!visibleNodes[selectedNodeIndex]) {
          return;
        }
        visibleNodes[selectedNodeIndex].setAttribute("aria-selected", "true");
        return;
      default:
    }
  }

  /* Public Methods */
  return {
    init: function() {
      var autocompleteFields = document.querySelectorAll(".g-ac");

      for (var i=0; i < autocompleteFields.length; i++) {
        var target = autocompleteFields[i].dataset.target;
        _setup(autocompleteFields[i], target);
        _bind(autocompleteFields[i], target);
      }
    }
  };

})();

document.addEventListener("DOMContentLoaded", function() {
  juis.autocomplete.init();
});


text:
import cPickle as pkl
import sys
import time
import numpy as np
import theano
import theano.tensor as tensor
import traceback

from collections import OrderedDict
from theano import config
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from optimizer import optimizer
from data import data_loader

SEED = 123

loader = data_loader.load_data
preparer = data_loader.prepare_data

def zipp(params, tparams):
    for kk, vv in params.iteritems():
        tparams[kk].set_value(vv)

def unzip(zipped):
    new_params = OrderedDict()
    for kk, vv in zipped.iteritems():
        new_params[kk] = vv.get_value()
    return new_params

def numpy_floatX(data):
    return np.asarray(data, dtype=config.floatX)

def ortho_weight(ndim):
    W = np.random.randn(ndim, ndim)
    u, s, v = np.linalg.svd(W)
    return u.astype(config.floatX)

def init_lstm_paras(options, params, prefix='lstm'):
    W = np.concatenate([ortho_weight(options['word_embeding_dimension']), ortho_weight(options['word_embeding_dimension']), ortho_weight(options['word_embeding_dimension']), ortho_weight(options['word_embeding_dimension'])], axis=1)
    params[prefix + '_W'] = W
    U = np.concatenate([ortho_weight(options['word_embeding_dimension']), ortho_weight(options['word_embeding_dimension']), ortho_weight(options['word_embeding_dimension']), ortho_weight(options['word_embeding_dimension'])], axis=1)
    params[prefix + '_U'] = U
    b = np.zeros((4 * options['word_embeding_dimension'],))
    params[prefix + '_b'] = b.astype(config.floatX)

    return params

def init_paras(model_options):
    params = OrderedDict()
    randn = np.random.rand(model_options['max_word_id'], model_options['word_embeding_dimension'])
    params['Wemb'] = (0.01 * randn).astype(config.floatX)
    params = init_lstm_paras(model_options, params, prefix='lstm')
    params['U'] = 0.01 * np.random.randn(model_options['word_embeding_dimension'], model_options['ydim']).astype(config.floatX)
    params['b'] = np.zeros((model_options['ydim'],)).astype(config.floatX)
    return params

def init_tparams(params):
    tparams = OrderedDict()
    for kk, pp in params.iteritems():
        tparams[kk] = theano.shared(params[kk], name=kk)

    return tparams

def lstm(tparams, state_below, model_options, prefix='lstm', mask =None):
    nsteps = state_below.shape[0]
    if state_below.ndim == 3:
        n_samples = state_below.shape[1]
    else:
        n_samples = 1

    assert mask is not None

    def _slice(_x, n, dim):
        if _x.ndim == 3:
            return _x[:, n * dim:(n + 1) * dim]
        return _x[:, n * dim:(n+1)*dim]

    def _step(m_, x_, h_, c_):
        preact = tensor.dot(h_, tparams[prefix + '_U'])
        preact += x_

        i = tensor.nnet.sigmoid(_slice(preact, 0, model_options['word_embeding_dimension']))
        f = tensor.nnet.sigmoid(_slice(preact, 1, model_options['word_embeding_dimension']))
        o = tensor.nnet.sigmoid(_slice(preact, 2, model_options['word_embeding_dimension']))
        c = tensor.tanh(_slice(preact, 3, model_options['word_embeding_dimension']))

        c = f * c_ + i * c
        c = m_[:, None] * c + (1. - m_)[:, None] * c_
        h = o * tensor.tanh(c)
        h = m_[:, None] * h + (1. - m_)[:, None] * h_

        return h, c

    state_below = (tensor.dot(state_below, tparams[prefix + '_W']) + tparams[prefix + '_b'])
    dim_proj = model_options['word_embeding_dimension']
    rval, updates = theano.scan(_step, sequences=[mask, state_below], outputs_info=[tensor.alloc(numpy_floatX(0.), n_samples, dim_proj), tensor.alloc(numpy_floatX(0.), n_samples, dim_proj)], name= prefix+'_layers', n_steps=nsteps)
    return rval[0]

def dropout_layer(state_before, use_noise, trng):
    proj = tensor.switch(use_noise, (state_before * trng.binomial(state_before.shape, p=0.5, n=1, dtype=state_before.dtype)),state_before * 0.5)
    return proj

def pred_probs(f_pred_prob, prepare_data, data, iterator, verbose=False):
    n_samples = len(data[:,0])
    probs = np.zeros((n_samples, 2)).astype(config.floatX)
    n_done = 0

    for _, valid_index in iterator:
        x, mask, y = prepare_data(np.array(zip([data[:,0][t] for t in valid_index], np.array(data[:,1])[valid_index])), max_sample_len=None)

        pred_probs = f_pred_prob(x, mask)
        probs[valid_index, :] = pred_probs
        n_done += len(valid_index)

        if verbose:
            print '%d/%d samples classified' % (n_done, n_samples)
    return probs

def pred_error(f_pred, prepare_data, data, iterator, verbose=False):
    valid_err = 0
    for _, valid_index in iterator:
        x, mask, y = prepare_data(np.array(zip([data[:,0][t] for t in valid_index], np.array(data[:,1])[valid_index])), max_sample_len=None)
        preds = f_pred(x, mask)
        targets = np.array(data[:,1])[valid_index]
        valid_err += (preds == targets).sum()
    valid_err = 1. - numpy_floatX(valid_err) / len(data[0])
    return valid_err

def build_model(tparams, model_options):
    trng = RandomStreams(SEED)
    use_noise = theano.shared(numpy_floatX(0.))
    x = tensor.matrix('x', dtype='int64')
    mask = tensor.matrix('mask', dtype=config.floatX)
    y = tensor.vector('y', dtype='int64')

    n_timesteps = x.shape[0]
    #max_len
    n_samples = x.shape[1]
    #?

    emb = tparams['Wemb'][x.flatten()].reshape([n_timesteps, n_samples, model_options['word_embeding_dimension']])
    #Wemb->(10000, 128),(10000?one_hot?*sentence_len?)->(10000*sentence_len*dim)
    proj = lstm(tparams, emb, model_options, prefix='lstm', mask=mask)

    proj = (proj * mask[:, :, None]).sum(axis=0)
    proj = proj / mask.sum(axis=0)[:, None]
    if model_options['use_dropout']:
        proj = dropout_layer(proj, use_noise, trng)

    pred = tensor.nnet.softmax(tensor.dot(proj, tparams['U']) + tparams['b'])
    f_pred_prob = theano.function([x, mask], pred, name='f_pred_prob')
    f_pred = theano.function([x, mask], pred.argmax(axis=1), name='f_pred')

    off = 1e-8
    if pred.dtype == 'float16':
        off = 1e-6

    cost = -tensor.log(pred[tensor.arange(n_samples), y] + off).mean()
    return use_noise, x, mask, y, f_pred_prob, f_pred, cost

def get_minibatches_idx(n, minibatch_size, shuffle=False):
    idx_list = np.arange(n, dtype="int32")
    if shuffle:np.random.shuffle(idx_list)
    minibatches = []
    minibatch_start = 0
    for i in range(n // minibatch_size):
        minibatches.append(idx_list[minibatch_start: minibatch_start + minibatch_size])
        minibatch_start += minibatch_size
    if (minibatch_start != n):
        minibatches.append(idx_list[minibatch_start:])
    return zip(range(len(minibatches)), minibatches)

def train_model(samples, sample_dict, max_sample_len=50, max_word_id = 10000, seed=123, word_embeding_dimension=128, use_dropout=True, valid_batch_size=64, batch_size=16,\
                decay_c=0., lrate=0.0001, validFreq=370, saveFreq=1110, dispFreq=10, max_epochs=500, patience=10):

    #params init&data load
    model_options = locals().copy()
    train_set, valid_set, test_set = loader(samples, sample_dict, max_sample_len, max_word_id, seed)
    ydim = np.max(train_set[:,1]) + 1
    model_options['ydim'] = ydim
    params = init_paras(model_options)
    tparams = init_tparams(params)
    #build model
    (use_noise, x, mask, y, f_pred_prob, f_pred, cost) = build_model(tparams, model_options)

    if decay_c > 0.:
        decay_c = theano.shared(numpy_floatX(decay_c), name='decay_c')
        weight_decay = 0.
        weight_decay += (tparams['U'] ** 2).sum()
        weight_decay *= decay_c
        cost += weight_decay

    f_cost = theano.function([x, mask, y], cost, name='f_cost')
    grads = tensor.grad(cost, wrt=tparams.values())
    f_grad = theano.function([x, mask, y], grads, name='f_grad')
    lr = tensor.scalar(name='lr')
    f_grad_shared, f_update = optimizer.adadelta(lr, tparams, grads, x, mask, y, cost)
    print 'Optimization'

    kf_valid = get_minibatches_idx(len(valid_set[:,0]), valid_batch_size)
    kf_test = get_minibatches_idx(len(test_set[:, 0]), valid_batch_size)
    print "%d train examples" % len(train_set[:,0])
    print "%d valid examples" % len(valid_set[:,0])
    print "%d test examples" % len(test_set[:,0])
    history_errs = []
    best_p = None
    bad_count = 0

    if validFreq == -1:
        validFreq = len(train[0]) / batch_size
    if saveFreq == -1:
        saveFreq = len(train[0]) / batch_size

    uidx = 0
    estop = False
    start_time = time.time()

    #train_testing loop
    try:
        for eidx in xrange(max_epochs):
            n_samples = 0
            kf = get_minibatches_idx(len(train_set[:,0]), batch_size)

            for oidx, train_idx in kf:
                uidx += 1
                use_noise.set_value(1.0)

                y = [train_set[:,1][t] for t in train_idx]
                x = [train_set[:,0][t] for t in train_idx]

                x, mask, y =  preparer(np.array(zip(x, y)))
                y = list(y)

                n_samples += x.shape[1]
                cost = f_grad_shared(x, mask, y)
                f_update(lrate)

                if np.isnan(cost) or np.isinf(cost):
                    print 'NaN detected'
                    return 1., 1., 1.

                if np.mod(uidx, dispFreq) == 0:
                    print 'Epoch ', eidx, 'Update ', uidx, 'Cost ', cost

                if np.mod(uidx, validFreq) == 0:
                    use_noise.set_value(0.)
                    train_err = pred_error(f_pred, preparer, train_set, kf)
                    valid_err = pred_error(f_pred, preparer, valid_set, kf_valid)
                    test_err = pred_error(f_pred, preparer, test_set, kf_test)
                    history_errs.append([valid_err, test_err])

                    if (uidx == 0 or valid_err <= np.array(history_errs)[:,0].min()):
                        best_p = unzip(tparams)
                        bad_counter = 0
                    print ('Train ', train_err, 'Valid ', valid_err, 'Test ', test_err)
                    if (len(history_errs) > patience and valid_err >= np.array(history_errs)[:-patience, 0].min()):
                        bad_counter += 1
                        if bad_counter > patience:
                            print 'Early Stop!'
                            estop = True
                            break

            print 'Seen %d samples' % n_samples

    except Exception,e:
        print traceback.format_exc()

    end_time = time.time()
    if best_p is not None:
        zipp(best_p, tparams)
    else:
        best_p = unzip(tparams)

    use_noise.set_value(0.)
    kf_train_sorted = get_minibatches_idx(len(train_set[:,0]), batch_size)
    train_err = pred_error(f_pred, preparer, train_set, kf_train_sorted)
    valid_err = pred_error(f_pred, preparer, valid_set, kf_valid)
    test_err = pred_error(f_pred, preparer, test_set, kf_test)

    print 'Train ', train_err, 'Valid ', valid_err, 'Test ', test_err
    print 'The code run for %d epochs, with %f sec/epochs' % ((eidx + 1), (end_time - start_time) / (1. * (eidx + 1)))
    print >> sys.stderr, ('Training took %.1fs' % (end_time - start_time))

    return train_err, valid_err, test_err

if __name__ == '__main__':
    imdb_data = '/home/disk3/zhangxuan/DL_Pipeline/data/imdb.pkl'
    imdb_dict_data = '/home/disk3/zhangxuan/DL_Pipeline/data/imdb.dict.pkl'
    train_model(samples=imdb_data, sample_dict=imdb_dict_data, max_epochs=100)