text:
use strict;
use Data::Dumper;
use Bio::KBase::Utilities::ScriptThing;
use Carp;

#
# This is a SAS Component
#

=head1 NAME

get_entity_Locality

=head1 SYNOPSIS

get_entity_Locality [-c N] [-a] [--fields field-list] < ids > table.with.fields.added

=head1 DESCRIPTION

A locality is a geographic location.

Example:

    get_entity_Locality -a < ids > table.with.fields.added

would read in a file of ids and add a column for each field in the entity.

The standard input should be a tab-separated table (i.e., each line
is a tab-separated set of fields).  Normally, the last field in each
line would contain the id. If some other column contains the id,
use

    -c N

where N is the column (from 1) that contains the id.

This is a pipe command. The input is taken from the standard input, and the
output is to the standard output.

=head2 Related entities

The Locality entity has the following relationship links:

=over 4

=item HasUnits ObservationalUnit

=back

=head1 COMMAND-LINE OPTIONS

Usage: get_entity_Locality [arguments] < ids > table.with.fields.added

    -a		    Return all available fields.
    -c num          Select the identifier from column num.
    -i filename     Use filename rather than stdin for input.
    --fields list   Choose a set of fields to return. List is a comma-separated list of strings.
    -a		    Return all available fields.
    --show-fields   List the available fields.

The following fields are available:

=over 4

=item source_name

Name or description of the location used as a collection site.

=item city

City of the collecting site.

=item state

State or province of the collecting site.

=item country

Country of the collecting site.

=item origcty

3-letter ISO 3166-1 extended country code for the country of origin.

=item elevation

Elevation of the collecting site, expressed in meters above sea level.  Negative values are allowed.

=item latitude

Latitude of the collecting site, recorded as a decimal number.  North latitudes are positive values and south latitudes are negative numbers.

=item longitude

Longitude of the collecting site, recorded as a decimal number.  West longitudes are positive values and east longitudes are negative numbers.

=item lo_accession

gazeteer ontology term ID

=back

=head1 AUTHORS

L<The SEED Project|http://www.theseed.org>

=cut

our $usage = <<'END';
Usage: get_entity_Locality [arguments] < ids > table.with.fields.added

    -c num          Select the identifier from column num
    -i filename     Use filename rather than stdin for input
    --fields list   Choose a set of fields to return. List is a comma-separated list of strings.
    -a		    Return all available fields.
    --show-fields   List the available fields.

The following fields are available:

    source_name
        Name or description of the location used as a collection site.
    city
        City of the collecting site.
    state
        State or province of the collecting site.
    country
        Country of the collecting site.
    origcty
        3-letter ISO 3166-1 extended country code for the country of origin.
    elevation
        Elevation of the collecting site, expressed in meters above sea level.  Negative values are allowed.
    latitude
        Latitude of the collecting site, recorded as a decimal number.  North latitudes are positive values and south latitudes are negative numbers.
    longitude
        Longitude of the collecting site, recorded as a decimal number.  West longitudes are positive values and east longitudes are negative numbers.
    lo_accession
        gazeteer ontology term ID
END

use Bio::KBase::CDMI::CDMIClient;
use Getopt::Long;

#Default fields

my @all_fields = ( 'source_name', 'city', 'state', 'country', 'origcty', 'elevation', 'latitude', 'longitude', 'lo_accession' );
my %all_fields = map { $_ => 1 } @all_fields;

my $column;
my $a;
my $f;
my $i = "-";
my @fields;
my $help;
my $show_fields;
my $geO = Bio::KBase::CDMI::CDMIClient->new_get_entity_for_script('c=i'		 => \$column,
								  "all-fields|a" => \$a,
								  "help|h"	 => \$help,
								  "show-fields"	 => \$show_fields,
								  "fields=s"	 => \$f,
								  'i=s'		 => \$i);
if ($help)
{
    print $usage;
    exit 0;
}

if ($show_fields)
{
    print STDERR "Available fields:\n";
    print STDERR "\t$_\n" foreach @all_fields;
    exit 0;
}

if ($a && $f)
{
    print STDERR "Only one of the -a and --fields options may be specified\n";
    exit 1;
}
if ($a)
{
    @fields = @all_fields;
}
elsif ($f) {
    my @err;
    for my $field (split(",", $f))
    {
	if (!$all_fields{$field})
	{
	    push(@err, $field);
	}
	else
	{
	    push(@fields, $field);
	}
    }
    if (@err)
    {
	print STDERR "get_entity_Locality: unknown fields @err. Valid fields are: @all_fields\n";
	exit 1;
    }
} else {
    print STDERR $usage;
    exit 1;
}

my $ih;
if ($i eq '-')
{
    $ih = \*STDIN;
}
else
{
    open($ih, "<", $i) or die "Cannot open input file $i: $!\n";
}

while (my @tuples = Bio::KBase::Utilities::ScriptThing::GetBatch($ih, undef, $column)) {
    my @h = map { $_->[0] } @tuples;
    my $h = $geO->get_entity_Locality(\@h, \@fields);
    for my $tuple (@tuples) {
        my @values;
        my ($id, $line) = @$tuple;
        my $v = $h->{$id};
	if (! defined($v))
	{
	    #nothing found for this id
	    print STDERR $line,"\n";
     	} else {
	    foreach $_ (@fields) {
		my $val = $v->{$_};
		push (@values, ref($val) eq 'ARRAY' ? join(",", @$val) : $val);
	    }
	    my $tail = join("\t", @values);
	    print "$line\t$tail\n";
        }
    }
}
__DATA__


text:
using EventSpike.Runtime;
using Logary;
using MassTransit;
using Topshelf;

