text:
from pyfftw import (
    FFTW, empty_aligned,
    interfaces,
    _all_types_np, _all_types_human_readable, _supported_types
    )
from pyfftw.builders._utils import _rc_dtype_pairs
import numpy as np
import unittest
import warnings

@unittest.skipIf(len(_all_types_human_readable) == len(_supported_types), "All data types available")
class FFTWPartialTest(unittest.TestCase):

    def __init__(self, *args, **kwargs):

        super(FFTWPartialTest, self).__init__(*args, **kwargs)

        if not hasattr(self, 'assertRaisesRegex'):
            self.assertRaisesRegex = self.assertRaisesRegexp

    def test_failure(self):
        for dtype, npdtype in zip(['32', '64', 'ld'], [np.complex64, np.complex128, np.clongdouble]):
            if dtype == 'ld' and np.dtype(np.clongdouble) == np.dtype(np.complex128):
                # skip this test on systems where clongdouble is complex128
                continue
            if dtype not in _supported_types:
                a = empty_aligned((1,1024), npdtype, n=16)
                b = empty_aligned(a.shape, dtype=a.dtype, n=16)
                msg = "Rebuild pyFFTW with support for %s precision!" % _all_types_human_readable[dtype]
                with self.assertRaisesRegex(NotImplementedError, msg):
                    FFTW(a,b)

    def conversion(self, missing, alt1, alt2):
        '''If the ``missing`` precision is not available, the builder should convert to
           ``alt1`` precision. If that isn't available either, it should fall back to
           ``alt2``. If input precision is lost, a warning should be emitted.

        '''

        missing, alt1, alt2 = [np.dtype(x) for x in (missing, alt1, alt2)]
        if _all_types_np[missing]  in _supported_types:
            return

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            itemsize = alt1.itemsize
            a = empty_aligned((1, 512), dtype=missing)
            b = interfaces.numpy_fft.fft(a)
            res = _rc_dtype_pairs.get(alt1.char, None)
            if res is not None:
                self.assertEqual(b.dtype, res)
            else:
                itemsize = alt2.itemsize
                self.assertEqual(b.dtype, _rc_dtype_pairs[alt2.char])

            if itemsize < missing.itemsize:
                print(itemsize, missing.itemsize)
                assert len(w) == 1
                assert "Narrowing conversion" in str(w[-1].message)
                print("Found narrowing conversion from %d to %d bytes" % (missing.itemsize, itemsize))
            else:
                assert len(w) == 0

    def test_conversion(self):
        self.conversion('float32', 'float64', 'longdouble')
        self.conversion('float64', 'longdouble', 'single')
        self.conversion('longdouble', 'float64', 'float32')

test_cases = (
        FFTWPartialTest,)

test_set = None

if __name__ == '__main__':

    run_test_suites(test_cases, test_set)


text:
class HierarchiesController < ApplicationController
  layout 'admin/home'

  def index
    @hierarchies = Hierarchy.all
  end

  def new
    @hierarchy = Hierarchy.new
  end

  def create
    @hierarchy = Hierarchy.new(params[:hierarchy])
    @hierarchy.save!

    redirect_to hierarchies_path
  end

  def destroy
    Hierarchy.find(params[:id]).destroy

    redirect_to hierarchies_path
  end

end

redpajama_set_name: RedPajamaGithub


text:
@interface DDAddChatGroup : NSObject
@property (nonatomic,retain)NSString* name;
@property (nonatomic,retain)NSMutableArray* users;
@property (nonatomic,retain)DDAddChatGroup* groups;
@property (nonatomic,assign)NSInteger priority;
@property (nonatomic,assign)NSInteger departmentID;
@property (nonatomic,assign)NSInteger parentDepartmentID;
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:right="1dp" android:left="1dp" android:bottom="2dp">
        <!-- BACKGROUND -->
        <shape
            android:shape="rectangle">
            <solid android:color="@color/colorAccentDark"/>
            <corners android:radius="2dp"/>
        </shape>
    </item>
</layer-list>


text: Copyright © Your Website 2014


text:
\chapter{Introducción}

\section{Motivación}

La cantidad de procesamiento cada vez es mayor y los centros de datos (CPD) cada vez son más grandes y consumen más. Ademas se sabe que el consumo de un CPD es constante a lo largo del tiempo, por esto cada vez se opta por suministrar dichos centros con energía obtenida de fuentes renovables, ya que pueden suponer un ahorro energético considerable. Aunque aun no es practicable alimentar un CPD completamente con energías renovables, se puede asegurar gran parte del consumo con estas fuentes.

Uno de los problemas del abastecimiento con energías renovables es la impredecibilidad de las fuentes, el sol y el viento. Estas dos fuentes no son constantes en el tiempo (El sol sale y se esconde cada día y el viento sopla con mayor o menor fuerza en función del estado de la atmósfera). En consecuencia la producción es muy inestable y aleatoria.

La solución clásica a estos problemas es almacenar la energía en baterías para el consumo en momentos de no producción.

Otro problema es que las baterías suelen tener una duración y no puede asegurarse todos los periodos de no producción. Así que finalmente se deberá consumir energía de la red eléctrica.

Pongamos un ejemplo: Si se acerca un periodo de no producción de 8 horas y las baterías duran 4 horas, en que 4 horas sera mejor usar las baterías?

En principio nos debería dar igual, pero si nos encontramos en un país en el que hay tarifas horarias quizá convendría usar las baterías en el momento en que la electricidad es mas cara.
De este pensamiento surge la predicción energética.

Si pudiésemos predecir con moderada exactitud la energía que se producirá, podremos realizar un plan que permitirá ahorrar costes en gran medida

\section{Propósito}

Nuestro objetivo es examinar qué metodología tiene los mejores resultados observados en la predicción energética de una planta solar y una eólica con un horizonte de 24h.

Para la predicción se pueden usar 2 tipos de modelos de predicción: Modelos analíticos, que se basan en realizar un análisis exhaustivo del problema y proporcionar una solución detallada, y Modelos auto-regresivos, que se describen un proceso que proporciona una salida la cual depende linealmente de sus valores anteriores o "histórico".

Dado que queremos obtener un conjunto de reglas genéricas, optaremos por usar modelos autor-regresivos que se basan en el histórico para realizar predicciones y permiten abstraernos de la planta, el panel y las condiciones.

Con estos modelos, realizaremos predicciones con valores extraídos de una planta solar/eólica (Simulada) y tras extraer los resultados de la predicción y el error, analizaremos los diferentes puntos.

Ademas definiremos Horizonte de predicción como el limite máximo en términos temporales en los cuales se puede realizar una predicción válida. En nuestro caso será el periodo máximo para las predicciones.
El horizonte de predicción puede adquirir cualquier valor, desde ultra-corto plazo como puede ser de minutos hasta a largo plazo como son semanas.

En materia de predicción energética, la precisión primará sobre la lejanía del horizonte de predicción, por esto barajaremos valores cercanos. Además, debido a la periodicidad del sol y la duración habitual de las baterías optaremos por 24 horas, que es el valor mínimo de calidad de días y esta por encima de la duración de un equipo de baterías (Esto podría ser 8 horas).


text:
<?php

namespace BaleenTest\Migrations\Service\Runner;

use Baleen\Migrations\Migration\Options;
use Baleen\Migrations\Migration\Options\Direction;
use Baleen\Migrations\Service\Runner\CollectionRunner;
use Baleen\Migrations\Service\Runner\Event\Collection\CollectionAfterEvent;
use Baleen\Migrations\Service\Runner\Event\Collection\CollectionBeforeEvent;
use Baleen\Migrations\Service\Runner\Event\Migration\MigrateBeforeEvent;
use Baleen\Migrations\Service\Runner\Event\Migration\MigrationEvent;
use Baleen\Migrations\Common\Event\PublisherInterface;
use Baleen\Migrations\Delta\Collection\Collection;
use Baleen\Migrations\Delta\Comparator\IdComparator;
use Baleen\Migrations\Delta\DeltaInterface;
use Mockery as m;

/**
 * Class CollectionRunnerTest
 * @author Gabriel Somoza <gabriel@strategery.io>
 */
class CollectionRunnerTest extends RunnerTestCase
{
    /**
     * testRunCollection
     * @param $versions
     * @param $goal
     * @param Direction $direction
     * @param $resultMatrix
     * @throws \Exception
     * @dataProvider runCollectionProvider
     */
    public function testRunCollection($versions, $goal, Direction $direction, $resultMatrix)
    {
        switch ($versions) {
            case 'all-migrated':
                $versions = $this->getAllMigratedVersionsFixture();
                break;
            case 'no-migrated':
                $versions = $this->getNoMigratedVersionsFixture();
                break;
            case 'mixed-migrated':
                $versions = $this->getMixedVersionsFixture();
                break;
            default:
                throw new \Exception('invalid key specified for this test!');
        }

        $collection = new Collection($versions, null, new IdComparator());
        $target = $collection->find($goal);

        /** @var PublisherInterface|m\Mock $publisher */
        $publisher = m::mock(PublisherInterface::class);
        $publisher->shouldReceive('publish')
            ->with(m::type(CollectionBeforeEvent::class))
            ->once();
        $publisher->shouldReceive('publish')
            ->with(m::type(CollectionAfterEvent::class))
            ->once();

        $previousProgress = 0;
        $publisher->shouldReceive('publish')
            ->with(m::on(function ($val) use (&$previousProgress) {
                if (!$val instanceof MigrationEvent) {
                    return false;
                }
                $progress = $val->getContext()->getProgress();

                // check that progress increments for every new migration event
                if ($val instanceof MigrateBeforeEvent) {
                    $hasProgressed = $progress->getCurrent() > $previousProgress;
                } else {
                    $hasProgressed = true;
                    $previousProgress = $progress->getCurrent();
                }
                return $progress->getTotal() == 12 && $hasProgressed;
            }))
            ->zeroOrMoreTimes(); // we're not testing this

        $runner = new CollectionRunner($collection, null, $publisher);
        $options = (new Options($direction))->withExceptionOnSkip(false);
        $runner->run($target, $options);

        // ASSERTS
        $map = $collection->map(function(DeltaInterface $v) {
            return $v->isMigrated();
        });
        $resultMatrix = array_map(function($item) {
            return (bool) $item;
        }, $resultMatrix);
        $this->assertEquals($resultMatrix, array_values($map));
    }

