text:
/**
    Changelog:
    1.0.7
        - Fixed a problem with calculating frame positions when layout is vertical.
    1.0.6
        - In 1.06, all background-positions are cached on instantiation, so we don't need to calculate before entering a new frame. This dramatically increases performance. Inspired by Jeremy Petrequin's jsMovieclip.
    1.0.5
        - Now, when events are dispatched, a reference to the instance is passed along
    1.0.4
        - Fixed demos so they work with the new project architecture - also updated to jQuery 1.9.1
        - Added AMD factory
        - Moved SpriteClipEvent so it is no longer global. It is now a static member of SpriteClip and is accessed via SpriteClip.Event.ENTER_FRAME, SpriteClip.Event.PLAYING etc.
        - Removed docs as the output was ugly - will replace with another doc library once researched
    1.0.3
        - Split the project into seperate classes
        - Added grunt to build the project - To begin with uglification, concatenation and jsdoc3 - see docs folder for documentation
    1.0.2
        - Renamed SpriteClipEvent.PLAY and SpriteClipEvent.STOP to .PLAYING and .STOPPED and made sure that they are dispatched like so:
          STOPPED: when a clip is stopped completely or when a playing clip is told to play in a different direction
          PLAYING: when a clip that isnt playing starts to play - including when a playing clip is told to play in a different direction
        - Rewrote a lot of comments

    1.0.1
        - Changed rewindToAndStop method name to rewindtoAndStop for case consistency (like as3 gotoAndStop)
        - Changed playToAndStop method name to playtoAndStop for case consistency (like as3 gotoAndStop)
        - Added a public read only property for layout - either "horizontal" or "vertical" that matches what was passed in via settings
        - Added event types PLAY and STOP that are dispatched when play() and stop() are called
*/
(function (factory) {
    if (typeof define === "function" && define.amd) {
        // AMD. Register as an anonymous module.
        define(["jquery"], factory);
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    //Force EC5 strict mode
    "use strict"


text:
@implementation UISearchBar(SOBackgroundView)
- (UIView *)searchBackgroundView {
    for (UIView *view in self.subviews) {
        // for before iOS7.0
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            return (view);
        }
        // for later iOS7.0(include)
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            return ([view.subviews firstObject]);
        }
    }
    return (nil);
}

- (UIView *)searchTextFieldView {
    for(UIView *view in self.subviews) {
        if([view isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
            return (view);
        }
        for(UIView *subview in view.subviews) {
            if([subview isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                return (subview);
            }
        }
    }
    return (nil);
}

@end

redpajama_set_name: RedPajamaGithub


text:
layout: "journal_by_tag"
tag: "nature"
title: "Naturaleza"
description: "Etiquetas"
permalink: "/blog/tag/nature/"
header-img: "img/archive-bg.jpg"
---


text:
using System.Runtime.Serialization;
using ServiceStack.WebHost.Endpoints.Tests.Support.Types;

namespace ServiceStack.WebHost.Endpoints.Tests.Support.Operations
{
	[DataContract]
	public class GetCustomer
	{
		[DataMember]
		public long CustomerId { get; set; }
	}

	[DataContract]
	public class GetCustomerResponse
	{
		[DataMember]
		public Customer Customer { get; set; }
	}
}


text: module.exports = new (require('fragment-cache'))();


text:
function getKey(privateKey) {
    var promise = new Promise(function(resolve, reject) {
        var request = require("request");
        request("https://runkit.io/aplet123/full-encryption/1.0.0?method=getKey&text=" + privateKey, function(error, response, body) {
            if (!error) {
                if (response.statusCode == 200) {
                    var data = JSON.parse(body);
                    if (data.error) {
                        reject(data.error.toUpperCase());
                    } else {
                        resolve(data.text);
                    }
                } else {
                    reject("API MAY BE DOWN OR IS NOT WORKING PROPERLY");
                }
            } else {
                reject("UNKNOWN ERROR");
            }
        });
    });
    return promise;
}

function encrypt(publicKey, text) {
    var promise = new Promise(function(resolve, reject) {
        var request = require("request");
        request("https://runkit.io/aplet123/full-encryption/1.0.0?method=encrypt&key=" + publicKey + "&text=" + text, function(error, response, body) {
            if (!error) {
                if (response.statusCode == 200) {
                    var data = JSON.parse(body);
                    if (data.error) {
                        reject(data.error.toUpperCase());
                    } else {
                        resolve(data.text);
                    }
                } else {
                    reject("API MAY BE DOWN OR IS NOT WORKING PROPERLY");
                }
            } else {
                reject("UNKNOWN ERROR");
            }
        });
    });
    return promise;
}

function decrypt(privateKey, text) {
    var promise = new Promise(function(resolve, reject) {
        var request = require("request");
        request("https://runkit.io/aplet123/full-encryption/1.0.0?method=decrypt&key=" + privateKey + "&text=" + text, function(error, response, body) {
            if (!error) {
                if (response.statusCode == 200) {
                    var data = JSON.parse(body);
                    if (data.error) {
                        reject(data.error.toUpperCase());
                    } else {
                        resolve(data.text);
                    }
                } else {
                    reject("API MAY BE DOWN OR IS NOT WORKING PROPERLY");
                }
            } else {
                reject("UNKNOWN ERROR");
            }
        });
    });
    return promise;
}

module.exports = {
    getKey,
    encrypt,
    decrypt
};


text:
mirrorthisvideo
===============

Simple site that uses the Vidme API to mirror online videos

http://mirrorthisvideo.com


text:
import ast
import utils
import json

# third-party modules
import pandas as pd

class DB(object):
	def __init__(self):
		self._groups = utils.SafeDict()

		#: Plane data as calculated by :func:`iago.Analyser.Analyser.dynamic_plane`
		self.planes = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'name': ('Plane name', None),
			'normal_x': ('Normal vector: x component', None),
			'normal_y': ('Normal vector: y component', None),
			'normal_z': ('Normal vector: z component', None),
			'support_x': ('Support point: x component', 'angstrom'),
			'support_y': ('Support point: y component', 'angstrom'),
			'support_z': ('Support point: z component', 'angstrom'),
		})

		#: Atom-atom distance data as calculated by :func:`iago.Analyser.Analyser.dynamic_distance`
		self.distances = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'name': ('Distance set name', None),
			'atom1': ('First atom index', None),
			'atom2': ('Second atom index', None),
			'dist': ('Distance', 'angstrom')
		})

		#: Atom-plane distance data as calculated by :func:`iago.Analyser.Analyser.dynamic_distance`
		self.planedistances = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'name': ('Distance set name', None),
			'plane': ('Plane name', None),
			'atom1': ('First atom index', None),
			'dist': ('Distance', 'angstrom')
		})

		self.energies = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'total': ('Total energy', 'hartree'),
			'conserved': ('Conserved quantity', 'hartree'),
			'coreself': ('Core-Self energy', 'hartree'),
			'corehamiltonian': ('Core Hamiltonian', 'hartree'),
			'hartree': ('Hartree energy', 'hartree'),
			'xc': ('Exchange-Correlation energy', 'hartree'),
			'hfx': ('Hartree-Fock Exchange energy', 'hartree'),
			'dispersion': ('Dispersion energy', 'hartree'),
			'potential': ('Potential energy', 'hartree'),
			'kinetic': ('Kinetic energy', 'hartree'),
			'drift': ('Energy drift per atom', 'kelvin')
		})

		self.cells = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'a': ('First cell length', 'angstrom'),
			'b': ('Second cell length', 'angstrom'),
			'c': ('Third cell length', 'angstrom'),
			'alpha': ('First cell angle', 'degrees'),
			'beta': ('Second cell angle', 'degrees'),
			'gamma': ('Third cell angle', 'degrees'),
			'volume': ('Cell volume', 'angstrom**3'),
		})

		self.ensembles = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'temperature': ('Temperature', 'kelvin'),
			'pressure': ('Pressure', 'bar'),
		})

		self.meta = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'iasd': ('Integrated absolute spin density', None),
			's2': ('Determinant S**2', None),
			'scfcycles': ('Number of SCF cycles', None),
			'otcycles': ('Number of outer SCF cycles', None),
			'globaleri': ('Number of ERI evaluated', None)
		})

		self.points = utils.annotated_data_frame({
			'run': ('Run', None),
			'frame': ('Frame number', None),
			'name': ('Point set name', None),
			'x': ('X position', 'angstrom'),
			'y': ('Y position', 'angstrom'),
			'z': ('Z position', 'angstrom'),
			'fractional_x': ('Fractional x position', None),
			'fractional_y': ('Fractional y position', None),
			'fractional_z': ('Fractional z position', None),
		})

		self.input = utils.Map()
		self.output = pd.DataFrame()

		self._data_tables = 'meta ensembles cells energies'.split()
		self._stock_tables = 'planes distances planedistances points'.split()

	@staticmethod
	def _transfer_missing_units(origin, destination, columns):
		for column in columns:
			destination._iago_units[column] = origin._iago_units[column]
			destination._iago_comments[column] = origin._iago_comments[column]

	def assign_output_columns(self):
		for table in self._data_tables:
			overlap = (set(self.output.columns) & set(self.__dict__[table].columns)) - set(['run', 'frame'])
			if len(overlap) == 0:
				continue

			newtable = self.__dict__[table].append(self.output[['run', 'frame'] + list(overlap)])
			DB._transfer_missing_units(self.__dict__[table], newtable, ['run', 'frame'] + list(overlap))
			self.__dict__[table] = newtable
			self.output.drop(list(overlap), inplace=True, axis=1)

	@property
	def groups(self):
		""" Known static atom groups.

		:return: Dictionary with group names as key, list of 0-based atom indices as value.
		"""
		return self._groups

	def write(self, fh, format='hdf5'):
		""" Writes the database to disk or stream.

		:param fh: File handle or filename.
		:param format: File format. Either hdf5 or json.
		"""
		format = format.lower()

		if format == 'json':
			self._write_json(fh)
		elif format == 'hdf5':
			self._write_hdf5(fh)
		else:
			raise ValueError('No such format supported: %s' % format)

	def _write_hdf5(self, fh):
		""" Writes the database as hdf5 to disk.

		:param fh: File handle or filename."""
		hdf = pd.HDFStore(fh, mode='a')
		hdf.put('groups', self.groups.to_dataframe())

		for table in self._stock_tables:
			hdf.put(table, getattr(self, table))
			hdf.put('%s_meta' % table, pd.DataFrame.from_dict(getattr(self, table).annotations_to_dict()))

		# String properties
		sdf = pd.DataFrame.from_dict({'labels': ['input', ], 'values': [str(self.input), ]})
		hdf.put('strings', sdf)

		hdf.put('output', self.output)

		# data tables
		for table in self._data_tables:
			hdf.put(table, getattr(self, table))
			hdf.put('%s_meta' % table, pd.DataFrame.from_dict(getattr(self, table).annotations_to_dict()))

		# finalise
		hdf.close()

	def _write_json(self, fh):
		""" Writes the database as json to disk.

		:param fh: File handle or filename."""
		if not hasattr(fh, 'write'):
			fh = open(fh, 'w')

		data = dict()

		# groups
		data['groups'] = self.groups

		for table in self._stock_tables:
			data[table] = getattr(self, table).to_dict('list')
			data['%s-meta' % table] = getattr(self, table).annotations_to_dict()

		# input / output
		data['input'] = self.input
		data['output'] = self.output.to_dict('list')
		# data['output-meta'] = self.output.annotations_to_dict()
		# data tables
		for table in self._data_tables:
			data[table] = self.__dict__[table].to_dict('list')
			data[table + '-meta'] = self.__dict__[table].annotations_to_dict()

		# finalise
		fh.write(json.dumps(data, separators=(',', ':')))

	def read(self, handle=None, name=None, format='json'):
		""" Reads the database from disk or stream.

		:param handle: File handle. Either `handle` or `name` has to be specified.
		:param name: File name. Either `handle` or `name` has to be specified.
		:param format: Either JSON or HDF5.
		"""
		if handle is None and name is None:
			raise ValueError('Nothing to read specified.')

		if format == 'json':
			if handle is None:
				handle = open(name)
			self._read_json(handle)
		elif format == 'hdf5':
			self._read_hdf5(name)
		else:
			raise ValueError('No such format supported: %s' % format)

	def _read_hdf5(self, filename):
		""" Reads the HDF5 database from disk.

		:param fh: File handle or filename.
		"""
		hdf = pd.HDFStore(filename, mode='r')
		self._groups = utils.SafeDict.from_dataframe(hdf.get('groups'))

		for table in self._stock_tables:
			pdt = hdf.get(table)
			meta = hdf.get('%s_meta' % table).to_dict(orient='list')
			setattr(self, table, utils.annotated_data_frame(meta, pdt))

		# String properties
		sdf = hdf.get('strings') #.to_dict(orient='list')
		input = sdf[sdf['labels']=='input']['values'].values[0]

		self.input = utils.Map(ast.literal_eval(input))

		self.output = hdf.get('output')

		# data tables
		for table in self._data_tables:
			pdt = hdf.get(table)
			meta = hdf.get('%s_meta' % table).to_dict(orient='list')
			setattr(self, table, utils.annotated_data_frame(meta, pdt))

		# finalise
		hdf.close()

	def _read_json(self, fh):
		""" Reads the JSON database from disk or stream.

		:param fh: File handle or filename.
		"""
		data = json.load(fh)

		# groups
		try:
			self._groups = utils.SafeDict(data['groups'])
		except KeyError:
			pass
		# planes
		try:
			self.planes = utils.annotated_data_frame(data['planes-meta'], data['planes'])
		except KeyError:
			pass
		# distances
		try:
			self.distances = utils.annotated_data_frame(data['distances-meta'], data['distances'])
		except KeyError:
			pass
		try:
			self.planedistances = utils.annotated_data_frame(data['planedistances-meta'], data['planedistances'])
		except KeyError:
			pass
		# points
		try:
			self.points = utils.annotated_data_frame(data['points-meta'], data['points'])
		except KeyError:
			pass
		# input / output
		try:
			self.input = utils.Map(data['input'])
		except KeyError:
			pass
		# self.output = utils.AnnotatedDataFrame(data['output-meta'], data['output'])
		try:
			self.output = pd.DataFrame.from_dict(data['output'])
		except KeyError:
			pass
		# data tables
		for table in self._data_tables:
			try:
				self.__dict__[table] = utils.annotated_data_frame(data[table + '-meta'], data[table])
			except KeyError:
				pass
		# cleanup
		fh.close()

	def monitor(self, quantity):
		for table in self._data_tables:
			tobj = self.__dict__[table]
			if quantity in tobj.columns:
				# keep dependency local to this function
				import matplotlib.pyplot as plt
				plt.plot(tobj['frame'], tobj[quantity])
				unit = tobj.explain(quantity).Unit.values[0]
				if unit == 'No unit available.':
					unit = 'n/a'
				label = '%s in %s' % (tobj.explain(quantity).Comment.values[0], unit)
				plt.ylabel(label)
				plt.xlabel('Frame')
				return
		raise ValueError('No such quantity.')