namespace EventSpike.ApprovalProcessor.ServiceHost
{
    internal class ApprovalProcessorServiceControl :
        ServiceControl
    {
        private readonly LogManager _logManager;
        private readonly IServiceBus _bus;
        private readonly ISystemInitializer _initializer;

        public ApprovalProcessorServiceControl(LogManager logManager, IServiceBus bus, ISystemInitializer initializer)
        {
            _logManager = logManager;
            _bus = bus;
            _initializer = initializer;
        }

        public bool Start(HostControl hostControl)
        {
            _initializer.Initialize();

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            _logManager.Dispose();
            _bus.Dispose();

            return true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from case9_1_1 import *

class Case9_1_5(Case9_1_1):

   DESCRIPTION = """Send text message message with payload of length 8 * 2**20 (8M)."""

   EXPECTATION = """Receive echo'ed text message (with payload as sent)."""

   def init(self):
      self.DATALEN = 8 * 2**20
      self.PAYLOAD = "BAsd7&jh23"
      self.WAITSECS = 100
      self.reportTime = True


text:
import argparse
import numpy as np
import pylink
import math
import jinja2
import matplotlib.pyplot as plt

def _interpolate(tgt, vals, off):
    def __search(tgt, vals):
        low = 0
        hi = len(vals)
        cur = int(hi/2)
        while (hi - low) > 1:
            if vals[cur][0] > tgt:
                hi = cur
                cur = int(low + (cur - low)/2)
            elif vals[cur][0] < tgt:
                low = cur
                cur = int(cur + (hi - cur)/2)
            elif vals[cur][0] == tgt:
                return cur
        return low

    lo = __search(tgt, vals)

    # correct value
    if vals[lo][0] == tgt:
        return vals[lo][off]

    hi = lo + 1
    x0 = vals[lo][0]
    x1 = vals[hi][0]
    y0 = vals[lo][off]
    y1 = vals[hi][off]
    rate = (y1-y0)/(x1-x0)
    return rate*(tgt-x0)+y0

class HyperSpectralSNRBudget(object):

    def __init__(self,
                 orbital_solar_irradiance,
                 ground_solar_irradiance,
                 reflectance_db=pylink.to_db(0.5),
                 fore_optics_efficiency_db=pylink.to_db(0.95),
                 focusing_optics_efficiency_db=pylink.to_db(0.95),
                 grating_efficiency_db=pylink.to_db(0.8),
                 sensor_quantum_efficiency_db=pylink.to_db(0.8),
                 read_out_noise_e=50,
                 pixel_pitch_um=15,
                 fwhm_nm=10,
                 gsd_m=15,
                 gmc=1,
                 lambda_nm=1990,
                 lens_radius_m=0.3,
                 bits_per_sample=12,
                 spatial_channels=640):

        self.tribute = {
            # Constants
            'orbital_solar_irradiance_w': orbital_solar_irradiance,
            'ground_solar_irradiance_w': ground_solar_irradiance,
            'speed_of_light_m_s': 299792458,
            'plancks_constant': 6.626068*10**-34,
            'grav_const': 6.67*10**-11,
            'earth_mass_kg': 5.98*10**24,
            'reflectance_db': reflectance_db,
            'fore_optics_efficiency_db': fore_optics_efficiency_db,
            'grating_efficiency_db': grating_efficiency_db,
            'focusing_optics_efficiency_db': focusing_optics_efficiency_db,
            'sensor_quantum_efficiency_db': sensor_quantum_efficiency_db,
            'read_out_noise_e': read_out_noise_e,
            'pixel_pitch_um': pixel_pitch_um,
            'fwhm_nm': fwhm_nm,
            'gsd_m': gsd_m,
            'gmc': gmc,
            'lambda_nm': lambda_nm,
            'lens_radius_m': lens_radius_m,
            'bits_per_sample': bits_per_sample,
            'spatial_channels': spatial_channels,

            # Calculators
            'incident_power_flux_density_dbw_m2_nm': self._incident_power_flux_density_dbw_m2_nm,
            'reflected_power_flux_density_dbw_m2_nm': self._reflected_power_flux_density_dbw_m2_nm,
            'reflected_power_density_dbw_nm': self._reflected_power_density_dbw_nm,
            'reflected_power_dbw': self._reflected_power_dbw,
            'power_flux_at_lens_dbw_m2': self._power_flux_at_lens_dbw_m2,
            'received_power_dbw': self._received_power_dbw,
            'orbital_velocity_km_per_s': self._orbital_velocity_km_per_s,
            'orbital_period_s': self._orbital_period_s,
            'shutter_time_s': self._shutter_time_s,
            'energy_at_sensor_dbj': self._energy_at_sensor_dbj,
            'signal_electrons_in_well_dbe': self._signal_electrons_in_well_dbe,
            'noise_electrons_dbe': self._noise_electrons_dbe,
            'snr_db': self._snr_db,
            'ground_area_dbm2': self._ground_area_dbm2,
            'optical_loss_db': self._optical_loss_db,
            'atmospheric_loss_db': self._atmospheric_loss_db,
            }

    def _incident_power_flux_density_dbw_m2_nm(self, model):
        PFD = max(_interpolate(model.lambda_nm,
                               model.ground_solar_irradiance_w,
                               1),
                  1e-10)
        return pylink.to_db(PFD)

    def _reflected_power_flux_density_dbw_m2_nm(self, model):
        # Incoming Power Flux
        Pi = model.incident_power_flux_density_dbw_m2_nm

        # Lambertian Reflectance (dimensionless)
        Rl = model.reflectance_db

        # Reflected Power Flux
        Pr = Pi + Rl

        return Pr

    def _ground_area_dbm2(self, model):
        return pylink.to_db(model.spatial_channels * model.gsd_m**2)

    def _reflected_power_density_dbw_nm(self, model):
        return (0.0
                + model.reflected_power_flux_density_dbw_m2_nm
                + model.ground_area_dbm2)

    def _reflected_power_dbw(self, model):
        return (1.0
                + model.reflected_power_density_dbw_nm
                + pylink.to_db(model.fwhm_nm))

    def _atmospheric_loss_db(self, model):
        # Power incident on the atmosphere
        Pi = _interpolate(model.lambda_nm,
                          model.orbital_solar_irradiance_w,
                          1)
        Pi = pylink.to_db(Pi)

        # Power transmitted through the atmosphere
        Pt = model.incident_power_flux_density_dbw_m2_nm

        return Pi - Pt

    def _power_flux_at_lens_dbw_m2(self, model):
        # Approximate the pixel as a point source and apply spreading loss
        # The approsimate transmission gain is 3dB as lambertian reflectors
        D = model.slant_range_km*1000
        spreading_loss_db = pylink.to_db(math.pi*2*D**2)
        return (0.0
                + model.reflected_power_dbw
                - spreading_loss_db
                - model.atmospheric_loss_db)

    def _received_power_dbw(self, model):
        # Incident Power Flux
        Pi = model.power_flux_at_lens_dbw_m2

        # Collecting Aperture Area
        A = pylink.to_db(math.pi * model.lens_radius_m**2)

        return Pi + A

    def _orbital_velocity_km_per_s(self, model):
        G = model.grav_const
        M = model.earth_mass_kg
        Re = model.earth_radius_km
        Alt = model.mean_orbit_altitude_km
        R = 1000 * (Re + Alt)
        return (G * M / R)**.5 / 1000.0

    def _orbital_period_s(self, model):
        v = model.orbital_velocity_km_per_s * 1000
        Re = model.earth_radius_km
        Alt = model.mean_orbit_altitude_km
        R = 1000 * (Re + Alt)
        return 2 * math.pi * R / v

    def _shutter_time_s(self, model):
        # Great Circle Circumference (m)
        Gc = model.earth_radius_km * 1000 * math.pi * 2

        # Orbital Period
        To = model.orbital_period_s

        # Ground Speed
        Gs = Gc / To

        # Time required to traverse the GSD
        T = model.gsd_m / Gs

        # GMC Factor
        return T * model.gmc

    def _optical_loss_db(self, model):
        # These efficiencies are all negative numbers, and this
        # function is meant to return a positive number (ie dB's of
        # loss as opposed to dB's of transmission), so we multiply by
        # negative 1.
        return -1 * (0.0
                     + model.fore_optics_efficiency_db
                     + model.grating_efficiency_db
                     + model.focusing_optics_efficiency_db)

    def _energy_at_sensor_dbj(self, model):
        # Energy striking the primary lens
        P_lens = model.received_power_dbw + pylink.to_db(model.shutter_time_s)

        # Optical losses associated with inefficiencies
        # Losses associated with the focal plane sensor
        P_sensor = P_lens - model.optical_loss_db

        return P_sensor

    def _signal_electrons_in_well_dbe(self, model):
        E_sensor = model.energy_at_sensor_dbj
        E_pixel = E_sensor - pylink.to_db(model.spatial_channels)
        P_r = E_pixel + model.sensor_quantum_efficiency_db
        lambda_dbm = pylink.to_db(model.lambda_nm) - 90
        h_db = pylink.to_db(model.plancks_constant)
        c_db = pylink.to_db(model.speed_of_light_m_s)
        return P_r + lambda_dbm - h_db - c_db

    def _noise_electrons_dbe(self, model):
        N = (0.0
             + model.read_out_noise_e
             + pylink.from_db(model.signal_electrons_in_well_dbe/2))
        return pylink.to_db(N)

    def _snr_db(self, model):
        return model.signal_electrons_in_well_dbe - model.noise_electrons_dbe


text:
// Load modules

var Events = require('events');
var Http = require('http');
var Https = require('https');
var Os = require('os');
var Path = require('path');
var Shot = require('shot');
var Boom = require('boom');
var Hoek = require('hoek');
var LruCache = require('lru-cache');
var Auth = require('./auth');
var Defaults = require('./defaults');
var Request = require('./request');
var Router = require('./router');
var Schema = require('./schema');
var Views = require('./views');
var Ext = require('./ext');
// Pack delayed required inline

// Declare internals

var internals = {};

exports = module.exports = internals.Server = function (/* host, port, options */) {        // all optional

    Hoek.assert(this.constructor === internals.Server, 'Server must be instantiated using new');

    var Pack = require('./pack');           // Delayed required to avoid circular dependencies

    // Register as event emitter

    Events.EventEmitter.call(this);

    // Validate arguments

    Hoek.assert(arguments.length <= 4, 'Too many arguments');          // 4th is for internal Pack usage

    var argMap = {
        string: 'host',
        number: 'port',
        object: 'options'
    };

    var args = {};
    for (var a = 0, al = arguments.length; a < al; ++a) {
        var argVal = arguments[a];
        if (argVal === undefined) {
            continue;
        }

        if (argVal instanceof Pack) {
            args.pack = arguments[a];
            continue;
        }

        var type = typeof argVal;

        if (type === 'string' && isFinite(+argVal)) {
            type = 'number';
            argVal = +argVal;
        }

        var key = argMap[type];
        Hoek.assert(key, 'Bad server constructor arguments: no match for arg type:', type);
        Hoek.assert(!args[key], 'Bad server constructor arguments: duplicated arg type:', type, '(values: `' + args[key] + '`, `' + argVal + '`)');
        args[key] = argVal;
    }

    this.settings = Hoek.applyToDefaults(Defaults.server, args.options || {});
    Schema.assert('server', this.settings);

    this.settings.labels = Hoek.unique([].concat(this.settings.labels));       // Convert string to array and removes duplicates

    // Set basic configuration

    this._unixDomainSocket = (args.host && args.host.indexOf('/') !== -1);
    this._windowsNamedPipe = (args.host && args.host.indexOf('\\\\.\\pipe\\') === 0);
    Hoek.assert(!this._unixDomainSocket || args.port === undefined, 'Cannot specify port with a UNIX domain socket');
    Hoek.assert(!this._windowsNamedPipe || args.port === undefined, 'Cannot specify port with a Windows named pipe');
    this._host = (args.host ? (this._unixDomainSocket ? Path.resolve(args.host) : (this._windowsNamedPipe ? args.host : args.host.toLowerCase())) : '');
    this._port = (args.port !== undefined ? args.port : (this.settings.tls ? 443 : 80));
    this._onConnection = null;          // Used to remove event listener on stop

    Hoek.assert(!this.settings.location || this.settings.location.charAt(this.settings.location.length - 1) !== '/', 'Location setting must not contain a trailing \'/\'');

    var socketTimeout = (this.settings.timeout.socket === undefined ? 2 * 60 * 1000 : this.settings.timeout.socket);
    Hoek.assert(!this.settings.timeout.server || !socketTimeout || this.settings.timeout.server < socketTimeout, 'Server timeout must be shorter than socket timeout');
    Hoek.assert(!this.settings.timeout.client || !socketTimeout || this.settings.timeout.client < socketTimeout, 'Client timeout must be shorter than socket timeout');

    // Server facilities

    this._started = false;
    this.auth = new Auth(this);                                                 // Required before _router
    this._router = new Router(this);
    this._etags = (this.settings.files.etagsCacheMaxSize ? LruCache({ max: this.settings.files.etagsCacheMaxSize }) : null);

    // Server load

    Hoek.assert(this.settings.load.sampleInterval || (!this.settings.load.maxEventLoopDelay && !this.settings.load.maxHeapUsedBytes && !this.settings.load.maxRssBytes), 'Load sample interval must be set in enable load limits');

    this._eventLoopTimer = null;
    this._loadBench = new Hoek.Bench();
    this.load = {
        eventLoopDelay: 0,
        heapUsed: 0,
        rss: 0
    };

    /*
        onRequest:      New request, before handing over to the router (allows changes to the request method, url, etc.)
        onPreAuth:      After cookie parse and before authentication (skipped if state error)
        onPostAuth:     After authentication (and payload processing) and before validation (skipped if auth or payload error)
        onPreHandler:   After validation and body parsing, before route handler (skipped if auth or validation error)
        onPostHandler:  After route handler returns, before sending response (skipped if onPreHandler not called)
        onPreResponse:  Before response is sent (always called)
    */

    this._ext = new Ext(['onRequest', 'onPreAuth', 'onPostAuth', 'onPreHandler', 'onPostHandler', 'onPreResponse']);

    this._stateDefinitions = {};

    if (args.pack) {
        this.pack = args.pack;
    }
    else {
        this.pack = new Pack({ cache: this.settings.cache, debug: this.settings.debug });
        this.pack._server(this);
    }

    this.plugins = {};                                      // Registered plugin APIs by plugin name
    this.app = {};                                          // Place for application-specific state without conflicts with hapi, should not be used by plugins
    this.methods = this.pack._methods.methods;              // Method functions

    // Generate CORS headers

    this.settings.cors = Hoek.applyToDefaults(Defaults.cors, this.settings.cors);
    if (this.settings.cors) {
        this.settings.cors._headers = this.settings.cors.headers.concat(this.settings.cors.additionalHeaders).join(', ');
        this.settings.cors._methods = this.settings.cors.methods.concat(this.settings.cors.additionalMethods).join(', ');
        this.settings.cors._exposedHeaders = this.settings.cors.exposedHeaders.concat(this.settings.cors.additionalExposedHeaders).join(', ');

        if (this.settings.cors.origin.length) {
            this.settings.cors._origin = {
                any: false,
                qualified: [],
                qualifiedString: '',
                wildcards: []
            };

            if (this.settings.cors.origin.indexOf('*') !== -1) {
                Hoek.assert(this.settings.cors.origin.length === 1, 'Cannot specify cors.origin * together with other values');
                this.settings.cors._origin.any = true;
            }
            else {
                for (var c = 0, cl = this.settings.cors.origin.length; c < cl; ++c) {
                    var origin = this.settings.cors.origin[c];
                    if (origin.indexOf('*') !== -1) {
                        this.settings.cors._origin.wildcards.push(new RegExp('^' + Hoek.escapeRegex(origin).replace(/\\\*/g, '.*').replace(/\\\?/g, '.') + '$'));
                    }
                    else {
                        this.settings.cors._origin.qualified.push(origin);
                    }
                }

                Hoek.assert(this.settings.cors.matchOrigin || !this.settings.cors._origin.wildcards.length, 'Cannot include wildcard origin values with matchOrigin disabled');
                this.settings.cors._origin.qualifiedString = this.settings.cors._origin.qualified.join(' ');
            }
        }
    }

    // Generate security headers

    this.settings.security = Hoek.applyToDefaults(Defaults.security, this.settings.security);
    if (this.settings.security) {
        if (this.settings.security.hsts) {
            if (this.settings.security.hsts === true) {
                this.settings.security._hsts = 'max-age=15768000';
            } else if (typeof this.settings.security.hsts === 'number') {
                this.settings.security._hsts = 'max-age=' + this.settings.security.hsts;
            } else {
                this.settings.security._hsts = 'max-age=' + (this.settings.security.hsts.maxAge || 15768000);
                if (this.settings.security.hsts.includeSubdomains) {
                    this.settings.security._hsts += '; includeSubdomains';
                }
            }
        }

        if (this.settings.security.xframe) {
            if (this.settings.security.xframe === true) {
                this.settings.security._xframe = 'DENY';
            } else if (typeof this.settings.security.xframe === 'string') {
                this.settings.security._xframe = this.settings.security.xframe.toUpperCase()
            } else {
                if (this.settings.security.xframe.rule === 'allow-from') {
                    if (!this.settings.security.xframe.source) {
                        this.settings.security._xframe = 'SAMEORIGIN';
                    } else {
                        this.settings.security._xframe = 'ALLOW-FROM ' + this.settings.security.xframe.source;
                    }
                } else {
                    this.settings.security._xframe = this.settings.security.xframe.rule.toUpperCase();
                }
            }
        }
    }

    // Initialize Views

    if (this.settings.views) {
        this._views = new Views.Manager(this.settings.views);
    }

    // Create server

    if (this.settings.tls) {
        this.listener = Https.createServer(this.settings.tls, this._dispatch());
    }
    else {
        this.listener = Http.createServer(this._dispatch());
    }

    this._agents = {};
    if (this.settings.maxSockets !== false) {
        this._agents.https = new Https.Agent();
        this._agents.https.maxSockets = this.settings.maxSockets;

        this._agents.insecureAgent = new Https.Agent({ rejectUnauthorized: false });
        this._agents.insecureAgent.maxSockets = this.settings.maxSockets;

        this._agents.http = new Http.Agent();
        this._agents.http.maxSockets = this.settings.maxSockets;
    }

    // Server information

    this.info = {
        host: this._host || '0.0.0.0'
    };

    if (this._unixDomainSocket ||
        this._windowsNamedPipe) {

        this.info.port = 0;
        this.info.protocol = (this._unixDomainSocket ? 'unix' : 'windows');
        this.info.uri = this.info.protocol + ':' + this._host;
    }
    else {
        this.info.port = this._port || 0;
        this.info.protocol = (this.settings.tls ? 'https' : 'http');

        if (this.info.port) {
            this.info.uri = this.info.protocol + '://' + (this._host || Os.hostname() || 'localhost') + ':' + this.info.port;
        }
    }
};

Hoek.inherits(internals.Server, Events.EventEmitter);

internals.Server.prototype._dispatch = function (options) {

    var self = this;

    options = options || {};
    var load = this.load;
    var limits = this.settings.load;

    return function (req, res) {

        // Create request

        var request = new Request(self, req, res, options);

        // Check load

        if (limits.sampleInterval &&
            ((limits.maxEventLoopDelay && (load.eventLoopDelay > limits.maxEventLoopDelay || self._loadBench.elapsed() > limits.maxEventLoopDelay)) ||
            (limits.maxHeapUsedBytes && load.heapUsed > limits.maxHeapUsedBytes) ||
            (limits.maxRssBytes && load.rss > limits.maxRssBytes))) {

            self.log(['hapi', 'load'], load);
            request._reply(Boom.serverTimeout('Server under heavy load', load));
        }
        else {

            // Execute request lifecycle

            request._protect.domain.run(function () {

                request._execute();
            });
        }
    };
};

internals.Server.prototype.table = function (host) {

    return this._router.table(host);
};

internals.Server.prototype.start = function (callback) {

    this.pack.start(callback);
};

internals.Server.prototype._start = function (callback) {

    var self = this;

    if (this._started) {
        return Hoek.nextTick(callback)();
    }

    this._started = true;

    // Load measurements

    if (this.settings.load.sampleInterval) {
        var loopSample = function () {

            self._loadBench.reset();
            var measure = function () {

                var mem = process.memoryUsage();

                self.load.eventLoopDelay = (self._loadBench.elapsed() - self.settings.load.sampleInterval);
                self.load.heapUsed = mem.heapUsed;
                self.load.rss = mem.rss;

                loopSample();
            };

            self._eventLoopTimer = setTimeout(measure, self.settings.load.sampleInterval);
        };

        loopSample();
    }

    // Setup listener

    this._connections = {};
    var onListening = function () {

        // Update the host, port, and uri with active values

        if (!self._unixDomainSocket ||
            !self._windowsNamedPipe) {

            var address = self.listener.address();
            self.info.host = self._host || address.address || '0.0.0.0';
            self.info.port = address.port;
            self.info.uri = self.info.protocol + '://' + (self._host || Os.hostname() || 'localhost') + ':' + self.info.port;
        }

        return callback();
    };

    this.listener.once('listening', onListening);

    this._onConnection = function (connection) {

        var key = connection.remoteAddress + ':' + connection.remotePort;
        self._connections[key] = connection;

        connection.once('close', function () {

            delete self._connections[key];
        });
    };

    this.listener.on('connection', this._onConnection);

    if (this._unixDomainSocket ||
        this._windowsNamedPipe) {

        this.listener.listen(this._host);
    }
    else {
        this.listener.listen(this._port, this._host);
    }
};

internals.Server.prototype.stop = function (options, callback) {

    this.pack.stop(options, callback);
};

internals.Server.prototype._stop = function (options, callback) {

    var self = this;

    options = options || {};
    options.timeout = options.timeout || 5000;                                              // Default timeout to 5 seconds

    if (!this._started) {
        return Hoek.nextTick(callback)();
    }

    this._started = false;

    if (this._eventLoopTimer) {
        clearTimeout(this._eventLoopTimer);
    }

    var timeoutId = setTimeout(function () {

        Object.keys(self._connections).forEach(function (key) {

            self._connections[key].destroy();
        });
    }, options.timeout);

    this.listener.close(function () {

        self.listener.removeListener('connection', self._onConnection);
        clearTimeout(timeoutId);
        callback();
    });
};

internals.Server.prototype.log = function (tags, data, timestamp) {

    this.pack.log(tags, data, timestamp, this);
};

internals.Server.prototype.ext = function () {

    return this._ext.add.apply(this._ext, arguments);
};

internals.Server.prototype._ext = function () {

    return this._ext.add.apply(this._ext, arguments);
};

internals.Server.prototype.route = function (configs) {

    this._route(configs);
};

internals.Server.prototype._route = function (configs, env) {

    this._router.add(configs, env);
};

internals.Server.prototype.state = function (name, options) {

    Hoek.assert(name && typeof name === 'string', 'Invalid name');
    Hoek.assert(!this._stateDefinitions[name], 'State already defined:', name);
    Hoek.assert(!options || !options.encoding || ['base64json', 'base64', 'form', 'iron', 'none'].indexOf(options.encoding) !== -1, 'Bad encoding');

    this._stateDefinitions[name] = Hoek.applyToDefaults(Defaults.state, options || {});
};

internals.Server.prototype.views = function (options) {

    Hoek.assert(!this._views, 'Cannot set server views manager more than once');
    this._views = new Views.Manager(options);
};

internals.Server.prototype.cache = function (name, options) {

    Schema.assert('cachePolicy', options, name);
    Hoek.assert(!options.segment, 'Cannot override segment name in server cache');
    return this.pack._provisionCache(options, 'server', name);
};

internals.Server.prototype.inject = function (options, callback) {

    var requestOptions = (options.credentials ? { credentials: options.credentials } : null);
    delete options.credentials;

    var needle = this._dispatch(requestOptions);
    Shot.inject(needle, options, function (res) {

        if (res.raw.res._hapi) {
            res.result = res.raw.res._hapi.result;
            delete res.raw.res._hapi;
        }
        else {
            res.result = res.payload;
        }

        return callback(res);
    });
};

internals.Server.prototype.method = function () {

    return this.pack._method.apply(this.pack, arguments);
};

internals.Server.prototype.handler = function () {

    return this.pack._handler.apply(this.pack, arguments);
};


text:
<?php

namespace Ductape\Command\Utility;

use Ductape\Command\AbstractCommand;
use Ductape\Command\CommandValue;
use Ductape\Ductape;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class RunCommand extends AbstractCommand {

    protected function configure() {
        parent::configure();

        $this
                ->setName('run')
                ->setDescription('Runs ductape setup')
                ->addArgument('commands', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, '', array('ductape.json'))
                ->addOption('return-data', 'return', InputOption::VALUE_OPTIONAL, 'Which dataset to return. Defaults to last dataset used.')
//                ->addArgument('filter', InputArgument::REQUIRED, 'Filter in Chequer Query Language.')
            ;

    }

    public function getInputSets() {
        return array(Ductape::SET_DATA => array());
    }

    public function getOutputSets() {
        return array(Ductape::SET_DATA => array());
    }

    protected function execute( InputInterface $input, OutputInterface $output ) {

        $data = $this->getApplication()->getDataset(Ductape::SET_ALL);

        $commands = $this->getInputValue('commands', $input, CommandValue::TYPE_FILE)->asArray();

        if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
            $output->writeln(sprintf("Running %d commands:", count($commands)));
        }

        $construction = new Ductape();
        $construction->setAutoExit(false);
        // copy all sets
        $construction->setDataset($data, Ductape::SET_ALL);
        // read specified data
        $construction->setDataset($this->readInputData($input, $output), Ductape::SET_DATA);

        $construction->runCommands($commands, $output);

        $data = null;
        $returnData = $this->getInputValue('return-data', $input);
        if ($returnData->isEmpty()) {
            $data = $construction->getDataset($construction->lastDataSet);
        } elseif ($returnData->asBool()) {
            $data = $construction->getDataset($returnData->asString());
        }

        if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
            $output->writeln(sprintf("Finished running...", count($commands)));
        }

        if ($data !== null) {
            $this->writeOutputData($data, $input, $output);
        }
    }

}


text: loc = 'blazewebtestapp.modules.tests.tasks.init_db'


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Event Recorder Manager</title>
    <link rel="stylesheet" type="text/css" href="../../../resources/css/ext-all.css" />

