text:
import { Express2 } from '@server/express/express2'
import supertest, { SuperAgentTest } from 'supertest'
import { INVALID_DATA } from '@common/type/error-const'
import { closeAllObjects, getObject, initObjectContext } from '@server/oman/oman'

describe('Express2 Error', () => {

  let web: Express2
  let sat: SuperAgentTest

  beforeAll(async () => {
    initObjectContext('config/raysoda-test.json')
    web = await getObject('Express2') as Express2
    await web.start()
    sat = supertest.agent(web.server)
  })

  afterAll(async () => {
    await closeAllObjects()
  })

  it('404 if api url not exist', async () => {
    await sat.get('/api/test/undefined-url').expect(404)
  })
  it('404 if not handled', async () => {
    await sat.get('/api/no-action').expect(404)
  })
  it('404 if page url not exist', async () => {
    await sat.get('/undefined-page').expect(404).expect(/<title>Error/)
  })
  it('api INVALID_DATA', async () => {
    const res = await sat.get('/api/invalid-data').expect(200)
    expect(res.type).toBe('application/json')
    expect(res.body.err).toContain(INVALID_DATA)
  })
  it('api [INVALID_DATA]', async () => {
    const res = await sat.get('/api/invalid-data-array').expect(200)
    expect(res.type).toBe('application/json')
    expect(res.body.err).toContain(INVALID_DATA)
  })
  it('api system error', async () => {
    const res = await sat.get('/api/system-error').expect(200)
    expect(res.type).toBe('application/json')
    expect(res.body.err[0].name).toBe('Error')
    expect(res.body.err[0].message).toMatch(/System Error/)
    expect(res.body.err[0].field).toBe('_system')
  })
  it('page system error', async () => {
    const res = await sat.get('/system-error').expect(200).expect(/<title>Error/)
    expect(res.type).toBe('text/html')
  })

})


text:
description("Tests dynamic updates of the 'r' attribute of the SVGCircleElement object")
createSVGTestCase();

var circleElement = createSVGElement("circle");
circleElement.setAttribute("cx", "150");
circleElement.setAttribute("cy", "150");
circleElement.setAttribute("r", "1");
circleElement.setAttribute("fill", "green");

rootSVGElement.appendChild(circleElement);
shouldBeEqualToString("circleElement.getAttribute('r')", "1");

function repaintTest() {
    circleElement.setAttribute("r", "150");
    shouldBeEqualToString("circleElement.getAttribute('r')", "150");

    completeTest();
}

var successfullyParsed = true;

redpajama_set_name: RedPajamaGithub


text:
/* Autogenerated with Kurento Idl */

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

var inherits = require('inherits');

var kurentoClient = require('kurento-client');

var disguise = kurentoClient.disguise;

var checkType      = kurentoClient.checkType;
var ChecktypeError = checkType.ChecktypeError;

var Transaction = kurentoClient.TransactionsManager.Transaction;

var Endpoint = require('./Endpoint');

function noop(error, result) {
  if (error) console.trace(error);

  return result
};

/**
 * @classdesc
 *  Interface for endpoints the require a URI to work.
 *  An example of this, would be a :rom:cls:`PlayerEndpoint` whose URI property
 *  could be used to locate a file to stream.
 *
 * @abstract
 * @extends module:core/abstracts.Endpoint
 *
 * @constructor module:core/abstracts.UriEndpoint
 *
 * @fires {@link module:core#event:UriEndpointStateChanged UriEndpointStateChanged}
 */
function UriEndpoint(){
  UriEndpoint.super_.call(this);
};
inherits(UriEndpoint, Endpoint);

//
// Public properties
//

/**
 * State of the endpoint
 *
 * @alias module:core/abstracts.UriEndpoint#getState
 *
 * @param {module:core/abstracts.UriEndpoint~getStateCallback} [callback]
 *
 * @return {external:Promise}
 */
UriEndpoint.prototype.getState = function(callback){
  var transaction = (arguments[0] instanceof Transaction)
                  ? Array.prototype.shift.apply(arguments)
                  : undefined;

  var usePromise = false;

  if (callback == undefined) {
    usePromise = true;
  }

  if(!arguments.length) callback = undefined;

  callback = (callback || noop).bind(this)

  return disguise(this._invoke(transaction, 'getState', callback), this)
};
/**
 * @callback module:core/abstracts.UriEndpoint~getStateCallback
 * @param {external:Error} error
 * @param {module:core/complexTypes.UriEndpointState} result
 */

/**
 * The uri for this endpoint.
 *
 * @alias module:core/abstracts.UriEndpoint#getUri
 *
 * @param {module:core/abstracts.UriEndpoint~getUriCallback} [callback]
 *
 * @return {external:Promise}
 */
UriEndpoint.prototype.getUri = function(callback){
  var transaction = (arguments[0] instanceof Transaction)
                  ? Array.prototype.shift.apply(arguments)
                  : undefined;

  var usePromise = false;

  if (callback == undefined) {
    usePromise = true;
  }

  if(!arguments.length) callback = undefined;

  callback = (callback || noop).bind(this)

  return disguise(this._invoke(transaction, 'getUri', callback), this)
};
/**
 * @callback module:core/abstracts.UriEndpoint~getUriCallback
 * @param {external:Error} error
 * @param {external:String} result
 */

//
// Public methods
//

/**
 * Pauses the feed
 *
 * @alias module:core/abstracts.UriEndpoint.pause
 *
 * @param {module:core/abstracts.UriEndpoint~pauseCallback} [callback]
 *
 * @return {external:Promise}
 */
UriEndpoint.prototype.pause = function(callback){
  var transaction = (arguments[0] instanceof Transaction)
                  ? Array.prototype.shift.apply(arguments)
                  : undefined;

  var usePromise = false;

  if (callback == undefined) {
    usePromise = true;
  }

  if(!arguments.length) callback = undefined;

  callback = (callback || noop).bind(this)

  return disguise(this._invoke(transaction, 'pause', callback), this)
};
/**
 * @callback module:core/abstracts.UriEndpoint~pauseCallback
 * @param {external:Error} error
 */

/**
 * Stops the feed
 *
 * @alias module:core/abstracts.UriEndpoint.stop
 *
 * @param {module:core/abstracts.UriEndpoint~stopCallback} [callback]
 *
 * @return {external:Promise}
 */
UriEndpoint.prototype.stop = function(callback){
  var transaction = (arguments[0] instanceof Transaction)
                  ? Array.prototype.shift.apply(arguments)
                  : undefined;

  var usePromise = false;

  if (callback == undefined) {
    usePromise = true;
  }

  if(!arguments.length) callback = undefined;

  callback = (callback || noop).bind(this)

  return disguise(this._invoke(transaction, 'stop', callback), this)
};
/**
 * @callback module:core/abstracts.UriEndpoint~stopCallback
 * @param {external:Error} error
 */

/**
 * @alias module:core/abstracts.UriEndpoint.constructorParams
 */
UriEndpoint.constructorParams = {
};

/**
 * @alias module:core/abstracts.UriEndpoint.events
 *
 * @extends module:core/abstracts.Endpoint.events
 */
UriEndpoint.events = Endpoint.events.concat(['UriEndpointStateChanged']);

/**
 * Checker for {@link module:core/abstracts.UriEndpoint}
 *
 * @memberof module:core/abstracts
 *
 * @param {external:String} key
 * @param {module:core/abstracts.UriEndpoint} value
 */
function checkUriEndpoint(key, value)
{
  if(!(value instanceof UriEndpoint))
    throw ChecktypeError(key, UriEndpoint, value);
};

module.exports = UriEndpoint;

UriEndpoint.check = checkUriEndpoint;


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61968.Customers;
using TTC2017.SmartGrids.CIM.IEC61968.Metering;
using TTC2017.SmartGrids.CIM.IEC61968.Work;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations;

namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCustomers
{

    /// <summary>
    /// The public interface for SubscribePowerCurve
    /// </summary>
    [DefaultImplementationTypeAttribute(typeof(SubscribePowerCurve))]
    [XmlDefaultImplementationTypeAttribute(typeof(SubscribePowerCurve))]
    public interface ISubscribePowerCurve : IModelElement, ICurve
    {

        /// <summary>
        /// The PricingStructure property
        /// </summary>
        IPricingStructure PricingStructure
        {
            get;
            set;
        }

        /// <summary>
        /// Gets fired before the PricingStructure property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> PricingStructureChanging;

        /// <summary>
        /// Gets fired when the PricingStructure property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> PricingStructureChanged;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<versioned.host.exp.exponent.modules.api.components.picker.CheckedTextViewImpl
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@android:id/text1"
    style="?android:attr/spinnerDropDownItemStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:padding="16dp"
    tools:viewBindingIgnore="true"/>


text:
package org.apache.xml.security.utils;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * The Internationalization (I18N) pack.
 *
 */
public final class I18n {

    /** Field NOT_INITIALIZED_MSG */
    public static final String NOT_INITIALIZED_MSG =
        "You must initialize the xml-security library correctly before you use it. "
        + "Call the static method \"org.apache.xml.security.Init.init();\" to do that "
        + "before you use any functionality from that library.";

    /** Field resourceBundle */
    private static ResourceBundle resourceBundle;

    /** Field alreadyInitialized */
    private static boolean alreadyInitialized = false;

    /**
     * Constructor I18n
     *
     */
    private I18n() {
        // we don't allow instantiation
    }

    /**
     * Method translate
     *
     * translates a message ID into an internationalized String, see alse
     * XMLSecurityException.getExceptionMEssage(). The strings are
     * stored in the ResourceBundle, which is identified in
     * exceptionMessagesResourceBundleBase
     *
     * @param message
     * @param args is an Object[] array of strings which are inserted into
     * the String which is retrieved from the ResouceBundle
     * @return message translated
     */
    public static String translate(String message, Object[] args) {
        return getExceptionMessage(message, args);
    }

    /**
     * Method translate
     *
     * translates a message ID into an internationalized String, see also
     * XMLSecurityException.getExceptionMessage()
     *
     * @param message
     * @return message translated
     */
    public static String translate(String message) {
        return getExceptionMessage(message);
    }

    /**
     * Method getExceptionMessage
     *
     * @param msgID
     * @return message translated
     *
     */
    public static String getExceptionMessage(String msgID) {
        try {
            return resourceBundle.getString(msgID);
        } catch (Throwable t) {
            if (org.apache.xml.security.Init.isInitialized()) {
                return "No message with ID \"" + msgID
                + "\" found in resource bundle \""
                + Constants.exceptionMessagesResourceBundleBase + "\"";
            }
            return I18n.NOT_INITIALIZED_MSG;
        }
    }

    /**
     * Method getExceptionMessage
     *
     * @param msgID
     * @param originalException
     * @return message translated
     */
    public static String getExceptionMessage(String msgID, Exception originalException) {
        try {
            Object[] exArgs = { originalException.getMessage() };
            return MessageFormat.format(resourceBundle.getString(msgID), exArgs);
        } catch (Throwable t) {
            if (org.apache.xml.security.Init.isInitialized()) {
                return "No message with ID \"" + msgID
                + "\" found in resource bundle \""
                + Constants.exceptionMessagesResourceBundleBase
                + "\". Original Exception was a "
                + originalException.getClass().getName() + " and message "
                + originalException.getMessage();
            }
            return I18n.NOT_INITIALIZED_MSG;
        }
    }

    /**
     * Method getExceptionMessage
     *
     * @param msgID
     * @param exArgs
     * @return message translated
     */
    public static String getExceptionMessage(String msgID, Object[] exArgs) {
        try {
            return MessageFormat.format(resourceBundle.getString(msgID), exArgs);
        } catch (Throwable t) {
            if (org.apache.xml.security.Init.isInitialized()) {
                return "No message with ID \"" + msgID
                + "\" found in resource bundle \""
                + Constants.exceptionMessagesResourceBundleBase + "\"";
            }
            return I18n.NOT_INITIALIZED_MSG;
        }
    }

    /**
     * Method init
     *
     * @param languageCode
     * @param countryCode
     */
    public static synchronized void init(String languageCode, String countryCode) {
        if (alreadyInitialized) {
            return;
        }

        I18n.resourceBundle =
            ResourceBundle.getBundle(
                Constants.exceptionMessagesResourceBundleBase,
                new Locale(languageCode, countryCode)
            );
        alreadyInitialized = true;
    }

    /**
     * Method init
     * @param resourceBundle
     */
    public static synchronized void init(ResourceBundle resourceBundle) {
        if (alreadyInitialized) {
            return;
        }

        I18n.resourceBundle = resourceBundle;
        alreadyInitialized = true;
    }
}


text:
Kato is a butler for your $HOME. He is named after Inspector Clouseau's
butler from the Pink Panther series of movies. Kato looks after your dotfiles,
your $PATH, your ~/bin, cleans up for you, and more.

### Can I get Kato for my $HOME?

Kato is an NPM package so he is easy to install, you just need to have
[node](http://nodejs.org/) installed.

`npm install -g kato`

Kato is not quite ready for employment yet, but when he is, you'll
wonder what you did without him.

### Stay tuned for more developments.

Created in 2013 by [Jacob Degeling](mailto:me@jacobdegeling.com)

Released under the MIT licence.


text:
<?xml version="1.0" encoding="utf-8"?>
<com.github.bigexcalibur.herovideo.ui.widget.banner.BannerView
    android:id="@+id/home_recommended_banner"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />


text:
/*
 * @bug 4337857
 * @summary Verify that custom serialization methods declared with incorrect
 *          return types are not invoked.
 */

import java.io.*;

class A implements Serializable {
    private static final long serialVersionUID = 0L;

    static boolean readObjectNoDataCalled;

    private Object readObjectNoData() throws ObjectStreamException {
        readObjectNoDataCalled = true;
        return null;
    }
}

class B extends A {
    private static final long serialVersionUID = 0L;

    static boolean readObjectCalled;
    static boolean readResolveCalled;

    private Integer readObject(ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        readObjectCalled = true;
        in.defaultReadObject();
        return null;
    }

    private B readResolve() throws ObjectStreamException {
        readResolveCalled = true;
        return this;
    }
}

public class Read {
    public static void main(String[] args) throws Exception {
        ObjectInputStream oin =
            new ObjectInputStream(new FileInputStream("tmp.ser"));
        B b = (B) oin.readObject();
        if (A.readObjectNoDataCalled) {
            throw new Error("readObjectNoData with wrong return type called");
        } else if (B.readObjectCalled) {
            throw new Error("readObject with wrong return type called");
        } else if (B.readResolveCalled) {
            throw new Error("readResolve with wrong return type called");
        }
    }
}


text:
from waldur_core.logging.loggers import EventLogger, event_logger
from waldur_core.structure import models as structure_models

from . import models

class ResourceActionEventLogger(EventLogger):
    resource = structure_models.BaseResource
    action_details = dict

    class Meta:
        event_types = (
            'resource_pull_scheduled',
            'resource_pull_succeeded',
            'resource_pull_failed',
            # volume
            'resource_attach_scheduled',
            'resource_attach_succeeded',
            'resource_attach_failed',
            'resource_detach_scheduled',
            'resource_detach_succeeded',
            'resource_detach_failed',
            'resource_extend_scheduled',
            'resource_extend_succeeded',
            'resource_extend_failed',
            # instance
            'resource_update_security_groups_scheduled',
            'resource_update_security_groups_succeeded',
            'resource_update_security_groups_failed',
            'resource_change_flavor_scheduled',
            'resource_change_flavor_succeeded',
            'resource_change_flavor_failed',
            'resource_assign_floating_ip_scheduled',
            'resource_assign_floating_ip_succeeded',
            'resource_assign_floating_ip_failed',
            'resource_stop_scheduled',
            'resource_stop_succeeded',
            'resource_stop_failed',
            'resource_start_scheduled',
            'resource_start_succeeded',
            'resource_start_failed',
            'resource_restart_scheduled',
            'resource_restart_succeeded',
            'resource_restart_failed',
            'resource_extend_volume_scheduled',
            'resource_extend_volume_succeeded',
            'resource_extend_volume_failed',
            'resource_retype_scheduled',
            'resource_retype_succeeded',
            'resource_retype_failed',
            'resource_unassign_floating_ip_scheduled',
            'resource_unassign_floating_ip_succeeded',
            'resource_unassign_floating_ip_failed',
            'resource_update_internal_ips_scheduled',
            'resource_update_internal_ips_succeeded',
            'resource_update_internal_ips_failed',
            'resource_update_allowed_address_pairs_scheduled',
            'resource_update_allowed_address_pairs_succeeded',
            'resource_update_allowed_address_pairs_failed',
            'resource_update_floating_ips_scheduled',
            'resource_update_floating_ips_succeeded',
            'resource_update_floating_ips_failed',
        )
        event_groups = {'resources': event_types}

    @staticmethod
    def get_scopes(event_context):
        resource = event_context['resource']
        project = resource.project
        return {resource, project, project.customer}

class BackupScheduleEventLogger(EventLogger):
    resource = models.Instance
    backup_schedule = models.BackupSchedule

    class Meta:
        event_types = (
            'resource_backup_schedule_created',
            'resource_backup_schedule_deleted',
            'resource_backup_schedule_activated',
            'resource_backup_schedule_deactivated',
            'resource_backup_schedule_cleaned_up',
        )
        event_groups = {'resources': event_types}

    @staticmethod
    def get_scopes(event_context):
        return ResourceActionEventLogger.get_scopes(event_context)

class SnapshotScheduleEventLogger(EventLogger):
    resource = models.Volume
    snapshot_schedule = models.SnapshotSchedule

    class Meta:
        event_types = (
            'resource_snapshot_schedule_created',
            'resource_snapshot_schedule_deleted',
            'resource_snapshot_schedule_activated',
            'resource_snapshot_schedule_deactivated',
            'resource_snapshot_schedule_cleaned_up',
        )
        event_groups = {'resources': event_types}

    @staticmethod
    def get_scopes(event_context):
        return ResourceActionEventLogger.get_scopes(event_context)

class BackupEventLogger(EventLogger):
    resource = models.Instance

    class Meta:
        event_types = (
            'resource_backup_creation_scheduled',
            'resource_backup_creation_succeeded',
            'resource_backup_creation_failed',
            'resource_backup_restoration_scheduled',
            'resource_backup_restoration_succeeded',
            'resource_backup_restoration_failed',
            'resource_backup_deletion_scheduled',
            'resource_backup_deletion_succeeded',
            'resource_backup_deletion_failed',
            'resource_backup_schedule_creation_succeeded',
            'resource_backup_schedule_update_succeeded',
            'resource_backup_schedule_deletion_succeeded',
            'resource_backup_schedule_activated',
            'resource_backup_schedule_deactivated',
        )

    @staticmethod
    def get_scopes(event_context):
        return ResourceActionEventLogger.get_scopes(event_context)

class FloatingIPEventLogger(EventLogger):
    floating_ip = models.FloatingIP
    instance = models.Instance

    class Meta:
        event_types = (
            'openstack_floating_ip_connected',
            'openstack_floating_ip_disconnected',
        )
        event_groups = {'resources': event_types}

    @staticmethod
    def get_scopes(event_context):
        floating_ip = event_context['floating_ip']
        instance = event_context['instance']
        return [
            floating_ip,
            instance,
        ]

event_logger.register('openstack_resource_action', ResourceActionEventLogger)
event_logger.register('openstack_backup_schedule', BackupScheduleEventLogger)
event_logger.register('openstack_snapshot_schedule', SnapshotScheduleEventLogger)
event_logger.register('openstack_backup', BackupEventLogger)
event_logger.register('openstack_tenant_floating_ip', FloatingIPEventLogger)


text:
require_relative '../../spec_helper'

describe 'Client Interface:' do
  describe 'Support Event Streaming Operations' do

    before(:all) do
      SpecHelper.generate_service(['Events'], multiple_files: false)
    end

    let(:stream) {
      [
        # eventheader & eventpayload(blob)
        { message_type: 'event', event_type: :a, member_a: 'foo', member_b: StringIO.new('bar') },
        # eventpayload(string)
        { message_type: 'event', event_type: :b, member_c: 'baz' },
        # eventpayload(structure)
        { message_type: 'event', event_type: :c, member_d: {struct_member_a: 'foo', struct_member_b: 'bar'} },
        # an unmodeled error event
        { message_type: 'error', error_code: 'InternalError', error_message: 'An internal server error occurred'}
      ].each
    }
    let(:client) {
      Events::Client.new(
        region: 'us-west-2',
        credentials: Aws::Credentials.new('akid', 'secret'),
        stub_responses: {foo: {
          payload: stream
        }}
      )
    }

    it 'supports eventstream object for `event_stream_handler` option' do
      handler = Events::EventStreams::BarPayload.new
      tracker = {}
      handler.on_a_event {|e| tracker[:a] = e}
      handler.on_b_event {|e| tracker[:b] = e}
      handler.on_c_event {|e| tracker[:c] = e}
      resp = client.foo(event_stream_handler: handler)

      expect(tracker[:a].member_a).to eq('foo')
      expect(tracker[:a].member_b.read).to eq('bar')
      expect(tracker[:b].member_c.read).to eq('baz')
      expect(tracker[:c].member_d.struct_member_a).to eq('foo')
      expect(tracker[:c].member_d.struct_member_b).to eq('bar')
      expect(resp.payload).to be_a(Enumerator)
    end

    it 'support Proc object for `event_stream_handler` option' do
      tracker = {}
      handler = Proc.new do |stream|
        stream.on_a_event {|e| tracker[:a] = e}
        stream.on_b_event {|e| tracker[:b] = e}
        stream.on_c_event {|e| tracker[:c] = e}
      end
      resp = client.foo(event_stream_handler: handler)

      expect(tracker[:a].member_a).to eq('foo')
      expect(tracker[:a].member_b.read).to eq('bar')
      expect(tracker[:b].member_c.read).to eq('baz')
      expect(tracker[:c].member_d.struct_member_a).to eq('foo')
      expect(tracker[:c].member_d.struct_member_b).to eq('bar')
      expect(resp.payload).to be_a(Enumerator)
    end

    it 'supports no `event_stream_handler` option input' do
      resp = client.foo

      expect(resp.payload).to be_a(Enumerator)
      resp.payload.each do |event|
        case event.event_type
        when :a
          expect(event.member_a).to eq('foo')
          expect(event.member_b.read).to eq('bar')
        when :b
          expect(event.member_c.read).to eq('baz')
        when :c
          expect(event.member_d.struct_member_a).to eq('foo')
          expect(event.member_d.struct_member_b).to eq('bar')
        end
      end
    end

    it 'supports block streaming' do
      tracker = {}
      resp = client.foo do |stream|
        stream.on_event {|event| tracker[event.event_type] = event}
      end

      expect(tracker[:a].member_a).to eq('foo')
      expect(tracker[:a].member_b.read).to eq('bar')
      expect(tracker[:b].member_c.read).to eq('baz')
      expect(tracker[:c].member_d.struct_member_a).to eq('foo')
      expect(tracker[:c].member_d.struct_member_b).to eq('bar')
      expect(resp.payload).to be_a(Enumerator)
    end

    it 'supports `event_stream_handler` and block streaming at same time' do
      tracker = {later: []}
      handler = Events::EventStreams::BarPayload.new
      handler.on_a_event {|e| tracker[:a] = e}
      handler.on_b_event {|e| tracker[:b] = e}
      handler.on_c_event {|e| tracker[:c] = e}
      resp = client.foo(event_stream_handler: handler) do |stream|
        stream.on_event {|e| tracker[:later] << e}
      end

      expect(tracker[:a].member_a).to eq('foo')
      expect(tracker[:a].member_b.read).to eq('bar')
      expect(tracker[:b].member_c.read).to eq('baz')
      expect(tracker[:c].member_d.struct_member_a).to eq('foo')
      expect(tracker[:c].member_d.struct_member_b).to eq('bar')
      # error event is also an event
      expect(tracker[:later].size).to eq(4)
      expect(tracker[:later][0]).to eq(tracker[:a])
      expect(tracker[:later][1]).to eq(tracker[:b])
      expect(tracker[:later][2]).to eq(tracker[:c])
      expect(resp.payload).to be_a(Enumerator)
    end

    it 'supports error event' do
      error = nil
      handler = Events::EventStreams::BarPayload.new
      handler.on_error_event do |e|
        error = e
        raise e
      end
      expect {
        client.foo(event_stream_handler: handler)
      }.to raise_error(Aws::Errors::EventError)
      expect(error.error_code).to eq('InternalError')
      expect(error.error_message).to eq('An internal server error occurred')
    end

  end
end


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

import java.io.IOException;

import db.DBHandle;
import ghidra.framework.data.DomainObjectAdapterDB;
import ghidra.trace.model.TraceUserData;
import ghidra.util.task.TaskMonitor;

public class DBTraceUserData extends DomainObjectAdapterDB implements TraceUserData {

	private static String getName(DBTrace trace) {
		return trace.getName() + "_UserData";
	}

	protected DBTraceUserData(DBTrace trace) throws IOException {
		super(new DBHandle(), getName(trace), 500, trace);
		// TODO: Create database and such
	}

	public DBTraceUserData(DBHandle dbh, DBTrace trace, TaskMonitor monitor) {
		super(dbh, getName(trace), 500, trace);
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean isChangeable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
AUX
===

AUX is a small set of auxillary tools. Currently it consits of a time.Duration
humanizer which is simply a transliteration of the Ruby interface.


text:
include ../Make.Rules

ifeq ($(DEBUG_REL),yes)
 LIBNAME=libpamcd
else
 LIBNAME=libpamc
endif
VERSION=.$(MAJOR_REL)
MODIFICATION=.$(MINOR_REL)

CFLAGS += $(MOREFLAGS) $(DYNAMIC) $(STATIC)

# dynamic library names

LIBNAMED = $(LIBNAME).$(DYNTYPE)
LIBNAMEDNAME = $(LIBNAMED)$(VERSION)
LIBNAMEDFULL = $(LIBNAMEDNAME)$(MODIFICATION)

# static library name

LIBNAMEDSTATIC = $(LIBNAME).a

LIBOBJECTS = pamc_client.o pamc_converse.o pamc_load.o

ifeq ($(DYNAMIC_LIBPAM),yes)
DLIBOBJECTS = $(addprefix dynamic/,$(LIBOBJECTS))
endif

ifeq ($(STATIC_LIBPAM),yes)
SLIBOBJECTS = $(addprefix static/,$(LIBOBJECTS))
endif

# ---------------------------------------------
## rules

all: dirs $(LIBNAMED) $(LIBNAMEDSTATIC)

dirs:
ifeq ($(DYNAMIC_LIBPAM),yes)
	$(MKDIR) dynamic
endif
ifeq ($(STATIC_LIBPAM),yes)
	$(MKDIR) static
endif

dynamic/%.o : %.c
	$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@

static/%.o : %.c
	$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@

$(LIBNAMED): $(DLIBOBJECTS)
ifeq ($(DYNAMIC_LIBPAM),yes)
    ifeq ($(USESONAME),yes)
	$(LD_L) $(SOSWITCH) $(LIBNAMEDNAME) -o $@ $(DLIBOBJECTS) $(MODULES) $(LINKLIBS)
    else
	$(LD_L) -o $@ $(DLIBOBJECTS) $(MODULES)
    endif
    ifeq ($(NEEDSONAME),yes)
	rm -f $(LIBNAMEDFULL)
	ln -s $(LIBNAMED) $(LIBNAMEDFULL)
	rm -f $(LIBNAMEDNAME)
	ln -s $(LIBNAMED) $(LIBNAMEDNAME)
    endif
endif

$(LIBNAMEDSTATIC): $(SLIBOBJECTS)
ifeq ($(STATIC_LIBPAM),yes)
	$(AR) rc $@ $(SLIBOBJECTS) $(MODULES)
	$(RANLIB) $@
endif

install: all
	$(MKDIR) $(FAKEROOT)$(INCLUDED)
	$(INSTALL) -m 644 include/security/pam_client.h $(FAKEROOT)$(INCLUDED)
ifeq ($(DYNAMIC_LIBPAM),yes)
	$(MKDIR) $(FAKEROOT)$(libdir)
	$(INSTALL) -m $(SHLIBMODE) $(LIBNAMED) $(FAKEROOT)$(libdir)/$(LIBNAMEDFULL)
	$(LDCONFIG)
  ifneq ($(DYNTYPE),"sl")
	( cd $(FAKEROOT)$(libdir) ; rm -f $(LIBNAMED) ; ln -s $(LIBNAMEDNAME) $(LIBNAMED) )
  endif
endif
ifeq ($(STATIC_LIBPAM),yes)
	$(INSTALL) -m 644 $(LIBNAMEDSTATIC) $(FAKEROOT)$(libdir)
endif

remove:
	rm -f $(FAKEROOT)$(INCLUDED)/pam_client.h
	rm -f $(FAKEROOT)$(libdir)/$(LIBNAMEDFULL)
	rm -f $(FAKEROOT)$(libdir)/$(LIBNAMED)
	$(LDCONFIG)
	rm -f $(FAKEROOT)$(libdir)/$(LIBNAMEDSTATIC)

clean:
	rm -f a.out core *~ static/*.o dynamic/*.o
	rm -f *.a *.out *.o *.so ./include/security/*~
	if [ -d dynamic ]; then rmdir dynamic ; fi
	if [ -d static ]; then rmdir static ; fi


text:
package com.outworkers.morpheus.engine.query

import com.outworkers.morpheus.DataType
import com.outworkers.morpheus.builder.{DefaultQueryBuilder, DefaultSQLSyntax, SQLBuiltQuery}
import com.outworkers.morpheus.Row
import com.outworkers.morpheus.column.AbstractColumn

private[morpheus] abstract class BaseQueryCondition(val clause: SQLBuiltQuery)

case class QueryAssignment(clause: SQLBuiltQuery)

abstract class SelectOperatorClause[T : DataType](val qb: SQLBuiltQuery) {
  def fromRow(row: Row): T
}

/**
 * This is a wrapper clause for primary conditions.
 * They wrap the Clause used in a "WHERE" or "AND" query.
 *
 * Only indexed columns can produce a QueryCondition via "WHERE" and "AND" operators.
 * @param clause The clause to use.
 */
case class QueryCondition(override val clause: SQLBuiltQuery, count: Int = 0) extends BaseQueryCondition(clause) {

  /**
   * This implementation is used to handle enclosing parentheses for an unknown number of OR operator usages.
   * Since an unlimited number of OR operators and conditions can be chained to form a single WHERE or AND clause,
   * we need a way to delimit the full clause by enclosing parentheses without knowing how many OR clauses there are or without knowing what the internals
   * of a clause look like. Clauses like the IN clause have their own set of parentheses.
   * An example: {@code SELECT* FROM something WHERE (a = 5 OR a in (5, 10, 15)) }.
   *
   * Using the count parameter we can count the number of combinations in a manner invisible to the user. If the count is 0,
   * append the left '(' and the right ')' and for everyone thereafter, remove the ')', add the new clause, add a ')',
   * effectively always moving the right ')' to the end of the full WHERE or AND clause.
   *
   * @param condition The QueryCondition to OR with.
   * @return A new QueryCondition, where the underlying query has been OR-ed.
   */
  def or(condition: QueryCondition): QueryCondition = {
    if (count == 0) {
      QueryCondition(DefaultQueryBuilder.or(
        clause.prepend(DefaultSQLSyntax.`(`),
        condition.clause.append(DefaultSQLSyntax.`)`)),
        count + 1
      )
    } else {
      QueryCondition(DefaultQueryBuilder.or(
        SQLBuiltQuery(clause.queryString.dropRight(1)),
        condition.clause.append(DefaultSQLSyntax.`)`)),
        count + 1
      )
    }
  }
}

case class BetweenClause[T: DataType](qb: SQLBuiltQuery) {

  def and(value: T): QueryCondition = {
    QueryCondition(
      qb.forcePad
        .append(DefaultSQLSyntax.and)
        .forcePad.append(implicitly[DataType[T]].serialize(value))
    )
  }
}

/**
 * This encloses the full list of available comparison operators.
 * @param col The column to cast to an IndexedColumn.
 * @tparam T The type of the value the column holds.
 */
private[morpheus] abstract class AbstractQueryColumn[T: DataType](col: AbstractColumn[T]) {

  /**
   * The equals operator. Will return a match if the value equals the database value.
   * @param value The value to search for in the database.
   * @return A QueryCondition, wrapping a QueryBuilder clause.
   */
  def eqs(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.eqs(col.name, col.toQueryString(value)))
  }

  def lt(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.lt(col.name, col.toQueryString(value)))
  }

  def <(value: T): QueryCondition = lt(value)

  def lte(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.lte(col.name, col.toQueryString(value)))
  }

  def <=(value: T): QueryCondition = lte(value)

  def gt(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.gt(col.name, col.toQueryString(value)))
  }

  def >(value: T): QueryCondition = gt(value)

  def gte(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.gte(col.name, col.toQueryString(value)))
  }

  def >=(value: T): QueryCondition = gte(value)

  def !=(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.!=(col.name, col.toQueryString(value)))
  }

  def <>(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.!=(col.name, col.toQueryString(value)))
  }

  def like(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.like(col.name, col.toQueryString(value)))
  }

  def notLike(value: T): QueryCondition = {
    QueryCondition(col.table.queryBuilder.notLike(col.name, col.toQueryString(value)))
  }

  def in(values: List[T]) : QueryCondition = {
    val primitive = implicitly[DataType[T]]
    QueryCondition(col.table.queryBuilder.in(col.name, values.map(primitive.serialize)))
  }

  def in(values: T*): QueryCondition = {
    val primitive = implicitly[DataType[T]]
    QueryCondition(col.table.queryBuilder.in(col.name, values.map(primitive.serialize)))
  }

  def notIn(values: List[T]) : QueryCondition = {
    val primitive = implicitly[DataType[T]]
    QueryCondition(col.table.queryBuilder.notIn(col.name, values.map(primitive.serialize)))
  }

  def notIn(values: T*) : QueryCondition = {
    val primitive = implicitly[DataType[T]]
    QueryCondition(col.table.queryBuilder.notIn(col.name, values.map(primitive.serialize)))
  }

  def isNull: QueryCondition = {
    QueryCondition(col.table.queryBuilder.isNull(SQLBuiltQuery(col.name)))
  }

  def isNotNull: QueryCondition = {
    QueryCondition(col.table.queryBuilder.isNotNull(SQLBuiltQuery(col.name)))
  }

  def between(value: T): BetweenClause[T] = {
    BetweenClause(
      col.table.queryBuilder.between(col.name, col.toQueryString(value))
    )
  }

  def notBetween(value: T): BetweenClause[T] = {
    BetweenClause(
      col.table.queryBuilder.notBetween(col.name, col.toQueryString(value))
    )
  }
}