text:
using NUnit.Framework;

namespace Hidari0415.UstdCsv2Ju.Tests
{
	public class JUnitStyleFailureElementTests
	{
		[SetUp]
		public void SetUp()
		{

		}

		[Test]
		public void NoArgumentInitTest()
		{
			var jUnitFailureElement = new JUnitStyleFailureElement();
			jUnitFailureElement.Message.Is("");
			jUnitFailureElement.Type.Is("");
		}

		[Test]
		public void SingleArgumentInitTest()
		{
			var jUnitFailureElement = new JUnitStyleFailureElement("type");
			jUnitFailureElement.Message.Is("");
			jUnitFailureElement.Type.Is("type");
		}

		[Test]
		public void TwoArgumentsInitTest()
		{
			var jUnitFailureElement = new JUnitStyleFailureElement("type", "message");
			jUnitFailureElement.Message.Is("message");
			jUnitFailureElement.Type.Is("type");
		}
	}
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Fixer\PhpUnit;

use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
use PhpCsFixer\WhitespacesFixerConfig;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 *
 * @covers \PhpCsFixer\Fixer\PhpUnit\PhpUnitExpectationFixer
 */
final class PhpUnitExpectationFixerTest extends AbstractFixerTestCase
{
    /**
     * @param string      $expected
     * @param null|string $input
     * @param array       $config
     *
     * @dataProvider provideTestFixCases
     */
    public function testFix($expected, $input = null, array $config = [])
    {
        $this->fixer->configure($config);
        $this->doTest($expected, $input);
    }

    public function provideTestFixCases()
    {
        return [
            [
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            aaa();
            $this->expectException(\'RuntimeException\');
            $this->expectExceptionMessage(\'msg\'/*B*/);
            $this->expectExceptionCode(/*C*/123);
            zzz();
        }
    }',
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            aaa();
            $this->setExpectedException(\'RuntimeException\', \'msg\'/*B*/, /*C*/123);
            zzz();
        }
    }',
            ],
            [
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            aaa();
            $this->expectException(\'RuntimeException\'/*B*/  /*B2*/);
            $this->expectExceptionCode(/*C*/123);
            zzz();
        }
        function testFnc2()
        {
            aaa();
            $this->expectException(\'RuntimeException\');
            $this->expectExceptionMessage(/*B*/ null /*B2*/ + 1);
            $this->expectExceptionCode(/*C*/123);
            zzz();
        }
    }',
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            aaa();
            $this->setExpectedException(\'RuntimeException\',/*B*/ null /*B2*/,/*C*/123);
            zzz();
        }
        function testFnc2()
        {
            aaa();
            $this->setExpectedException(\'RuntimeException\',/*B*/ null /*B2*/ + 1,/*C*/123);
            zzz();
        }
    }',
            ],
            [
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            $this->expectException(
                \Exception::class
            );
        }
    }',
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            $this->setExpectedException(
                \Exception::class
            );
        }
    }',
            ],
            [
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            $this->expectException(
                \Exception::class
            );
            $this->expectExceptionMessage(
                "foo"
            );
            $this->expectExceptionCode(
                123
            );
        }
    }',
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            $this->setExpectedException(
                \Exception::class,
                "foo",
                123
            );
        }
    }',
            ],
            [
                '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testFoo()
    {
        $this->expectException("RuntimeException");
        $this->expectExceptionMessage("Msg");
        $this->expectExceptionCode(123);
        foo();
    }

    public function testBar()
    {
        $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
        bar();
    }
}',
                '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testFoo()
    {
        $this->setExpectedException("RuntimeException", "Msg", 123);
        foo();
    }

    public function testBar()
    {
        $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
        bar();
    }
}',
                ['target' => PhpUnitTargetVersion::VERSION_5_2],
            ],
            [
                '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testFoo()
    {
        $this->expectException("RuntimeException");
        $this->expectExceptionMessage("Msg");
        $this->expectExceptionCode(123);
        foo();
    }

    public function testBar()
    {
        $this->expectException("RuntimeException");
        $this->expectExceptionMessageRegExp("/Msg.*/");
        $this->expectExceptionCode(123);
        bar();
    }
}',
                '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testFoo()
    {
        $this->setExpectedException("RuntimeException", "Msg", 123);
        foo();
    }

    public function testBar()
    {
        $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
        bar();
    }
}',
                ['target' => PhpUnitTargetVersion::VERSION_5_6],
            ],
            [
                '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testFoo()
    {
        $this->expectException("RuntimeException");
        $this->expectExceptionMessage("Msg");
        $this->expectExceptionCode(123);
        foo();
    }

    public function testBar()
    {
        $this->expectException("RuntimeException");
        $this->expectExceptionMessageRegExp("/Msg.*/");
        $this->expectExceptionCode(123);
        bar();
    }
}',
                '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testFoo()
    {
        $this->setExpectedException("RuntimeException", "Msg", 123);
        foo();
    }

    public function testBar()
    {
        $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
        bar();
    }
}',
                ['target' => PhpUnitTargetVersion::VERSION_NEWEST],
            ],
        ];
    }

    /**
     * @param string      $expected
     * @param null|string $input
     *
     * @dataProvider provideMessyWhitespacesCases
     */
    public function testMessyWhitespaces($expected, $input = null)
    {
        $expected = str_replace(['    ', "\n"], ["\t", "\r\n"], $expected);
        if (null !== $input) {
            $input = str_replace(['    ', "\n"], ["\t", "\r\n"], $input);
        }

        $this->fixer->setWhitespacesConfig(new WhitespacesFixerConfig("\t", "\r\n"));

        $this->doTest($expected, $input);
    }

    public function provideMessyWhitespacesCases()
    {
        return [
            [
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            aaa();
            $this->expectException(\'RuntimeException\');
            $this->expectExceptionMessage(\'msg\'/*B*/);
            $this->expectExceptionCode(/*C*/123);
            zzz();
        }
    }',
                '<?php
    final class MyTest extends \PHPUnit_Framework_TestCase
    {
        function testFnc()
        {
            aaa();
            $this->setExpectedException(\'RuntimeException\', \'msg\'/*B*/, /*C*/123);
            zzz();
        }
    }',
            ],
        ];
    }
}