    <!-- GC -->

    <script type="text/javascript" src="../../../ext.js"></script>
    <script type="text/javascript">
        Ext.Loader.setPath({
            'Ext.ux': '..'
        });
        Ext.require([
            '*',
            'Ext.ux.event.RecorderManager'
        ]);

        Ext.onReady(function () {
            var vp = Ext.create('Ext.Viewport', {
                    layout: 'fit',
                    items: [{
                        xtype: 'eventrecordermanager',
                        attachTo: window.opener
                    }]
                });
        });
    </script>
</head>
<body>
</body>
</html>


text:
<?php

namespace Custom\View\Helper;

use \Zend\View\Helper\Navigation as Father;
class Navigation extends Father
{
    public function getPluginManager()
    {
        if (null === $this->plugins) {
            $this->setPluginManager(new \Custom\View\Helper\Navigation\PluginManager());
        }
        return $this->plugins;
    }
}


text:
from ..abstract_tool import AbstractTool
from .orbittoolgui import Ui_OrbitToolGUI
from PyQt5 import QtGui

class OrbitTool(AbstractTool):

    def __init__(self, parent):
        super(OrbitTool, self).__init__(parent)
        self._name = "Orbit Tool"
        self._parent = parent

        # --- Initialize the GUI --- #
        self._orbitToolWindow = QtGui.QMainWindow()
        self._orbitToolGUI = Ui_OrbitToolGUI()
        self._orbitToolGUI.setupUi(self._orbitToolWindow)