    /**
     * runCollectionProvider
     * NOTE: testRunCollection expects each matrix to have exactly 12 items
     *
     * @return array
     */
    public function runCollectionProvider()
    {
        $allMigrated = 'all-migrated';
        $noMigrated = 'no-migrated';
        $mixedMigrated = 'mixed-migrated';

        // collection, goal, direction, up/down matrix
        return [
            // last, up
            [$allMigrated, 'last', Direction::up(), array_fill(0, 12, 1)],
            [$noMigrated, 'last', Direction::up(), array_fill(0, 12, 1)],
            [$mixedMigrated, 'last', Direction::up(), array_fill(0, 12, 1)],
            // last, down
            [$allMigrated, 'last', Direction::down(), array_fill(0, 12, 0)],
            [$noMigrated, 'last', Direction::down(), array_fill(0, 12, 0)],
            [$mixedMigrated, 'last', Direction::down(), array_fill(0, 12, 0)],
            // first, up
            [$allMigrated, 'first', Direction::up(), array_fill(0, 12, 1)],
            [$noMigrated, 'first', Direction::up(), [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
            [$mixedMigrated, 'first', Direction::up(), $this->getUpdatedMixedMatrix([0], 1)],
            // first, down
            [$allMigrated, 'first', Direction::down(), [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
            [$noMigrated, 'first', Direction::down(), array_fill(0, 12, 0)],
            [$mixedMigrated, 'first', Direction::down(), $this->getUpdatedMixedMatrix([0], 0)],
            // v08, up
            [$allMigrated, 'v06', Direction::up(), array_fill(0, 12, 1)],
            [$noMigrated, 'v06', Direction::up(), [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]],
            [$mixedMigrated, 'v06', Direction::up(), $this->getUpdatedMixedMatrix(range(0, 5), 1)],
            // v08, down
            [$allMigrated, 'v06', Direction::down(), [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]],
            [$noMigrated, 'v06', Direction::down(), array_fill(0, 12, 0)],
            [$mixedMigrated, 'v06', Direction::down(), $this->getUpdatedMixedMatrix(range(0, 5), 0)],
        ];
    }
}


text:
#region License

#endregion

using System.Collections;

namespace Spring.Collections
{
    /// <summary>
    /// Synchronized <see cref="IDictionaryEnumerator"/> that should be returned by synchronized
    /// dictionary implementations in order to ensure that the enumeration is thread safe.
    /// </summary>
    /// <author>Aleksandar Seovic</author>
    internal class SynchronizedDictionaryEnumerator : SynchronizedEnumerator, IDictionaryEnumerator
    {
        public SynchronizedDictionaryEnumerator(object syncRoot, IDictionaryEnumerator enumerator)
            : base(syncRoot, enumerator)
        {
        }

        protected IDictionaryEnumerator Enumerator
        {
            get { return (IDictionaryEnumerator) enumerator; }
        }

        public object Key
        {
            get
            {
                lock (syncRoot)
                {
                    return Enumerator.Key;
                }
            }
        }

        public object Value
        {
            get
            {
                lock (syncRoot)
                {
                    return Enumerator.Value;
                }
            }
        }

        public DictionaryEntry Entry
        {
            get
            {
                lock (syncRoot)
                {
                    return Enumerator.Entry;
                }
            }
        }
    }
}


text:
package org.usc.demo.temp.bak;

import java.text.SimpleDateFormat;

/**
 *
 * @author Shunli
 */
public class Test41 {
    private static boolean isMatchDateTimeFormat(String dateTime) {
        try {
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateTime);
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    public static void main(String[] args) {
        System.out.println(isMatchDateTimeFormat("2016-11-23"));
        System.out.println(isMatchDateTimeFormat("2016-11-23 17:10:00"));

        // DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        // DATE_TIME_FORMATTER.parseDateTime(text)
    }

}


text:
require 'test_helper'

class Salesforce.connection::RestApiTest < ActiveSupport::TestCase
  def test_supported_objects
    connection.expects(:get).with("sobjects.json", :format => :json).returns({ "sobjects" => [ { "name" => "Account"}, { "name" => "Contact"}]})
    assert_equal [ "Account", "Contact" ], connection.supported_objects
  end

  def fields(object_name)
    raise ObjectNotSupported.new(object_name) unless supported_objects.include?(object_name)
    get("sobjects/#{object_name}/describe.json", :format => :json)["fields"]
  end

  def test_fields
    connection.expects(:supported_objects).returns(["Account"])
    connection.expects(:get).with("sobjects/Account/describe.json", :format => :json).returns("fields" => :fields)
    assert_equal :fields, connection.fields("Account")
  end

  def test_fields__fails
    connection.expects(:supported_objects).returns(["Account__c"])
    connection.expects(:get).never
    assert_raises Salesforce::ObjectNotSupported do
      connection.fields("Account")
    end
  end

  def test_find_object_by_id
    connection.expects(:get).with("sobjects/Bill__c/a123456789.json?fields=Account__c,Name,Due_Date__c", :format => :json).returns(:result)
    assert_equal :result, connection.find_object_by_id('Bill__c', 'a123456789', 'Account__c,Name,Due_Date__c' )
  end

  def test_update
    fields = { "Account__c" => 'a4000', 'Due_Date__c' => "08/10/2029"}
    connection.expects(:patch).with("sobjects/Bill__c/a123456789.json", fields.to_json, :format => :json).returns(stub(:code => 204))
    assert connection.update('Bill__c', 'a123456789', fields)
  end

  def test_create__succeeds
    fields = { "Account__c" => 'a4000', 'Due_Date__c' => "08/10/2029"}
    connection.expects(:post).with('sobjects/Bill__c.json', fields.to_json, :format => :json).returns({ "success" => true, "id" => "newid"})
    assert_equal "newid", connection.create('Bill__c', fields)
  end

  def test_create__fails
    fields = { "Account__c" => 'a4000', 'Due_Date__c' => "08/10/2029"}
    connection.expects(:post).with('sobjects/Bill__c.json', fields.to_json, :format => :json).returns({ "success" => false, "errors" => "something"})
    assert_raises Salesforce::RecordInvalid do
      connection.create('Bill__c', fields)
    end
  end

  def test_delete
    connection.expects(:delete).with("sobjects/Bill__c/a123456789")
    connection.destroy("Bill__c", "a123456789")
  end

  def connection
    Salesforce.connection
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CMakeRunConfigurationManager" shouldGenerate="true" assignedExecutableTargets="true" buildAllGenerated="true">
    <generated>
      <config projectName="LinkedList" targetName="LinkedList" />
    </generated>
  </component>
  <component name="CMakeSettings" AUTO_RELOAD="false" GENERATION_PASS_SYSTEM_ENVIRONMENT="true">
    <ADDITIONAL_GENERATION_ENVIRONMENT>
      <envs />
    </ADDITIONAL_GENERATION_ENVIRONMENT>
  </component>
  <component name="ChangeListManager">
    <list default="true" id="9b6b0e99-79a0-42df-983e-a2d1b90eee3a" name="Default" comment="Added Stack">
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
    </list>
    <ignored path="LinkedList.iws" />
    <ignored path=".idea/workspace.xml" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="LinkedList" />
  </component>
  <component name="Git.Settings">
    <option name="PREVIOUS_COMMIT_AUTHORS">
      <list>
        <option value="Kuzon Chen <kuzoncby@gmail.com>" />
      </list>
    </option>
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
  </component>
  <component name="JsBuildToolGruntFileManager" detection-done="true" />
  <component name="JsBuildToolPackageJson" detection-done="true" />
  <component name="JsGulpfileManager">
    <detection-done>true</detection-done>
  </component>
  <component name="ProjectFrameBounds">
    <option name="x" value="20" />
    <option name="y" value="20" />
    <option name="width" value="1400" />
    <option name="height" value="830" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
      <manualOrder />
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="LinkedList" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.CidrFilesViewHelper$MyProjectTreeStructure$1" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="last_opened_file_path" value="$PROJECT_DIR$" />
    <property name="WebServerToolWindowFactoryState" value="false" />
  </component>
  <component name="RunManager" selected="Application.Build All">
    <configuration default="true" type="CMakeRunConfiguration" factoryName="Application" PASS_PARENT_ENVS_2="true" PROJECT_NAME="LinkedList" TARGET_NAME="LinkedList" CONFIG_NAME="Debug">
      <envs />
      <method />
    </configuration>
    <configuration default="false" name="Build All" type="CMakeRunConfiguration" factoryName="Application" PASS_PARENT_ENVS_2="true" CONFIG_NAME="Debug" EXPLICIT_BUILD_TARGET_NAME="all">
      <envs />
      <method />
    </configuration>
    <configuration default="false" name="LinkedList" type="CMakeRunConfiguration" factoryName="Application" PASS_PARENT_ENVS_2="true" PROJECT_NAME="LinkedList" TARGET_NAME="LinkedList" CONFIG_NAME="Debug" RUN_TARGET_PROJECT_NAME="LinkedList" RUN_TARGET_NAME="LinkedList">
      <envs />
      <method />
    </configuration>
    <list size="2">
      <item index="0" class="java.lang.String" itemvalue="Application.Build All" />
      <item index="1" class="java.lang.String" itemvalue="Application.LinkedList" />
    </list>
  </component>
  <component name="ShelveChangesManager" show_recycled="false">
    <option name="remove_strategy" value="false" />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="9b6b0e99-79a0-42df-983e-a2d1b90eee3a" name="Default" comment="" />
      <created>1462884567601</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1462884567601</updated>
    </task>
    <task id="LOCAL-00001" summary="Added Stack">
      <created>1462886883534</created>
      <option name="number" value="00001" />
      <option name="presentableId" value="LOCAL-00001" />
      <option name="project" value="LOCAL" />
      <updated>1462886883534</updated>
    </task>
    <option name="localTasksCounter" value="2" />
    <servers />
  </component>
  <component name="ToolWindowManager">
    <frame x="20" y="20" width="1400" height="830" extended-state="0" />
    <editor active="false" />
    <layout>
      <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.24945295" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="CMake" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <MESSAGE value="Added Stack" />
    <option name="LAST_COMMIT_MESSAGE" value="Added Stack" />
    <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="true" />
    <option name="REARRANGE_BEFORE_PROJECT_COMMIT" value="true" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
</project>


text:
#ifndef Header_Superpowered3BandEQ
#define Header_Superpowered3BandEQ

#include "SuperpoweredFX.h"
struct eqInternals;

/**
 @brief Classic three-band equalizer with unique characteristics and total kills.

 It doesn't allocate any internal buffers and needs just a few bytes of memory.

 @param bands Low/mid/high gain. Read-write. 1.0f is "flat", 2.0f is +6db. Kill is enabled under -40 db (0.01f).
 @param enabled True if the effect is enabled (processing audio). Read only. Use the enable() method to set.
 */
class Superpowered3BandEQ: public SuperpoweredFX {
public:
    float bands[3]; // READ-WRITE parameter.

/**
 @brief Turns the effect on/off.
 */
    void enable(bool flag);

/**
 @brief Create an eq instance with the current sample rate value.

 Enabled is false by default, use enable(true) to enable. Example: Superpowered3BandEQ eq = new Superpowered3BandEQ(44100);
*/
    Superpowered3BandEQ(unsigned int samplerate);
    ~Superpowered3BandEQ();

/**
 @brief Sets the sample rate.

 @param samplerate 44100, 48000, etc.
 */
    void setSamplerate(unsigned int samplerate);
/**
 @brief Reset all internals, sets the instance as good as new and turns it off.
 */
    void reset();

/**
 @brief Processes the audio.

 It's not locked when you call other methods from other threads, and they not interfere with process() at all.

 @return Put something into output or not.

 @param input 32-bit interleaved stereo input buffer. Can point to the same location with output (in-place processing).
 @param output 32-bit interleaved stereo output buffer. Can point to the same location with input (in-place processing).
 @param numberOfSamples Should be 20 minimum.
*/
    bool process(float *input, float *output, unsigned int numberOfSamples);

private:
    eqInternals *internals;
    Superpowered3BandEQ(const Superpowered3BandEQ&);
    Superpowered3BandEQ& operator=(const Superpowered3BandEQ&);
};

#endif


text:
from __future__ import absolute_import

import pytest

from pdbuddy.matchers.base import BaseMatcher

def test_raises_not_implemented_error():
    with pytest.raises(NotImplementedError):
        assert BaseMatcher()(object())


text:
package org.jboss.resteasy.test.cdi.injection;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionBook;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionBookBag;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionBookBagLocal;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionBookCollection;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionBookReader;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionBookResource;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionBookWriter;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionDependentScoped;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionNewBean;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionResourceProducer;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionScopeInheritingStereotype;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionScopeStereotype;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionStatefulEJB;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionStereotypedApplicationScope;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionStereotypedDependentScope;
import org.jboss.resteasy.test.cdi.injection.resource.CDIInjectionUnscopedResource;
import org.jboss.resteasy.test.cdi.util.Constants;
import org.jboss.resteasy.test.cdi.util.Counter;
import org.jboss.resteasy.test.cdi.util.PersistenceUnitProducer;
import org.jboss.resteasy.test.cdi.util.UtilityProducer;
import org.jboss.resteasy.util.HttpResponseCodes;
import org.jboss.resteasy.utils.PortProviderUtil;
import org.jboss.resteasy.utils.TestUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

/**
 * @tpSubChapter CDI
 * @tpChapter Integration tests
 * @tpTestCaseDetails This is a collection of tests addressed to the interactions of
 *                    Resteasy, CDI, EJB, and so forth in the context of a JEE Application Server.
 *                    It tests the injection of a variety of beans into Resteasy objects.
 * @tpSince RESTEasy 3.0.16
 */
@RunWith(Arquillian.class)
@RunAsClient
public class InjectionTest extends AbstractInjectionTestBase {
    protected static final Logger log = LogManager.getLogger(InjectionTest.class.getName());

    static Client client;

    static ParameterizedType BookCollectionType = new ParameterizedType() {
        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{CDIInjectionBook.class};
        }

        @Override
        public Type getRawType() {
            return Collection.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    };
    public class InjectionCollection implements ParameterizedType {
        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{CDIInjectionBook.class};
        }

        @Override
        public Type getRawType() {
            return Collection.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }

    private static int invocationCounter;

    @SuppressWarnings(value = "unchecked")
    @Deployment
    public static Archive<?> createTestArchive() {
        WebArchive war = TestUtil.prepareArchive(InjectionTest.class.getSimpleName());
        war.addClass(AbstractInjectionTestBase.class)
                .addClasses(CDIInjectionBook.class, CDIInjectionBookResource.class, Constants.class, UtilityProducer.class, BookCollectionType.getClass())
                .addClasses(Counter.class, CDIInjectionBookCollection.class, CDIInjectionBookReader.class, CDIInjectionBookWriter.class)
                .addClasses(CDIInjectionDependentScoped.class, CDIInjectionStatefulEJB.class, CDIInjectionUnscopedResource.class)
                .addClasses(CDIInjectionBookBagLocal.class, CDIInjectionBookBag.class)
                .addClasses(CDIInjectionNewBean.class)
                .addClasses(CDIInjectionScopeStereotype.class, CDIInjectionScopeInheritingStereotype.class)
                .addClasses(CDIInjectionStereotypedApplicationScope.class, CDIInjectionStereotypedDependentScope.class)
                .addClasses(Resource.class, CDIInjectionResourceProducer.class, PersistenceUnitProducer.class)
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsResource(InjectionTest.class.getPackage(), "persistence.xml", "META-INF/persistence.xml");
        return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null);
    }

    private String generateURL(String path) {
        return PortProviderUtil.generateURL(path, InjectionTest.class.getSimpleName());
    }

    @BeforeClass
    public static void init() {
        client = ClientBuilder.newClient();
    }

    @AfterClass
    public static void close() {
        client.close();
    }

    @Before
    public void preparePersistenceTest() throws Exception {
        log.info("Dumping old records.");

        WebTarget base = client.target(generateURL("/empty/"));
        Response response = base.request().post(Entity.text(new String()));
        invocationCounter++;
        response.close();
    }

    /**
     * @tpTestDetails Addresses the correct handling of built-in scopes. E.g.
     * 1) Providers are in the application scope, whether they are annotated or not.
     * 2) Resources are in the request scope, annotated or not.
     * 3) Objects in the dependent scope, when injected into JAX-RS objects, are handled properly.
     * 4) Singletons in the application scope, when injected in request scoped JAX-RS resources as
     *    EJB proxies or Weld proxies, are handled properly.
     * A side effect of 3) and 4) is to test that beans managed by CDI (managed beans, singleton beans,
     * stateless EJBs) are injected properly into JAX-RS objects.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testVerifyScopes() throws Exception {
        log.info("starting testVerifyScopes()");

        WebTarget base = client.target(generateURL("/verifyScopes/"));
        Response response = base.request().get();
        invocationCounter++;
        log.info("First status: " + response.getStatus());
        assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();
        response = base.request().get();
        invocationCounter++;
        log.info("Second status: " + response.getStatus());
        assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();
    }

    /**
     * @tpTestDetails Addresses the injection of managed beans, singletons, and stateless EJBs into JAX-RS objects.
     *                Uses a singleton (BookCollection) to interact with an EntityManager.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testEJBs() throws Exception {
        log.info("starting testEJBs()");

        // Create book.
        WebTarget base = client.target(generateURL("/create/"));
        CDIInjectionBook book1 = new CDIInjectionBook("RESTEasy: the Sequel");
        Response response = base.request().post(Entity.entity(book1, "application/test+xml"));
        invocationCounter++;
        assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        log.info("Status: " + response.getStatus());
        int id1 = response.readEntity(int.class);
        log.info("Id of response book: " + id1);
        Assert.assertEquals(Counter.INITIAL_VALUE, id1);
        response.close();

        // Create another book.
        base = client.target(generateURL("/create/"));
        CDIInjectionBook book2 = new CDIInjectionBook("RESTEasy: It's Alive");
        response = base.request().post(Entity.entity(book2, "application/test+xml"));
        invocationCounter++;
        assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        log.info("Status: " + response.getStatus());
        int id2 = response.readEntity(int.class);
        log.info("Id of response book: " + id2);
        Assert.assertEquals(Counter.INITIAL_VALUE + 1, id2);
        response.close();

        // Retrieve first book.
        base = client.target(generateURL("/book/" + id1));
        response = base.request().accept("application/test+xml").get();
        invocationCounter++;
        log.info("Status: " + response.getStatus());
        assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        CDIInjectionBook result = response.readEntity(CDIInjectionBook.class);
        log.info("Book from response: " + book1);
        Assert.assertEquals(book1, result);
        response.close();

        // Retrieve second book.
        base = client.target(generateURL("/book/" + id2));
        response = base.request().accept("application/test+xml").get();
        invocationCounter++;
        log.info("Status: " + response.getStatus());
        assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        result = response.readEntity(CDIInjectionBook.class);
        log.info("Book from response: " + book2);
        Assert.assertEquals(book2, result);
        response.close();

        // Retrieve all books.
        base = client.target(generateURL("/books"));
        response = base.request().accept(MediaType.APPLICATION_XML).get();
        invocationCounter++;
        log.info("Status: " + response.getStatus());
        @SuppressWarnings("unchecked")
        Collection<CDIInjectionBook> books = response.readEntity(new GenericType<>(BookCollectionType));
        log.info("Collection from response: " + books);
        Assert.assertEquals(2, books.size());
        Iterator<CDIInjectionBook> it = books.iterator();
        CDIInjectionBook b1 = it.next();
        CDIInjectionBook b2 = it.next();
        log.info("First book in list: " + b1);
        log.info("Second book in list: " + b2);
        Assert.assertTrue(book1.equals(b1) && book2.equals(b2) || book1.equals(b2) && book2.equals(b1));
        response.close();

        // Test EntityManager injected in BookResource
        base = client.target(generateURL("/entityManager"));
        response = base.request().post(Entity.text(new String()));
        invocationCounter++;
        log.info("Status: " + response.getStatus());
        assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();
    }

    /**
     * @tpTestDetails This test verifies that a session scoped SFSB survives throughout the course of a session and is
     * re-injected into the request scoped BookResource over the course of the session.  Also, it is destroyed
     * and replaced when an invocation is made on BookResource after the session ends.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testSessionScope() throws Exception {
        log.info("starting testSessionScope()");
        client.close();
        client = ClientBuilder.newClient();

        // Need to supply each ClientRequest with a single ClientExecutor to maintain a single
        // cookie cache, which keeps the session alive.
        //ClientExecutor executor = new ApacheHttpClient4Executor();

        // Create a book, which gets stored in the session scoped BookBag.
        WebTarget base = client.target(generateURL("/session/add/"));
        CDIInjectionBook book1 = new CDIInjectionBook(13, "Dead Man Napping");
        Response response = base.request().post(Entity.entity(book1, Constants.MEDIA_TYPE_TEST_XML));
        invocationCounter++;
        log.info("status: " + response.getStatus());
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();

        // Create another book, which should get stored in the same BookBag.
        base = client.target(generateURL("/session/add/"));
        CDIInjectionBook book2 = new CDIInjectionBook(Counter.INITIAL_VALUE, "Dead Man Dozing");
        response = base.request().post(Entity.entity(book2, Constants.MEDIA_TYPE_TEST_XML));
        invocationCounter++;
        log.info("status: " + response.getStatus());
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();

        // Get the current contents of the BookBag, and verify that it holds both of the books sent in the
        // previous two invocations.  When this method is called, the session is terminated.
        base = client.target(generateURL("/session/get/"));
        response = base.request().get();
        invocationCounter++;
        log.info("status: " + response.getStatus());
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        @SuppressWarnings("unchecked")
        Collection<CDIInjectionBook> books = response.readEntity(new GenericType<>(BookCollectionType));
        log.info("Collection from response: " + books);
        Assert.assertEquals(2, books.size());
        Iterator<CDIInjectionBook> it = books.iterator();
        CDIInjectionBook b1 = it.next();
        CDIInjectionBook b2 = it.next();
        log.info("First book in list: " + b1);
        log.info("Second book in list: " + b2);
        Assert.assertTrue(book1.equals(b1) && book2.equals(b2) || book1.equals(b2) && book2.equals(b1));
        response.close();

        // Verify that the BookBag has been replaced by a new, empty one for the new session.
        base = client.target(generateURL("/session/test/"));
        response = base.request().post(Entity.text(new String()));
        invocationCounter++;
        log.info("status: " + response.getStatus());
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();
    }

    /**
     * @tpTestDetails Tests the injection of JMS Producers, Consumers, and Queues using producer fields and methods.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testJMS() throws Exception {
        log.info("starting testJMS()");

        // Send a book title.
        WebTarget base = client.target(generateURL("/produceMessage/"));
        String title = "Dead Man Lounging";
        CDIInjectionBook book = new CDIInjectionBook(23, title);
        Response response = base.request().post(Entity.entity(book, Constants.MEDIA_TYPE_TEST_XML));
        invocationCounter++;
        log.info("status: " + response.getStatus());
        log.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();

        // Verify that the received book title is the one that was sent.
        base = client.target(generateURL("/queue/consumeMessage/"));
        log.info("consuming book");
        response = base.request().get();
        invocationCounter++;
        log.info("status: " + response.getStatus());
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(title, response.readEntity(String.class));
        response.close();
    }

    /**
     * @tpTestDetails Verifies that BookResource.postConstruct() and preDestroy() are called for each invocation.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testPostConstructPreDestroy() throws Exception {
        log.info("starting testPostConstructPreDestroy()");

        // Send a book title.
        log.info("invocationCounter: " + invocationCounter);
        WebTarget base = client.target(generateURL("/getCounters/"));
        Response response = base.request().get();
        log.info("status: " + response.getStatus());
        String result = response.readEntity(String.class);
        log.info("Response: " + result);
        log.info("InvocationCounter: " + invocationCounter);
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        String[] counters = result.split(":");
        Assert.assertTrue(invocationCounter + 1 == Integer.valueOf(counters[0])); // invocations of postConstruct()
        Assert.assertTrue(invocationCounter == Integer.valueOf(counters[1]));     // invocations of preDestroy()
        response.close();
    }

    /**
     * @tpTestDetails Verifies that ResourceProducer disposer method has been called for Queue.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testDisposer() throws Exception {
        log.info("starting testDisposer()");
        WebTarget base = client.target(generateURL("/disposer/"));
        Response response = base.request().get();
        invocationCounter++;
        log.info("status: " + response.getStatus());
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        response.close();
    }
}


text:
require 'gom'
require 'couchdb'
require File.join(File.dirname(__FILE__), "storage")

GOM::Storage::Adapter.register :couchdb, GOM::Storage::CouchDB::Adapter


text:
import EasyJson.{EasyJson, ParseError}
import org.scalatest._

class RootObjectTest extends FlatSpec {
    "EasyJson" should "be able to load an empty list" in {
        EasyJson.loads("[]")
    }
    it should "be able to load an empty object" in {
        EasyJson.loads("{}")
    }
    it should "be able to load list with one empty string" in {
        EasyJson.loads("[\"\"]")
    }
    it should "be able to load object with one empty key" in {
        EasyJson.loads("{\"\":\"\"}")
    }
    it should "be able to load a list of integers" in {
        EasyJson.loads("[0,1,1,2,3,5,8]")
    }
    it should "be able to load a list of floats" in {
        EasyJson.loads("[0.1,1.2,2.3,3.14]")
    }
    it should "be able to load a list of strings" in {
        EasyJson.loads("[\"\", \"\", \"abc\"]")
    }
    it should "be able to load a list of lists" in {
        EasyJson.loads("[[], [1, 2, 3]]")
    }
    it should "be able to load a list of objects" in {
        EasyJson.loads("[{}, {\"\":\"\",\"a\":\"b\"}]")
    }
    it should "be able to load a mixed list" in {
        EasyJson.loads("[\"\", \"\", \"abc\", 1, 3.14, 8, [], {}]")
    }
    it should "be able to load an object with lists as values" in {
        EasyJson.loads("{\"a\": [], \"b\": [1, 2, 3]}")
    }
    it should "be able to load an object with only empty lists as values" in {
        EasyJson.loads("{\"a\": [], \"b\": []}")
    }
    it should "be able to load dataset 0" in {
        EasyJson.loads("{\"meta\": {}, \"options\": {}, \"data\": []}")
    }
    it should "be able to load dataset 1" in {
        EasyJson.loads("{\"meta\": {}, \"options\": {}, \"data\": [0, 0, 0, 1, 2, 100, 0]}")
    }
    it should "be able to load dataset 2" in {
        EasyJson.loads("{\"meta\": {}, \"options\": {\"title\": \"Workload\", \"axisLabels\": [\"Day\", \"Work\"], \"axisUnits\": [\"\", \"h\"], \"gridOn\": false, \"gridSize\": 0}, \"data\": [0, 0, 0, 1, 2, 100, 0]}")
    }
    it should "be able to load dataset 3" in {
        EasyJson.loads("{\"meta\": {\"version\": \"0.1.0\", \"libVersion\": \"0.1.0\", \"author\": \"John Smith\", \"created\": \"2017-04-23\", \"modified\": \"2017-04-23\"}, \"options\": {\"title\": \"Workload\", \"axisLabels\": [\"Day\", \"Work\"], \"axisUnits\": [\"\", \"h\"], \"gridOn\": false, \"gridSize\": 0}, \"data\": [0, 0, 0, 1, 2, 100, 0]}")
    }
    it should "throw an error on invalid root type (integer)" in {
        assertThrows[ParseError] {
            EasyJson.loads("0")
        }
    }
    it should "throw an error on invalid root type (float)" in {
        assertThrows[ParseError] {
            EasyJson.loads("0.0")
        }
    }
    it should "throw an error on invalid root type (string)" in {
        assertThrows[ParseError] {
            EasyJson.loads("\"a\"")
        }
    }
    it should "throw an error on invalid root type (true)" in {
        assertThrows[ParseError] {
            EasyJson.loads("true")
        }
    }
    it should "throw an error on invalid root type (false)" in {
        assertThrows[ParseError] {
            EasyJson.loads("false")
        }
    }
    it should "throw an error on invalid root type (none)" in {
        assertThrows[ParseError] {
            EasyJson.loads("none")
        }
    }
}

class SimpleValueTest extends FlatSpec {
    "EasyJson" should "be able to load true" in {
        EasyJson.loads("true", true)
    }
    it should "be able to load false" in {
        EasyJson.loads("false", true)
    }
    it should "be able to load null" in {
        EasyJson.loads("null", true)
    }
}

class StringTest extends FlatSpec {
    "EasyJson" should "be able to load an empty string" in {
        EasyJson.loads("\"\"", true)
    }
    it should "be able to load a string with one space" in {
        EasyJson.loads("\" \"", true)
    }
    it should "be able to load a string with example name" in {
        EasyJson.loads("\"Example Name\"", true)
    }
    it should "be able to load a string with some data" in {
        EasyJson.loads("\"a b.32 asf!!\"", true)
    }
    it should "be able to load a string only an integer" in {
        EasyJson.loads("\"42\"", true)
    }
    it should "be able to load a string only a float" in {
        EasyJson.loads("\"3.14\"", true)
    }
    it should "be able to load a string with escaped chars" in {
        EasyJson.loads("\"\\\"abc\"", true)
    }
}

class IntegerTest extends FlatSpec {
    "EasyJson" should "be able to load 0" in {
        EasyJson.loads("0", true)
    }
    it should "be able to load 1" in {
        EasyJson.loads("1", true)
    }
    it should "be able to load -1" in {
        EasyJson.loads("-1", true)
    }
    it should "be able to load 42" in {
        EasyJson.loads("42", true)
    }
    it should "be able to load -42" in {
        EasyJson.loads("-42", true)
    }
}

class FloatTest extends FlatSpec {
    "EasyJson" should "be able to load zero" in {
        EasyJson.loads("0.0", true)
    }
    it should "be able to load negative zero" in {
        EasyJson.loads("-0.0", true)
    }
    it should "be able to load an approximation of pi" in {
        EasyJson.loads("3.14", true)
    }
    it should "be able to load a negative approximation of pi" in {
        EasyJson.loads("-3.14", true)
    }
    it should "throw an error when loading NaN" in {
        assertThrows[ParseError] {
            EasyJson.loads("NaN", true)
        }
    }
    it should "throw an error when loading Infinity" in {
        assertThrows[ParseError] {
            EasyJson.loads("Infinity", true)
        }
    }
    it should "throw an error when loading Inf" in {
        assertThrows[ParseError] {
            EasyJson.loads("Inf", true)
        }
    }
    it should "throw an error when loading negative Infinity" in {
        assertThrows[ParseError] {
            EasyJson.loads("-Infinity", true)
        }
    }
    it should "throw an error when loading negative Inf" in {
        assertThrows[ParseError] {
            EasyJson.loads("-Inf", true)
        }
    }
}


text:
title: Failed to create component design time exception
description: Failed to create component design time exception. Check it now!
type: how-to
page_title: Failed to create component design time exception
slug: failed-to-create-component-design-time-exception
res_type: kb
---

|Product Version|Product|Author|Last modified|
|----|----|----|----|
|Q1 2014|RadControls for WinForms|Georgi Georgiev|March 13, 2014|

## Problem:

*Failed to create component. The error message follows: "System.Runtime.InteropServices.COMException"*

![](images/failed-to-create-component-design-time-exception.png)

If you have used UI for WinForms and have changed your versions at some (you have installed more than one version of the suite on your computer) point you may have encountered this exception. It is caused when you have referenced Telerik assemblies in your project versioned different than the ones in your Toolbox e.g your project references Q1 2013 while in your toolbox you have Q2 2014. When you drag an item from the Toolbox Visual Studio automatically attempts to add references to your project needed for the dragged component. However, since you already have this assembly referenced, but with different version, exception is thrown.

## Solution:

Before taking any actions you should know what versions are your assemblies. To see the version of the items in the Visual Studio Toolbox it is enough to move your mouse over any Telerik UI for WinForms item and a tool tip with the version information will appear. To get the version of your referenced assemblies you should expand the References of your project, click any Telerik dll and press F4, this will display a window which contains information about the version of the file.

Basically you need make both versions of the assemblies to match. From this point on there are a few options:

1. Remove all versions of Telerik UI for WinForms from your computer and install just the latest one. Than update your project references to this. This should fix all issues by replacing the assemblies in your [GAC](http://msdn.microsoft.com/en-us/library/yf1d93sz%28v=vs.110%29.aspx) and Toolbox.
2. Update the items in your Toolbox. This can be done automatically or manually:
    1. The automatic process is described in the following article VSX – [Toolbox Configurator](https://docs.telerik.com/devtools/winforms/visual-studio-integration/visual-studio-extensions/toolbox-configurator).
    2. Description of the manual process can be found in the following KB article - [Manually add RadControls for WinForms to the VS Toolbox](/support/kb/winforms/details/manually-add-radcontrols-for-winforms-to-the-vs-toolbox).
3. Change the referenced assemblies in your project to match the ones in your Toolbox. Information about this is available in the MSDN article [Managing Project References](http://msdn.microsoft.com/en-us/library/ez524kew.aspx).


text:
package therian.operator.copy;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.TypeLiteral;
import org.junit.Before;
import org.junit.Test;

import therian.OperationException;
import therian.TherianModule;
import therian.operation.Copy;
import therian.operator.OperatorTest;
import therian.operator.convert.CopyingConverter;
import therian.operator.convert.DefaultCopyingConverter;
import therian.position.Position;
import therian.testfixture.Author;
import therian.testfixture.Book;
import therian.testfixture.Employee;
import therian.testfixture.MetasyntacticVariable;
import therian.testfixture.Person;
import therian.util.Positions;

/**
 *
 */
public class ContainerCopierTest extends OperatorTest {
    private interface LocalTypes {
        static final TypeLiteral<Set<Book>> SET_OF_BOOK = new TypeLiteral<Set<Book>>() {};
        static final TypeLiteral<List<Book>> LIST_OF_BOOK = new TypeLiteral<List<Book>>() {};
        static final TypeLiteral<List<Employee>> LIST_OF_EMPLOYEE = new TypeLiteral<List<Employee>>() {};
    }

    public static class Jerk implements Person {
        private final String lastName;
        private final String firstName;
        private final String middleName;

        public Jerk(String... name) {
            lastName = name.length > 0 ? name[0] : null;
            firstName = name.length > 1 ? name[1] : null;
            if (name.length < 3) {
                middleName = null;
            } else {
                middleName = StringUtils.join(Arrays.asList(name).subList(2, name.length), ' ');
            }
        }

        @Override
        public String getFirstName() {
            return firstName;
        }

        @Override
        public String getMiddleName() {
            return middleName;
        }

        @Override
        public String getLastName() {
            return lastName;
        }

    }

    private Book[] books;
    private Jerk[] jerks;

    @Before
    public void setupData() {
        MetasyntacticVariable[] values = MetasyntacticVariable.values();
        books = new Book[values.length];
        for (int i = 0; i < values.length; i++) {
            books[i] = new Book();
            books[i].setTitle(values[i].name());
            Author author = new Author();
            author.setFirstName("Neal");
            author.setLastName("Stephenson");
            books[i].setAuthor(author);
        }
        jerks =
            new Jerk[] { new Jerk("Morris", "Keith"), new Jerk("Hetson", "Greg"), new Jerk("Rogerson", "Roger"),
                new Jerk("Lehrer", "Keith", "Michael", "\"Lucky\"") };
    }

    @Override
    protected TherianModule module() {
        return TherianModule.create().withOperators(new ContainerCopier.ToIterable(), new ContainerCopier.ToIterator(),
            new ContainerCopier.ToEnumeration(), new ContainerCopier.ToArray(), CopyingConverter.IMPLEMENTING_SET,
            CopyingConverter.IMPLEMENTING_LIST, new DefaultCopyingConverter(), new BeanCopier());
    }

    @Test
    public void testToList() {
        final Book[] targetElements = { new Book(), new Book(), new Book() };
        final List<Book> targetValue = new ArrayList<Book>(Arrays.asList(targetElements));

        final Position.Readable<List<Book>> target = Positions.readOnly(LocalTypes.LIST_OF_BOOK, targetValue);

        therianContext.eval(Copy.to(target, Positions.readOnly(books)));
        assertEquals(targetElements.length, targetValue.size());

        int index = 0;
        for (Book targetBook : targetValue) {
            assertSame(targetElements[index], targetBook);
            assertEquals("book " + index, books[index++], targetBook);
        }
    }

    @Test
    public void testToUnmodifiableList() {
        final Book[] targetElements = { new Book(), new Book(), new Book() };
        final List<Book> targetValue = Collections.unmodifiableList(new ArrayList<Book>(Arrays.asList(targetElements)));

        final Position.Readable<List<Book>> target = Positions.readOnly(LocalTypes.LIST_OF_BOOK, targetValue);

        therianContext.eval(Copy.to(target, Positions.readOnly(books)));
        assertEquals(targetElements.length, targetValue.size());

        int index = 0;
        for (Book targetBook : targetValue) {
            assertSame(targetElements[index], targetBook);
            assertEquals("book " + index, books[index++], targetBook);
        }
    }

    @Test
    public void testToSmallerSet() {
        final Book targetElement = new Book();
        final Set<Book> targetValue = new LinkedHashSet<>();
        targetValue.add(targetElement);
        final Position.Readable<Set<Book>> target = Positions.readOnly(LocalTypes.SET_OF_BOOK, targetValue);

        therianContext.eval(Copy.to(target, Positions.readOnly(books)));
        assertEquals(books.length, targetValue.size());
        assertSame(targetElement, targetValue.iterator().next());

        int index = 0;
        for (Book targetBook : targetValue) {
            assertEquals("book " + index, books[index++], targetBook);
        }
    }

    @Test(expected = OperationException.class)
    public void testToUnmodifiableSmallerSet() {
        therianContext.eval(Copy.to(Positions.readOnly(LocalTypes.SET_OF_BOOK, Collections.singleton(new Book())),
            Positions.readOnly(books)));
    }

    @Test
    public void testToUnmodifiableSmallerSetWithWritableTargetPosition() {
        final Book targetElement = new Book();
        final Position.ReadWrite<Set<Book>> target =
            Positions.readWrite(LocalTypes.SET_OF_BOOK, Collections.singleton(targetElement));

        therianContext.eval(Copy.to(target, Positions.readOnly(books)));
        assertEquals(books.length, target.getValue().size());
        assertSame(targetElement, target.getValue().iterator().next());
        assertArrayEquals(books, target.getValue().toArray());
    }

    @Test
    public void testSingletonToSet() {
        final Book targetElement = new Book();
        final Position.Readable<Set<Book>> target =
            Positions.readOnly(LocalTypes.SET_OF_BOOK, Collections.singleton(targetElement));
        therianContext.eval(Copy.to(target, Positions.readOnly(books[0])));
        assertSame(targetElement, target.getValue().iterator().next());
        assertEquals(books[0], targetElement);
    }

    @Test
    public void testSingletonToLargerList() {
        final Book[] targetElements = { new Book(), new Book(), new Book() };
        final List<Book> targetValue = new ArrayList<>(Arrays.asList(targetElements));
        final Position.Readable<List<Book>> target = Positions.readOnly(LocalTypes.LIST_OF_BOOK, targetValue);
        therianContext.eval(Copy.to(target, Positions.readOnly(books[0])));

        assertEquals(targetElements.length, targetValue.size());

        int index = 0;
        final Iterator<Book> targetValues = targetValue.iterator();
        assertSame(targetElements[index], targetValues.next());
        assertEquals(books[0], targetElements[index++]);

        final Book blank = new Book();
        assertSame(targetElements[index], targetValues.next());
        assertEquals(blank, targetElements[index++]);
        assertSame(targetElements[index], targetValues.next());
        assertEquals(blank, targetElements[index++]);
        assertFalse(targetValues.hasNext());
    }

    @Test
    public void testSingletonToEmptySet() {
        final LinkedHashSet<Book> targetValue = new LinkedHashSet<>();
        final Position.Readable<Set<Book>> target = Positions.readOnly(LocalTypes.SET_OF_BOOK, targetValue);
        therianContext.eval(Copy.to(target, Positions.readOnly(books[0])));
        assertSame(targetValue, target.getValue());
        assertEquals(1, targetValue.size());
        assertEquals(books[0], targetValue.iterator().next());
    }

    @Test(expected = OperationException.class)
    public void testSingletonToUnmodifiableEmptySet() {
        therianContext.eval(Copy.to(
            Positions.readOnly(LocalTypes.SET_OF_BOOK, Collections.unmodifiableSet(new HashSet<>())),
            Positions.readOnly(books[0])));
    }

    @Test
    public void testSingletonToUnmodifiableEmptySetWithWritableTargetPosition() {
        final Position.ReadWrite<Set<Book>> target =
            Positions.readWrite(LocalTypes.SET_OF_BOOK, Collections.unmodifiableSet(new HashSet<>()));
        therianContext.eval(Copy.to(target, Positions.readOnly(books[0])));
        assertEquals(1, target.getValue().size());
        assertSame(books[0], target.getValue().iterator().next());
    }

    @Test
    public void testTypeConversionToList() {
        final List<Employee> targetList = new ArrayList<>();
        therianContext.eval(Copy.to(Positions.readOnly(LocalTypes.LIST_OF_EMPLOYEE, targetList),
            Positions.readOnly(jerks)));
        final Iterator<Employee> eachEmployee = targetList.iterator();

        for (Jerk jerk : Arrays.asList(jerks)) {
            assertTrue(eachEmployee.hasNext());
            final Employee employee = eachEmployee.next();
            assertEquals(jerk.getFirstName(), employee.getFirstName());
            assertNull(employee.getMiddleName());
            assertEquals(jerk.getLastName(), employee.getLastName());
        }
        assertFalse(eachEmployee.hasNext());
    }

    @Test
    public void testToArray() {
        assertFalse(
            "Cannot use ContainerCopier to copy to null target elements",
            therianContext.supports(Copy.to(
                Positions.readWrite(MetasyntacticVariable[].class,
                    new MetasyntacticVariable[MetasyntacticVariable.values().length]),
                Positions.readOnly(MetasyntacticVariable.values()))));
    }

    @Test
    public void testToNull() {
        // using a writable target would allow the ELCoercionConverter to convert the null source value to a null target
        // value
        assertFalse(
            "Cannot use ContainerCopier to copy to read-only null target",
            therianContext.supports(Copy.to(Positions.readOnly(MetasyntacticVariable[].class, (MetasyntacticVariable[]) null),
                Positions.readOnly(MetasyntacticVariable.values()))));
    }
}


text:
@import MobileCoreServices;

@interface BWAuthenticationViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *restaurantImage;
@property (strong, nonatomic) IBOutlet UITextField *usernameTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UIButton *authenticateButton;
@property (strong, nonatomic) IBOutlet UIButton *cancelButton;

@property (strong, nonatomic) IBOutlet UIButton *loginButton;
@property (strong, nonatomic) IBOutlet UIButton *signUpButton;
@property (strong, nonatomic) IBOutlet UIButton *avatarButton;
@property (strong, nonatomic) IBOutlet UIView *avatarBackgroundView;

@property BOOL isLoggingIn;

@property(strong) UIImage* avatar;

@end

@implementation BWAuthenticationViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.isLoggingIn = NO;
    self.avatarBackgroundView.hidden = YES;
    self.avatarButton.hidden = YES;
    [self.avatarButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [self clearAvatar];

    [self.cancelButton  setTitle:NSLocalizedString(@"Cancel", @"")
                        forState:UIControlStateNormal];

    [self.signUpButton  setTitle:NSLocalizedString(@"Sign up", @"")
                        forState:UIControlStateNormal];

    [self.loginButton   setTitle:NSLocalizedString(@"Already have an account? Log in!", @"")
                        forState:UIControlStateNormal];

    self.usernameTextField.placeholder = NSLocalizedString(@"Username", @"");
    self.passwordTextField.placeholder = NSLocalizedString(@"Password", @"");
}

-(void)animateToAuthenticationWithTitle:(NSString*)title{

    [UIView animateWithDuration:0.25
                     animations:^{

                         self.signUpButton.alpha = 0.0;
                         self.loginButton.alpha = 0.0;
                         if(!self.isLoggingIn){
                             self.restaurantImage.alpha = 0.0;
                         }
                     }
                     completion:^(BOOL finished) {

                         if(finished){

                             if(!self.isLoggingIn){
                                 self.restaurantImage.hidden = YES;
                             }

                             [self.authenticateButton setTitle:title
                                                      forState:UIControlStateNormal];

                             self.avatarButton.alpha = 0.0;
                             self.usernameTextField.alpha = 0.0;
                             self.passwordTextField.alpha = 0.0;
                             self.authenticateButton.alpha = 0.0;
                             self.cancelButton.alpha = 0.0;

                             [UIView animateWithDuration:0.15
                                              animations:^{

                                                  self.signUpButton.hidden = YES;
                                                  self.loginButton.hidden = YES;

                                                  if(!self.isLoggingIn){
                                                      self.avatarButton.hidden = NO;
                                                      self.avatarBackgroundView.hidden = NO;
                                                  }
                                                  self.usernameTextField.hidden = NO;
                                                  self.passwordTextField.hidden = NO;
                                                  self.authenticateButton.hidden = NO;
                                                  self.cancelButton.hidden = NO;

                                              }
                                              completion:^(BOOL finished) {

                                                  if(finished){
                                                      [UIView animateWithDuration:0.25
                                                                       animations:^{
                                                                           self.usernameTextField.alpha = 1.0;
                                                                           self.passwordTextField.alpha = 1.0;
                                                                           self.authenticateButton.alpha = 1.0;
                                                                           self.cancelButton.alpha = 1.0;

                                                                           if(!self.isLoggingIn){
                                                                               self.avatarButton.alpha = 1.0;
                                                                           }
                                                                       }];
                                                  }
                                              }];

                         }

                     }];
}

#pragma mark - Actions

- (IBAction)showSignUpViews:(id)sender {
    self.isLoggingIn = NO;
    [self clearAvatar];
    [self animateToAuthenticationWithTitle:NSLocalizedString(@"Sign up", @"")];
}

- (IBAction)showLoginViews:(id)sender {
    self.isLoggingIn = YES;
    [self clearAvatar];
    [self animateToAuthenticationWithTitle:NSLocalizedString(@"Login", @"")];
}

-(void)applyAvatar:(UIImage*)avatar{
    self.avatar = [avatar imageScaledToSize:kDefaultAvatarResolution];
    [self.avatarButton setImage:self.avatar
                       forState:UIControlStateNormal];
}

-(void)clearAvatar{

    self.avatarButton.imageView.layer.borderWidth = 2.5f;
    self.avatarButton.imageView.layer.borderColor = [[UIColor colorWithRed:0x00/255.0
                                                                     green:0x99/255.0
                                                                      blue:0xFF/255.0
                                                                     alpha:1.0] CGColor];
    self.avatarButton.imageView.layer.cornerRadius = 10.0f;
    self.avatarButton.imageView.layer.masksToBounds = YES;
    self.avatarButton.imageView.clipsToBounds = YES;

    self.avatar = nil;
    [self.avatarButton setImage:[UIImage imageNamed:@"avatar"]
                       forState:UIControlStateNormal];
}

- (IBAction)cancelAuthenticationSelection:(id)sender {

    [UIView animateWithDuration:0.25
                     animations:^{
                         self.avatarButton.alpha = 0.0;
                         self.usernameTextField.alpha = 0.0;
                         self.passwordTextField.alpha = 0.0;
                         self.authenticateButton.alpha = 0.0;
                         self.cancelButton.alpha = 0.0;
                     }
                     completion:^(BOOL finished) {

                         if(finished){

                             self.usernameTextField.text = @"";
                             self.passwordTextField.text = @"";

                             [UIView animateWithDuration:0.15
                                              animations:^{

                                                  self.signUpButton.hidden = NO;
                                                  self.loginButton.hidden = NO;
                                                  self.restaurantImage.hidden = NO;

                                                  self.avatarButton.hidden = YES;
                                                  self.avatarBackgroundView.hidden = YES;
                                                  self.usernameTextField.hidden = YES;
                                                  self.passwordTextField.hidden = YES;
                                                  self.authenticateButton.hidden = YES;
                                                  self.cancelButton.hidden = YES;

                                              }
                                              completion:^(BOOL finished) {

                                                  if(finished){
                                                      [UIView animateWithDuration:0.25
                                                                       animations:^{
                                                                           self.restaurantImage.alpha = 1.0;
                                                                           self.signUpButton.alpha = 1.0;
                                                                           self.loginButton.alpha = 1.0;
                                                                       }];
                                                  }
                                              }];

                         }
                     }];
}

- (IBAction)performAuthentication:(id)sender {

    NSString* username = self.usernameTextField.text;
    NSString* password = self.passwordTextField.text;

    if(self.isLoggingIn){

        [BWLoader show];
        [BWUser loginUser:username
                 password:password
                    block:^(BOOL loggedIn) {

                        if(loggedIn){

                            [BWLoader dismissAsSuccess:^{

                                [BWSettings sharedInstance].savedPassword = password;
                                [BWSettings sharedInstance].savedUsername = username;

                                [self.navigationController dismissViewControllerAnimated:YES completion:^{
                                    if(self.loggedInBlock){
                                        self.loggedInBlock();
                                        self.loggedInBlock = nil;
                                    }
                                }];

                            }];

                        }
                        else{
                            [BWLoader dismissAsFailure:nil];
                        }

                    }];

    }
    else{

        if(!self.avatar){
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Oops", @"")
                                                                           message:NSLocalizedString(@"You need to select an avatar", @"")
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Ok", @"")
                                                      style:UIAlertActionStyleDefault
                                                    handler:^(UIAlertAction * _Nonnull action) {
                                                        [alert dismissViewControllerAnimated:YES completion:nil];
                                                    }]];
            [self presentViewController:alert animated:YES completion:nil];
            return;

        }

        [BWLoader show];
        [BWUser signUpUser:username
                  password:password
                    avatar:self.avatar
                     block:^(BOOL loggedIn) {
                         if(loggedIn){

                             [BWLoader dismissAsSuccess:^{

                                 [BWSettings sharedInstance].savedPassword = password;
                                 [BWSettings sharedInstance].savedUsername = username;

                                 [self.navigationController dismissViewControllerAnimated:YES completion:^{
                                     if(self.loggedInBlock){
                                         self.loggedInBlock();
                                         self.loggedInBlock = nil;
                                     }
                                 }];

                             }];

                         }
                         else{
                             [BWLoader dismissAsFailure:nil];
                         }
                     }];

    }

}
- (IBAction)selectAvatar:(id)sender {
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Select your avatar", @"")
                                                                         message:NSLocalizedString(@"You can pick a photo from your library or shoot one", @"")
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];

    [actionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"")
                                                    style:UIAlertActionStyleCancel
                                                  handler:^(UIAlertAction *action) {

                                                      // Cancel button tappped.
                                                      [actionSheet dismissViewControllerAnimated:YES completion:nil];

                                                  }]];