text:
namespace Nancy.Session.InProc.InProcSessionsManagement.ByQueryStringParam {
  using System;
  using Cryptography;
  using FakeItEasy;
  using Xunit;

  public class ByQueryStringParamIdentificationMethodFixture {
    private readonly ByQueryStringParamIdentificationMethod _byQueryStringParamIdentificationMethod;
    private readonly IEncryptionProvider _fakeEncryptionProvider;
    private readonly IHmacProvider _fakeHmacProvider;
    private readonly IHmacValidator _fakeHmacValidator;
    private readonly IResponseManipulatorForSession _fakeResponseManipulatorForSession;
    private readonly ISessionIdentificationDataProvider _fakeSessionIdentificationDataProvider;
    private readonly ISessionIdFactory _fakeSessionIdFactory;
    private readonly string _parameterName;
    private readonly InProcSessionsConfiguration _validConfiguration;

    public ByQueryStringParamIdentificationMethodFixture() {
      _fakeEncryptionProvider = A.Fake<IEncryptionProvider>();
      _fakeHmacProvider = A.Fake<IHmacProvider>();
      _validConfiguration = new InProcSessionsConfiguration();
      _fakeSessionIdentificationDataProvider = A.Fake<ISessionIdentificationDataProvider>();
      _fakeHmacValidator = A.Fake<IHmacValidator>();
      _fakeSessionIdFactory = A.Fake<ISessionIdFactory>();
      _fakeResponseManipulatorForSession = A.Fake<IResponseManipulatorForSession>();
      _byQueryStringParamIdentificationMethod = new ByQueryStringParamIdentificationMethod(
        _fakeEncryptionProvider,
        _fakeHmacProvider,
        _fakeSessionIdentificationDataProvider,
        _fakeHmacValidator,
        _fakeSessionIdFactory,
        _fakeResponseManipulatorForSession);
      _parameterName = "TheNameOfTheParameter";
      _byQueryStringParamIdentificationMethod.ParameterName = _parameterName;
    }

    [Fact]
    public void Given_null_crypto_configuration_then_throws() {
      Assert.Throws<ArgumentNullException>(() => new ByQueryStringParamIdentificationMethod(null));
    }

    [Fact]
    public void Given_null_encryption_provider_then_throws() {
      Assert.Throws<ArgumentNullException>(
        () => new ByQueryStringParamIdentificationMethod(null, _fakeHmacProvider, _fakeSessionIdentificationDataProvider, _fakeHmacValidator, _fakeSessionIdFactory, _fakeResponseManipulatorForSession));
    }

    [Fact]
    public void Given_null_hmac_provider_then_throws() {
      Assert.Throws<ArgumentNullException>(
        () => new ByQueryStringParamIdentificationMethod(_fakeEncryptionProvider, null, _fakeSessionIdentificationDataProvider, _fakeHmacValidator, _fakeSessionIdFactory, _fakeResponseManipulatorForSession));
    }

    [Fact]
    public void Given_null_session_data_provider_then_throws() {
      Assert.Throws<ArgumentNullException>(() => new ByQueryStringParamIdentificationMethod(_fakeEncryptionProvider, _fakeHmacProvider, null, _fakeHmacValidator, _fakeSessionIdFactory, _fakeResponseManipulatorForSession));
    }

    [Fact]
    public void Given_null_hmac_validator_then_throws() {
      Assert.Throws<ArgumentNullException>(
        () => new ByQueryStringParamIdentificationMethod(_fakeEncryptionProvider, _fakeHmacProvider, _fakeSessionIdentificationDataProvider, null, _fakeSessionIdFactory, _fakeResponseManipulatorForSession));
    }

    [Fact]
    public void Given_null_session_id_factory_then_throws() {
      Assert.Throws<ArgumentNullException>(
        () => new ByQueryStringParamIdentificationMethod(_fakeEncryptionProvider, _fakeHmacProvider, _fakeSessionIdentificationDataProvider, _fakeHmacValidator, null, _fakeResponseManipulatorForSession));
    }

    [Fact]
    public void Given_null_response_manipulator_then_throws() {
      Assert.Throws<ArgumentNullException>(() => new ByQueryStringParamIdentificationMethod(_fakeEncryptionProvider, _fakeHmacProvider, _fakeSessionIdentificationDataProvider, _fakeHmacValidator, _fakeSessionIdFactory, null));
    }

    [Fact]
    public void On_creation_sets_default_parameter_name() {
      var newInstance = new ByQueryStringParamIdentificationMethod(_fakeEncryptionProvider, _fakeHmacProvider, _fakeSessionIdentificationDataProvider, _fakeHmacValidator, _fakeSessionIdFactory, _fakeResponseManipulatorForSession);
      Assert.Equal("_nsid", newInstance.ParameterName);
    }

    public class Load : ByQueryStringParamIdentificationMethodFixture {
      private readonly NancyContext _context;
      private readonly SessionId _newSessionId;

      public Load() {
        _context = new NancyContext {Request = new Request("GET", "http://www.google.be?_nsid=01HMAC02SessionId")};

        _newSessionId = new SessionId(Guid.NewGuid(), false);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).Returns(_newSessionId);
      }

      [Fact]
      public void Given_null_context_then_throws() {
        Assert.Throws<ArgumentNullException>(() => _byQueryStringParamIdentificationMethod.GetCurrentSessionId(null));
      }

      [Fact]
      public void When_context_contains_no_session_identification_data_then_returns_new_session_id() {
        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(null);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(_newSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(A<string>._)).MustNotHaveHappened();
      }

      [Fact]
      public void When_querystring_does_not_have_a_valid_hmac_then_returns_new_session_id() {
        var sessionIdentificationData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(false);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(_newSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(A<string>._)).MustNotHaveHappened();
      }

      [Fact]
      public void When_decrypted_session_id_is_not_valid_then_returns_new_session_id() {
        var sessionIdentificationData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(true);
        A.CallTo(() => _fakeEncryptionProvider.Decrypt(sessionIdentificationData.SessionId)).Returns(string.Empty);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(_newSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(A<string>._)).MustNotHaveHappened();
      }

      [Fact]
      public void When_decrypted_session_id_is_not_a_valid_guid_then_returns_new_session_id() {
        const string invalidDecryptedSessionId = "This is not a valid guid!";
        var sessionIdentificationData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(true);
        A.CallTo(() => _fakeEncryptionProvider.Decrypt(sessionIdentificationData.SessionId)).Returns(invalidDecryptedSessionId);
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(invalidDecryptedSessionId)).Returns(null);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(_newSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(invalidDecryptedSessionId)).MustHaveHappened();
      }

      [Fact]
      public void When_decrypted_session_id_is_valid_then_returns_session_id_from_querystring() {
        var expectedSessionId = new SessionId(Guid.NewGuid(), false);
        var decryptedSessionId = expectedSessionId.Value.ToString();
        var sessionIdentificationData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(true);
        A.CallTo(() => _fakeEncryptionProvider.Decrypt(sessionIdentificationData.SessionId)).Returns(decryptedSessionId);
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(decryptedSessionId)).Returns(expectedSessionId);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(expectedSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustNotHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(decryptedSessionId)).MustHaveHappened();
      }
    }

    public class Save : ByQueryStringParamIdentificationMethodFixture {
      private readonly NancyContext _context;
      private readonly SessionId _validSessionId;

      public Save() {
        _validSessionId = new SessionId(Guid.NewGuid(), true);
        _context = new NancyContext {Request = new Request("GET", "http://www.google.be")};
      }

      [Fact]
      public void Given_null_context_then_throws() {
        Assert.Throws<ArgumentNullException>(() => _byQueryStringParamIdentificationMethod.SaveSessionId(_validSessionId, null));
      }

      [Fact]
      public void Given_null_session_id_then_throws() {
        Assert.Throws<ArgumentNullException>(() => _byQueryStringParamIdentificationMethod.SaveSessionId(null, _context));
      }

      [Fact]
      public void Given_context_without_request_then_throws() {
        var contextWithoutRequest = new NancyContext();
        Assert.Throws<ArgumentException>(() => _byQueryStringParamIdentificationMethod.SaveSessionId(_validSessionId, contextWithoutRequest));
      }

      [Fact]
      public void Given_empty_session_id_then_throws() {
        var emptySessionId = new SessionId(Guid.Empty, false);
        Assert.Throws<ArgumentException>(() => _byQueryStringParamIdentificationMethod.SaveSessionId(emptySessionId, _context));
      }

      [Fact]
      public void Given_session_id_is_not_new_then_does_nothing() {
        var existingSessionId = new SessionId(Guid.NewGuid(), false);
        _byQueryStringParamIdentificationMethod.SaveSessionId(existingSessionId, _context);
        A.CallTo(() => _fakeResponseManipulatorForSession.ModifyResponseToRedirectToSessionAwareUrl(A<NancyContext>._, A<SessionIdentificationData>._, A<string>._)).MustNotHaveHappened();
      }

      [Fact]
      public void Given_session_id_is_new_then_manipulates_response() {
        const string encryptedSessionId = "ABC_sessionid_xyz";
        var hmacBytes = new byte[] {1, 2, 3};

        A.CallTo(() => _fakeEncryptionProvider.Encrypt(_validSessionId.Value.ToString())).Returns(encryptedSessionId);
        A.CallTo(() => _fakeHmacProvider.GenerateHmac(encryptedSessionId)).Returns(hmacBytes);
        A.CallTo(() => _fakeHmacProvider.HmacLength).Returns(hmacBytes.Length);

        _byQueryStringParamIdentificationMethod.SaveSessionId(_validSessionId, _context);

        A.CallTo(
          () =>
            _fakeResponseManipulatorForSession.ModifyResponseToRedirectToSessionAwareUrl(
              _context,
              A<SessionIdentificationData>.That.Matches(sid => sid.SessionId == encryptedSessionId && HmacComparer.Compare(sid.Hmac, hmacBytes, _fakeHmacProvider.HmacLength)),
              _parameterName)).MustHaveHappened();
      }
    }
  }
}