        self._orbitToolGUI.apply_button.clicked.connect(self.callback_apply)
        self._orbitToolGUI.cancel_button.clicked.connect(self.callback_cancel)

        self._has_gui = True
        self._need_selection = True
        self._min_selections = 1
        self._max_selections = None
        self._redraw_on_exit = True

        self.values = [None, None, None]

    # --- Required Functions --- #

    def run(self):

        # --- Calculate the positions to center the window --- #
        screen_size = self._parent.screen_size()
        _x = 0.5 * (screen_size.width() - self._orbitToolWindow.width())
        _y = 0.5 * (screen_size.height() - self._orbitToolWindow.height())

        # --- Show the GUI --- #
        self._orbitToolWindow.show()
        self._orbitToolWindow.move(_x, _y)

    # --- GUI-related Functions --- #

    def open_gui(self):
        self.run()

    def close_gui(self):
        self._orbitToolWindow.close()

    def callback_apply(self):
        if self.apply() == 0:
            self._redraw()
            self.close_gui()

    def callback_cancel(self):
        self.close_gui()

    # --- Tool-related Functions --- #

    def check_step_numbers(self):

        step_texts = [self._orbitToolGUI.step_1, self._orbitToolGUI.step_2,
                      self._orbitToolGUI.step_3]

        self.values = [None, None, None]

        for i, step in enumerate(step_texts):
            s_txt = step.text()
            if len(s_txt) == 0:
                step.setStyleSheet("color: #000000")

            try:
                if "." in s_txt:
                    step.setStyleSheet("color: #FF0000")
                else:
                    self.values[i] = int(s_txt)  # Try to convert the input to an int
                    step.setStyleSheet("color: #000000")

            except ValueError:

                # Set the text color to red
                step.setStyleSheet("color: #FF0000")

    def apply(self):

        self.check_step_numbers()

        if None in self.values:
            return 1

        for dataset in self._selections:
            dataset.xy_orbit(self.values, center=self._orbitToolGUI.center_orbit.isChecked())

        return 0


text:
var gulp = require('gulp');
var less = require('gulp-less');
var concat = require('gulp-concat');
var gulpFilter = require('gulp-filter');
var minifyCss = require('gulp-minify-css');

gulp.task('html', function() {

    var filter = gulpFilter(['*.html', '!X*.html']);

    return gulp.src('source/*.html')
               .pipe(filter)
               .pipe(gulp.dest('dist/'));
});

gulp.task('css01', function() { return gulp.src('bower_components/bootstrap/dist/css/*.min.css').pipe(gulp.dest('dist/css')); });
gulp.task('css02', function() { return gulp.src('bower_components/font-awesome/css/*.min.css').pipe(gulp.dest('dist/css')); });
gulp.task('css03', function() { return gulp.src('source/css/layout.css').pipe(minifyCss()).pipe(gulp.dest('dist/css')); });
gulp.task('cssall', ['css01','css02','css03']);

gulp.task('fonts', function() { return gulp.src('bower_components/font-awesome/fonts/*').pipe(gulp.dest('dist/css/fonts')); });

gulp.task('theme', function () {
    return gulp.src('source/css/*.less')
               .pipe(less())
               .pipe(gulp.dest('dist/css'));
});
gulp.task('js01', function() { return gulp.src('bower_components/jquery/dist/jquery.min.js').pipe(gulp.dest('dist/js')); });
gulp.task('js02', function() { return gulp.src('bower_components/bootstrap/dist/js/bootstrap.min.js').pipe(gulp.dest('dist/js')); });
gulp.task('js03', function() { return gulp.src('bower_components/bootstrap/js/dropdown.js').pipe(gulp.dest('dist/js')); });
gulp.task('jsall', ['js01','js02','js03','theme']);

gulp.task('all', ['html','js01','js02','js03','css01','css02','css03','theme','fonts']);

/* gulp.task('default', function() {
 return gulp.src('source/*.html')
 .pipe(gulp.dest('dist/'));
 });
*/


text:
package identitymapper

import (
	"fmt"
	"reflect"
	"testing"

	kapi "k8s.io/kubernetes/pkg/api"
	kerrs "k8s.io/kubernetes/pkg/api/errors"

	authapi "github.com/openshift/origin/pkg/auth/api"
	"github.com/openshift/origin/pkg/user/api"
	userapi "github.com/openshift/origin/pkg/user/api"
	"github.com/openshift/origin/pkg/user/registry/test"
)

type testNewIdentityGetter struct {
	called    int
	responses []interface{}
}

func (t *testNewIdentityGetter) UserForNewIdentity(ctx kapi.Context, preferredUserName string, identity *userapi.Identity) (*userapi.User, error) {
	t.called++
	if len(t.responses) < t.called {
		return nil, fmt.Errorf("Called at least %d times, only %d responses registered", t.called, len(t.responses))
	}
	switch response := t.responses[t.called-1].(type) {
	case error:
		return nil, response
	case *userapi.User:
		return response, nil
	default:
		return nil, fmt.Errorf("Invalid response type registered: %#v", response)
	}
}

func TestGetPreferredUsername(t *testing.T) {
	identity := &api.Identity{}

	identity.ProviderUserName = "foo"
	if preferred := getPreferredUserName(identity); preferred != "foo" {
		t.Errorf("Expected %s, got %s", "foo", preferred)
	}

	identity.Extra = map[string]string{authapi.IdentityPreferredUsernameKey: "bar"}
	if preferred := getPreferredUserName(identity); preferred != "bar" {
		t.Errorf("Expected %s, got %s", "bar", preferred)
	}
}

func TestProvision(t *testing.T) {
	testcases := map[string]struct {
		ProviderName     string
		ProviderUserName string

		ExistingIdentity           *userapi.Identity
		ExistingUser               *userapi.User
		NewIdentityGetterResponses []interface{}

		ExpectedActions  []test.Action
		ExpectedError    bool
		ExpectedUserName string
	}{
		"no identity, create user succeeds": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity: nil,
			ExistingUser:     nil,
			NewIdentityGetterResponses: []interface{}{
				makeUser("bobUserUID", "bob", "idp:bob"),
			},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter creates user
				{Name: "CreateIdentity", Object: makeIdentity("", "idp", "bob", "bobUserUID", "bob")},
			},
			ExpectedUserName: "bob",
		},
		"no identity, alreadyexists error retries": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity: nil,
			ExistingUser:     nil,
			NewIdentityGetterResponses: []interface{}{
				kerrs.NewAlreadyExists(userapi.Resource("User"), "bob"),
				makeUser("bobUserUID", "bob", "idp:bob"),
			},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter returns error
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter creates user
				{Name: "CreateIdentity", Object: makeIdentity("", "idp", "bob", "bobUserUID", "bob")},
			},
			ExpectedUserName: "bob",
		},
		"no identity, conflict error retries": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity: nil,
			ExistingUser:     nil,
			NewIdentityGetterResponses: []interface{}{
				kerrs.NewConflict(userapi.Resource("User"), "bob", fmt.Errorf("conflict")),
				makeUser("bobUserUID", "bob", "idp:bob"),
			},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter returns error
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter creates user
				{Name: "CreateIdentity", Object: makeIdentity("", "idp", "bob", "bobUserUID", "bob")},
			},
			ExpectedUserName: "bob",
		},
		"no identity, only retries 3 times": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity: nil,
			ExistingUser:     nil,
			NewIdentityGetterResponses: []interface{}{
				kerrs.NewConflict(userapi.Resource("User"), "bob", fmt.Errorf("conflict")),
				kerrs.NewConflict(userapi.Resource("User"), "bob", fmt.Errorf("conflict")),
				kerrs.NewConflict(userapi.Resource("User"), "bob", fmt.Errorf("conflict")),
				kerrs.NewConflict(userapi.Resource("User"), "bob", fmt.Errorf("conflict")),
			},

			ExpectedActions: []test.Action{
				// original attempt
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter returns error
				// retry #1
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter returns error
				// retry #2
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter returns error
				// retry #3
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter returns error
			},
			ExpectedError: true,
		},
		"no identity, unknown error does not retry": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity: nil,
			ExistingUser:     nil,
			NewIdentityGetterResponses: []interface{}{
				fmt.Errorf("other error"),
			},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				// ... new identity user getter returns error
			},
			ExpectedError: true,
		},

		"existing identity, no user reference": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity:           makeIdentity("bobIdentityUID", "idp", "bob", "", ""),
			ExistingUser:               nil,
			NewIdentityGetterResponses: []interface{}{},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
			},
			ExpectedError: true,
		},
		"existing identity, missing user reference": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity:           makeIdentity("bobIdentityUID", "idp", "bob", "bobUserUID", "bob"),
			ExistingUser:               nil,
			NewIdentityGetterResponses: []interface{}{},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				{Name: "GetUser", Object: "bob"},
			},
			ExpectedError: true,
		},
		"existing identity, invalid user UID reference": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity:           makeIdentity("bobIdentityUID", "idp", "bob", "bobUserUIDInvalid", "bob"),
			ExistingUser:               makeUser("bobUserUID", "bob", "idp:bob"),
			NewIdentityGetterResponses: []interface{}{},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				{Name: "GetUser", Object: "bob"},
			},
			ExpectedError: true,
		},
		"existing identity, user reference without identity backreference": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity:           makeIdentity("bobIdentityUID", "idp", "bob", "bobUserUID", "bob"),
			ExistingUser:               makeUser("bobUserUID", "bob" /*, "idp:bob"*/),
			NewIdentityGetterResponses: []interface{}{},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				{Name: "GetUser", Object: "bob"},
			},
			ExpectedError: true,
		},
		"existing identity, user reference": {
			ProviderName:     "idp",
			ProviderUserName: "bob",

			ExistingIdentity:           makeIdentity("bobIdentityUID", "idp", "bob", "bobUserUID", "bob"),
			ExistingUser:               makeUser("bobUserUID", "bob", "idp:bob"),
			NewIdentityGetterResponses: []interface{}{},

			ExpectedActions: []test.Action{
				{Name: "GetIdentity", Object: "idp:bob"},
				{Name: "GetUser", Object: "bob"},
			},
			ExpectedUserName: "bob",
		},
	}

	for k, tc := range testcases {
		actions := []test.Action{}
		identityRegistry := &test.IdentityRegistry{
			Get:     map[string]*api.Identity{},
			Actions: &actions,
		}
		userRegistry := &test.UserRegistry{
			Get:     map[string]*api.User{},
			Actions: &actions,
		}
		if tc.ExistingIdentity != nil {
			identityRegistry.Get[tc.ExistingIdentity.Name] = tc.ExistingIdentity
		}
		if tc.ExistingUser != nil {
			userRegistry.Get[tc.ExistingUser.Name] = tc.ExistingUser
		}

		newIdentityUserGetter := &testNewIdentityGetter{responses: tc.NewIdentityGetterResponses}

		provisionMapper := &provisioningIdentityMapper{
			identity:             identityRegistry,
			user:                 userRegistry,
			provisioningStrategy: newIdentityUserGetter,
		}

		identity := authapi.NewDefaultUserIdentityInfo(tc.ProviderName, tc.ProviderUserName)
		user, err := provisionMapper.UserFor(identity)
		if tc.ExpectedError != (err != nil) {
			t.Errorf("%s: Expected error=%v, got %v", k, tc.ExpectedError, err)
			continue
		}
		if !tc.ExpectedError && user.GetName() != tc.ExpectedUserName {
			t.Errorf("%s: Expected username %v, got %v", k, tc.ExpectedUserName, user.GetName())
			continue
		}

		if newIdentityUserGetter.called != len(tc.NewIdentityGetterResponses) {
			t.Errorf("%s: Expected %d calls to UserForNewIdentity, got %d", k, len(tc.NewIdentityGetterResponses), newIdentityUserGetter.called)
		}

		for i, action := range actions {
			if len(tc.ExpectedActions) <= i {
				t.Fatalf("%s: expected %d actions, got extras: %#v", k, len(tc.ExpectedActions), actions[i:])
				continue
			}
			expectedAction := tc.ExpectedActions[i]
			if !reflect.DeepEqual(expectedAction, action) {
				t.Fatalf("%s: expected\n\t%s %#v\nGot\n\t%s %#v", k, expectedAction.Name, expectedAction.Object, action.Name, action.Object)
				continue
			}
		}
		if len(actions) < len(tc.ExpectedActions) {
			t.Errorf("Missing %d additional actions:\n\t%#v", len(tc.ExpectedActions)-len(actions), tc.ExpectedActions[len(actions):])
		}
	}
}