class SQLQueryColumn[T: DataType](col: AbstractColumn[T]) extends AbstractQueryColumn[T](col)

case class QueryOrder(clause: SQLBuiltQuery)

abstract class AbstractOrderingColumn[T: DataType](col: AbstractColumn[T]) {
  def asc: QueryOrder = QueryOrder(col.table.queryBuilder.asc(col.name))
  def desc: QueryOrder = QueryOrder(col.table.queryBuilder.desc(col.name))
}


text:
export { getMarkupFromTree, getDataFromTree } from "./getDataFromTree.js";
export { renderToStringWithData } from "./renderToStringWithData.js";
export { RenderPromises } from "./RenderPromises.js";
//# sourceMappingURL=index.js.map


text:
import {Routes,RouterModule} from "@angular/router"
import {UserComponent} from "./components/user.component"
import {GalleryComponent} from "./components/gallery.component"
import {PostComponent} from "./components/post.component";
import {AppComponent} from "./app.component";
import {AutoCompleteComponent} from "./components/autocomplete.component";

const APP_ROUTES : Routes = [
    {path:'',redirectTo:'user',pathMatch:'full'},
    {path:'user',component:UserComponent},
    {path:'post',component:PostComponent},
    {path:'gallery',component:GalleryComponent},
    {path:'autocomplete',component:AutoCompleteComponent},
]