text:
=========
extension
=========

Many OpenStack server APIs include API extensions that enable
additional functionality.

.. autoprogram-cliff:: openstack.common
   :command: extension *


text:
var hasCORS = require('has-cors');
var globalThis = require('./globalThis');

module.exports = function (opts) {
  var xdomain = opts.xdomain;

  // scheme must be same when usign XDomainRequest
  // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  var xscheme = opts.xscheme;

  // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  // https://github.com/Automattic/engine.io-client/pull/217
  var enablesXDR = opts.enablesXDR;

  // XMLHttpRequest can be disabled on IE
  try {
    if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
      return new XMLHttpRequest();
    }
  } catch (e) { }

  // Use XDomainRequest for IE8 if enablesXDR is true
  // because loading bar keeps flashing when using jsonp-polling
  // https://github.com/yujiosaka/socke.io-ie8-loading-example
  try {
    if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
      return new XDomainRequest();
    }
  } catch (e) { }

  if (!xdomain) {
    try {
      return new globalThis[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
    } catch (e) { }
  }
};


text:
// This file is partially included in the manual, do not modify
// without updating the references in the *.tex files!
// Manual references: lines 31-51 (Error.tex)

#ifndef CAF_EXIT_REASON_HPP
#define CAF_EXIT_REASON_HPP

#include "caf/error.hpp"

namespace caf {

/// This error category represents fail conditions for actors.
enum class exit_reason : uint8_t {
  /// Indicates that an actor finished execution without error.
  normal = 0,
  /// Indicates that an actor died because of an unhandled exception.
  unhandled_exception,
  /// Indicates that the exit reason for this actor is unknown, i.e.,
  /// the actor has been terminated and no longer exists.
  unknown,
  /// Indicates that an actor pool unexpectedly ran out of workers.
  out_of_workers,
  /// Indicates that an actor was forced to shutdown by a user-generated event.
  user_shutdown,
  /// Indicates that an actor was killed unconditionally.
  kill,
  /// Indicates that an actor finishied execution because a connection
  /// to a remote link was closed unexpectedly.
  remote_link_unreachable,
  /// Indicates that an actor was killed because it became unreachable.
  unreachable
};

/// Returns a string representation of given exit reason.
const char* to_string(exit_reason x);

/// @relates exit_reason
error make_error(exit_reason);

} // namespace caf

#endif // CAF_EXIT_REASON_HPP


text:
title: IntelliJ IDEA UI Guidelines
---


text:
import { normalize, schema } from 'normalizr'
import normalizeMiddleware from '../normalize'

const create = () => {
  const store = {}
  const next = jest.fn()
  const invoke = action => normalizeMiddleware(store)(next)(action)
  return { store, next, invoke }
}
const userSchema = new schema.Entity('users')
const user = { id: 1, name: 'user' }

describe('normalizeMiddleware', () => {
  it('normalizes', () => {
    const { next, invoke } = create()
    const action = {
      type: 'FETCH',
      payload: user,
      meta: {
        normalizr: { schema: userSchema },
      },
    }
    invoke(action)

    expect(next).toHaveBeenCalledWith({
      ...action,
      payload: normalize(user, userSchema),
    })
  })

  it('does not normalize when error reponse', () => {
    const { next, invoke } = create()
    const action = {
      type: 'FETCH',
      payload: ['error'],
      error: true,
      meta: {
        normalizr: { schema: userSchema },
      },
    }
    invoke(action)

    expect(next).toHaveBeenCalledWith(action)
  })

  it('does not normalize when no meta option', () => {
    const { next, invoke } = create()
    const action = {
      type: 'FETCH',
      payload: user,
    }
    invoke(action)

    expect(next).toHaveBeenCalledWith(action)
  })

  it('does not normalize when payload is a promise object', () => {
    const { next, invoke } = create()
    const action = {
      type: 'FETCH',
      payload: Promise.resolve(),
      meta: {
        normalizr: { schema: userSchema },
      },
    }
    invoke(action)

    expect(next).toHaveBeenCalledWith(action)
  })
})


text:
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center"
                android:orientation="vertical"
                tools:context=".LinearLayout" >

                        <TextView
                            android:id="@+id/videoInformation"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:paddingLeft="10px"
                            android:paddingTop="20px"
                            android:text="Video Information"
                            android:textSize="23sp" />

                                    <LinearLayout
                                        android:layout_width="fill_parent"
                                        android:layout_height="wrap_content"
                                        android:orientation="horizontal"
                                        android:paddingTop="20px">

                                        <TextView
                                            android:id="@+id/broadcastText"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:paddingLeft="10px"
                                            android:paddingTop="20px"
                                            android:text="Broadcaster:"
                                            android:textSize="18sp" />

                                        <TextView
                                            android:id="@+id/broadcastString"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginLeft="40px"
                                            android:layout_weight="0.50"
                                            android:paddingTop="20px"
                                            android:text="@string/broadcaster"
                                            android:textSize="18sp" />

                                    </LinearLayout>

                                    <LinearLayout
                                    android:layout_width="fill_parent"
                                    android:layout_height="wrap_content"
                                    android:orientation="horizontal"
                                    android:paddingTop="20px"
                                     >

                                                        <TextView
                                                            android:id="@+id/locationText"
                                                            android:layout_width="wrap_content"
                                                            android:layout_height="wrap_content"
                                                            android:paddingLeft="10px"
                                                            android:paddingTop="20px"
                                                            android:text="Location:"
                                                            android:textSize="18sp" />

                                                        <TextView
                                                            android:id="@+id/locationString"
                                                            android:layout_width="wrap_content"
                                                            android:layout_height="wrap_content"
                                                            android:layout_gravity="center_horizontal"
                                                            android:layout_marginLeft="40px"
                                                            android:layout_weight="0.50"
                                                            android:paddingTop="20px"
                                                            android:textSize="18sp"
                                                            android:text="@string/location"/>

                                    </LinearLayout>

                                    <LinearLayout
                                    android:layout_width="fill_parent"
                                    android:layout_height="wrap_content"
                                    android:orientation="horizontal"
                                    android:paddingTop="20px"
                                     >

                                                        <TextView
                                                            android:id="@+id/viewsText"
                                                            android:layout_width="wrap_content"
                                                            android:layout_height="wrap_content"
                                                            android:paddingLeft="10px"
                                                            android:paddingTop="20px"
                                                            android:text="Video Views:"
                                                            android:textSize="18sp" />

                                                        <TextView
                                                            android:id="@+id/viewsString"
                                                            android:layout_width="wrap_content"
                                                            android:layout_height="wrap_content"
                                                            android:layout_gravity="center_horizontal"
                                                            android:layout_marginLeft="40px"
                                                            android:layout_weight="0.50"
                                                            android:paddingTop="20px"
                                                            android:textSize="18sp"
                                                            android:text="@string/views" />

                                    </LinearLayout>

            </LinearLayout>


text:
package ms

import (
	"encoding/json"
	"github.com/kuzzleio/sdk-go/types"
)

// Ttl returns the remaining time to live of a key, in seconds,
// or a negative value if the key does not exist or if it is persistent.
func (ms *Ms) Ttl(key string, options types.QueryOptions) (int, error) {
	result := make(chan *types.KuzzleResponse)

	type body struct {
		Keys []string `json:"keys"`
	}

	query := &types.KuzzleRequest{
		Controller: "ms",
		Action:     "ttl",
		Id:         key,
	}
	go ms.Kuzzle.Query(query, options, result)

	res := <-result

	if res.Error.Error() != "" {
		return 0, res.Error
	}
	var returnedResult int
	json.Unmarshal(res.Result, &returnedResult)

	return returnedResult, nil
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorDividerLight"><!--点击时波纹的颜色 -->
    <item android:drawable="@color/white" /><!--未点击时控件的颜色 -->
</ripple>


text:
package gov.cdc.sdp.cbr.queue;

import java.util.List;
import java.util.Map;

import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

public class DatabaseQueueCreationConsumerTest extends CamelTestSupport {

    private static final String route_id = "test_consume";
    private static final String driver = "org.postgresql.Driver";
    private static final String username = "sdp_dbq";
    private static final String password = "bob";
    private static final String dsurl = "jdbc:postgresql://localhost:5432/cbr_db";

    private static final String tableName = "temp_fake_table";
    private static final String drop_temp_table = "drop table if exists " + tableName;
    private static final String does_table_exist = "select * from pg_tables where tablename='" + tableName + "'";

    @EndpointInject(uri = "mock:mock_endpoint")
    protected MockEndpoint mock_endpoint;

    @Produce(uri = "direct:start")
    protected ProducerTemplate template;

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry jndi = super.createRegistry();
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driver);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setUrl(dsurl);
        jndi.bind("dataSource", ds);
        return jndi;
    }

    @Override
    protected void doPreSetup() throws Exception {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driver);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setUrl(dsurl);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
        List<Map<String, Object>> lst;

        jdbcTemplate.update(drop_temp_table);
        lst = jdbcTemplate.queryForList(does_table_exist);
        // Ensure table has been dropped prior to routes being built in setup
        assertEquals(0, lst.size());
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        // Run during setup before the test, builds the route
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("sdpqueue:temp_fake_table?dataSource=#dataSource").id(route_id).to("mock:result");
            }
        };
    }

    @Test
    public void testCreateConsume() throws Exception {
        String rid = context().getRoutes().get(0).getId();
        assertEquals(rid, route_id);
        // Ensure that the route was built

        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driver);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setUrl(dsurl);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        List<Map<String, Object>> lst;
        lst = jdbcTemplate.queryForList(does_table_exist);
        assertEquals(1, lst.size());
        // Ensure that the table exists now
        // Literally nothing else needs to be done
    }
}


text:
using System;
using NUnit.Framework;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