    [actionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Camera", @"")
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction *action) {

                                                      [actionSheet dismissViewControllerAnimated:YES completion:nil];

                                                      UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
                                                      imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                                                      imagePicker.delegate = self;
                                                      imagePicker.allowsEditing = YES;
                                                      [imagePicker setMediaTypes:@[(__bridge NSString*)kUTTypeImage]];
                                                      [self showViewController:imagePicker sender:nil];

                                                  }]];

    [actionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Photos library", @"")
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction *action) {

                                                      [actionSheet dismissViewControllerAnimated:YES completion:nil];

                                                      UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
                                                      imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                                                      imagePicker.delegate = self;
                                                      imagePicker.allowsEditing = YES;
                                                      [imagePicker setMediaTypes:@[(__bridge NSString*)kUTTypeImage]];
                                                      [self showViewController:imagePicker sender:nil];

                                                  }]];

    // Present action sheet.
    [self presentViewController:actionSheet animated:YES completion:nil];
}

#pragma mark - Screen rotation

-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
}

#pragma mark - UIImagePickerController

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];

    if(chosenImage == nil){
        chosenImage = info[UIImagePickerControllerOriginalImage];
    }

    [self applyAvatar:chosenImage];

    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;
{
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

@end


text:
'use strict';

angular.module('listwinners', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/listwinners', {
    templateUrl: 'listwinners/listwinners.html',
    controller: 'ListWinnersCtrl'
  });
}])