text:
package org.camunda.bpm.engine.rest.sub.task.impl;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;

import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.identity.Authentication;
import org.camunda.bpm.engine.rest.TaskRestService;
import org.camunda.bpm.engine.rest.dto.task.CommentDto;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.sub.task.TaskCommentResource;
import org.camunda.bpm.engine.task.Comment;

public class TaskCommentResourceImpl implements TaskCommentResource {

  private ProcessEngine engine;
  private String taskId;
  private String rootResourcePath;

  public TaskCommentResourceImpl(ProcessEngine engine, String taskId, String rootResourcePath) {
    this.engine = engine;
    this.taskId = taskId;
    this.rootResourcePath = rootResourcePath;
  }

  public List<CommentDto> getComments() {
    if (!isHistoryEnabled()) {
      return Collections.emptyList();
    }

    ensureTaskExists(Status.NOT_FOUND);

    List<Comment> taskComments = engine.getTaskService().getTaskComments(taskId);

    List<CommentDto> comments = new ArrayList<CommentDto>();
    for (Comment comment : taskComments) {
      comments.add(CommentDto.fromComment(comment));
    }

    return comments;
  }

  public CommentDto getComment(String commentId) {
    ensureHistoryEnabled(Status.NOT_FOUND);

    Comment comment = engine.getTaskService().getTaskComment(taskId, commentId);
    if (comment == null) {
      throw new InvalidRequestException(Status.NOT_FOUND, "Task comment with id " + commentId + " does not exist for task id '" + taskId + "'.");
    }

    return CommentDto.fromComment(comment);
  }

  public CommentDto createComment(UriInfo uriInfo, CommentDto commentDto) {
    ensureHistoryEnabled(Status.FORBIDDEN);
    ensureTaskExists(Status.BAD_REQUEST);

    Comment comment;

    try {
      comment = engine.getTaskService().createComment(taskId, null, commentDto.getMessage());
    }
    catch (ProcessEngineException e) {
      throw new InvalidRequestException(Status.BAD_REQUEST, e, "Not enough parameters submitted");
    }

    URI uri = uriInfo.getBaseUriBuilder()
      .path(rootResourcePath)
      .path(TaskRestService.PATH)
      .path(taskId + "/comment/" + comment.getId())
      .build();

    CommentDto resultDto = CommentDto.fromComment(comment);

    // GET /
    resultDto.addReflexiveLink(uri, HttpMethod.GET, "self");

    return resultDto;
  }

  private boolean isHistoryEnabled() {
    IdentityService identityService = engine.getIdentityService();
    Authentication currentAuthentication = identityService.getCurrentAuthentication();
    try {
      identityService.clearAuthentication();
      int historyLevel = engine.getManagementService().getHistoryLevel();
      return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE;
    } finally {
      identityService.setAuthentication(currentAuthentication);
    }
  }

  private void ensureHistoryEnabled(Status status) {
    if (!isHistoryEnabled()) {
      throw new InvalidRequestException(status, "History is not enabled");
    }
  }

  private void ensureTaskExists(Status status) {
    HistoricTaskInstance historicTaskInstance = engine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
    if (historicTaskInstance == null) {
      throw new InvalidRequestException(status, "No task found for task id " + taskId);
    }
  }

}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Souscategorie
 *
 * @ORM\Table(name="souscategorie")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\SouscategorieRepository")
 */
class Souscategorie
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="libelle", type="string", length=255)
     */
    private $libelle;

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

    /**
     * Set libelle
     *
     * @param string $libelle
     *
     * @return Souscategorie
     */
    public function setLibelle($libelle)
    {
        $this->libelle = $libelle;

        return $this;
    }

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


text:
package com.thebluealliance.androidclient.activities.settings;

import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.thebluealliance.androidclient.Analytics;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.accounts.AccountHelper;
import com.thebluealliance.androidclient.activities.LaunchActivity;
import com.thebluealliance.androidclient.datafeed.Database;
import com.thebluealliance.androidclient.gcm.GCMAuthHelper;
import com.thebluealliance.androidclient.gcm.GCMMessageHandler;
import com.thebluealliance.androidclient.helpers.ModelHelper;
import com.thebluealliance.androidclient.models.Favorite;