export const routing = RouterModule.forRoot(APP_ROUTES);


text:
from hazelcast.protocol.builtin import FixSizedTypesCodec, CodecUtil
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import END_FRAME_BUF, END_FINAL_FRAME_BUF, SIZE_OF_FRAME_LENGTH_AND_FLAGS, create_initial_buffer_custom
from hazelcast.sql import _SqlError
from hazelcast.protocol.builtin import StringCodec

_CODE_ENCODE_OFFSET = 2 * SIZE_OF_FRAME_LENGTH_AND_FLAGS
_CODE_DECODE_OFFSET = 0
_ORIGINATING_MEMBER_ID_ENCODE_OFFSET = _CODE_ENCODE_OFFSET + INT_SIZE_IN_BYTES
_ORIGINATING_MEMBER_ID_DECODE_OFFSET = _CODE_DECODE_OFFSET + INT_SIZE_IN_BYTES
_INITIAL_FRAME_SIZE = _ORIGINATING_MEMBER_ID_ENCODE_OFFSET + UUID_SIZE_IN_BYTES - SIZE_OF_FRAME_LENGTH_AND_FLAGS

class SqlErrorCodec:
    @staticmethod
    def encode(buf, sql_error, is_final=False):
        initial_frame_buf = create_initial_buffer_custom(_INITIAL_FRAME_SIZE)
        FixSizedTypesCodec.encode_int(initial_frame_buf, _CODE_ENCODE_OFFSET, sql_error.code)
        FixSizedTypesCodec.encode_uuid(initial_frame_buf, _ORIGINATING_MEMBER_ID_ENCODE_OFFSET, sql_error.originating_member_id)
        buf.extend(initial_frame_buf)
        CodecUtil.encode_nullable(buf, sql_error.message, StringCodec.encode)
        CodecUtil.encode_nullable(buf, sql_error.suggestion, StringCodec.encode)
        if is_final:
            buf.extend(END_FINAL_FRAME_BUF)
        else:
            buf.extend(END_FRAME_BUF)

    @staticmethod
    def decode(msg):
        msg.next_frame()
        initial_frame = msg.next_frame()
        code = FixSizedTypesCodec.decode_int(initial_frame.buf, _CODE_DECODE_OFFSET)
        originating_member_id = FixSizedTypesCodec.decode_uuid(initial_frame.buf, _ORIGINATING_MEMBER_ID_DECODE_OFFSET)
        message = CodecUtil.decode_nullable(msg, StringCodec.decode)
        is_suggestion_exists = False
        suggestion = None
        if not msg.peek_next_frame().is_end_frame():
            suggestion = CodecUtil.decode_nullable(msg, StringCodec.decode)
            is_suggestion_exists = True
        CodecUtil.fast_forward_to_end_frame(msg)
        return _SqlError(code, message, originating_member_id, is_suggestion_exists, suggestion)


text:
$(document).ready(function(){
	$('#submitFeedback').on('click', function(){
		var ajaxData = $('#feebackForm').serialize() + '&action=send_feedback';

		$.post('./_Public/db_request?do=send_feedback', ajaxData , function(data){
			var json = JSON.parse(data);
			if(json.growl == 'success'){
				$('#feebackForm')[0].reset();
				confirm(json.msg);
			}else{
				confirm(json.msg);
			}

		});
	});
});


text:
__requires__ = 'setuptools==0.6c11'
import sys
from pkg_resources import load_entry_point

sys.exit(
   load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')()
)


text:
layout: page
title: Cardenas - Foley Wedding
date: 2016-05-24
author: Ashley Mckee
tags: weekly links, java
status: published
summary: Sed non interdum nibh. Donec ultricies.
banner: images/banner/wedding.jpg
booking:
  startDate: 02/28/2016
  endDate: 03/03/2016
  ctyhocn: HSVHCHX
  groupCode: CFW
published: true
---
Vivamus condimentum laoreet massa, et eleifend mi pretium ut. Pellentesque non tincidunt nunc. Curabitur volutpat aliquam leo vitae ultrices. Vivamus sagittis ut odio ac sagittis. Vivamus id justo nisl. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque at consectetur nisi. Nam efficitur elit quis orci commodo consectetur. Curabitur pulvinar nibh id varius laoreet. Nunc mi libero, gravida eu ornare eu, facilisis vel eros. Quisque lorem elit, tempus sed urna vitae, tempus porta odio.
Mauris mollis vitae nulla quis condimentum. Morbi vitae neque tellus. Curabitur id velit leo. Cras molestie quam ligula, eget malesuada urna imperdiet nec. Integer dolor sem, convallis ornare massa at, posuere rutrum risus. In pharetra venenatis quam. Aliquam non ligula lobortis, cursus purus id, rutrum arcu. Etiam ut varius enim. Donec ante dui, facilisis at eros et, interdum aliquet ante. Nullam sed sapien sit amet nisl porta malesuada. Praesent justo leo, condimentum sed tristique eget, auctor a ex. Phasellus vel leo eu quam condimentum semper. Mauris aliquam ut nibh et sagittis.

* Proin tincidunt risus tincidunt dui cursus, at accumsan ligula mollis
* Aliquam sed eros eu neque pharetra posuere
* Aenean maximus mi sed congue convallis.

Mauris in ipsum rhoncus, egestas nisi ut, lobortis metus. Cras vestibulum ante non odio facilisis, ut tempus purus euismod. Cras nunc magna, eleifend vitae tincidunt eget, eleifend et quam. Pellentesque mollis varius tortor at hendrerit. Ut pretium est sit amet ultricies placerat. Nunc accumsan elit ut suscipit suscipit. Cras ac quam ac dui molestie rhoncus. Quisque id lacinia tellus, id venenatis neque. Vivamus porttitor faucibus eleifend. Quisque lobortis sed risus sit amet accumsan. Fusce consequat eleifend elit, ac porttitor est tempor sit amet.


text:
$packageName = '{{PackageName}}'
$softwareName = "SketchUp [0-9]*"
$installerType = 'msi'
$silentArgs = '/quiet /qn /norestart'
$validExitCodes = @(0,3010)

[array]$key = Get-UninstallRegistryKey -SoftwareName $softwareName