.controller('ListWinnersCtrl', ['$scope', '$http', function($scope, $http) {

        $scope.winners=[];

        $http.get('http://192.168.1.110:8080/webquest/listplayers').
            success(function(data, status, headers, config) {
                $scope.winners=data;
                console.log(data);

            }).
            error(function(data, status, headers, config) {
                /* TODO error*/
                alert("error");

            });
}]);


text:
class SessionsController < ApplicationController

  def new
    @cart = current_cart
  end

  def create
  	user = User.find_by(name: params[:sessions][:name])
  	if user and user.authenticate(params[:sessions][:password])
  		session[:user_id] = user.id
  		flash[:success] = 'Welcome to Pragmatic Bookshelf '
  		redirect_to admin_path
  	else
  		redirect_to login_url, alert: 'Invalid user/password combination'
  	end
  end

  def destroy
    session[:user_id] = nil
    flash[:success] = 'Logged out'
    redirect_to root_path
  end

  private
  	def set_cart
  		@cart = current_cart
  	end
end


text:
void highly_optimised_subroutine()
{
raven::set::cRunWatch runwatch("highly_optimised_subroutine");
Sleep( 2 );
}

void badly_written_function()
{
raven::set::cRunWatch runwatch("badly_written_function");
for (int k = 1; k < 1000; k++ )
{
highly_optimised_subroutine();
}
}