package com.quantconnect.lean.Tests.Indicators {
    [TestFixture]
    public class CommodityChannelIndexTests
    {
        [Test]
        public void ComparesAgainstExternalData() {
            cci = new CommodityChannelIndex(14);
            TestHelper.TestIndicator(cci, "spy_with_cci.txt", "Commodity Channel Index (CCI) 14", 1e-2);
        }

        [Test]
        public void ResetsProperly() {
            cci = new CommodityChannelIndex(2);
            cci.Update(new TradeBar
            {
                Symbol = Symbols.SPY,
                Time = DateTime.Today,
                Open = 3m,
                High = 7m,
                Low = 2m,
                Close = 5m,
                Volume = 10
            });
            Assert.IsFalse(cci.IsReady);
            cci.Update(new TradeBar
            {
                Symbol = Symbols.SPY,
                Time = DateTime.Today.AddSeconds(1),
                Open = 3m,
                High = 7m,
                Low = 2m,
                Close = 5m,
                Volume = 10
            });
            Assert.IsTrue(cci.IsReady);

            cci.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(cci);
            TestHelper.AssertIndicatorIsInDefaultState(cci.TypicalPriceAverage);
            TestHelper.AssertIndicatorIsInDefaultState(cci.TypicalPriceMeanDeviation);
        }
    }
}


text:
function ROS_TiltCtrl()
{
    this.active = false;
    this.ros_edison_callback = null;
    this.rosobj = null;
    this.$div = null;
    this.onConnectCallback = null;
    this.axes = [];

    //Check if tilting is available
    if (window.DeviceOrientationEvent)
    {
        window.addEventListener('deviceorientation', ROS_TiltCtrl.activateTiltCtrl, false);
    }

}

ROS_TiltCtrl.prototype.disableTiltSupport = function()
{
    this.active = false;
    if(this.$div !== null)
    {
        this.$div.css('display','none');
    }
}

ROS_TiltCtrl.activateTiltCtrl = function(event)
{
    if(!ros_tiltctrl.active)
    {
        if(typeof(ros_tiltctrl.onConnectCallback) === "function")
        {
            ros_tiltctrl.onConnectCallback();
        }
        ros_tiltctrl.active = true;
    }

    if(ros_tiltctrl.$div !== null)
    {
        window.removeEventListener('deviceorientation', ROS_TiltCtrl.activateTiltCtrl, false);
        window.addEventListener('deviceorientation', ROS_TiltCtrl.onTilt, false);
    }
}

ROS_TiltCtrl.onTilt = function(event)
{
    if(ros_tiltctrl.active)
    {
        //Gamma determines the drive level
        //Alpha the rotation
        ros_tiltctrl.axes[1] = event.gamma/90;
        ros_tiltctrl.axes[0] = (event.alpha-90)/90;

        if(ros_tiltctrl.ros_edison_callback != null)
        {
            ros_tiltctrl.ros_edison_callback(ros_tiltctrl.rosobj);
        }
    }
}

ROS_TiltCtrl.prototype.linkROSEdison = function(cb, obj)
{
    this.ros_edison_callback = cb;
    this.rosobj = obj;
}

var ros_tiltctrl = new ROS_TiltCtrl();


text:
require 'test_helper'