$key | ForEach-Object {
  Uninstall-ChocolateyPackage -PackageName $packageName `
                              -FileType $installerType `
                              -SilentArgs "$($_.PSChildName) $silentArgs" `
                              -ValidExitCodes $validExitCodes
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DotNetProgrammersToolbox.Account
{

    public partial class ChangePasswordSuccess
    {
    }
}


text:
(function() {
  'use strict';

  angular.module('cla.directives')
    .directive('details', function() {
      return {
        restrict: 'E',
        link: function(scope, element) {
          var hasNativeSupport = 'open' in document.createElement('details'),
              notSummaryChildren,
              toggleShow;

          // return if browser already has native support
          if (hasNativeSupport) { return; }

          notSummaryChildren = element.children(':not(summary)');
          // hide on load
          notSummaryChildren.hide();

          toggleShow = function () {
            notSummaryChildren
              .toggle()
              .toggleClass('is-open');
            element
              .toggleClass('is-open');
          };

          element
            .addClass('is-notnative')
            .on('click', toggleShow);
        }
      };
    });
}());


text:
import asyncio
from .decorator import decorate
from .assertions import assert_corofunction

@decorate
def defer(coro, delay=1):
    """
    Returns a coroutine function wrapper that will defer the given coroutine
    execution for a certain amount of seconds in a non-blocking way.

    This function can be used as decorator.

    Arguments:
        coro (coroutinefunction): coroutine function to defer.
        delay (int/float): number of seconds to defer execution.

    Raises:
        TypeError: if coro argument is not a coroutine function.

    Returns:
        filtered values (list): ordered list of resultant values.

    Usage::

        # Usage as function
        await paco.defer(coro, delay=1)
        await paco.defer(coro, delay=0.5)

        # Usage as decorator
        @paco.defer(delay=1)
        async def mul_2(num):
            return num * 2

        await mul_2(2)
        # => 4

    """
    assert_corofunction(coro=coro)

    @asyncio.coroutine
    def wrapper(*args, **kw):
        # Wait until we're done
        yield from asyncio.sleep(delay)
        return (yield from coro(*args, **kw))

    return wrapper


text:
raise NotImplementedError(
    'No mac context yet...feel free to contribute!'
)


text:
if ENV['CODECLIMATE_REPO_TOKEN']
  require 'codeclimate-test-reporter'
  CodeClimate::TestReporter.start
end

require 'active_support/all'
require 'timecop'
require 'itunes_receipt_mock'

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end


text:
package shoehorn;

import java.util.Map;

/**
 * @author Ryan Brainard
 */
public class Shoehorn {

    @SuppressWarnings("UnusedDeclaration")
    public static void premain(String agentArgs) {
        new Shoehorn(System.getenv(), new MappingLoader().load(System.getenv())).shoehorn();
    }

    private final Map<String, String> environment;
    private final Map<String, String> mappings;

    public Shoehorn(Map<String, String> environment, Map<String, String> mappings) {
        this.environment = environment;
        this.mappings = mappings;
    }

    void shoehorn() {
        for (Map.Entry<String, String> map : mappings.entrySet()) {
            final String propName = map.getKey();
            final String envName = map.getValue();

            if (!environment.containsKey(envName)) {
                continue;
            }

            System.setProperty(propName, environment.get(envName));
            System.out.println("Shoehorned [" + envName + "] into [" + propName + "]");
        }
    }
}


text:
<Record name="ld_bcn_org_rpts_t" type="delimited">
  <Field name="fin_coa_cd"                      type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="org_cd"                          type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="obj_id"                          type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="ver_nbr"                         type="numeric"    nullable="true"  trim="false" delimiter="|"  />
  <Field name="rpts_to_fin_coa_cd"              type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="rpts_to_org_cd"                  type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="rc_cd"                           type="string"     nullable="true"  trim="false" delimiter="|\r\n" />
</Record>


text:
package org.synyx.urlaubsverwaltung.mail;

import org.springframework.core.io.ByteArrayResource;
import org.synyx.urlaubsverwaltung.person.MailNotification;
import org.synyx.urlaubsverwaltung.person.Person;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class Mail {

    private final List<Person> mailAddressRecipients;
    private final MailNotification mailNotificationRecipients;
    private final boolean sendToTechnicalMail;

    private final String templateName;
    private final Map<String, Object> templateModel;

    private final String subjectMessageKey;
    private final Object[] subjectMessageArguments;

    private final List<MailAttachment> mailAttachments;

    Mail(List<Person> mailAddressRecipients, MailNotification mailNotificationRecipients, boolean sendToTechnicalMail,
         String templateName, Map<String, Object> templateModel, String subjectMessageKey,
         Object[] subjectMessageArguments, List<MailAttachment> mailAttachments) {
        this.mailAddressRecipients = mailAddressRecipients;
        this.mailNotificationRecipients = mailNotificationRecipients;
        this.sendToTechnicalMail = sendToTechnicalMail;
        this.templateName = templateName;
        this.templateModel = templateModel;
        this.subjectMessageKey = subjectMessageKey;
        this.subjectMessageArguments = subjectMessageArguments;
        this.mailAttachments = mailAttachments;
    }

    public Optional<List<Person>> getMailAddressRecipients() {
        return Optional.ofNullable(mailAddressRecipients);
    }

    public Optional<MailNotification> getMailNotificationRecipients() {
        return Optional.ofNullable(mailNotificationRecipients);
    }

    public boolean isSendToTechnicalMail() {
        return sendToTechnicalMail;
    }

    public String getTemplateName() {
        return templateName;
    }

    public Map<String, Object> getTemplateModel() {
        return templateModel;
    }

    public String getSubjectMessageKey() {
        return subjectMessageKey;
    }

    public Object[] getSubjectMessageArguments() {
        return subjectMessageArguments;
    }

    public Optional<List<MailAttachment>> getMailAttachments() {
        return Optional.ofNullable(mailAttachments);
    }

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

    /**
     * Mail Builder for an easier way to create a mail
     */
    public static class Builder {

        private List<Person> mailAddressRecipients = new ArrayList<>();
        private MailNotification mailNotificationRecipients;
        private boolean sendToTechnicalMail;

        private String templateName;
        private Map<String, Object> templateModel = new HashMap<>();

        private String subjectMessageKey;
        private Object[] subjectMessageArguments;

        private List<MailAttachment> mailAttachments;

        public Mail.Builder withTechnicalRecipient(boolean sendToTechnicalMail) {
            this.sendToTechnicalMail = sendToTechnicalMail;
            return this;
        }

        public Mail.Builder withRecipient(MailNotification mailNotification) {
            this.mailNotificationRecipients = mailNotification;
            return this;
        }

        public Mail.Builder withRecipient(Person recipient) {
            withRecipient(List.of(recipient));
            return this;
        }

        public Mail.Builder withRecipient(List<Person> recipients) {
            if (mailAddressRecipients == null) {
                mailAddressRecipients = new ArrayList<>();
            }

            this.mailAddressRecipients.addAll(recipients);
            return this;
        }

        public Mail.Builder withTemplate(String templateName, Map<String, Object> templateModel) {
            this.templateName = templateName;
            this.templateModel = templateModel;
            return this;
        }

        public Mail.Builder withSubject(String subjectMessageKey, Object... subjectMessageArguments) {
            this.subjectMessageKey = subjectMessageKey;
            this.subjectMessageArguments = subjectMessageArguments;
            return this;
        }

        public Mail.Builder withAttachment(String name, ByteArrayResource attachment) {
            if (mailAttachments == null) {
                mailAttachments = new ArrayList<>();
            }

            this.mailAttachments.add(new MailAttachment(name, attachment));
            return this;
        }

        public Mail build() {
            return new Mail(mailAddressRecipients, mailNotificationRecipients, sendToTechnicalMail,
                templateName, templateModel, subjectMessageKey, subjectMessageArguments,
                mailAttachments);
        }
    }
}


text:
<?php
/**
 *
 * This file is part of Aura for PHP.
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Filter\Rule\Validate;

use Aura\Filter\Rule\AbstractDateTime;

/**
 *
 * Validate that a value can be represented as a date/time.
 *
 * @package Aura.Filter
 *
 */
class DateTime extends AbstractDateTime
{
    /**
     *
     * Validate that a value can be represented as a date/time.
     *
     * @param object $subject The subject to be filtered.
     *
     * @param string $field The subject field name.
     *
     * @return bool
     *
     */
    public function __invoke($subject, $field)
    {
        $value = $subject->$field;
        $datetime = $this->newDateTime($value);
        return (bool) $datetime;
    }
}


text:
const assert = require('assert');
const testUtils = require('../test-utils');
const mysql = require('./index');

const connection = {
  name: 'test mysql',
  driver: 'mysql',
  host: 'localhost',
  database: 'sqlpad',
  username: 'sqlpad',
  password: 'sqlpad',
  maxRows: 10000,
};

const dropTable = 'DROP TABLE IF EXISTS test;';
const createTable = 'CREATE TABLE test (id int);';
const inserts = 'INSERT INTO test (id) VALUES (1), (2), (3);';

describe('drivers/mysql', function () {
  before(function () {
    this.timeout(10000);
    return mysql
      .runQuery(dropTable, connection)
      .then(() => mysql.runQuery(createTable, connection))
      .then(() => mysql.runQuery(inserts, connection));
  });

  it('tests connection', function () {
    return mysql.testConnection(connection);
  });

  it('getSchema()', function () {
    return mysql.getSchema(connection).then((schemaInfo) => {
      const column = testUtils.getColumn(schemaInfo, 'sqlpad', 'test', 'id');
      assert(column.hasOwnProperty('dataType'));
    });
  });

  it('runQuery under limit', function () {
    return mysql
      .runQuery('SELECT id FROM test WHERE id = 1;', connection)
      .then((results) => {
        assert(!results.incomplete, 'not incomplete');
        assert.equal(results.rows.length, 1, 'rows length');
      });
  });

  it('runQuery over limit', function () {
    const limitedConnection = { ...connection, maxRows: 2 };
    return mysql
      .runQuery('SELECT * FROM test;', limitedConnection)
      .then((results) => {
        assert(results.incomplete, 'incomplete');
        assert.equal(results.rows.length, 2, 'row length');
      });
  });

  it('returns descriptive error message', function () {
    let error;
    return mysql
      .runQuery('SELECT * FROM missing_table;', connection)
      .catch((e) => {
        error = e;
      })
      .then(() => {
        assert(error);
        assert(error.toString().indexOf('missing_table') > -1);
      });
  });

  it('Client handles client interface', async function () {
    const client = new mysql.Client(connection);
    await client.connect();
    await client.runQuery('START TRANSACTION');
    await client.runQuery('SELECT 1 AS val');
    await client.runQuery('ROLLBACK');
    await client.disconnect();
  });
});


text:
[![Gem Version](https://img.shields.io/gem/v/dump.svg?style=flat)](https://rubygems.org/gems/dump)
[![Build Status](https://img.shields.io/travis/toy/dump/master.svg?style=flat)](https://travis-ci.org/toy/dump)
[![Code Climate](https://img.shields.io/codeclimate/github/toy/dump.svg?style=flat)](https://codeclimate.com/github/toy/dump)

# Dump

Rails app rake and capistrano tasks to create and restore dumps of database and assets.

Tested against rails 2.3, 3.1, 3.2, 4.0, 4.1, 4.2.

Works with ruby 1.8.7, 1.9.3, 2.0, 2.1, 2.2 (rails 4.0 requires at least ruby 1.9), nominally works with jruby (see [travis](https://travis-ci.org/toy/dump)).

## Install

Put in Gemfile if you are using bundler:

    gem 'dump'

Install as plugin for rails 3 (not recommended):

    rails plugin install git://github.com/toy/dump.git

Install as plugin for rails 2:

    script/plugin install git://github.com/toy/dump.git

### Capistrano integration

To get capistrano tasks in rails 3, put in `config/deploy.rb`:

    require 'dump/capistrano'

### Assets config

`config/assets` holds paths of dirs you want to dump in file:

    public/audios
    public/flash
    public/images/upload
    public/videos

Generate in rails 3:

    rails generate assets_config

Generate in rails 2:

    script/generate assets_config

## Capistrano integration

When using cap tasks, dump folder should be in persistent place and be linked to application folder, or you will lose all dumps every deploy. Default recipe creates link on after `deploy:update_code`.

You can use cap dump:* tasks to control dumps on remote server. Don't forget to deploy application to remote server before using dump:remote tasks.
Also you can set custom remote rake binary in your deploy.rb like:

    set :rake, "/custom/rake"

## Usage

    # create dump
    rake dump
    rake dump:create

    # list avaliable dumps
    rake dump:versions

    # restore dump
    rake dump:restore

    # delete old and unfinished dumps (all non tgz files will be deleted if they are not locked)
    rake dump:cleanup

### Environment variables

#### While creating dumps:

`DESC`, `DESCRIPTION` — free form description of dump

    rake dump DESC='uploaded photos'

`TAGS`, `TAG` — comma separated list of tags

    rake dump TAGS='photos,videos'

`ASSETS` — comma or colon separated list of paths or globs to dump

    rake dump ASSETS='public/system:public/images/masks/*'
    rake dump ASSETS='public/system,public/images/masks/*'

`TABLES` — comma separated list of tables to dump or if prefixed by "-" — to skip; by default only sessions table is skipped; schema_info and schema_migrations are always included if they are present

dump all tables except sessions:

    rake dump

dump all tables:

    rake dump TABLES='-'

dump only people, pages and photos tables:

    rake dump TABLES='people,pages,photos'

dump all tables except people and pages:

    rake dump TABLES='-people,pages'

#### While restoring dumps:

`LIKE`, `VER`, `VERSION` — filter dumps by full dump name

    rake dump:versions LIKE='2009'
    rake dump:restore LIKE='2009' # restores last dump matching 2009

`TAGS`, `TAG` — comma separated list of tags
without '+' or '-' — dump should have any of such tags
prefixed with '+' — dump should have every tag with prefix
prefixed with '-' — dump should not have any of tags with prefix

select dumps with tags photos or videos:

    rake dump:restore TAGS='photos,videos'

select dumps with tags photos and videos:

    rake dump:restore TAGS='+photos,+videos'

skip dumps with tags mirror and archive:

    rake dump:restore TAGS='-mirror,-archive'

select dumps with tags photos or videos, with tag important and without mirror:

    rake dump:restore TAGS='photos,videos,+important,-mirror'

`MIGRATE_DOWN` — don't run down for migrations not present in dump if you pass "0", "no" or "false"; pass "reset" to recreate (drop and create) db
by default all migrations which are not present in dump are ran down

don't run down for migrations:

    rake dump:restore MIGRATE_DOWN=no

reset database:

    rake dump:restore MIGRATE_DOWN=reset

`RESTORE_SCHEMA` — don't read/change schema if you pass "0", "no" or "false" (useful to just restore data for table; note that schema info tables are also not restored)

don't restore schema:

    rake dump:restore RESTORE_SCHEMA=no

`RESTORE_TABLES` — works as TABLES, but for restoring

restores only people, pages and photos tables:

    rake dump RESTORE_TABLES='people,pages,photos'

restores all tables except people and pages:

    rake dump TABLES='-people,pages'

`RESTORE_ASSETS` — works as ASSETS, but for restoring

    rake dump RESTORE_ASSETS='public/system/a,public/system/b'
    rake dump RESTORE_ASSETS='public/system/a:public/images/masks/*/new*'

#### For listing dumps:

`LIKE`, `VER`, `VERSION` and `TAG`, `TAGS` as for restoring

`SUMMARY` — output info about dump: "1", "true" or "yes" for basic info, "2" or "schema" to display schema as well

    rake dump:versions SUMMARY=1
    rake dump:versions SUMMARY=full # output schema too

#### For cleanup:

`LIKE`, `VER`, `VERSION` and `TAG`, `TAGS` as for restoring

`LEAVE` — number of dumps to leave

    rake dump:cleanup LEAVE=10
    rake dump:cleanup LEAVE=none

### cap tasks

For all cap commands environment variables are same as for rake tasks

`TRANSFER_VIA` — transfer method (rsync, sftp or scp)
By default transferring task will try to transfer using rsync if it is present, else it will try to use sftp and scp

force transfer using scp:

    cap dump:remote:download TRANSFER_VIA=scp
    cap dump:mirror:down TRANSFER_VIA=scp

`BACKUP`, `AUTOBACKUP`, `AUTO_BACKUP` — no autobackup if you pass "0", "no" or "false"
by default backup is created before mirroring

don't create backup:

    cap dump:mirror:down BACKUP=0
    cap dump:mirror:down AUTOBACKUP=no
    cap dump:mirror:down AUTO_BACKUP=false

#### Basic cap tasks are same as rake tasks

    cap dump:local
    cap dump:local:create
    cap dump:local:restore
    cap dump:local:versions
    cap dump:local:cleanup

    cap dump:remote
    cap dump:remote:create
    cap dump:remote:restore
    cap dump:remote:versions
    cap dump:remote:cleanup

#### Dump exchanging tasks

transfer selected dump to remote server:

    cap dump:local:upload

transfer selected dump to local:

    cap dump:remote:download

#### Mirroring tasks

mirror local to remote (create local dump, upload it to remote and restore it there):

    cap dump:mirror:up

mirror remote to local (create remote dump, download it from remote and restore on local):

    cap dump:mirror:down

#### Backuping tasks

backup remote on local (create remote dump and download it):

    cap dump:backup:create

restore backup (upload dump and restore on remote):

    cap dump:backup:restore

#### If you have separate db server

by default, dump's capistrano tasks use remote server with role :db, :primary => true. If you have separate db server, and want to use dump with assets, you should run cap tasks as following:

    cap dump:mirror:down HOSTS=myappserver.com

where myappserver.com is application server carrying assets with database access.

## Copyright

Copyright (c) 2008-2015 Ivan Kuchin. See LICENSE.txt for details.


text:
package com.github.mike10004.xvfbmanager;

import com.google.common.collect.Iterables;
import org.junit.Test;

import static org.junit.Assert.*;

public class ListTreeNodeTest {

    @Test
    public void getLevel() throws Exception {
        TreeNode<Integer> l1, l2, l3;
        TreeNode<Integer> root = node(0)
                .addChild(l1 = node(1))
                .addChild(node(1).addChild(l2 = node(2)).addChild(node(2).addChild(l3 = node(3))))
                .addChild(node(1));
        System.out.format("bfs: %s%n", Iterables.toString(root.breadthFirstTraversal().labels()));
        assertEquals("level", 0, root.getLevel());
        assertEquals("level", 1, l1.getLevel());
        assertEquals("level", 2, l2.getLevel());
        assertEquals("level", 3, l3.getLevel());
    }

    private static <E> ListTreeNode<E> node(E label) {
        return new ListTreeNode<>(label);
    }

    @Test
    public void isRoot() throws Exception {
        ListTreeNode<String> root = new ListTreeNode<>("root");
        assertTrue("isRoot", root.isRoot());
        ListTreeNode<String> child = new ListTreeNode<>("child");
        root.addChild(child);
        assertFalse("isRoot", child.isRoot());
    }

    @Test
    public void isLeaf() throws Exception {
        ListTreeNode<String> root = new ListTreeNode<>("root");
        assertTrue("isLeaf", root.isLeaf());
        ListTreeNode<String> child = new ListTreeNode<>("child");
        root.addChild(child);
        assertFalse("isLeaf", root.isLeaf());
        assertTrue("isLeaf", child.isLeaf());
    }

}


text:
#ifndef __WLF_DISPLAY_H
#define __WLF_DISPLAY_H

#include <wayland-client.h>

typedef struct wlf_display wlfDisplay;

#include "wlfreerdp.h"

struct wlf_display
{
	struct wl_display* display;
	struct wl_registry* registry;
	struct wl_compositor* compositor;
	struct wl_shell* shell;
	struct wl_shm* shm;
	struct wl_seat* seat;
};

wlfDisplay* wlf_CreateDisplay(void);
void wlf_RefreshDisplay(wlfDisplay* display);
void wlf_DestroyDisplay(wlfContext* wlfc, wlfDisplay* display);

#endif /* __WLF_DISPLAY_H */


text:
<?php
/**
*
* min preset returns the basic toolbar configuration set for CKEditor.
* @author denoll <denoll@denoll.ru>
* @link http://www.denoll.ru/
*/
return [
'height' => 200,
'toolbarGroups' => [
['name' => 'undo'],
['name' => 'basicstyles', 'groups' => ['basicstyles', 'cleanup']],
['name' => 'colors'],
],
'removeButtons' => 'Subscript,Superscript,Flash,Table,HorizontalRule,SpecialChar,PageBreak,Iframe', //Smiley,
'removePlugins' => 'elementspath',
'resize_enabled' => false
];


text:
import styled from 'styled-components';

const FlexKey = styled.div`
  display: flex;
  flex-wrap: wrap;
  width: 33.333%;
`;
export default FlexKey;


text:
Promisify.js
============

Convert event to Promises/A style API


text:
package com.gauravbytes.hellogb.component;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 *
 * @author Gaurav Rai Mazra Catch me
 */
@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
	private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);

	@Override
	public void run(String... args) throws Exception {
		logger.info(
				"Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.",
				Arrays.toString(args));
	}

}


text:
@import url("taskstatistics.css");

div.trend {
	left: 0;
	right: auto;
}

.taskstatsresults th {
	text-align: right;
}

.taskstatsresults th, .taskstatsresults td {
	padding: 9px 32px 9px 10px;
}

.taskstatsresults .resourcecount {
	text-align: right;
}


text:
package org.apache.spot.dns

import org.apache.spark.broadcast.Broadcast
import org.apache.spark.sql.functions._
import org.apache.spot.utilities.DomainProcessor.{DomainInfo, extractDomainInfo}
import org.apache.spot.utilities.Quantiles
import org.apache.spot.utilities.data.validation.InvalidDataHandler

import scala.util.{Success, Try}

/**
  * Convert DNS log entries into "words" for topic modelling analyses.
  *
  * @param frameLengthCuts Quantile cut-offs for discretizing frame length in word construction.
  * @param timeCuts Quantile cut-offs for discretizing the time of day in word construction.
  * @param subdomainLengthCuts Quantile cut-offs for discretizing subdomain length in word construction.
  * @param entropyCuts Quantile cut-offs for discretizing entropy in word construction.
  * @param numberPeriodsCuts Quantile cut-offs for discretizing the number of periods in word construction.
  * @param topDomainsBC List of most popular top level domain names.
  * @param userDomain User's domain for internal network.
  */
class DNSWordCreation(frameLengthCuts: Array[Double],
                      timeCuts: Array[Double],
                      subdomainLengthCuts: Array[Double],
                      entropyCuts: Array[Double],
                      numberPeriodsCuts: Array[Double],
                      topDomainsBC: Broadcast[Set[String]],
                      userDomain: String) extends Serializable {

  /**
    * Create a new UDF for adding a word column to a dataframe.
    * The dataframe must provide the following columns:
    *
    * A string timestamp, a long unixtimestamp, an integer framelength,
    * a string client IP, a string query name, a string query class, an integer query type
    * and an integer query response code.
    *
    * @return A dataframe UDF of signature:
    *         (timeStamp: String, unixTimeStamp: Long, frameLength: Int, clientIP: String,
    *         queryName: String, queryClass: String, dnsQueryType: Int, dnsQueryRCode :Int) =>  Word: String
    */
  def wordCreationUDF =
    udf((timeStamp: String,
         unixTimeStamp: Long,
         frameLength: Int,
         clientIP: String,
         queryName: String,
         queryClass: String,
         dnsQueryType: Int,
         dnsQueryRcode: Int) => dnsWord(timeStamp,
      unixTimeStamp,
      frameLength,
      clientIP,
      queryName,
      queryClass,
      dnsQueryType,
      dnsQueryRcode))

  /**
    * Simplify a DNS log entry into a word.
    *
    * @param timeStamp     Timestamp as a string.
    * @param unixTimeStamp Unix timestamp as a 64 bit integer
    * @param frameLength   Framelength as an integer.
    * @param clientIP      IP of client making DNS query as string.
    * @param queryName     URL being queried.
    * @param queryClass    Query class as string.
    * @param dnsQueryType  Query type as integer.
    * @param dnsQueryRcode Query response code as integer.
    * @return The word representation of the DNS entry.
    */

  def dnsWord(timeStamp: String,
              unixTimeStamp: Long,
              frameLength: Int,
              clientIP: String,
              queryName: String,
              queryClass: String,
              dnsQueryType: Int,
              dnsQueryRcode: Int): String = {

    Try {
      val DomainInfo(domain, topDomain, subdomain, subdomainLength, subdomainEntropy, numPeriods) =
        extractDomainInfo(queryName, topDomainsBC, userDomain)

      Seq(topDomain,
        Quantiles.bin(frameLength.toDouble, frameLengthCuts),
        Quantiles.bin(unixTimeStamp.toDouble, timeCuts),
        Quantiles.bin(subdomainLength.toDouble, subdomainLengthCuts),
        Quantiles.bin(subdomainEntropy, entropyCuts),
        Quantiles.bin(numPeriods.toDouble, numberPeriodsCuts),
        dnsQueryType,
        dnsQueryRcode).mkString("_")
    } match {
      case Success(word) => word
      case _ => InvalidDataHandler.WordError
    }

  }
}


text:
<?php

// $Id$

require_once('../../../../../boot.inc.php');
boot('my_site_adm');

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/pages/ci/ci_article/ci_article_edit_wp.class.php');

session_start();

global $_MODULES_REGISTER;
$user_auth_config = $_MODULES_REGISTER->get_module_config('admin_user_auth');

$page = new CI_Article_Edit_WP('ci_article_edit', 'admin/modules/tangra_cms/ci/ci_article/ci_article_manage.php', $user_auth_config);
$SITE->run($page, new Web_Context);


text:
require 'spec_helper'

describe Kikambii::Feature do

  let(:runner) { mock.as_null_object }
  subject { described_class.new feature: "feature/test.feature", scenarios: [1, 10], runner: runner }

  describe "#run" do
    it "should run feature command for each scenario" do
      runner.should_receive(:run).with("feature/test.feature:1")
      runner.should_receive(:run).with("feature/test.feature:10")

      subject.run
    end

    it "should increment attemps number" do
      subject.run
      subject.attemps.should == 1
    end

    context "when all runs were true" do
      before do
        runner.stub(:run).and_return(true)
      end

      it { subject.run.should be_true }
    end

    context "when some run fail" do
      before do
        runner.stub(:run).and_return(false)
      end

      it { subject.run.should be_false }
    end

    context "when runner return true" do
      before do
        runner.stub(:run).with("feature/test.feature:1").and_return(false)
        runner.stub(:run).with("feature/test.feature:10").and_return(true)

        subject.run
      end

      it "should not run the same scenario again" do
        runner.should_receive(:run).with("feature/test.feature:1")
        runner.should_not_receive(:run).with("feature/test.feature:10")

        subject.run
      end
    end

    context "when attemps sold up" do
      before do
        subject.instance_variable_set "@attemps", 3
      end

      it "should not run any scenario" do
        runner.should_not_receive(:run)
        subject.run
      end
    end
  end

  describe "#fail?" do
    context "when attemps sold up" do

      context "and there are scenarios to run" do
        before do
          subject.instance_variable_set "@scenarios", ["1"]
        end

        it { subject.fail?.should be_true }
      end

      context "and there aren't scenarios to run" do
        before do
          subject.instance_variable_set "@scenarios", []
        end

        it { subject.fail?.should be_false }
      end
    end
  end
end


text:
import useStyles from 'isomorphic-style-loader/useStyles';
import React from 'react';
import PropTypes from 'prop-types';
import s from './ErrorPage.css';

export function ErrorPageWithoutStyle({ error }) {
  if (__DEV__ && error) {
    return (
      <>

{error.name}

{error.stack}

      </>
    );
  }

  return (
    <>

Error

Sorry, a critical error occurred on this page.

    </>
  );
}

ErrorPageWithoutStyle.propTypes = {
  error: PropTypes.shape({
    name: PropTypes.string.isRequired,
    message: PropTypes.string.isRequired,
    stack: PropTypes.string.isRequired,
  }),
};

ErrorPageWithoutStyle.defaultProps = {
  error: null,
};

export default function ErrorPage(props) {
  useStyles(s);
  return ErrorPageWithoutStyle(props);
}


text:
/*
  Place all the styles related to the matching controller here.
  They will automatically be included in application.css.
*/

/* for the menu editor */
.menu-editor {
  list-style: none;
  padding: 0;
  background-color: whitesmoke;
  min-height:64px;
  padding-bottom: 12px;

  li {
    padding: 8px 4px;
    cursor: pointer;
    display: block;
    min-height: 52px;

    img {
      margin-right: 8px;
    }
  }
}


text:
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var notify = require('gulp-notify');
var autoprefixer = require('gulp-autoprefixer');
var inject = require('gulp-inject');
var config = require('../config');

gulp.task('sass', function () {
    var cssStream = gulp.src(config.sass.src)
        .pipe(sass())
        .on("error", notify.onError(function (error) {
            return error.message;
        }))
        .pipe(autoprefixer({
            browsers: ['last 2 version']
        }))
        .pipe(gulp.dest(config.sass.dest));

    return gulp.src(config.markup.dest + '/**/*.html')
        .pipe(inject(cssStream, {read: false, ignorePath: config.inject.ignore, addRootSlash: false, name: 'style'}))
        .pipe(gulp.dest(config.markup.dest)).pipe(browserSync.reload({
            stream: true
        }));
});


text:
require "knjrbfw"

class RgettextPoedit
  def initialize(args)
    @args  = args
    @files = args[:files]
    @translations = {}
    @method_names = ["_", "gettext"]
    @valid_beginning = '(^|\s+|\(|\{|<%=\s*)'
    @comments = []
  end

  def parse_files
    raise "No files was given." if !@files || @files.empty?

    @files.each do |filepath|
      parse_filepath(filepath)
    end
  end

  def write_file
    raise "No output-filepath was given." unless @args[:output_filepath]

    File.open(@args[:output_filepath], "w") do |fp|
      fp.write(generate_output)
    end
  end

  def generate_output
    # Generate and write output.
    @output = ""
    @translations.each do |translation, data|
      @output << "\n" if @output.length > 0

      data[:files].each do |file|
        @output << "#: #{file[:filepath]}:#{file[:line_no]}\n"
      end

      data[:comments].each do |comment|
        puts "Comment: #{comment}"
        @output << "#. #{comment}\n"
      end

      @output << "msgid \"#{translation}\"\n"
      @output << "msgstr \"\"\n"
    end

    return @output
  end

private

  # Opens a file, reads the content while keeping track of line-numbers and saves found translations.
  def parse_filepath(filepath)
    File.open(filepath, "r") do |fp|
      line_no = 0
      fp.each_line do |line|
        line_no += 1
        next if should_skip_line(filepath, line_no, line)
        parse_content(filepath, line_no, line)
      end
    end
  end

  # Scans content for translations and saves them.
  def parse_content(filepath, line_no, content)
    content.scan(/^\s*#\. (.+)$/) do |match|
      add_comment(match[0])
    end

    @method_names.each do |method_name|
      # Scan for the various valid formats.
      content.scan(/#{@valid_beginning}#{Regexp.escape(method_name)}\s*\("(.+?)"/) do |match|
        add_translation(filepath, line_no, match[1])
      end

      content.scan(/#{@valid_beginning}#{Regexp.escape(method_name)}\s*"(.+?)"/) do |match|
        add_translation(filepath, line_no, match[1])
      end

      content.scan(/#{@valid_beginning}#{Regexp.escape(method_name)}\s*\('(.+?)'/) do |match|
        add_translation(filepath, line_no, match[1])
      end

      content.scan(/#{@valid_beginning}#{Regexp.escape(method_name)}\s*'(.+?)'/) do |match|
        add_translation(filepath, line_no, match[1])
      end
    end
  end

  def should_skip_line(filepath, line_no, line)
    # Skip the line if it is a comment in Haml.
    return true if File.extname(filepath) == ".haml" && line.match(/^(\s*)-(\s*)#/)
    return false
  end

  def add_comment(comment)
    @comments << comment
  end

  def add_translation(filepath, line_no, translation)
    if !@translations.key?(translation)
      @translations[translation] = {:files => [], :comments => @comments}
    else
      @translations[translation][:comments] += @comments
    end

    @translations[translation][:files] << {:filepath => filepath, :line_no => line_no}
    @comments = []
  end
end


text:
require.config({
    paths: {
        'jquery': '../bower_components/jquery/dist/jquery',
        'async': '../bower_components/requirejs-plugins/src/async',
        'jquery-color': '../bower_components/jquery-color/jquery.color'
    },
    shim: {
        'lodash': {
            exports: '_'
        },
        'google': {
            'deps': ['document'],
            'exports' : 'google'
        },
        'jquery-color': {
            'deps': ['jquery']
        }
    }
});

require(['jquery','async!http://maps.google.com/maps/api/js?sensor=false', 'jquery-color'], function($) {
    var currentPosition;

    initialize();

    function saveLocation() {
        var data = getFormData();
        if(!data) {
            return;
        }

        // *** Insert the save logic here ***
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: "http://localhost:8010/api/location",
            data: JSON.stringify(data)
        }).done(function(response) {
            console.log(response);
        }).fail(function(error) {
            console.log(error);
        });
    }

    function initialize() {
        var mapOptions = {
            zoom: 8,
            center:  new google.maps.LatLng(-25.363882, 131.044922)
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
        var marker;

        google.maps.event.addListener(map, 'click', function(e) {
            changePosition(e.latLng);
        });

        function changePosition(latLng) {
            marker = marker || new google.maps.Marker({
                position: map.getCenter(),
                map: map
            });
            marker.setPosition(latLng);
            currentPosition = latLng;

            $('#latitude').html(latLng.lat());
            $('#longitude').html(latLng.lng());
        }

        $("#saveLocationBtn").click(saveLocation);
    }

    /**
     * Validates the form and does some UI logic. Ensures we have entered currentPosition and tags.
     * @returns {Object | null}
     */
    function getFormData() {
        var isValid = true;
        var $tags = $("#tags");
        var tags = $tags.val();
        var $name = $("#name");
        var name = $name.val();

        var $noTagsMsg = $("#noTagsMsg");
        var $noNameMsg = $("#noNameMsg");

        if(!tags) {
            $tags.keypress(function() {
                $noTagsMsg.hide();
            });
            flashElement($noTagsMsg);
            $noTagsMsg.show();
            isValid = false;
        } else {
            $noTagsMsg.hide();
        }

        if(!name) {
            $name.keypress(function() {
                $noNameMsg.hide();
            });
            flashElement($noNameMsg);
            $noNameMsg.show();
            isValid = false;
        } else {
            $noNameMsg.hide();
        }

        if(!currentPosition) {
            flashElement($("#positionWrp"));
            isValid = false;
        }

        if(isValid) {
            return {
                name: name,
                position: {
                    lng: currentPosition.lng(),
                    lat: currentPosition.lat()
                },
                tags: tags.trim().split(' ')
            }
        }
    }

    function flashElement(el){
        el.stop().css("background-color", "#FFAFAF").animate({ backgroundColor: "#FFFFFF"}, 1500);
    }
});


text:
// Postgres specific functions for goiardi database work.

package datastore

import (
	"fmt"
	"github.com/ctdk/goiardi/config"
	"strings"
)

func formatPostgresqlConStr(p interface{}) string {
	params := p.(config.PostgreSQLdb)
	var conParams []string

	if params.Username != "" {
		cu := fmt.Sprintf("user=%s", params.Username)
		conParams = append(conParams, cu)
	}
	if params.Password != "" {
		cp := fmt.Sprintf("password=%s", params.Password)
		conParams = append(conParams, cp)
	}
	if params.Host != "" {
		cp := fmt.Sprintf("host=%s", params.Host)
		conParams = append(conParams, cp)
	}
	if params.Port != "" {
		cp := fmt.Sprintf("port=%s", params.Port)
		conParams = append(conParams, cp)
	}
	if params.Dbname != "" {
		cp := fmt.Sprintf("dbname=%s", params.Dbname)
		conParams = append(conParams, cp)
	}
	if params.SSLMode != "" {
		cp := fmt.Sprintf("sslmode=%s", params.SSLMode)
		conParams = append(conParams, cp)
	}

	constr := strings.Join(conParams, " ")

	return constr
}


text:
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace SpiderBot
{
	public class BaseViewModel : INotifyPropertyChanged, IDisposable
	{
		public event PropertyChangedEventHandler PropertyChanged;

		public BaseViewModel ()
		{

		}
		public void Dispose ()
		{
			ClearEvents ();
		}

		internal bool ProcPropertyChanged<T> (ref T currentValue, T newValue, [CallerMemberName] string propertyName = "")
		{
			return PropertyChanged.SetProperty (this, ref currentValue, newValue, propertyName);
		}

		internal void ProcPropertyChanged (string propertyName)
		{
			if (PropertyChanged != null) {
				PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
			}
		}

		public void ClearEvents ()
		{
			if (PropertyChanged == null)
				return;
			var invocation = PropertyChanged.GetInvocationList ();
			foreach (var p in invocation)
				PropertyChanged -= (PropertyChangedEventHandler)p;
		}
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace EventHub.Tests.ScenarioTests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using Microsoft.Azure.Management.EventHub;
    using Microsoft.Azure.Management.EventHub.Models;
    using Microsoft.Rest.Azure;
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
    using TestHelper;
    using Xunit;
    public partial class ScenarioTests
    {
        [Fact]
        public void DisasterRecoveryCreateGetUpdateDelete()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                InitializeClients(context);

                var location = "South Central US";// this.ResourceManagementClient.GetLocationFromProvider();

                var resourceGroup = "Default-EventHub-SouthCentralUS";//this.ResourceManagementClient.TryGetResourceGroup(location);
                //if (string.IsNullOrWhiteSpace(resourceGroup))
                //{
                //    resourceGroup = TestUtilities.GenerateName(EventHubManagementHelper.ResourceGroupPrefix);
                //    this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup);
                //}

                var namespaceName = TestUtilities.GenerateName(EventHubManagementHelper.NamespacePrefix);

                // Create namespace 1
                var createNamespaceResponse = this.EventHubManagementClient.Namespaces.CreateOrUpdate(resourceGroup, namespaceName,
                    new EHNamespace()
                    {
                        Location = location,
                        Sku = new Sku
                        {
                            Name = SkuName.Standard,
                            Tier = SkuTier.Standard
                        },
                        Tags = new Dictionary<string, string>()
                        {
                            {"tag1", "value1"},
                            {"tag2", "value2"}
                        }
                    });

                Assert.NotNull(createNamespaceResponse);
                Assert.Equal(createNamespaceResponse.Name, namespaceName);
                TestUtilities.Wait(TimeSpan.FromSeconds(5));

                // Create namespace 2
                var namespaceName2 = TestUtilities.GenerateName(EventHubManagementHelper.NamespacePrefix);
                var createNamespaceResponse2 = this.EventHubManagementClient.Namespaces.CreateOrUpdate(resourceGroup, namespaceName2,
                    new EHNamespace()
                    {
                        Location = location,
                        Sku = new Sku
                        {
                            Name = SkuName.Standard,
                            Tier = SkuTier.Standard
                        },
                        Tags = new Dictionary<string, string>()
                        {
                            {"tag1", "value1"},
                            {"tag2", "value2"}
                        }
                    });

                Assert.NotNull(createNamespaceResponse2);
                Assert.Equal(createNamespaceResponse2.Name, namespaceName2);
                TestUtilities.Wait(TimeSpan.FromSeconds(5));

                // Create a Disaster Recovery -
                var disasterRecoveryName = TestUtilities.GenerateName(EventHubManagementHelper.DisasterRecoveryPrefix);

                var DisasterRecoveryResponse = EventHubManagementClient.DisasterRecoveryConfigs.CreateOrUpdate(resourceGroup, namespaceName, disasterRecoveryName, new ArmDisasterRecovery()
                {
                    PartnerNamespace = namespaceName2
                });
                Assert.NotNull(DisasterRecoveryResponse);
                TestUtilities.Wait(TimeSpan.FromSeconds(10));

                //// Get the created DisasterRecovery config - Primary
                var disasterRecoveryGetResponse = EventHubManagementClient.DisasterRecoveryConfigs.Get(resourceGroup, namespaceName, disasterRecoveryName);
                Assert.NotNull(disasterRecoveryGetResponse);
                Assert.Equal(disasterRecoveryGetResponse.Role, RoleDisasterRecovery.Primary);

                //// Get the created DisasterRecovery config - Secondary
                var disasterRecoveryGetResponse_Sec = EventHubManagementClient.DisasterRecoveryConfigs.Get(resourceGroup, namespaceName2, disasterRecoveryName);
                Assert.NotNull(disasterRecoveryGetResponse_Sec);
                Assert.Equal(disasterRecoveryGetResponse_Sec.Role, RoleDisasterRecovery.Secondary);

                var disasterRecoveryGetResponse_Accepted = EventHubManagementClient.DisasterRecoveryConfigs.Get(resourceGroup, namespaceName, disasterRecoveryName);

                while (EventHubManagementClient.DisasterRecoveryConfigs.Get(resourceGroup, namespaceName, disasterRecoveryName).ProvisioningState != ProvisioningStateDR.Succeeded)
                {
                    TestUtilities.Wait(TimeSpan.FromSeconds(10));
                }

                //// Break Pairing
                EventHubManagementClient.DisasterRecoveryConfigs.BreakPairing(resourceGroup, namespaceName, disasterRecoveryName);
                TestUtilities.Wait(TimeSpan.FromSeconds(10));

                while (EventHubManagementClient.DisasterRecoveryConfigs.Get(resourceGroup, namespaceName, disasterRecoveryName).ProvisioningState != ProvisioningStateDR.Succeeded)
                {
                    TestUtilities.Wait(TimeSpan.FromSeconds(10));
                }

                var DisasterRecoveryResponse_update = EventHubManagementClient.DisasterRecoveryConfigs.CreateOrUpdate(resourceGroup, namespaceName, disasterRecoveryName, new ArmDisasterRecovery()
                {
                    PartnerNamespace = namespaceName2
                });
                Assert.NotNull(DisasterRecoveryResponse_update);
                TestUtilities.Wait(TimeSpan.FromSeconds(10));

                while (EventHubManagementClient.DisasterRecoveryConfigs.Get(resourceGroup, namespaceName, disasterRecoveryName).ProvisioningState != ProvisioningStateDR.Succeeded)
                {
                    TestUtilities.Wait(TimeSpan.FromSeconds(10));
                }

                // Fail over
                EventHubManagementClient.DisasterRecoveryConfigs.FailOver(resourceGroup, namespaceName2, disasterRecoveryName);
                TestUtilities.Wait(TimeSpan.FromSeconds(10));

                while (EventHubManagementClient.DisasterRecoveryConfigs.Get(resourceGroup, namespaceName2, disasterRecoveryName).ProvisioningState != ProvisioningStateDR.Succeeded)
                {
                    TestUtilities.Wait(TimeSpan.FromSeconds(10));
                }

                // Get all Disaster Recovery for a given NameSpace
                var getListisasterRecoveryResponse = EventHubManagementClient.DisasterRecoveryConfigs.List(resourceGroup, namespaceName2);
                Assert.NotNull(getListisasterRecoveryResponse);
                Assert.True(getListisasterRecoveryResponse.Count<ArmDisasterRecovery>() >= 1);

                // Delete the DisasterRecovery
                EventHubManagementClient.DisasterRecoveryConfigs.Delete(resourceGroup, namespaceName2, disasterRecoveryName);
                TestUtilities.Wait(TimeSpan.FromSeconds(10));
            }
        }
    }
}


text:
module Cms::Reference
  module StCategory
    extend ActiveSupport::Concern

    included do
      embeds_ids :st_categories, class_name: "Category::Node::Base"
      permit_params category_ids: []
    end

    def st_parent_categories
      categories = []
      parents = st_categories.sort_by { |cate| cate.filename.count("/") }
      while parents.present?
        parent = parents.shift
        parents = parents.map { |c| c.filename !~ /^#{parent.filename}\// ? c : nil }.compact
        categories << parent
      end
      categories
    end
  end
end


text:
import { dissocPath } from "../fp";
export = dissocPath;


text:
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author John Kelly <wablam@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class SpacesBeforeSemicolonFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php for ($uu = 0; ; ++$uu) {}',
                '<?php for ($uu = 0    ;    ; ++$uu) {}',
            ),
            array(
                '<?php
$this
    ->setName(\'readme1\')
    ->setDescription(\'Generates the README content, based on the fix command help\')
;',
            ),
            array(
                '<?php
$this
    ->setName(\'readme2\')
    ->setDescription(\'Generates the README content, based on the fix command help\')
    ;',
            ),
            array(
                '<?php echo "$this->foo(\'with param containing ;\') ;";',
                '<?php echo "$this->foo(\'with param containing ;\') ;" ;',
            ),
            array(
                '<?php $this->foo();',
                '<?php $this->foo() ;',
            ),
            array(
                '<?php $this->foo(\'with param containing ;\');',
                '<?php $this->foo(\'with param containing ;\') ;',
            ),
            array(
                '<?php $this->foo(\'with param containing ) ; \');',
                '<?php $this->foo(\'with param containing ) ; \') ;',
            ),
            array(
                '<?php $this->foo("with param containing ) ; ");',
                '<?php $this->foo("with param containing ) ; ")  ;',
            ),
            array(
                '<?php
    $foo
        ->bar(1)
        ->baz(2)
    ;',
            ),
            array(
                '<?php
    $foo
        ->bar(1)
        //->baz(2)
    ;',
            ),
            array(
                '<?php $this->foo();',
            ),
            array(
                '<?php $this->foo("with semicolon in string) ; ");',
            ),
        );
    }
}


text:
package syscall_test

import (
	"fmt"
	"syscall"
	"testing"
	"unsafe"
)

func TestConvertFromDirent11(t *testing.T) {
	const (
		filenameFmt  = "%04d"
		numFiles     = 64
		fixedHdrSize = int(unsafe.Offsetof(syscall.Dirent_freebsd11{}.Name))
	)

	namlen := len(fmt.Sprintf(filenameFmt, 0))
	reclen := syscall.Roundup(fixedHdrSize+namlen+1, 4)
	old := make([]byte, numFiles*reclen)
	for i := 0; i < numFiles; i++ {
		dent := syscall.Dirent_freebsd11{
			Fileno: uint32(i + 1),
			Reclen: uint16(reclen),
			Type:   syscall.DT_REG,
			Namlen: uint8(namlen),
		}
		rec := make([]byte, reclen)
		copy(rec, (*[fixedHdrSize]byte)(unsafe.Pointer(&dent))[:])
		copy(rec[fixedHdrSize:], fmt.Sprintf(filenameFmt, i+1))
		copy(old[i*reclen:], rec)
	}

	buf := make([]byte, 2*len(old))
	n := syscall.ConvertFromDirents11(buf, old)

	names := make([]string, 0, numFiles)
	_, _, names = syscall.ParseDirent(buf[:n], -1, names)

	if len(names) != numFiles {
		t.Errorf("expected %d files, have %d; names: %q", numFiles, len(names), names)
	}

	for i, name := range names {
		if expected := fmt.Sprintf(filenameFmt, i+1); name != expected {
			t.Errorf("expected names[%d] to be %q; got %q", i, expected, name)
		}
	}
}