void well_written_function()
{
raven::set::cRunWatch runwatch("well_written_function");
for (int k = 1; k < 10; k++ )
{
highly_optimised_subroutine();
}
}

void func5()
{
	raven::set::cRunWatch runwatch("func5");
}
void func4()
{
	raven::set::cRunWatch runwatch("func4");
	func5();
}
void func3()
{
	raven::set::cRunWatch runwatch("func3");
	func4();
}
void func2()
{
	raven::set::cRunWatch runwatch("func2");
	func3();
}
void func1()
{
	raven::set::cRunWatch runwatch("func1");
	func2();
}

int _tmain(int argc, _TCHAR* argv[])
{
raven::set::cRunWatch::StartDaisyChain();

//well_written_function();
//badly_written_function();

{
raven::set::cRunWatch runwatch("main");
func1();
func3();
}

raven::set::cRunWatch::Report();

raven::set::cRunWatch::Report( L"runwatch_test.log");

return 0;
}


text:
  <its-breadcrumb breadcrumbs="home" active="Contact"></its-breadcrumb>

{{ 'contact.details' | translate }}

        {{ (dataService.observableDataMap.get('contact') | async)?.address }}

{{ (dataService.observableDataMap.get('contact') | async)?.city }}, {{ (dataService.observableDataMap.get('contact') | async)?.state }} {{ (dataService.observableDataMap.get('contact') | async)?.zip }}

    {{ 'contact.notification.welcome' | translate }}