class PodTest < Krane::TestCase
  include ResourceCacheTestHelper

  def test_deploy_failed_is_true_for_missing_image_error
    container_state = {
      "state" => {
        "waiting" => {
          "message" => "rpc error: code = 2 desc = Error: image library/some-invalid-image not found",
          "reason" => "ErrImagePull",
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))
    assert(pod.deploy_failed?)

    expected_msg = <<~STRING
      The following containers encountered errors:
      > hello-cloud: Failed to pull image busybox. Did you wait for it to be built and pushed to the registry before deploying?
    STRING
    assert_equal(expected_msg.strip, pod.failure_message)
  end

  def test_deploy_failed_is_true_for_missing_tag_error
    message = "rpc error: code = 2 desc = Tag thisImageIsBad not found in repository docker.io/library/hello-world"
    container_state = {
      "state" => {
        "waiting" => {
          "message" => message,
          "reason" => "ErrImagePull",
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))
    assert(pod.deploy_failed?)

    expected_msg = <<~STRING
      The following containers encountered errors:
      > hello-cloud: Failed to pull image busybox. Did you wait for it to be built and pushed to the registry before deploying?
    STRING
    assert_equal(expected_msg.strip, pod.failure_message)
  end

  def test_deploy_failed_is_false_for_intermittent_image_error
    container_state = {
      "state" => {
        "waiting" => {
          "message" => "Failed to pull image 'gcr.io/*': rpc error: code = 2 desc = net/http: request canceled",
          "reason" => "ErrImagePull",
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))

    refute(pod.deploy_failed?)
    assert_nil(pod.failure_message)
  end

  def test_deploy_failed_is_false_for_image_pull_backoff
    # Backoffs start quickly enough that failing eagerly on this basis alone (without further error details)
    # leads to many incorrect failure judgements at scale
    container_state = {
      "state" => {
        "waiting" => {
          "message" => "Back-off pulling image 'docker.io/library/hello-world'",
          "reason" => "ImagePullBackOff",
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))

    refute(pod.deploy_failed?)
    assert_nil(pod.failure_message)
  end

  def test_deploy_failed_is_true_for_container_config_error_post_18
    container_state = {
      "state" => {
        "waiting" => {
          "message" => "The reason it failed",
          "reason" => "CreateContainerConfigError",
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))

    assert(pod.deploy_failed?)
    expected_msg = <<~STRING
      The following containers encountered errors:
      > hello-cloud: Failed to generate container configuration: The reason it failed
    STRING
    assert_equal(expected_msg.strip, pod.failure_message)
  end

  def test_deploy_failed_is_true_for_crash_loop_backoffs
    container_state = {
      "lastState" => {
        "terminated" => { "exitCode" => 1 },
      },
      "state" => {
        "waiting" => {
          "message" => "Back-off 10s restarting failed container=init-crash-loop-back-off pod=init-crash-74b6dfcdc5",
          "reason" => "CrashLoopBackOff",
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))

    assert(pod.deploy_failed?)
    expected_msg = <<~STRING
      The following containers encountered errors:
      > hello-cloud: Crashing repeatedly (exit 1). See logs for more information.
    STRING
    assert_equal(expected_msg.strip, pod.failure_message)
  end

  def test_deploy_failed_is_true_for_container_cannot_run_error
    container_state = {
      "state" => {
        "terminated" => {
          "message" => "/not/a/command: no such file or directory",
          "reason" => "ContainerCannotRun",
          "exitCode" => 127,
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))

    assert(pod.deploy_failed?)
    expected_msg = <<~STRING
      The following containers encountered errors:
      > hello-cloud: Failed to start (exit 127): /not/a/command: no such file or directory
    STRING
    assert_equal(expected_msg.strip, pod.failure_message)
  end

  def test_deploy_failed_is_false_for_container_cannot_run_error_with_128_exit_code
    container_state = {
      "state" => {
        "terminated" => {
          "message" => "Error: failed to start container 'foo': Error response from daemon: grpc: the client" \
                       "connection is closing",
          "reason" => "ContainerCannotRun",
          "exitCode" => 128,
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))

    refute_predicate(pod, :deploy_failed?)
    assert_nil(pod.failure_message)
  end

  def test_deploy_failed_is_true_for_container_cannot_run_with_crash_loop_backoff
    container_state = {
      "state" => {
        "waiting" => {
          "message" => "Back-off 2m40s restarting failed container=myapp-container pod=myapp-pod_default",
          "reason" => "CrashLoopBackOff",
        },
      },
      "lastState" => {
        "terminated" => {
          "message" => "Error: failed to start container 'foo': Error response from daemon: grpc: the client" \
                       "connection is closing",
          "reason" => "ContainerCannotRun",
          "exitCode" => 128,
        },
      },
    }
    pod = build_synced_pod(build_pod_template(container_state: container_state))

    assert_predicate(pod, :deploy_failed?)
    assert_includes(pod.failure_message, 'Crashing repeatedly')
  end

  def test_deploy_failed_is_true_for_evicted_unmanaged_pods
    template = pod_spec.merge(
      "status" => {
        "message" => "The node was low on resource: nodefsInodes.",
        "phase" => "Failed",
        "reason" => "Evicted",
        "startTime" => "2018-04-13T22:43:23Z",
      }
    )
    pod = build_synced_pod(template)

    assert_predicate(pod, :deploy_failed?)
    assert_equal("Pod status: Failed (Reason: Evicted).", pod.failure_message)
  end

  def test_deploy_failed_is_false_for_evicted_managed_pods
    template = pod_spec.merge(
      "status" => {
        "message" => "The node was low on resource: nodefsInodes.",
        "phase" => "Failed",
        "reason" => "Evicted",
        "startTime" => "2018-04-13T22:43:23Z",
      }
    )
    pod = build_synced_pod(template, parent: mock)

    refute_predicate(pod, :deploy_failed?)
    assert_nil(pod.failure_message)
  end

  def test_deploy_failed_is_true_for_preempted_unmanaged_pods
    template = pod_spec.merge(
      "status" => {
        "message" => "Preempted in order to admit critical pod",
        "phase" => "Failed",
        "reason" => "Preempting",
        "startTime" => "2018-04-13T22:43:23Z",
      }
    )
    pod = build_synced_pod(template)

    assert_predicate(pod, :deploy_failed?)
    assert_equal("Pod status: Failed (Reason: Preempting).", pod.failure_message)
  end

  def test_deploy_failed_is_false_for_preempted_managed_pods
    template = pod_spec.merge(
      "status" => {
        "message" => "Preempted in order to admit critical pod",
        "phase" => "Failed",
        "reason" => "Preempting",
        "startTime" => "2018-04-13T22:43:23Z",
      }
    )
    pod = build_synced_pod(template, parent: mock)

    refute_predicate(pod, :deploy_failed?)
    assert_nil(pod.failure_message)
  end

  def test_deploy_failed_is_true_for_terminating_unmanaged_pods
    template = build_pod_template
    template["metadata"]["deletionTimestamp"] = "2018-04-13T22:43:23Z"
    pod = build_synced_pod(template)

    assert_predicate(pod, :terminating?)
    assert_predicate(pod, :deploy_failed?)
    assert_equal("Pod status: Terminating.", pod.failure_message)
  end

  def test_deploy_failed_is_false_for_terminating_managed_pods
    template = build_pod_template
    template["metadata"]["deletionTimestamp"] = "2018-04-13T22:43:23Z"
    pod = build_synced_pod(template, parent: mock)

    assert_predicate(pod, :terminating?)
    refute_predicate(pod, :deploy_failed?)
    assert_nil(pod.failure_message)
  end

  def test_deploy_failed_is_true_for_disappeared_unmanaged_pods
    template = build_pod_template
    pod = Krane::Pod.new(namespace: 'test', context: 'nope', definition: template,
      logger: @logger, deploy_started_at: Time.now.utc)
    cache = build_resource_cache(task_config: task_config)
    cache.expects(:get_instance).raises(Krane::Kubectl::ResourceNotFoundError)
    pod.sync(cache)

    assert_predicate(pod, :disappeared?)
    assert_predicate(pod, :deploy_failed?)
    assert_equal("Pod status: Disappeared.", pod.failure_message)
  end

  def test_deploy_failed_is_false_for_disappeared_managed_pods
    template = build_pod_template
    pod = Krane::Pod.new(namespace: 'test', context: 'nope', definition: template,
      logger: @logger, deploy_started_at: Time.now.utc, parent: mock)
    cache = build_resource_cache(task_config: task_config)
    cache.expects(:get_instance).raises(Krane::Kubectl::ResourceNotFoundError)
    pod.sync(cache)

    assert_predicate(pod, :disappeared?)
    refute_predicate(pod, :deploy_failed?)
    assert_nil(pod.failure_message)
  end

  private

  def pod_spec
    @pod_spec ||= YAML.load_file(File.join(fixture_path('for_unit_tests'), 'pod_test.yml'))
  end

  def build_synced_pod(template, parent: nil)
    pod = Krane::Pod.new(namespace: 'test', context: 'nope', definition: template,
      logger: @logger, deploy_started_at: Time.now.utc, parent: parent)
    stub_kind_get("Pod", items: [template])
    Krane::ContainerLogs.any_instance.stubs(:sync) unless parent.present?
    pod.sync(build_resource_cache)
    pod
  end

  def build_pod_template(container_state: {})
    pod_spec.merge(
      "status" => {
        "phase" => "Pending",
        "containerStatuses" => [
          {
            "lastState" => {},
            "state" => {},
            "name" => "hello-cloud",
            "ready" => false,
            "restartCount" => 0,
          }.merge(container_state),
        ],
      }
    )
  end
end


text:
var assert = require('assert');
var exec = require('exec-sync');
var fs = require('fs');
var nsgit = require('../build/Release/sgit');
var sgit = require('../lib/sgit');
var sleep = require('../node_modules/node-sleep');

describe('Node-native-sgit', function() {
	it("should be able to create a new repository", function(done) {
		nsgit.init_repository('./testrepo',function(err) {
			assert.equal(err,'');
			done();
		});
	});
	it("should be able to commit a single file", function(done) {
		exec('echo "this is a test" > ./testrepo/test.c');
		nsgit.commit_bypath('./testrepo','test.c','this is a test commit message',function(err) {
			nsgit.log_repository('./testrepo',function(err,log) {
				log = JSON.parse(log);
				var firstEntry = "";
				for (var i in log) {
					firstEntry = i;
					break;
				}
				assert(log[firstEntry].message,'this is a test commit message');
				done();
			});
		});
	});

	it("should be able to commit a single file in a subdirectory", function(done) {
                exec('mkdir ./testrepo/newfolder');
                exec('echo "this is a subfolder test" > ./testrepo/newfolder/test.c');
                nsgit.commit_bypath('./testrepo','newfolder/test.c','this is a test commit message for subfolder',function(err) {
                        nsgit.log_repository('./testrepo',function(err,log) {
                                log = JSON.parse(log);
                                var entry = "";
                                for (var i in log) {
                                        entry = i;
                                        break;
                                }
                                assert(log[entry].message,'this is a test commit message for subfolder');
				done();
                        });
                });
        });

        it("should be able to log history of a repo", function(done) {
                exec('echo "this is a test 2 editing this file" > ./testrepo/test.c');
                nsgit.commit_bypath('./testrepo','test.c','this is a revised commit message',function(err) {
                        nsgit.log_repository('./testrepo',function(err,log) {
                                log = JSON.parse(log);
                                var loop = 0;
                                for (var i in log) {
					if (loop == 0) {
                                		assert(log[i].message,'this is a test commit message');
					}
					else if (loop == 1) {
                                		assert(log[i].message,'this is a revised commit message');
					}
					else if (loop == 3) {
                                		assert(log[i].message,'this is a test commit message for subfolder');
					}
                                        loop++;
                                }
				done();
                        });
                });

        });

       	it("should clean up after itself", function() {
		exec("rm -rf ./testrepo");
		assert.strictEqual(fs.existsSync('./testrepo'),false);
	});
});
describe('Node-sgit', function() {
	it("should be able to create a new repository", function(done) {
		sgit.init('./testrepo',function(err) {
			assert.equal(err,'');
			done();
		});
	});

	it("should be able to commit a single file", function(done) {
		exec('echo "this is a test" > ./testrepo/test.c');
		sgit.commit('./testrepo/test.c','this is a test commit message',function(err) {
			sgit.log('./testrepo',function(err,log) {
				var firstEntry = "";
				for (var i in log) {
					firstEntry = i;
					break;
				}
				assert(log[firstEntry].message,'this is a test commit message');
				done();
			});
		});
	});

	it("should be able to commit a single file in a subdirectory", function(done) {
                exec('mkdir ./testrepo/newfolder');
                exec('echo "this is a subfolder test" > ./testrepo/newfolder/test.c');
                sgit.commit('./testrepo/newfolder/test.c','this is a test commit message for subfolder',function(err) {
                        sgit.log('./testrepo',function(err,log) {
                                var entry = "";
                                for (var i in log) {
                                        entry = i;
                                        break;
                                }
                                assert(log[entry].message,'this is a test commit messagefor subfolder');
				done();
                        });
                });
        });

        it("should be able to log history of a repo", function(done) {
                exec('echo "this is a test 2 editing this file" > ./testrepo/test.c');
                sgit.commit('./testrepo/test.c','this is a revised commit message',function(err) {
                        sgit.log('./testrepo',function(err,log) {
                                var loop = 0;
                                for (var i in log) {
					if (loop == 0) {
                                		assert(log[i].message,'this is a test commit message');
					}
					else if (loop == 2) {
                                		assert(log[i].message,'this is a revised commit message');
					}
					else if (loop == 3) {
                                		assert(log[i].message,'this is a test commit message for subfolder');
					}
                                        loop++;
                                }
				done();
                        });
                });

        });

        it("should clean up after itself", function() {
		exec("rm -rf ./testrepo");
		assert.strictEqual(fs.existsSync('./testrepo'),false);
	});
});


text:
import Vue from 'vue'
import inViewportDirective from 'vue-in-viewport-directive'

Vue.directive('in-viewport', inViewportDirective)


text:
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using DataExplorer.Domain.Columns;
using DataExplorer.Domain.Filters;

namespace DataExplorer.Persistence.Filters.Serializers
{
    public interface IFilterSetSerializer
    {
        XElement Serialize(IEnumerable<Filter> filters);

        IEnumerable<Filter> Deserialize(XElement xFilters, List<Column> columns);
    }
}


text: Build step that sends a Dockerfile for building to docker host that used for this build run.


text:
/*
 * Desc: Gazebo Error
 * Author: Nathan Koenig
 * Date: 07 May 2007
 */

#include "gazebo/common/Console.hh"
#include "gazebo/common/Exception.hh"

using namespace gazebo;
using namespace common;
using namespace std;

//////////////////////////////////////////////////
Exception::Exception()
{
}

//////////////////////////////////////////////////
Exception::Exception(const char *_file, int _line, std::string _msg)
{
  this->file = _file;
  this->line = _line;
  this->str = _msg;
  this->Print();
}

//////////////////////////////////////////////////
Exception::~Exception()
{
}

//////////////////////////////////////////////////
void Exception::Print() const
{
  gzerr << "EXCEPTION: " << *this << std::endl;
}

//////////////////////////////////////////////////
std::string Exception::GetErrorFile() const
{
  return this->file;
}

//////////////////////////////////////////////////
std::string Exception::GetErrorStr() const
{
  return this->str;
}

//////////////////////////////////////////////////
InternalError::InternalError()
{
}

//////////////////////////////////////////////////
InternalError::InternalError(const char *_file, int _line,
                             const std::string &_msg) :
  Exception(_file, _line, _msg)
{
}

//////////////////////////////////////////////////
InternalError::~InternalError()
{
}

//////////////////////////////////////////////////
AssertionInternalError::AssertionInternalError(
    const char * _file, int _line,
    const std::string &_expr,
    const std::string &_function,
    const std::string &_msg) :
  InternalError(_file, _line,
      "GAZEBO ASSERTION                     \n" +
      _msg                               + "\n" +
      "In function       : " + _function + "\n" +
      "Assert expression : " + _expr     + "\n")
{
}

//////////////////////////////////////////////////
AssertionInternalError::~AssertionInternalError()
{
}


text:
function mibChannelMixerTable_CellEditCallback(obj, Indices, PreviousData, modifier)
% function mibChannelMixerTable_CellEditCallback(obj, Indices, PreviousData, modifier)
% a callback edit of a cell in obj.mibView.handles.mibChannelMixerTable
%
% Parameters:
% Indices: row and column indices of the cell(s) edited
% PreviousData: previous data for the cell(s) edited
% modifier: a pressed key modifier, [], 'control', 'shift'

% Copyright (C) 07.12.2016, Ilya Belevich, University of Helsinki (ilya.belevich @ helsinki.fi)
% part of Microscopy Image Browser, http:\\mib.helsinki.fi
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% Updates
%

data = obj.mibView.handles.mibChannelMixerTable.Data;

selected = find(cell2mat(data(:,2))==1)';
if isempty(selected)
    data{Indices(1), 2} = PreviousData;
    obj.mibView.handles.mibChannelMixerTable.Data = data;
    return;
end;
if strcmp(modifier, 'control') % toggle between two color channels using the Ctrl modifier
    for i=1:size(data,1);        data{i,2} = 0;    end;    % clear selected channels
    data{Indices(1,1),2} = 1;
    obj.mibView.handles.mibChannelMixerTable.Data = data;
end

obj.mibModel.I{obj.mibModel.Id}.slices{3} = find(cell2mat(data(:,2))==1)';

if numel(obj.mibModel.I{obj.mibModel.Id}.slices{3}) == 1
    obj.mibView.handles.mibColChannelCombo.Value = obj.mibModel.I{obj.mibModel.Id}.slices{3}+1;    % update color channel combo box in the Selection panel
    obj.mibModel.I{obj.mibModel.Id}.selectedColorChannel = obj.mibModel.I{obj.mibModel.Id}.slices{3};
end
obj.redrawMibChannelMixerTable();
obj.plotImage(0);
end


text:
require "rubygems"
require "bundler/setup"
require "kakurenbo"

RSpec.configure do |config|
  config.color = true
  config.mock_framework = :rspec
  config.before(:all) {
    ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
  }
end

# Use ActiveSupport::Inflector#classify
Inflector = Class.new.extend(ActiveSupport::Inflector)

# Create temp table for test.
#
# @param name   [Symbol]        Name of table.
# @param &block [Proc{|t|...}]  Definition column block.
def create_temp_table(name, &block)
  raise 'No block given!' unless block_given?

  class_name = Inflector.classify(name)

  before :all do
    migration = ActiveRecord::Migration.new
    migration.verbose = false
    migration.create_table name, &block

    mock_class = Class.new(ActiveRecord::Base) do
      define_singleton_method(:name){ class_name }
      reset_table_name
    end

    Object.const_set class_name, mock_class
  end

  after :all do
    migration = ActiveRecord::Migration.new
    migration.verbose = false
    migration.drop_table name

    Object.class_eval { remove_const class_name }
  end
end


text:
This package provides a way to initialize possible errors and handle them with ease.

Installation
------------
The only requirement is the [Go Programming Language](https://golang.org/dl).

```bash
$ go get -u github.com/kataras/go-errors
```

Docs
------------

## New

`New` receives a message format and creates a new Error. Message format, which is created with .New, is never changes.

```go
import "github.com/kataras/go-errors"

var errUserAlreadyJoined = errors.New("User with username: %s was already joined in this room!")
```

## Format

`Format` is like `fmt.Sprintf` but for specific Error, returns a new error with the formatted message.

```go
import "github.com/kataras/go-errors"

var errUserAlreadyJoined = errors.New("User with username: %s was already joined in this room!")

func anything() error {
  return errUserAlreadyJoined.Format("myusername")
  // will return an error with message =
  // User with username: myusername was already joined in this room!
  //
}

```

## Append

`Append` and `AppendErr` adds a message to existing message and returns a new error.

```go
import "github.com/kataras/go-errors"

var errUserAlreadyJoined = errors.New("User with username: %s was already joined in this room!")

func anything() error {
  return errUserAlreadyJoined.Append("Please specify other room.").Format("myusername")
  // will return an error with message =
  // User with username: myusername was already joined in this room!
  // Please specify other room.
  //
}
```
```go
import "github.com/kataras/go-errors"

var errUserAlreadyJoined = errors.New("User with username: %s was already joined in this room!")
var errSpecifyOtherRoom  = errors.New("Please specify other room.")

func anything() error {
  return errUserAlreadyJoined.AppendErr(errSpecifyOtherRoom).Format("myusername")
  // will return an error with message =
  // User with username: myusername was already joined in this room!
  // Please specify other room.
  //
}

```

Use `AppendErr` with go standard error type

```go
import (
  "github.com/kataras/go-errors"
  "fmt"
)

var errUserAlreadyJoined = errors.New("User with username: %s was already joined in this room!")

func anything() error {
  err := fmt.Errorf("Please specify other room") // standard golang error

  return errUserAlreadyJoined.AppendErr(err).Format("myusername")
  // will return an error with message =
  // User with username: myusername was already joined in this room!
  // Please specify other room.
  //
}

```

go-* packages
------------

| Name        | Description
| ------------------|:---------------------:|
| [go-fs](https://github.com/kataras/go-fs)      | FileSystem utils and common net/http static files handlers
| [go-events](https://github.com/kataras/go-events) | EventEmmiter for Go
| [go-websocket](https://github.com/kataras/go-errors) | A websocket server and ,optionally, client side lib  for Go
| [go-ssh](https://github.com/kataras/go-ssh) | SSH Server, build ssh interfaces, remote commands and remote cli with ease
| [go-gzipwriter](https://github.com/kataras/go-gzipwriter) | Write gzip data to a io.Writer
| [go-mailer](https://github.com/kataras/go-mailer) | E-mail Sender, send rich mails with one call
| [rizla](https://github.com/kataras/rizla) | Monitor and live-reload of your Go App
| [Q](https://github.com/kataras/q) | HTTP2 Web Framework, 100% compatible with net/http
| [Iris](https://github.com/kataras/iris) | The fastest web framework. Built on top of fasthttp

FAQ
------------
Explore [these questions](https://github.com/kataras/go-errors/issues?go-errors=label%3Aquestion) or navigate to the [community chat][Chat].

Versioning
------------

Current: **v0.0.3**

People
------------
The author of go-errors is [@kataras](https://github.com/kataras).

If you're **willing to donate**, feel free to send **any** amount through paypal

[![](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kataras2006%40hotmail%2ecom&lc=GR&item_name=Iris%20web%20framework&item_number=iriswebframeworkdonationid2016&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)

Contributing
------------
If you are interested in contributing to the go-errors project, please make a PR.

License
------------

This project is licensed under the MIT License.

License can be found [here](LICENSE).

[Travis Widget]: https://img.shields.io/travis/kataras/go-errors.svg?style=flat-square
[Travis]: http://travis-ci.org/kataras/go-errors
[License Widget]: https://img.shields.io/badge/license-MIT%20%20License%20-E91E63.svg?style=flat-square
[License]: https://github.com/kataras/go-errors/blob/master/LICENSE
[Release Widget]: https://img.shields.io/badge/release-v0.0.3-blue.svg?style=flat-square
[Release]: https://github.com/kataras/go-errors/releases
[Chat Widget]: https://img.shields.io/badge/community-chat-00BCD4.svg?style=flat-square
[Chat]: https://kataras.rocket.chat/channel/go-errors
[ChatMain]: https://kataras.rocket.chat/channel/go-errors
[ChatAlternative]: https://gitter.im/kataras/go-errors
[Report Widget]: https://img.shields.io/badge/report%20card-A%2B-F44336.svg?style=flat-square
[Report]: http://goreportcard.com/report/kataras/go-errors
[Documentation Widget]: https://img.shields.io/badge/documentation-reference-5272B4.svg?style=flat-square
[Documentation]: https://www.gitbook.com/book/kataras/go-errors/details
[Language Widget]: https://img.shields.io/badge/powered_by-Go-3362c2.svg?style=flat-square
[Language]: http://golang.org
[Platform Widget]: https://img.shields.io/badge/platform-Any--OS-gray.svg?style=flat-square


text:
.class Landroid/widget/YearPickerView$2;
.super Ljava/lang/Object;
.source "YearPickerView.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/widget/YearPickerView;->setYear(I)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/YearPickerView;

.field final synthetic val$year:I

# direct methods
.method constructor <init>(Landroid/widget/YearPickerView;I)V
    .locals 0
    .param p1, "this$0"    # Landroid/widget/YearPickerView;
    .param p2, "val$year"    # I

    .prologue
    .line 94
    iput-object p1, p0, Landroid/widget/YearPickerView$2;->this$0:Landroid/widget/YearPickerView;

    iput p2, p0, Landroid/widget/YearPickerView$2;->val$year:I

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 3

    .prologue
    .line 97
    iget-object v1, p0, Landroid/widget/YearPickerView$2;->this$0:Landroid/widget/YearPickerView;

    invoke-static {v1}, Landroid/widget/YearPickerView;->-get0(Landroid/widget/YearPickerView;)Landroid/widget/YearPickerView$YearAdapter;

    move-result-object v1

    iget v2, p0, Landroid/widget/YearPickerView$2;->val$year:I

    invoke-virtual {v1, v2}, Landroid/widget/YearPickerView$YearAdapter;->getPositionForYear(I)I

    move-result v0

    .line 98
    .local v0, "position":I
    if-ltz v0, :cond_0

    iget-object v1, p0, Landroid/widget/YearPickerView$2;->this$0:Landroid/widget/YearPickerView;

    invoke-virtual {v1}, Landroid/widget/YearPickerView;->getCount()I

    move-result v1

    if-ge v0, v1, :cond_0

    .line 99
    iget-object v1, p0, Landroid/widget/YearPickerView$2;->this$0:Landroid/widget/YearPickerView;

    invoke-virtual {v1, v0}, Landroid/widget/YearPickerView;->setSelectionCentered(I)V

    .line 96
    :cond_0
    return-void
.end method


text:
function Assert-NotFalse
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $false, Position = 0)]
        [AllowNull()]
        [System.Object]
        $Value
    )

    $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
    if (-not $PSBoundParameters.ContainsKey('Verbose')) {
        $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') -as [System.Management.Automation.ActionPreference]
    }

    $fail = ($Value -is [System.Boolean]) -and (-not $Value)

    if ($fail -or ([System.Int32]$VerbosePreference)) {
        $message = & $_7ddd17460d1743b2b6e683ef649e01b7_newAssertionStatus -invocation $MyInvocation -fail:$fail

        Write-Verbose -Message $message

        if ($fail) {
            if (-not $PSBoundParameters.ContainsKey('Debug')) {
                $DebugPreference = [System.Int32]($PSCmdlet.GetVariableValue('DebugPreference') -as [System.Management.Automation.ActionPreference])
            }
            Write-Debug -Message $message
            $PSCmdlet.ThrowTerminatingError((& $_7ddd17460d1743b2b6e683ef649e01b7_newAssertionFailedError -message $message -innerException $null -value $Value))
        }
    }
}


text:
package ro.dcsi.internship;

public class WrappedCheckedException extends RuntimeException {
  private static final long serialVersionUID = -1796029080899107110L;

  public WrappedCheckedException() {
    super();
  }

  public WrappedCheckedException(String message, Throwable cause, boolean enableSuppression,
      boolean writableStackTrace) {
    super(message, cause, enableSuppression, writableStackTrace);
  }

  public WrappedCheckedException(String message, Throwable cause) {
    super(message, cause);
  }

  public WrappedCheckedException(String message) {
    super(message);
  }

  public WrappedCheckedException(Throwable cause) {
    super(cause);
  }
}


text:
<?php
App::uses('AppModel', 'Model');
/**
 * UserStatus Model
 *
 */
class SubsidiaryStatus extends AppModel {

	public $changeDbConfig = true;

/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';

}


text:
<?php
declare (strict_types=1);
namespace Recoil\Amqp\v091\Protocol\Queue;

use Recoil\Amqp\v091\Protocol\MethodFrame;
use Recoil\Amqp\v091\Protocol\OutgoingFrame;

final class QueuePurgeFrame implements MethodFrame, OutgoingFrame
{
    const METHOD_ID = 0x0032001e;

    public $frameChannelId = 0;
    public $reserved1 = 0; // short
    public $queue = ''; // shortstr
    public $nowait = false; // bit

    public static function create(
        $queue = null
      , $nowait = null
    ) {
        $frame = new self();

        if (null !== $queue) {
            $frame->queue = $queue;
        }
        if (null !== $nowait) {
            $frame->nowait = $nowait;
        }

        return $frame;
    }
}


text:
"""Split subscription object in several columns

Revision ID: b75f7c7164ca
Revises: f66a92f1895f
Create Date: 2017-08-22 14:33:55.543213

"""

# revision identifiers, used by Alembic.
revision = 'b75f7c7164ca'
down_revision = 'f66a92f1895f'

from alembic import op
import sqlalchemy as sa
import cineapp.migration_types

from sqlalchemy.dialects import mysql

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('push_notifications', sa.Column('auth_token', sa.String(length=128), nullable=True))
    op.add_column('push_notifications', sa.Column('endpoint_id', sa.String(length=255), nullable=False))
    op.add_column('push_notifications', sa.Column('public_key', sa.String(length=128), nullable=True))
    op.drop_column('push_notifications', 'subscription_id')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('push_notifications', sa.Column('subscription_id', mysql.VARCHAR(length=255), nullable=False))
    op.drop_column('push_notifications', 'public_key')
    op.drop_column('push_notifications', 'endpoint_id')
    op.drop_column('push_notifications', 'auth_token')
    # ### end Alembic commands ###


text:
lang:   EN
title:  A Giraffe Has Not Stolen Summary #7
answer:
class:  stretcher chapmark
ok:
error:
load:   prev;blurb2=Blurb.new :confused, "I can not believe Mt. Hood was stolen!"
---

Aha, you're here. And all in one piece. We're still going to make your app real,
but until then, let's review, okay?

### Classes
Everything in Ruby is some kind of object. Classes explain objects, how a certain object works.
For example, you made a few BlurbTM objects and these objects are explained in the Blurb
class.
In other words: you call them Blurb objects.
You can use classes to (kinda) model real life objects.

### Accessors
Accessors are variables attached to an object which can be used __outside__ the object.
(blurb2.time = Time.now)

### Object variables
Object variables are the same variables you're using for accessors, but __inside__ the object.
(@time = Time.now)


text:
package edu.mit.scansite.webservice.proteinscan;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import edu.mit.scansite.server.features.ProteinScanFeature;
import edu.mit.scansite.shared.DataAccessException;
import edu.mit.scansite.shared.transferobjects.DataSource;
import edu.mit.scansite.shared.transferobjects.HistogramStringency;
import edu.mit.scansite.shared.transferobjects.LightWeightProtein;
import edu.mit.scansite.shared.transferobjects.MotifClass;
import edu.mit.scansite.shared.transferobjects.MotifSelection;
import edu.mit.scansite.shared.transferobjects.ScanResultSite;
import edu.mit.scansite.shared.transferobjects.User;
import edu.mit.scansite.webservice.WebService;
import edu.mit.scansite.webservice.exception.ScansiteWebServiceException;
import edu.mit.scansite.webservice.transferobjects.MotifSite;
import edu.mit.scansite.webservice.transferobjects.ProteinScanResult;

/**
 * @author Tobieh
 * @author Thomas Bernwinkler
 * @author Konstantin Krismer
 */

public class ProteinScanWebService extends WebService {
	private static final String MOTIF_SEPARATOR = "~";

	// package private
	static ProteinScanResult doProteinScan(LightWeightProtein protein, String referenceProteome,
			String dataSourceShortName, DataSource localizationDataSource, String inputMotifShortNames,
			String motifClass, String stringencyValue) {

		// check motif input
		MotifClass mc = MotifClass.getDbValue(motifClass.toUpperCase());

		if (StringUtils.isBlank(dataSourceShortName)) {
			dataSourceShortName = "swissprot";
		}

		// If explicitly motifs picked: use them -- else motif class
		String[] motifShortNames;
		Set<String> motifShortNamesSet = null;
		if (StringUtils.isNotBlank(inputMotifShortNames)) {
			motifShortNames = inputMotifShortNames.split(MOTIF_SEPARATOR);
			if (motifShortNames.length > 0) {
				motifShortNamesSet = new HashSet<>();
				Collections.addAll(motifShortNamesSet, motifShortNames);
			}
		}

		// check stringency input
		HistogramStringency stringency = getStringency(stringencyValue);
		if (stringency == null || dataSourceShortName.isEmpty()) {
			stringency = getStringency("High");
		}

		// LightWeightProtein protein = new LightWeightProtein(proteinName,
		// proteinSequence);
		MotifSelection motifSelection = new MotifSelection();
		motifSelection.setMotifShortNames(motifShortNamesSet);
		motifSelection.setMotifClass(mc);
		final boolean showDomains = false;
		final boolean doCreateFiles = false;
		final User user = null;
		final String realPath = null; // only necessary if doCreateFiles or if showDomains

		try {
			ProteinScanFeature feature = new ProteinScanFeature();

			edu.mit.scansite.shared.dispatch.features.ProteinScanResult res = feature.doProteinScan(protein,
					motifSelection, stringency, showDomains, dataSourceShortName, referenceProteome,
					localizationDataSource, doCreateFiles, user, realPath);

			if (res.isSuccess()) {
				ProteinScanResult result = new ProteinScanResult();
				result.setProteinName(res.getResults().getProtein().getIdentifier());
				result.setProteinSequence(res.getResults().getProtein().getSequence());
				if (res.getResults().getHits() == null || res.getResults().getHits().isEmpty()) {
					result.setPredictedSite(new MotifSite[] {});
				} else {
					MotifSite[] sites = new MotifSite[res.getResults().getHits().size()];
					for (int i = 0; i < sites.length; ++i) {
						ScanResultSite site = res.getResults().getHits().get(i);
						sites[i] = new MotifSite(site.getScore(), site.getPercentile(),
								site.getMotif().getDisplayName(), site.getMotif().getShortName(), site.getSite(),
								site.getSiteSequence().replaceAll("\\<.*?\\>", ""));
					}
					result.setPredictedSite(sites);
				}

				return result;
			} else {
				throw new ScansiteWebServiceException(res.getFailureMessage());
			}
		} catch (DataAccessException e) {
			throw new ScansiteWebServiceException("Running ProteinScan service failed.");
		}
	}

	public static HistogramStringency getStringency(String stringencyValue) {
		if (stringencyValue == null || stringencyValue.isEmpty()) {
			stringencyValue = "high";
		}

		for (HistogramStringency str : HistogramStringency.values()) {
			if (str.getName().equalsIgnoreCase(stringencyValue)) {
				return str;
			}
		}
		return null;
	}
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('applications', '0002_auto_20190808_1609'),
    ]

    operations = [
        migrations.AddField(
            model_name='record',
            name='extension',
            field=models.CharField(blank=True, max_length=5, null=True),
        ),
    ]


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.coursera.capstone.android.fragment.CheckInSummaryFragment">

    <TextView
        android:id="@+id/patient_check_in_summary_text"
        android:textSize="@dimen/text_h1"
        android:textAlignment="center"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/patient_check_in_summary_title" />
    <TextView
        android:id="@+id/patient_check_in_summary_desc"
        android:layout_below="@id/patient_check_in_summary_text"
        android:textSize="@dimen/text_normal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/patient_check_in_summary_desc" />

     <!-- Questions -->
    <TextView
        android:id="@+id/patient_check_in_summary_questions_title"
        android:layout_below="@id/patient_check_in_summary_desc"
        android:paddingTop="@dimen/activity_horizontal_margin"
        android:textSize="@dimen/text_h2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/patient_check_in_summary_questions_text" />
    <LinearLayout
        android:id="@+id/patient_check_in_summary_questions"
        android:layout_below="@id/patient_check_in_summary_questions_title"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </LinearLayout>

    <!-- Pain medications -->
    <TextView
        android:id="@+id/patient_check_in_summary_medications_title"
        android:layout_below="@id/patient_check_in_summary_questions"
        android:paddingTop="@dimen/activity_horizontal_margin"
        android:textSize="@dimen/text_h2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/patient_check_in_summary_medications_text" />
    <LinearLayout
        android:id="@+id/patient_check_in_summary_medications"
        android:layout_below="@id/patient_check_in_summary_medications_title"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </LinearLayout>

    <Button
        android:id="@+id/patient_check_in_summary_submit"
        android:layout_alignParentBottom="true"
        style="@style/GreenButton"
        android:text="@string/patient_check_in_summary_submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>


text:
from __future__ import absolute_import, unicode_literals

__all__ = ['GitVcs']

import os

from urlparse import urlparse

from .base import Vcs, CommandError, UnknownRevision

class GitVcs(Vcs):
    binary_path = 'git'

    def get_default_env(self):
        return {
            'GIT_SSH': self.ssh_connect_path,
        }

    def get_default_revision(self):
        return 'master'

    @property
    def remote_url(self):
        if self.url.startswith(('ssh:', 'http:', 'https:')):
            parsed = urlparse(self.url)
            port = (':%s' % (parsed.port,) if parsed.port else '')
            url = '%s://%s@%s/%s' % (
                parsed.scheme,
                parsed.username or self.username or 'git',
                parsed.hostname + port,
                parsed.path.lstrip('/'),
            )
        else:
            url = self.url
        return url

    def run(self, cmd, **kwargs):
        cmd = [self.binary_path] + cmd
        try:
            return super(GitVcs, self).run(cmd, **kwargs)
        except CommandError as e:
            if e.stderr and 'unknown revision or path' in e.stderr:
                raise UnknownRevision(
                    cmd=e.cmd,
                    retcode=e.retcode,
                    stdout=e.stdout,
                    stderr=e.stderr,
                )
            raise

    def clone(self):
        self.run(['clone', '--mirror', self.remote_url, self.path])

    def update(self):
        # in case we have a non-mirror checkout, wipe it out
        if os.path.exists(os.path.join(self.workspace.path, '.git')):
            self.run(['rm', '-rf', self.workspace.path])
            self.clone()
        else:
            self.run(['fetch', '--all', '-p'])

    def checkout(self, ref, new_workspace):
        self.run(['clone', self.workspace.path, new_workspace.path],
                 workspace=new_workspace)
        self.run(['reset', '--hard', ref], workspace=new_workspace)

    def describe(self, ref):
        return self.run(['describe', '--always', '--abbrev=0', ref],
                        capture=True)