public class DevSettingsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new DevSettingsFragment())
                .commit();
    }

    public static class DevSettingsFragment extends PreferenceFragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.dev_preferences);

            Preference analytics_dryRyn = findPreference("analytics_dry_run");
            analytics_dryRyn.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    Analytics.setAnalyticsDryRun(getActivity(), (boolean) newValue);
                    return true;
                }
            });

            Preference addMyTBAItem = findPreference("add_mytba_item");
            addMyTBAItem.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    Favorite fav = new Favorite();
                    fav.setUserName(AccountHelper.getSelectedAccount(getActivity()));
                    fav.setModelKey("frc111");
                    fav.setModelEnum(ModelHelper.MODELS.TEAM.getEnum());
                    Database.getInstance(getActivity()).getFavoritesTable().add(fav);
                    return true;
                }
            });

            Preference testUpcomingMatchNotification = findPreference("test_upcoming_match_notification");
            testUpcomingMatchNotification.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    String data = "{\"match_key\":\"2014ilch_f1m2\",\"event_name\":\"Midwest Regional\",\"team_keys\":[\"frc111\",\"frc118\",\"frc254\",\"frc496\",\"frc1114\",\"frc2056\"],\"scheduled_time\":12345,\"predicted_time\":123456}";
                    GCMMessageHandler.handleMessage(getActivity(), "upcoming_match", data);
                    return true;
                }
            });

            Preference testScoreNotification = findPreference("test_score_notification");
            testScoreNotification.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    // Comment out different strings to see different types of notifications.
                    // This is kind of a hacky way of demonstrating notifications; it just removes
                    // teams from the alliance json objects to simulate different numbers of favorited teams.
                    // This will break once we actually check if teams are favorited while constructing notifications.

                    // All teams are favorited
                    //String data = "{\"event_name\":\"EVENT NAME\",\"match\":{\"comp_level\":\"f\",\"match_number\":1,\"videos\":[],\"time_string\":null,\"set_number\":1,\"key\":\"2010sc_f1m1\",\"time\":null,\"alliances\":{\"blue\":{\"score\":5,\"teams\":[\"frc1772\",\"frc2751\",\"frc1102\"]},\"red\":{\"score\":0,\"teams\":[\"frc1398\",\"frc343\",\"frc1261\"]}},\"event_key\":\"2010sc\"}}";
                    // 2 teams on winning alliance are favorited
                    //String data = "{\"event_name\":\"EVENT NAME\",\"match\":{\"comp_level\":\"f\",\"match_number\":1,\"videos\":[],\"time_string\":null,\"set_number\":1,\"key\":\"2010sc_f1m1\",\"time\":null,\"alliances\":{\"blue\":{\"score\":5,\"teams\":[\"frc1772\",\"frc2751\"]},\"red\":{\"score\":0,\"teams\":[]}},\"event_key\":\"2010sc\"}}";
                    // 1 team on losing alliance is favorited
                    //String data = "{\"event_name\":\"EVENT NAME\",\"match\":{\"comp_level\":\"f\",\"match_number\":1,\"videos\":[],\"time_string\":null,\"set_number\":1,\"key\":\"2010sc_f1m1\",\"time\":null,\"alliances\":{\"blue\":{\"score\":5,\"teams\":[]},\"red\":{\"score\":0,\"teams\":[\"frc1398\"]}},\"event_key\":\"2010sc\"}}";
                    // 2 teams on tied alliance are favorited
                    // String data = "{\"event_name\":\"EVENT NAME\",\"match\":{\"comp_level\":\"f\",\"match_number\":1,\"videos\":[],\"time_string\":null,\"set_number\":1,\"key\":\"2010sc_f1m1\",\"time\":null,\"alliances\":{\"blue\":{\"score\":5,\"teams\":[\"frc1772\",\"frc2751\"]},\"red\":{\"score\":5,\"teams\":[]}},\"event_key\":\"2010sc\"}}";
                    // 2 teams on each tied alliance are favorited
                    String data = "{\"event_name\":\"San Diego Regional\",\"match\":{\"comp_level\":\"f\",\"match_number\":1,\"videos\":[],\"time_string\":null,\"set_number\":1,\"key\":\"2010casd_f1m1\",\"time\":null,\"alliances\":{\"blue\":{\"score\":5,\"teams\":[\"frc1772\",\"frc2751\"]},\"red\":{\"score\":5,\"teams\":[\"frc1398\",\"frc343\"]}},\"event_key\":\"2010casd\"}}";
                    GCMMessageHandler.handleMessage(getActivity(), "score", data);
                    return true;
                }
            });

            Preference gcmRegister = findPreference("select_account");
            gcmRegister.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    GoogleAccountCredential credential = AccountHelper.getSelectedAccountCredential(getActivity());
                    getActivity().startActivity(credential.newChooseAccountIntent());
                    return false;
                }
            });
        }

        @Override
        public void onConnected(Bundle bundle) {
            GCMAuthHelper.registerInBackground(getActivity());
        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), getActivity(), 0).show();
            Preference redownload = findPreference("redownload_data");
            Intent redownloadIntent = new Intent(getActivity(), LaunchActivity.class);
            redownloadIntent.putExtra(LaunchActivity.REDOWNLOAD, true);
            redownload.setIntent(redownloadIntent);

        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            // Remove padding from the list view
            View listView = getView().findViewById(android.R.id.list);
            if (listView != null) {
                listView.setPadding(0, 0, 0, 0);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
package com.jakewharton.rxbinding4.view;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import androidx.test.annotation.UiThreadTest;
import androidx.test.core.app.ApplicationProvider;
import com.jakewharton.rxbinding4.RecordingObserver;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public final class RxViewGroupTest {
  private final Context context = ApplicationProvider.getApplicationContext();
  private final LinearLayout parent = new LinearLayout(context);
  private final View child = new View(context);

  @Test @UiThreadTest public void childViewEvents() {
    RecordingObserver<ViewGroupHierarchyChangeEvent> o = new RecordingObserver<>();
    RxViewGroup.changeEvents(parent).subscribe(o);
    o.assertNoMoreEvents(); // No initial value.

    parent.addView(child);
    assertEquals(new ViewGroupHierarchyChildViewAddEvent(parent, child), o.takeNext());

    parent.removeView(child);
    assertEquals(new ViewGroupHierarchyChildViewRemoveEvent(parent, child), o.takeNext());

    o.dispose();

    parent.addView(child);
    o.assertNoMoreEvents();
  }
}


text:
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System.Collections;
using System.Collections.Generic;
using Pash.Implementation;

namespace System.Management.Automation
{
    // TODO: can we replace the runtime with the ExecutionContext?
    internal class PipelineCommandRuntime : ICommandRuntime
    {
        internal ObjectStream outputResults { get; private set; }
        internal ObjectStream errorResults { get; private set; }
        internal PipelineProcessor pipelineProcessor { get; private set; }

        // TODO: hook the runtime to the Host for Debug and Error output
        internal PipelineCommandRuntime(PipelineProcessor pipelineProcessor)
        {
            this.pipelineProcessor = pipelineProcessor;
            this.outputResults = new ObjectStream();
            this.errorResults = new ObjectStream();
        }

        internal bool IsStopping
        {
            get
            {
                return (pipelineProcessor != null) && pipelineProcessor.Stopping;
            }
        }

        #region ICommandRuntime Members

        public Host.PSHost Host
        {
            get { throw new NotImplementedException(); }
        }

        public bool ShouldContinue(string query, string caption)
        {
            return true;
        }

        public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll)
        {
            return true;
        }

        public bool ShouldProcess(string target)
        {
            return true;
        }

        public bool ShouldProcess(string target, string action)
        {
            return true;
        }

        public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption)
        {
            return true;
        }

        public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason)
        {
            shouldProcessReason = ShouldProcessReason.None;
            return true;
        }

        public void ThrowTerminatingError(ErrorRecord errorRecord)
        {
            if (errorRecord.Exception != null)
            {
                throw errorRecord.Exception;
            }
            throw new InvalidOperationException(errorRecord.ToString());
        }

        public void WriteCommandDetail(string text)
        {
        }

        public void WriteDebug(string text)
        {
        }

        public void WriteError(ErrorRecord errorRecord)
        {
            errorResults.Write(PSObject.AsPSObject(errorRecord));
        }

        public void WriteObject(object sendToPipeline)
        {
            outputResults.Write(PSObject.AsPSObject(sendToPipeline));
        }

        public void WriteObject(object sendToPipeline, bool enumerateCollection)
        {
            if (enumerateCollection && !(sendToPipeline is string))
            {
                IEnumerator enumerator = GetEnumerator(sendToPipeline);
                if (enumerator != null)
                {
                    while (enumerator.MoveNext())
                    {
                        WriteObject(enumerator.Current);
                    }
                    return;
                }
            }

            WriteObject(sendToPipeline);
        }

        public void WriteProgress(ProgressRecord progressRecord)
        {
        }

        public void WriteProgress(long sourceId, ProgressRecord progressRecord)
        {
        }

        public void WriteVerbose(string text)
        {
        }

        public void WriteWarning(string text)
        {
        }

        #endregion

        private IEnumerator GetEnumerator(object obj)
        {
            IEnumerable enumerable = obj as IEnumerable;
            if (enumerable != null)
            {
                return enumerable.GetEnumerator();
            }
            IEnumerator enumerator = obj as IEnumerator;
            if (obj != null)
            {
                return enumerator;
            }

            return null;
        }
    }
}


text:
package de.ne0.sonar.plsql.parser.tables;

import static org.sonar.sslr.tests.Assertions.assertThat;

import org.junit.Test;
import org.sonar.sslr.parser.LexerlessGrammar;

import de.ne0.sonar.plsql.parser.PlSQLGrammar;

public class CreateSynonymTest {
	LexerlessGrammar g = PlSQLGrammar.createGrammar();

	@Test
	public void ok() {
		assertThat(g.rule(PlSQLGrammar.CREATE_SYNONYM))
				.matches("create or replace public synonym test for apptest.test;")
				.matches("create synonym test for apptest.test;");
	}
}


text:
#ifndef _version_h_
#define _version_h_

#ifdef __cplusplus
extern "C" {
#endif

void printVersion(const char *rcsid);

#ifdef __cplusplus
}
#endif

#endif /* _version_h_ */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- 默认配置,存放业务相关配置 -->
<!-- 所有配置都要有ID,所有配置的ID尽量唯一 -->
<resources>
	<resource id="selenium" description="selenium自动化测试">
		<property id="webdriver.ie.driver">C:\\Program Files (x86)\\Internet Explorer\\IEDriverServer.exe</property>
		<property id="WEB_APP_URL">http://10.111.125.142:7011/web/static/framework/main.jsp</property>
		<property id="screenShotLocation">C:\error</property>
		<configurations id="seleniumConfigurations">
			<configuration id="processConfig" path="/resources/selenium/process" loadAll="true" />
			<configuration id="areaConfig" path="/resources/selenium">
				<file id="area">selearea.xml</file>
			</configuration>
		</configurations>
		<configurations id="seleniumCommandConfig">
			<configuration id="commands" path="/resources/selenium">
				<file id="commands">Commands.xml</file>
			</configuration>
		</configurations>
		<configurations id="scriptsConfig">
			<configuration id="scriptsConfig" path="/resources/selenium/scripts" loadAll="true" />
		</configurations>
	</resource>
</resources>