{{ 'contact.message' | translate }}

      <form id="contactForm" name="sendMessage" [formGroup]="form" (ngSubmit)="submitForm(form.value)" novalidate>

            {{ 'contact.form.name.label' | translate }}
            <input type="text" class="form-control" id="name" name="name" [formControl]="form.controls['name']" [ngClass]="{ 'form-control-success': form.controls['name'].valid, 'form-control-danger': !form.controls['name'].valid }">
            {{ 'contact.form.name.help' | translate }}

{{ 'contact.form.name.validation.required' | translate }}

{{ 'contact.form.name.validation.minLength' | translate }}

{{ 'contact.form.name.validation.maxLength' | translate }}

            {{ 'contact.form.phone.label' | translate }}
            <input type="tel" class="form-control" id="phone" name="phone" [formControl]="form.controls['phone']" [ngClass]="{ 'form-control-success': form.controls['phone'].valid, 'form-control-danger': !form.controls['phone'].valid }">

{{ 'contact.form.phone.validation.required' | translate }}

{{ 'contact.form.phone.validation.pattern' | translate }}

            {{ 'contact.form.email.label' | translate }}
            <input type="email" class="form-control" id="email" name="email" [formControl]="form.controls['email']" [ngClass]="{ 'form-control-success': form.controls['email'].valid, 'form-control-danger': !form.controls['email'].valid }">