text:
<project default="jar:jar" xmlns:j="jelly:core" xmlns:maven="jelly:maven" xmlns:ant="jelly:ant">

	<goal name="laptop">
		<j:set var="config.name" value="laptop"/>
		<j:if test="${pom.artifactId == 'search'}">
			<j:set var="contextPath" value=""/>
			<j:set var="contextFile" value="ROOT.xml"/>
		</j:if>
	</goal>

	<goal name="stage">
		<echo>Changing tomcat.home from ${tomcat.home}...</echo>
		<j:set var="tomcat.home" value="/usr/local/stage/tomcat"/>
		<echo>...to ${tomcat.home}</echo>
		<echo>Changing jdbc.url from ${jdbc.url}...</echo>
		<j:set var="jdbc.url" value="jdbc:mysql://localhost:3306/stage_${pom.artifactId}"/>
		<echo>...to ${jdbc.url}</echo>
		<echo>Changing config.name from ${config.name}...</echo>
		<j:set var="config.name" value="stage"/>
		<echo>...to ${config.name}</echo>
		<j:set var="expanded" value="true"/>
		<j:set var="docBase" value="${tomcat.home}/../webapps/${pom.artifactId}"/>
		<j:if test="${pom.artifactId == 'search'}">
			<j:set var="contextPath" value=""/>
			<j:set var="contextFile" value="ROOT.xml"/>
		</j:if>
	</goal>

	<goal name="dev">
		<echo>Changing tomcat.home from ${tomcat.home}...</echo>
		<j:set var="tomcat.home" value="/usr/local/dev/tomcat"/>
		<echo>...to ${tomcat.home}</echo>
		<echo>Changing jdbc.url from ${jdbc.url}...</echo>
		<j:set var="jdbc.url" value="jdbc:mysql://localhost:3306/${pom.artifactId}"/>
		<echo>...to ${jdbc.url}</echo>
		<echo>Changing config.name from ${config.name}...</echo>
		<j:set var="config.name" value="dev"/>
		<echo>...to ${config.name}</echo>
		<j:set var="expanded" value="true"/>
		<j:set var="docBase" value="${tomcat.home}/../webapps/${pom.artifactId}"/>
		<j:if test="${pom.artifactId == 'search'}">
			<j:set var="contextPath" value=""/>
			<j:set var="contextFile" value="ROOT.xml"/>
		</j:if>
	</goal>

	<goal name="demo">
		<echo>Changing tomcat.home from ${tomcat.home}...</echo>
		<j:set var="tomcat.home" value="/usr/local/demo/tomcat"/>
		<echo>...to ${tomcat.home}</echo>
		<echo>Changing jdbc.url from ${jdbc.url}...</echo>
		<j:set var="jdbc.url" value="jdbc:mysql://localhost:3306/demo_${pom.artifactId}"/>
		<echo>...to ${jdbc.url}</echo>
		<echo>Changing config.name from ${config.name}...</echo>
		<j:set var="config.name" value="demo"/>
		<echo>...to ${config.name}</echo>
		<j:set var="expanded" value="true"/>
		<j:set var="docBase" value="${tomcat.home}/../webapps/${pom.artifactId}"/>
		<j:if test="${pom.artifactId == 'search'}">
			<j:set var="contextPath" value=""/>
			<j:set var="contextFile" value="ROOT.xml"/>
		</j:if>
	</goal>

	<goal name="live">
		<echo>Changing tomcat.home from ${tomcat.home}...</echo>
		<j:set var="tomcat.home" value="/usr/local/tomcat"/>
		<echo>...to ${tomcat.home}</echo>
		<echo>Changing jdbc.url from ${jdbc.url}...</echo>
		<j:set var="jdbc.url" value="jdbc:mysql://localhost:3306/${pom.artifactId}"/>
		<echo>...to ${jdbc.url}</echo>
		<echo>Changing config.name from ${config.name}...</echo>
		<j:set var="config.name" value="live"/>
		<echo>...to ${config.name}</echo>
		<j:set var="expanded" value="true"/>
		<j:set var="docBase" value="${tomcat.home}/../webapps/${pom.artifactId}"/>
		<j:if test="${pom.artifactId == 'search'}">
			<j:set var="contextPath" value=""/>
			<j:set var="contextFile" value="ROOT.xml"/>
		</j:if>
	</goal>

	<goal name="base">
		<echo>Changing tomcat.home from ${tomcat.home}...</echo>
		<j:set var="tomcat.home" value="/usr/local/tomcat"/>
		<echo>...to ${tomcat.home}</echo>
		<echo>Changing jdbc.url from ${jdbc.url}...</echo>
		<j:set var="jdbc.url" value="jdbc:mysql://localhost:3306/${pom.artifactId}"/>
		<echo>...to ${jdbc.url}</echo>
		<echo>Changing config.name from ${config.name}...</echo>
		<j:set var="config.name" value="base"/>
		<echo>...to ${config.name}</echo>
		<j:set var="expanded" value="true"/>
		<j:set var="docBase" value="${tomcat.home}/../webapps/${pom.artifactId}"/>
		<j:if test="${pom.artifactId == 'search'}">
			<j:set var="contextPath" value=""/>
			<j:set var="contextFile" value="ROOT.xml"/>
		</j:if>
	</goal>

	<goal name="deploy" prereqs="war:war"
			description="Deploys the war file into your tomcat home">
		<j:if test="${empty(trunk)}">
			<j:set var="trunk" value=".."/>
		</j:if>
		<j:if test="${pom.artifactId != 'search'}">
			<j:if test="${empty(contextPath)}">
				<j:set var="contextPath" value="/${pom.artifactId}"/>
			</j:if>
		</j:if>
		<echo>copied</echo>
		<j:if test="${empty(docBase)}">
			<j:set var="docBase" value="${tomcat.home}/../webapps/${pom.artifactId}"/>
			<j:set var="expanded" value="true"/>
		</j:if>
		<j:if test="${expanded == 'true'}">
			<copy
				file="${docBase}/sitemap.xml.gz"
				tofile="${docBase}/../sitemap.xml.gz"
				overwrite="true"
				failonerror="false"
			/>
		</j:if>
		<delete failonerror="true" dir="${docBase}" />
		<j:if test="${empty(contextFile)}">
			<j:set var="contextFile" value="${pom.artifactId}.xml"/>
		</j:if>
		<j:set var="contextSource" value="${pom.artifactId}.xml"/>
		<ant:available file="${contextSource}" property="contextSource.present"/>
		<j:choose>
			<j:when test="${contextSource.present}">
				<echo>Using given context source ${contextSource}</echo>
			</j:when>
			<j:otherwise>
				<j:set var="contextSource" value="${trunk}/defaultContext.xml"/>
				<echo>Using default context source ${contextSource}</echo>
			</j:otherwise>
		</j:choose>
		<echo>copying ${contextSource} to ${tomcat.home}/conf/Catalina/localhost/${contextFile}</echo>
		<copy file="${contextSource}"
			tofile="${tomcat.home}/conf/Catalina/localhost/${contextFile}" filtering="true" overwrite="true">
			<filterset>
				<filter token="docBase" value="${docBase}"/>
				<filter token="contextPath" value="${contextPath}"/>
				<filter token="config.name" value="${config.name}"/>
				<filter token="jdbc.driver" value="${jdbc.driver}"/>
				<filter token="jdbc.url" value="${jdbc.url}"/>
				<filter token="jdbc.username" value="${jdbc.username}"/>
				<filter token="jdbc.password" value="${jdbc.password}"/>
			</filterset>
		</copy>

		<j:if test="${expanded == 'true'}">
			<copy todir="${docBase}">
				<mkdir dir="${docBase}"/>
				<ant:fileset dir="${maven.build.dir}/${pom.artifactId}" />
			</copy>
			<copy
				file="${docBase}/../sitemap.xml.gz"
				tofile="${docBase}/sitemap.xml.gz"
				overwrite="true"
				failonerror="false"
			/>
		</j:if>

		<j:if test="${expanded != 'true'}">
			<copy todir="${docBase}/..">
				<ant:fileset file="${maven.build.dir}/${pom.artifactId}.war" />
			</copy>
		</j:if>
	</goal>

	<goal name="devdeploy">
		<j:if test="${pom.artifactId != 'search'}">
			<j:if test="${empty(contextPath)}">
				<j:set var="contextPath" value="/${pom.artifactId}"/>
			</j:if>
		</j:if>
		<j:if test="${empty(contextFile)}">
			<j:set var="contextFile" value="${pom.artifactId}.xml"/>
		</j:if>
		<j:set var="maven.test.skip" value="true" />
		<attainGoal name="war:init" />
		<j:set var="maven.war.webapp.dir" value="${maven.war.src}" />
		<echo>Deploying to local src webapp: ${maven.war.webapp.dir}</echo>

		<filter filtersfile="build.properties" />
		<filter filtersfile="project.properties" />
		<filter token="docBase" value="${maven.war.webapp.dir}" />
		<filter token="contextPath" value="${contextPath}"/>
		<filter token="config.name" value="${config.name}"/>
		<filter token="jdbc.driver" value="${jdbc.driver}"/>
		<filter token="jdbc.url" value="${jdbc.url}"/>
		<filter token="jdbc.username" value="${jdbc.username}"/>
		<filter token="jdbc.password" value="${jdbc.password}"/>
		<echo>copying ${pom.artifactId}.xml to ${tomcat.home}/conf/Catalina/localhost/${contextFile}</echo>
		<copy file="${pom.artifactId}.xml"
			tofile="${tomcat.home}/conf/Catalina/localhost/${contextFile}" filtering="true" overwrite="true"/>
		<echo>copied</echo>

		<attainGoal name="war:webapp" />
	</goal>

</project>


text:
title: Awesome Looking Picture!
layout: post
author: rory.collins
permalink: /awesome-looking-picture!/
source-id: 1pltlQd6zn8SkVvaggvnmDrzVKQJtiqf5Cmmir-RjoQs
published: true
---
I found this and I thought it looked AWESOME!!!!

![image alt text]({{ site.url }}/public/GMPs5JEqgLIQk6gggEEwkg_img_0.jpg)

Hope you like it!

Byeeee!


text:
<!DOCTYPE html>

        <meta charset="utf-8">

        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <title>Test of fox-tabbar</title>
        <link rel="stylesheet" href="../../fox-core/dist/foxui.css">

        <link rel="import" href="../../fox-icon/dist/fox-icon.html"/>
        <link rel="import" href="../dist/fox-tabbar.html"/>
        <link rel="import" href="../../fox-page/dist/fox-page.html"/>
        <link rel="import" href="../../fox-toolbar/dist/fox-toolbar.html"/>
        <link rel="import" href="../../fox-page-content/dist/fox-page-content.html"/>

        <fox-tabbar>

                <fox-icon icon="icon-star-filled"></fox-icon>
                精品推荐

                <fox-icon icon="icon-list"></fox-icon>
                排行榜

                <fox-icon icon="icon-person"></fox-icon>
                我的附近

                <fox-icon icon="icon-search"></fox-icon>
                搜索

                <fox-icon icon="icon-download"></fox-icon>
                更新

        </fox-tabbar>

        <fox-page>
            <fox-toolbar title="精品推荐"></fox-toolbar>

            <fox-page-content>