{{ 'contact.form.email.validation.required' | translate }}

{{ 'contact.form.email.validation.pattern' | translate }}

            {{ 'contact.form.message.label' | translate }}
            <textarea rows="10" cols="100" class="its form-control" id="message" name="message" [formControl]="form.controls['message']" [ngClass]="{ 'form-control-success': form.controls['message'].valid, 'form-control-danger': !form.controls['message'].valid }" maxlength="999"></textarea>
            {{ 'contact.form.message.help' | translate }}

{{ 'contact.form.message.validation.required' | translate }}

{{ 'contact.form.message.validation.minLength' | translate }}

{{ 'contact.form.message.validation.maxLength' | translate }}

        <button type="submit" class="btn btn-primary pull-right" [disabled]="!form.valid">{{ 'contact.form.submit' | translate }}</button>
      </form>


text:
package org.jfrog.artifactory.client.model.impl;

import com.fasterxml.jackson.annotation.JsonValue;

import org.jfrog.artifactory.client.model.PackageType;

public class CustomPackageTypeImpl implements PackageType {

    private String packageName;

    public CustomPackageTypeImpl(String packageName) {
        this.packageName = packageName;
    }

    @Override
    @JsonValue
    public String name() {
        return packageName;
    }

    @Override
    public boolean isCustom() {
        return true;
    }
}


text:
// Created by: Jeremy Bond
// Date: 10/06/2016

using UnityEngine;
using System.Collections;

public class PlayerAnimation : MonoBehaviour
{
	[SerializeField] private Sprite normalImage;
	[SerializeField] private Sprite[] eatAnimation;
	private SpriteRenderer render;

	/// <summary>
	/// Gives empty variables values.
	/// </summary>
	protected void Awake ()
	{
		render = GetComponent<SpriteRenderer> ();
	}
	/// <summary>
	/// Adds listeners.
	/// </summary>
	protected void OnEnable ()
	{
		EventManager.AddListener("PlayEatAnim", EatAnimTriggered);
	}
	/// <summary>
	/// Removes listeners.
	/// </summary>
	protected void OnDisable ()
	{
		EventManager.RemoveListener ("PlayEatAnim", EatAnimTriggered);
	}
	/// <summary>
	/// Function triggered when eat anim is called.
	/// </summary>
	private void EatAnimTriggered ()
	{
		StartCoroutine(PlayAnimation(eatAnimation));
	}
	/// <summary>
	/// Play destroy animation and after that destroying the tile
	/// </summary>
	/// <returns></returns>
	private IEnumerator PlayAnimation (Sprite[] animation)
	{
		for (int i = 0; i < animation.Length; i++)
		{
			render.sprite = animation[i];
			yield return new WaitForSeconds (0.01f);
			if (i == animation.Length - 1)
			{
				render.sprite = normalImage;
			}
		}
	}
}


text:
package org.ode4j.tests.joints;

import static org.ode4j.cpp.internal.ApiCppBody.dBodyAddForce;
import static org.ode4j.cpp.internal.ApiCppJoint.dJointGetSliderPosition;
import static org.ode4j.cpp.internal.ApiCppJoint.dJointGetSliderPositionRate;
import static org.ode4j.cpp.internal.ApiCppWorld.dWorldQuickStep;
import static org.ode4j.tests.UnitTestPlusPlus.CheckMacros.CHECK_CLOSE;

import org.junit.Test;

//This file create unit test for some of the functions found in:
//ode/src/joinst/slider.cpp
public class Fixture_dxJointSlider_B1_At_Zero_Axis_Along_X2
  extends Fixture_dxJointSlider_B1_At_Zero_Axis_Along_X {
  // Apply force on 1st body in the X direction also the Axis direction
  //
  //  X------->       X---------> Axis -->
  //  B1  F->      =>     B1
  //TEST_FIXTURE (Fixture_dxJointSlider_B1_At_Zero_Axis_Along_X,
  @Test public void test_dJointSetSliderPositionRate_Force_Along_Axis_on_B1()
    {
      CHECK_CLOSE (0.0, dJointGetSliderPosition(jId), 1e-4);
      CHECK_CLOSE (0.0, dJointGetSliderPositionRate(jId), 1e-4);

      dBodyAddForce(bId1, 1.0, 0, 0);
      dWorldQuickStep (wId, 1.0);

      CHECK_CLOSE (1, dJointGetSliderPositionRate(jId), 1e-4);
    }

  // Apply force on 1st body in the inverse X direction
  //
  //  X------->           X---------> Axis -->
  //  B1  <-F      => B1
  //TEST_FIXTURE (Fixture_dxJointSlider_B1_At_Zero_Axis_Along_X,
  @Test public void test_dJointSetSliderPositionRate_Force_Inverse_of_Axis_on_B1()
    {
      CHECK_CLOSE (0.0, dJointGetSliderPosition(jId), 1e-4);
      CHECK_CLOSE (0.0, dJointGetSliderPositionRate(jId), 1e-4);

      dBodyAddForce(bId1, -1.0, 0, 0);
      dWorldQuickStep (wId, 1.0);

      CHECK_CLOSE (-1, dJointGetSliderPositionRate(jId), 1e-4);
    }
  }


text:
module.exports = function (bt) {

    bt.match('nav', function (ctx) {
        ctx.setTag('nav');
        ctx.setAttr('role', 'navigation');

        ctx.setContent(' \
            <form action="http://google.com/search" method="get">\
                <fieldset role="search">\
                    <input type="hidden" name="q" value="site:makishvili.github.io/octopress">\
                    <input class="search" type="text" name="q" results="0" placeholder="Search">\
                </fieldset>\
            </form>\
            <fieldset class="mobile-nav"><select><option value="">Navigate…</option><option value="http://makishvili.github.io/octopress">» Главная</option><option value="http://makishvili.github.io/octopress/category/presentation">» Презентации</option><option value="http://makishvili.github.io/octopress/books">» Повести</option><option value="http://makishvili.github.io/octopress/blog/archives">» Архив</option></select></fieldset>
\

Главная
\

Презентации
\

Повести
\

Архив
\

\
        ');
    });

};


text:
@interface PCKConnectionDelegateWrapper ()

@property (nonatomic, assign) NSURLConnection *connection;
@property (nonatomic, copy) PCKConnectionDelegateWrapperCompletionBlock completionCallback;
@property (nonatomic, retain) NSMutableData *data;

@end

@implementation PCKConnectionDelegateWrapper

@synthesize connection = _connection;

+ (PCKConnectionDelegateWrapper *)wrapperForConnection:(NSURLConnection *)connection
                                    completionCallback:(PCKConnectionDelegateWrapperCompletionBlock)completionCallback
{
    return [[[PCKConnectionDelegateWrapper alloc] initWithConnection:connection
                                                  completionCallback:completionCallback] autorelease];
}

- (id)initWithConnection:(NSURLConnection *)connection
      completionCallback:(PCKConnectionDelegateWrapperCompletionBlock)completionCallback
{
    if (self = [super init]) {
        self.connection = connection;
        self.completionCallback = completionCallback;
        self.data = [NSMutableData data];
    }

    return self;
}

- (void)dealloc
{
    self.completionCallback = nil;
    [super dealloc];
}

- (id)delegate
{
    return self.connection.delegate;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
    return [self.delegate methodSignatureForSelector:selector];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    SEL selector = invocation.selector;
    if ([self.delegate respondsToSelector:selector]) {
        if (invocation.methodSignature.numberOfArguments > 2) {
            [invocation setArgument:&_connection atIndex:2];
        }
        [invocation invokeWithTarget:self.delegate];
    } else {
        [super forwardInvocation:invocation];
    }
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
    return [super respondsToSelector:aSelector] || [self.delegate respondsToSelector:aSelector];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if ([self.delegate respondsToSelector:_cmd]) {
        [self.delegate connection:self.connection didReceiveData:data];
    }
    [self.data appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if ([self.delegate respondsToSelector:_cmd]) {
        [self.delegate connection:self.connection didFailWithError:error];
    }
    self.completionCallback(nil);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if ([self.delegate respondsToSelector:_cmd]) {
        [self.delegate connectionDidFinishLoading:self.connection];
    }
    self.completionCallback(self.data);
}

@end


text:
package com.ssm.shiro;

import org.apache.shiro.authc.AuthenticationException;

/**
 * Created by admin on 2014/7/7.
 */
public class RepeatLoginException extends AuthenticationException {

    private static final long serialVersionUID = 3184431913337299518L;

    public RepeatLoginException() {
        super();
    }

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

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

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


text:
As a Custom operator, detection_postprocess is using Flexbuffers library. In the
unit test there is a need to use flexbuffers::Builder since the operator itself
use flexbuffers::Map. However flexbuffers::Builder can not be used for most
targets (basically only on X86), since it is using std::vector and std::map.
Therefore the flexbuffers::Builder data is pregenerated on X86.

# How to generate new data:

~~~
    ```g++ -I../../../micro/tools/make/downloads/flatbuffers/include generate_flexbuffers_data.cc && ./a.out > ../flexbuffers_generated_data.cc```

~~~


text:
package structures.data.actions.params;

import java.util.List;

import exceptions.ParameterParseException;
import structures.data.DataSound;
import structures.data.DataSprite;
import structures.data.actions.params.IParameter.type;
import utils.Utils;

public class SoundParam implements IParameter, ISelectable {
	private List<DataSound> myPossibleSounds;
	private DataSound mySelected;
	private String myOriginal;
	private String myTitle;
	public SoundParam(String title) {
		myTitle = title;
	}

	public void setSoundList(List<DataSound> possibleSounds) {
		myPossibleSounds = possibleSounds;
	}
	@Override
	public List<String> getOptions() {
		// TODO Auto-generated method stub
		return Utils.transform(myPossibleSounds, e -> e.getName());
	}

	@Override
	public void parse(String string) throws ParameterParseException {
		// TODO Auto-generated method stub
		myOriginal = string;
		DataSound found = Utils.first(myPossibleSounds, e -> (e.getName().equals(string)), null);
		if (found == null) {
			throw new ParameterParseException("No valid sound selected!");
		}
		mySelected = found;
	}

	@Override
	public String getOriginal() {
		// TODO Auto-generated method stub
		return mySelected.getName();
	}

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

	@Override
	public Object getValue() {
		// TODO Auto-generated method stub
		return mySelected;
	}

	@Override
	public type getType() {
		// TODO Auto-generated method stub
		return type.SOUND_SELECT;
	}

}