选中:

                    <button onclick="document.body.firstElementChild.select(2);">选中第三个 Tab</button>

                    <button onclick="document.body.firstElementChild.select('排行榜');">选中 "排行榜"</button>

            </fox-page-content>
        </fox-page>


text:
from __future__ import absolute_import, print_function
from skinfer.json_schema_merger import merge_schema
import unittest
from tests import fixtures

def recursive_sort(obj):
    """
    Recursively sort list or dict nested lists
    """

    if isinstance(obj, dict):
        for key, val in obj.iteritems():
            obj[key] = recursive_sort(val)
        _sorted = obj

    elif isinstance(obj, list):
        new_list = []
        for val in obj:
            new_list.append(recursive_sort(val))
        _sorted = sorted(new_list)

    else:
        _sorted = obj

    return _sorted

class TestJsonSchemaMerger(unittest.TestCase):
    def check_merge_result(self, first, second, expected):
        first_copy = first.copy()
        second_copy = second.copy()

        merged = merge_schema(first, second)
        merged_reversed = merge_schema(second, first)

        self.assertEqual(merged, expected)
        self.assertEqual(merged_reversed, expected)
        self.assertEqual(merged, merged_reversed)

        # ensuring we're not touching the originals:
        self.assertEqual(first, first_copy)
        self.assertEqual(second, second_copy)

    def test_merge_required_property_with_empty_object_schema(self):
        self.check_merge_result(
            fixtures.REQUIRE_OBJECT_TYPE,
            fixtures.REQUIRING_SOME_PROPERTY,
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string"},
                }
            }
        )

    def test_merge_schemas_with_different_required_properties(self):
        self.check_merge_result(
            fixtures.REQUIRING_SOME_PROPERTY,
            fixtures.REQUIRING_ANOTHER_PROPERTY,
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string"},
                    "another": {"type": "string"},
                }
            }
        )

    def test_merge_same_schema_gives_itself(self):
        self.check_merge_result(
            fixtures.REQUIRING_SOME_PROPERTY,
            fixtures.REQUIRING_SOME_PROPERTY,
            fixtures.REQUIRING_SOME_PROPERTY,
        )
        self.check_merge_result(
            fixtures.REQUIRING_SOME_PROPERTY_WITH_NESTED_OPTIONAL_AND_REQUIRED_PROPERTY,
            fixtures.REQUIRING_SOME_PROPERTY_WITH_NESTED_OPTIONAL_AND_REQUIRED_PROPERTY,
            fixtures.REQUIRING_SOME_PROPERTY_WITH_NESTED_OPTIONAL_AND_REQUIRED_PROPERTY,
        )
        self.check_merge_result(
            fixtures.REQUIRING_AN_ARRAY_PROPERTY,
            fixtures.REQUIRING_AN_ARRAY_PROPERTY,
            fixtures.REQUIRING_AN_ARRAY_PROPERTY,
        )

    def test_merge_schemas_with_nested_properties(self):
        self.check_merge_result(
            fixtures.REQUIRING_SOME_OBJECT_PROPERTY,
            fixtures.REQUIRING_SOME_PROPERTY_WITH_NESTED_OPTIONAL_AND_REQUIRED_PROPERTY,
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "required": ["something"],
                "properties": {
                    "something": {
                        "type": "object",
                        "properties": {
                            "nested_optional": {"type": "string"},
                            "nested_required": {"type": "string"},
                        }
                    },
                }
            }
        )

    def test_merge_one_schema_with_nested_array_property(self):
        self.check_merge_result(
            fixtures.REQUIRING_SOME_PROPERTY,
            fixtures.REQUIRING_AN_ARRAY_PROPERTY,
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "a_list": {
                        "type": "array",
                        "items": {"type": "string"}
                    },
                    "something": {"type": "string"}
                }
            }
        )

    def test_merge_both_schemas_with_nested_array_property(self):
        self.check_merge_result(
            fixtures.REQUIRING_AN_ARRAY_PROPERTY,
            fixtures.REQUIRING_AN_ARRAY_PROPERTY_PLUS_ANOTHER,
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "required": ["a_list"],
                "properties": {
                    "a_list": {
                        "type": "array",
                        "items": {"type": "string"},
                    },
                    "another_list": {
                        "type": "array",
                        "items": {"type": "number"},
                    }
                }
            }
        )

    def test_merge_array_with_tuple_validation(self):
        self.check_merge_result(
            fixtures.REQUIRING_AN_ARRAY_PROPERTY_WITH_TUPLE_VALIDATION,
            fixtures.REQUIRING_AN_ARRAY_PROPERTY_WITH_TUPLE_VALIDATION,
            {
                '$schema': 'http://json-schema.org/draft-04/schema',
                "required": ["array_with_tuple"],
                'type': 'object',
                'properties': {
                    'array_with_tuple': {
                        'items': [{'type': 'string'}, {'type': 'string'}],
                        'type': u'array'
                    }
                }
            }
        )

    def test_merge_simple_numbers(self):
        self.check_merge_result(
            fixtures.REQUIRING_NUMBER_PROPERTY,
            fixtures.REQUIRING_NUMBER_PROPERTY,
            {
                '$schema': 'http://json-schema.org/draft-04/schema',
                'type': 'object',
                'required': ['number_of_followers'],
                'properties': {
                    'number_of_followers': {
                        'type': 'number',
                    }
                }
            }
        )

    def test_merge_simple_boolean(self):
        self.check_merge_result(
            fixtures.REQUIRING_BOOLEAN_PROPERTY,
            fixtures.REQUIRING_BOOLEAN_PROPERTY,
            {
                '$schema': 'http://json-schema.org/draft-04/schema',
                'type': 'object',
                'required': ['is_this_on'],
                'properties': {
                    'is_this_on': {
                        'type': 'boolean',
                    }
                }
            }
        )

    def assertSchemaEqual(self, first, second):
        self.assertEqual(recursive_sort(first), recursive_sort(second))

    def test_merge_string_and_null(self):
        merged = merge_schema(
            fixtures.REQUIRING_NULL_PROPERTY,
            fixtures.REQUIRING_SOME_PROPERTY,
        )
        expected = {
            '$schema': 'http://json-schema.org/draft-04/schema',
            'type': 'object',
            'required': ['something'],
            'properties': {
                'something': {
                    'anyOf': [
                        {'type': 'string'},
                        {'type': 'null'},
                    ]
                }
            }
        }
        self.assertSchemaEqual(merged, expected)

    def test_merge_anyof(self):
        schema_with_anyof = {
            '$schema': 'http://json-schema.org/draft-04/schema',
            'type': 'object',
            'required': ['something'],
            'properties': {
                'something': {
                    'anyOf': [
                        {'type': 'string'},
                        {'type': 'null'},
                    ]
                }
            }
        }
        merged = merge_schema(fixtures.REQUIRING_SOME_PROPERTY, schema_with_anyof)
        self.assertSchemaEqual(merged, schema_with_anyof)

    def test_merge_null(self):
        self.check_merge_result(
            fixtures.REQUIRING_NULL_PROPERTY,
            fixtures.REQUIRING_NULL_PROPERTY,
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "required": ["something"],
                "properties": {
                    "something": {"type": "null"},
                }
            }
        )

    def test_merge_tuple_with_loose_array(self):
        self.check_merge_result(
            fixtures.REQUIRING_AN_ARRAY_PROPERTY_WITH_TUPLE_VALIDATION,
            fixtures.REQUIRING_AN_ARRAY_PROPERTY_CONFLICTING_WITH_TUPLE,
            {
                '$schema': 'http://json-schema.org/draft-04/schema',
                "required": ["array_with_tuple"],
                'type': 'object',
                'properties': {
                    'array_with_tuple': {
                        'items': {'type': 'string'},
                        'type': u'array'
                    }
                }
            }
        )

    def test_merge_string_keeping_custom_props(self):
        self.check_merge_result(
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "default": "botemo"},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "description": "Something"},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "description": "Something", "default": "botemo"},
                }
            }
        )

    def test_merge_string_minlength_nolength(self):
        self.check_merge_result(
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "minLength": 2},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string"},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "minLength": 2},
                }
            },
        )

    def test_merge_string_maxlength_nolength(self):
        self.check_merge_result(
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "maxLength": 22},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "minLength": 2},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "minLength": 2, "maxLength": 22},
                }
            },
        )

    def test_merge_string_minlength_maxlength(self):
        self.check_merge_result(
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "minLength": 2, "maxLength": 10},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "minLength": 4, "maxLength": 12},
                }
            },
            {
                '$schema': u'http://json-schema.org/draft-04/schema',
                "type": "object",
                "properties": {
                    "something": {"type": "string", "minLength": 2, "maxLength": 12},
                }
            }
        )


text:
using Plotter.Tweet.Processing;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Plotter.Tests.WinForms
{
    public partial class IOTest : Form
    {
        private ConcurrentQueue<Tweet.Tweet> _incomingQueue;

        public IOTest()
        {
            InitializeComponent();
            label3.Text = "";
            var syncContext = new WindowsFormsSynchronizationContext();

            _incomingQueue = new ConcurrentQueue<Tweet.Tweet>();
            QueueProcessor processor = new QueueProcessor(_incomingQueue, new TestDBContext());

            processor.TweetReady += (object sender, Tweet.Tweet e) =>
            {
                syncContext.Post((object userData) =>
                {
                    label3.Text = e.Text;

                    if (e.Image != null && e.Image.Length > 0)
                    {
                        MemoryStream ms = new MemoryStream(e.Image);
                        ms.Write(e.Image, 0, e.Image.Length);
                        ms.Position = 0;
                        pictureBox1.Image = Image.FromStream(ms);
                    }
                    else
                    {
                        pictureBox1.Image = null;
                    }
                }, null);
            };
        }

        private void button1_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = null;
            label3.Text = "";

            _incomingQueue.Enqueue(new Tweet.Tweet()
            {
                CreatorScreenName = "@test",
                Text = textBox1.Text
            });
            textBox1.Text = "";
        }
    }
}