text:
package iso

import (
  "testing"
)

var sum_tests_greetingextendedascii = []struct {
  byteslice   []byte
  expected    string
}{
  {[]byte{0x20, 0x20, 0x20, 0x20}, "    "},
  {[]byte{0x77, 0x65, 0x77, 0x20, 0x6c, 0x61, 0x64}, "wew lad"},
   // Strings are unicode and extended ASCII is not covered, thus bytes must be used in place
   // of expected characters, like ÿ in the next case.
  {[]byte{0xFF, 0x20}, "\xff "},
  {[]byte{0x5E, 0x5F, 0x5E}, "^_^"},
  {[]byte{0x34, 0x89, 0x20, 0xBB, 0xBB}, "4\x89 \xBB\xBB"},
  {[]byte{0x01, 0xBB, 0x10}, "\xBB"}, // Will pass in TestGreetingASCII, but fail WithError.
}

func TestGreetingExtendedASCII(t *testing.T) {
  // This test will pass despite errors
  // because the function always returns safe extended ASCII
  for _, v := range sum_tests_greetingextendedascii {
    val, _ := GreetingExtendedASCII(v.byteslice)
    if val != v.expected {
      t.Errorf("GreetingExtendedASCII(0x%X) returned %q, expected %q", v.byteslice, v.expected, val)
    }
  }
}

func TestGreetingExtendedASCIIWithError(t *testing.T) {
  for _, v := range sum_tests_greetingextendedascii {
    val, err := GreetingExtendedASCII(v.byteslice)
    if err != nil {
      t.Errorf("GreetingExtendedASCII(0x%X) returned error: %q", v.byteslice, err)
    } else if val != v.expected {
      t.Errorf("GreetingExtendedASCII(0x%X) returned %q, expected %q", v.byteslice, v.expected, val)
    }
  }
}


text:
<?php

/* SonataAdminBundle:CRUD:list_date.html.twig */
class __TwigTemplate_8facdeead26accbcd321b231a6d772bc extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'field' => array($this, 'block_field'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "SonataAdminBundle:CRUD:base_list_field.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 13
    public function block_field($context, array $blocks = array())
    {
        // line 14
        if (twig_test_empty($this->getContext($context, "value"))) {
            // line 15
            echo " ";
        } else {
            // line 17
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getContext($context, "value"), "F j, Y"), "html", null, true);
        }
    }

    public function getTemplateName()
    {
        return "SonataAdminBundle:CRUD:list_date.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package core

import (
	"github.com/pingcap/parser/mysql"
	"github.com/pingcap/parser/terror"
)

// error definitions.
var (
	ErrUnsupportedType                 = terror.ClassOptimizer.New(mysql.ErrUnsupportedType, mysql.MySQLErrName[mysql.ErrUnsupportedType])
	ErrAnalyzeMissIndex                = terror.ClassOptimizer.New(mysql.ErrAnalyzeMissIndex, mysql.MySQLErrName[mysql.ErrAnalyzeMissIndex])
	ErrWrongParamCount                 = terror.ClassOptimizer.New(mysql.ErrWrongParamCount, mysql.MySQLErrName[mysql.ErrWrongParamCount])
	ErrSchemaChanged                   = terror.ClassOptimizer.New(mysql.ErrSchemaChanged, mysql.MySQLErrName[mysql.ErrSchemaChanged])
	ErrTablenameNotAllowedHere         = terror.ClassOptimizer.New(mysql.ErrTablenameNotAllowedHere, mysql.MySQLErrName[mysql.ErrTablenameNotAllowedHere])
	ErrNotSupportedYet                 = terror.ClassOptimizer.New(mysql.ErrNotSupportedYet, mysql.MySQLErrName[mysql.ErrNotSupportedYet])
	ErrWrongUsage                      = terror.ClassOptimizer.New(mysql.ErrWrongUsage, mysql.MySQLErrName[mysql.ErrWrongUsage])
	ErrUnknown                         = terror.ClassOptimizer.New(mysql.ErrUnknown, mysql.MySQLErrName[mysql.ErrUnknown])
	ErrUnknownTable                    = terror.ClassOptimizer.New(mysql.ErrUnknownTable, mysql.MySQLErrName[mysql.ErrUnknownTable])
	ErrWrongArguments                  = terror.ClassOptimizer.New(mysql.ErrWrongArguments, mysql.MySQLErrName[mysql.ErrWrongArguments])
	ErrWrongNumberOfColumnsInSelect    = terror.ClassOptimizer.New(mysql.ErrWrongNumberOfColumnsInSelect, mysql.MySQLErrName[mysql.ErrWrongNumberOfColumnsInSelect])
	ErrBadGeneratedColumn              = terror.ClassOptimizer.New(mysql.ErrBadGeneratedColumn, mysql.MySQLErrName[mysql.ErrBadGeneratedColumn])
	ErrFieldNotInGroupBy               = terror.ClassOptimizer.New(mysql.ErrFieldNotInGroupBy, mysql.MySQLErrName[mysql.ErrFieldNotInGroupBy])
	ErrBadTable                        = terror.ClassOptimizer.New(mysql.ErrBadTable, mysql.MySQLErrName[mysql.ErrBadTable])
	ErrKeyDoesNotExist                 = terror.ClassOptimizer.New(mysql.ErrKeyDoesNotExist, mysql.MySQLErrName[mysql.ErrKeyDoesNotExist])
	ErrOperandColumns                  = terror.ClassOptimizer.New(mysql.ErrOperandColumns, mysql.MySQLErrName[mysql.ErrOperandColumns])
	ErrInvalidGroupFuncUse             = terror.ClassOptimizer.New(mysql.ErrInvalidGroupFuncUse, mysql.MySQLErrName[mysql.ErrInvalidGroupFuncUse])
	ErrIllegalReference                = terror.ClassOptimizer.New(mysql.ErrIllegalReference, mysql.MySQLErrName[mysql.ErrIllegalReference])
	ErrNoDB                            = terror.ClassOptimizer.New(mysql.ErrNoDB, mysql.MySQLErrName[mysql.ErrNoDB])
	ErrUnknownExplainFormat            = terror.ClassOptimizer.New(mysql.ErrUnknownExplainFormat, mysql.MySQLErrName[mysql.ErrUnknownExplainFormat])
	ErrWrongGroupField                 = terror.ClassOptimizer.New(mysql.ErrWrongGroupField, mysql.MySQLErrName[mysql.ErrWrongGroupField])
	ErrDupFieldName                    = terror.ClassOptimizer.New(mysql.ErrDupFieldName, mysql.MySQLErrName[mysql.ErrDupFieldName])
	ErrNonUpdatableTable               = terror.ClassOptimizer.New(mysql.ErrNonUpdatableTable, mysql.MySQLErrName[mysql.ErrNonUpdatableTable])
	ErrInternal                        = terror.ClassOptimizer.New(mysql.ErrInternal, mysql.MySQLErrName[mysql.ErrInternal])
	ErrNonUniqTable                    = terror.ClassOptimizer.New(mysql.ErrNonuniqTable, mysql.MySQLErrName[mysql.ErrNonuniqTable])
	ErrWindowInvalidWindowFuncUse      = terror.ClassOptimizer.New(mysql.ErrWindowInvalidWindowFuncUse, mysql.MySQLErrName[mysql.ErrWindowInvalidWindowFuncUse])
	ErrWindowInvalidWindowFuncAliasUse = terror.ClassOptimizer.New(mysql.ErrWindowInvalidWindowFuncAliasUse, mysql.MySQLErrName[mysql.ErrWindowInvalidWindowFuncAliasUse])
	ErrWindowNoSuchWindow              = terror.ClassOptimizer.New(mysql.ErrWindowNoSuchWindow, mysql.MySQLErrName[mysql.ErrWindowNoSuchWindow])
	ErrWindowCircularityInWindowGraph  = terror.ClassOptimizer.New(mysql.ErrWindowCircularityInWindowGraph, mysql.MySQLErrName[mysql.ErrWindowCircularityInWindowGraph])
	ErrWindowNoChildPartitioning       = terror.ClassOptimizer.New(mysql.ErrWindowNoChildPartitioning, mysql.MySQLErrName[mysql.ErrWindowNoChildPartitioning])
	ErrWindowNoInherentFrame           = terror.ClassOptimizer.New(mysql.ErrWindowNoInherentFrame, mysql.MySQLErrName[mysql.ErrWindowNoInherentFrame])
	ErrWindowNoRedefineOrderBy         = terror.ClassOptimizer.New(mysql.ErrWindowNoRedefineOrderBy, mysql.MySQLErrName[mysql.ErrWindowNoRedefineOrderBy])
	ErrWindowDuplicateName             = terror.ClassOptimizer.New(mysql.ErrWindowDuplicateName, mysql.MySQLErrName[mysql.ErrWindowDuplicateName])
	ErrPartitionClauseOnNonpartitioned = terror.ClassOptimizer.New(mysql.ErrPartitionClauseOnNonpartitioned, mysql.MySQLErrName[mysql.ErrPartitionClauseOnNonpartitioned])
	ErrWindowFrameStartIllegal         = terror.ClassOptimizer.New(mysql.ErrWindowFrameStartIllegal, mysql.MySQLErrName[mysql.ErrWindowFrameStartIllegal])
	ErrWindowFrameEndIllegal           = terror.ClassOptimizer.New(mysql.ErrWindowFrameEndIllegal, mysql.MySQLErrName[mysql.ErrWindowFrameEndIllegal])
	ErrWindowFrameIllegal              = terror.ClassOptimizer.New(mysql.ErrWindowFrameIllegal, mysql.MySQLErrName[mysql.ErrWindowFrameIllegal])
	ErrWindowRangeFrameOrderType       = terror.ClassOptimizer.New(mysql.ErrWindowRangeFrameOrderType, mysql.MySQLErrName[mysql.ErrWindowRangeFrameOrderType])
	ErrWindowRangeFrameTemporalType    = terror.ClassOptimizer.New(mysql.ErrWindowRangeFrameTemporalType, mysql.MySQLErrName[mysql.ErrWindowRangeFrameTemporalType])
	ErrWindowRangeFrameNumericType     = terror.ClassOptimizer.New(mysql.ErrWindowRangeFrameNumericType, mysql.MySQLErrName[mysql.ErrWindowRangeFrameNumericType])
	ErrWindowRangeBoundNotConstant     = terror.ClassOptimizer.New(mysql.ErrWindowRangeBoundNotConstant, mysql.MySQLErrName[mysql.ErrWindowRangeBoundNotConstant])
	ErrWindowRowsIntervalUse           = terror.ClassOptimizer.New(mysql.ErrWindowRowsIntervalUse, mysql.MySQLErrName[mysql.ErrWindowRowsIntervalUse])
	ErrWindowFunctionIgnoresFrame      = terror.ClassOptimizer.New(mysql.ErrWindowFunctionIgnoresFrame, mysql.MySQLErrName[mysql.ErrWindowFunctionIgnoresFrame])
	ErrUnsupportedOnGeneratedColumn    = terror.ClassOptimizer.New(mysql.ErrUnsupportedOnGeneratedColumn, mysql.MySQLErrName[mysql.ErrUnsupportedOnGeneratedColumn])
	ErrPrivilegeCheckFail              = terror.ClassOptimizer.New(mysql.ErrPrivilegeCheckFail, mysql.MySQLErrName[mysql.ErrPrivilegeCheckFail])
	ErrInvalidWildCard                 = terror.ClassOptimizer.New(mysql.ErrInvalidWildCard, mysql.MySQLErrName[mysql.ErrInvalidWildCard])
	ErrMixOfGroupFuncAndFields         = terror.ClassOptimizer.New(mysql.ErrMixOfGroupFuncAndFieldsIncompatible, mysql.MySQLErrName[mysql.ErrMixOfGroupFuncAndFieldsIncompatible])
	errTooBigPrecision                 = terror.ClassExpression.New(mysql.ErrTooBigPrecision, mysql.MySQLErrName[mysql.ErrTooBigPrecision])
	ErrDBaccessDenied                  = terror.ClassOptimizer.New(mysql.ErrDBaccessDenied, mysql.MySQLErrName[mysql.ErrDBaccessDenied])
	ErrTableaccessDenied               = terror.ClassOptimizer.New(mysql.ErrTableaccessDenied, mysql.MySQLErrName[mysql.ErrTableaccessDenied])
	ErrSpecificAccessDenied            = terror.ClassOptimizer.New(mysql.ErrSpecificAccessDenied, mysql.MySQLErrName[mysql.ErrSpecificAccessDenied])
	ErrViewNoExplain                   = terror.ClassOptimizer.New(mysql.ErrViewNoExplain, mysql.MySQLErrName[mysql.ErrViewNoExplain])
	ErrWrongValueCountOnRow            = terror.ClassOptimizer.New(mysql.ErrWrongValueCountOnRow, mysql.MySQLErrName[mysql.ErrWrongValueCountOnRow])
	ErrViewInvalid                     = terror.ClassOptimizer.New(mysql.ErrViewInvalid, mysql.MySQLErrName[mysql.ErrViewInvalid])
	ErrNoSuchThread                    = terror.ClassOptimizer.New(mysql.ErrNoSuchThread, mysql.MySQLErrName[mysql.ErrNoSuchThread])
	ErrUnknownColumn                   = terror.ClassOptimizer.New(mysql.ErrBadField, mysql.MySQLErrName[mysql.ErrBadField])
	ErrCartesianProductUnsupported     = terror.ClassOptimizer.New(mysql.ErrCartesianProductUnsupported, mysql.MySQLErrName[mysql.ErrCartesianProductUnsupported])
	ErrStmtNotFound                    = terror.ClassOptimizer.New(mysql.ErrPreparedStmtNotFound, mysql.MySQLErrName[mysql.ErrPreparedStmtNotFound])
	ErrAmbiguous                       = terror.ClassOptimizer.New(mysql.ErrNonUniq, mysql.MySQLErrName[mysql.ErrNonUniq])
	// Since we cannot know if user loggined with a password, use message of ErrAccessDeniedNoPassword instead
	ErrAccessDenied = terror.ClassOptimizer.New(mysql.ErrAccessDenied, mysql.MySQLErrName[mysql.ErrAccessDeniedNoPassword])
)

func init() {
	mysqlErrCodeMap := map[terror.ErrCode]uint16{
		mysql.ErrViewInvalid:                         mysql.ErrViewInvalid,
		mysql.ErrUnknown:                             mysql.ErrUnknown,
		mysql.ErrTablenameNotAllowedHere:             mysql.ErrTablenameNotAllowedHere,
		mysql.ErrUnsupportedType:                     mysql.ErrUnsupportedType,
		mysql.ErrAnalyzeMissIndex:                    mysql.ErrAnalyzeMissIndex,
		mysql.ErrWrongParamCount:                     mysql.ErrWrongParamCount,
		mysql.ErrSchemaChanged:                       mysql.ErrSchemaChanged,
		mysql.ErrNotSupportedYet:                     mysql.ErrNotSupportedYet,
		mysql.ErrWrongUsage:                          mysql.ErrWrongUsage,
		mysql.ErrUnknownTable:                        mysql.ErrUnknownTable,
		mysql.ErrWrongArguments:                      mysql.ErrWrongArguments,
		mysql.ErrBadGeneratedColumn:                  mysql.ErrBadGeneratedColumn,
		mysql.ErrFieldNotInGroupBy:                   mysql.ErrFieldNotInGroupBy,
		mysql.ErrBadTable:                            mysql.ErrBadTable,
		mysql.ErrKeyDoesNotExist:                     mysql.ErrKeyDoesNotExist,
		mysql.ErrOperandColumns:                      mysql.ErrOperandColumns,
		mysql.ErrInvalidGroupFuncUse:                 mysql.ErrInvalidGroupFuncUse,
		mysql.ErrIllegalReference:                    mysql.ErrIllegalReference,
		mysql.ErrNoDB:                                mysql.ErrNoDB,
		mysql.ErrUnknownExplainFormat:                mysql.ErrUnknownExplainFormat,
		mysql.ErrWrongGroupField:                     mysql.ErrWrongGroupField,
		mysql.ErrDupFieldName:                        mysql.ErrDupFieldName,
		mysql.ErrNonUpdatableTable:                   mysql.ErrNonUpdatableTable,
		mysql.ErrInternal:                            mysql.ErrInternal,
		mysql.ErrMixOfGroupFuncAndFieldsIncompatible: mysql.ErrMixOfGroupFuncAndFieldsIncompatible,
		mysql.ErrWrongNumberOfColumnsInSelect:        mysql.ErrWrongNumberOfColumnsInSelect,
		mysql.ErrWrongValueCountOnRow:                mysql.ErrWrongValueCountOnRow,
		mysql.ErrWindowInvalidWindowFuncUse:          mysql.ErrWindowInvalidWindowFuncUse,
		mysql.ErrWindowInvalidWindowFuncAliasUse:     mysql.ErrWindowInvalidWindowFuncAliasUse,
		mysql.ErrWindowNoSuchWindow:                  mysql.ErrWindowNoSuchWindow,
		mysql.ErrWindowCircularityInWindowGraph:      mysql.ErrWindowCircularityInWindowGraph,
		mysql.ErrWindowNoChildPartitioning:           mysql.ErrWindowNoChildPartitioning,
		mysql.ErrWindowNoInherentFrame:               mysql.ErrWindowNoInherentFrame,
		mysql.ErrWindowNoRedefineOrderBy:             mysql.ErrWindowNoRedefineOrderBy,
		mysql.ErrWindowDuplicateName:                 mysql.ErrWindowDuplicateName,
		mysql.ErrPartitionClauseOnNonpartitioned:     mysql.ErrPartitionClauseOnNonpartitioned,
		mysql.ErrDBaccessDenied:                      mysql.ErrDBaccessDenied,
		mysql.ErrTableaccessDenied:                   mysql.ErrTableaccessDenied,
		mysql.ErrSpecificAccessDenied:                mysql.ErrSpecificAccessDenied,
		mysql.ErrViewNoExplain:                       mysql.ErrViewNoExplain,
		mysql.ErrWindowFrameStartIllegal:             mysql.ErrWindowFrameStartIllegal,
		mysql.ErrWindowFrameEndIllegal:               mysql.ErrWindowFrameEndIllegal,
		mysql.ErrWindowFrameIllegal:                  mysql.ErrWindowFrameIllegal,
		mysql.ErrWindowRangeFrameOrderType:           mysql.ErrWindowRangeFrameOrderType,
		mysql.ErrWindowRangeFrameTemporalType:        mysql.ErrWindowRangeFrameTemporalType,
		mysql.ErrWindowRangeFrameNumericType:         mysql.ErrWindowRangeFrameNumericType,
		mysql.ErrWindowRangeBoundNotConstant:         mysql.ErrWindowRangeBoundNotConstant,
		mysql.ErrWindowRowsIntervalUse:               mysql.ErrWindowRowsIntervalUse,
		mysql.ErrWindowFunctionIgnoresFrame:          mysql.ErrWindowFunctionIgnoresFrame,
		mysql.ErrUnsupportedOnGeneratedColumn:        mysql.ErrUnsupportedOnGeneratedColumn,
		mysql.ErrNoSuchThread:                        mysql.ErrNoSuchThread,
		mysql.ErrAccessDenied:                        mysql.ErrAccessDenied,
		mysql.ErrPrivilegeCheckFail:                  mysql.ErrPrivilegeCheckFail,
		mysql.ErrCartesianProductUnsupported:         mysql.ErrCartesianProductUnsupported,
		mysql.ErrPreparedStmtNotFound:                mysql.ErrPreparedStmtNotFound,
		mysql.ErrNonUniq:                             mysql.ErrNonUniq,
		mysql.ErrBadField:                            mysql.ErrBadField,
		mysql.ErrNonuniqTable:                        mysql.ErrNonuniqTable,
		mysql.ErrTooBigPrecision:                     mysql.ErrTooBigPrecision,
		mysql.ErrInvalidWildCard:                     mysql.ErrInvalidWildCard,
	}
	terror.ErrClassToMySQLCodes[terror.ClassOptimizer] = mysqlErrCodeMap
}


text:
import testtools

from tempest.api.compute import base
from tempest.common import waiters
from tempest import config
from tempest import test

CONF = config.CONF

class LiveBlockMigrationTestJSON(base.BaseV2ComputeAdminTest):
    _host_key = 'OS-EXT-SRV-ATTR:host'

    @classmethod
    def setup_clients(cls):
        super(LiveBlockMigrationTestJSON, cls).setup_clients()
        cls.admin_hosts_client = cls.os_adm.hosts_client
        cls.admin_servers_client = cls.os_adm.servers_client

    @classmethod
    def resource_setup(cls):
        super(LiveBlockMigrationTestJSON, cls).resource_setup()

        cls.created_server_ids = []

    def _get_compute_hostnames(self):
        body = self.admin_hosts_client.list_hosts()
        return [
            host_record['host_name']
            for host_record in body
            if host_record['service'] == 'compute'
        ]

    def _get_server_details(self, server_id):
        body = self.admin_servers_client.show_server(server_id)
        return body

    def _get_host_for_server(self, server_id):
        return self._get_server_details(server_id)[self._host_key]

    def _migrate_server_to(self, server_id, dest_host):
        body = self.admin_servers_client.live_migrate_server(
            server_id, dest_host,
            CONF.compute_feature_enabled.block_migration_for_live_migration)
        return body

    def _get_host_other_than(self, host):
        for target_host in self._get_compute_hostnames():
            if host != target_host:
                return target_host

    def _get_server_status(self, server_id):
        return self._get_server_details(server_id)['status']

    def _get_an_active_server(self):
        for server_id in self.created_server_ids:
            if 'ACTIVE' == self._get_server_status(server_id):
                return server_id
        else:
            server = self.create_test_server(wait_until="ACTIVE")
            server_id = server['id']
            self.created_server_ids.append(server_id)
            return server_id

    def _volume_clean_up(self, server_id, volume_id):
        body = self.volumes_client.show_volume(volume_id)
        if body['status'] == 'in-use':
            self.servers_client.detach_volume(server_id, volume_id)
            self.volumes_client.wait_for_volume_status(volume_id, 'available')
        self.volumes_client.delete_volume(volume_id)

    def _test_live_block_migration(self, state='ACTIVE'):
        """Tests live block migration between two hosts.

        Requires CONF.compute_feature_enabled.live_migration to be True.

        :param state: The vm_state the migrated server should be in before and
                      after the live migration. Supported values are 'ACTIVE'
                      and 'PAUSED'.
        """
        # Live block migrate an instance to another host
        if len(self._get_compute_hostnames()) < 2:
            raise self.skipTest(
                "Less than 2 compute nodes, skipping migration test.")
        server_id = self._get_an_active_server()
        actual_host = self._get_host_for_server(server_id)
        target_host = self._get_host_other_than(actual_host)

        if state == 'PAUSED':
            self.admin_servers_client.pause_server(server_id)
            waiters.wait_for_server_status(self.admin_servers_client,
                                           server_id, state)

        self._migrate_server_to(server_id, target_host)
        waiters.wait_for_server_status(self.servers_client, server_id, state)
        self.assertEqual(target_host, self._get_host_for_server(server_id))

    @test.idempotent_id('1dce86b8-eb04-4c03-a9d8-9c1dc3ee0c7b')
    @testtools.skipUnless(CONF.compute_feature_enabled.live_migration,
                          'Live migration not available')
    def test_live_block_migration(self):
        self._test_live_block_migration()

    @test.idempotent_id('1e107f21-61b2-4988-8f22-b196e938ab88')
    @testtools.skipUnless(CONF.compute_feature_enabled.live_migration,
                          'Live migration not available')
    @testtools.skipUnless(CONF.compute_feature_enabled.pause,
                          'Pause is not available.')
    @testtools.skipUnless(CONF.compute_feature_enabled
                              .live_migrate_paused_instances,
                          'Live migration of paused instances is not '
                          'available.')
    def test_live_block_migration_paused(self):
        self._test_live_block_migration(state='PAUSED')

    @test.idempotent_id('e19c0cc6-6720-4ed8-be83-b6603ed5c812')
    @testtools.skipIf(not CONF.compute_feature_enabled.live_migration or not
                      CONF.compute_feature_enabled.
                      block_migration_for_live_migration,
                      'Block Live migration not available')
    @testtools.skipIf(not CONF.compute_feature_enabled.
                      block_migrate_cinder_iscsi,
                      'Block Live migration not configured for iSCSI')
    def test_iscsi_volume(self):
        # Live block migrate an instance to another host
        if len(self._get_compute_hostnames()) < 2:
            raise self.skipTest(
                "Less than 2 compute nodes, skipping migration test.")
        server_id = self._get_an_active_server()
        actual_host = self._get_host_for_server(server_id)
        target_host = self._get_host_other_than(actual_host)

        volume = self.volumes_client.create_volume(display_name='test')

        self.volumes_client.wait_for_volume_status(volume['id'],
                                                   'available')
        self.addCleanup(self._volume_clean_up, server_id, volume['id'])

        # Attach the volume to the server
        self.servers_client.attach_volume(server_id, volume['id'],
                                          device='/dev/xvdb')
        self.volumes_client.wait_for_volume_status(volume['id'], 'in-use')

        self._migrate_server_to(server_id, target_host)
        waiters.wait_for_server_status(self.servers_client,
                                       server_id, 'ACTIVE')
        self.assertEqual(target_host, self._get_host_for_server(server_id))


text:
package org.sakaiproject.nakamura.api.persondirectory;

import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;

public class PersonProviderExceptionTest {
  @Test
  public void testDefaultConstructor() {
    PersonProviderException e = new PersonProviderException();
    assertNull(e.getMessage());
    assertNull(e.getCause());
  }

  @Test
  public void testConstructorMessage() {
    PersonProviderException e = new PersonProviderException("Exception happened");
    assertEquals("Exception happened", e.getMessage());
    assertNull(e.getCause());
  }

  @Test
  public void testConstructorThrowable() {
    Exception ex = new Exception();
    PersonProviderException e = new PersonProviderException(ex);
    assertEquals(ex.getClass().getName(), e.getMessage());
    assertEquals(ex, e.getCause());
  }

  @Test
  public void testConstructorMessageThrowable() {
    Exception ex = new Exception();
    PersonProviderException e = new PersonProviderException("Exception happened", ex);
    assertEquals("Exception happened", e.getMessage());
    assertEquals(ex, e.getCause());
  }
}


text:
static const float FRICTION = 0.95f;
static const float BOUNCE = 0.60f;

// Forward Declaration to remove circular dependency
class AbstractGameObject;

struct RigidBody
{
private:
	// Pointer to owning object; used for transformations
	AbstractGameObject* owner;
	vec2 linearVelocity;
	void calculateGravity( float deltaTime );
	vec2 calcLinearMomentum( RigidBody* body2 );
public:
	float angularVelocity;
	GLfloat mass;
	RigidBody( AbstractGameObject* own );
	~RigidBody( void );
	void update( float deltaTime );
	void reset();
	const vec2 getLinearVelocity() { return linearVelocity; }
	const vec2 getMass() { return mass; }
	void stop() { linearVelocity = vec2( 0.0f, 0.0f ); }
	void setLinearVelocity( vec2 linVel ) { linearVelocity = linVel; }
	void addLinearVelocity( vec2 linVel ) { linearVelocity += linVel; }
	void collisionResponse( float depth, vec2 normal, RigidBody* collidingBody );
};

#endif


text:
/**
 * @author Charlie Calvert
 */

/*jshint devel:true, browser: true, jquery: true */

/*********************
 *  Technique One - Simple Object
 *********************/
var myObject = {
    myProperty01: 12,
    myProperty02: 4,
    myFunction01: function() {
        'use strict';
        return this.myProperty01 + this.myProperty02;
    }
};

/*********************
 *  Technique Two - Simple Function
 *********************/
function myFunction02() {
    'use strict';

    var myField01 = 3;
    var myField02 = 2;
    var nestedFunction = function() {
        return myField01 + myField02;
    };

    return nestedFunction();
}

/*********************
 *  Technique Three - Extend function with Prototype
 *********************/
var MyFunction03 = function() {
    'use strict';
};

MyFunction03.prototype.field01 = 2;
MyFunction03.prototype.field02 = 4;
MyFunction03.prototype.nestedFunction = function() {
    'use strict';
    return this.field01 + this.field02;
};

/*********************
 *  Technique Four - Modular Pattern
 *********************/
var MyFunction04 = (function() {
    'use strict';

    var field01 = 0;
    var field02 = 0;

    function MyFunction04(initField01, initField02) {
        field01 = initField01;
        field02 = initField02;
    }

    MyFunction04.prototype.nestedFunction = function() {
        return field01 + field02;
    };

    return MyFunction04;
}());

var App = (function() {

    function App() { }

    App.prototype.initialize = function() {

    };

    return App;
})();

$(document).ready(function() {
    'use strict';

    $("#techObject").html(myObject.myFunction01());

    // Technique Two (Simple Function)
    $("#techFunction").html(myFunction02());

    // Technique Three (prototype)
    var myFunction03 = new MyFunction03();
    $("#techPrototype").html(myFunction03.nestedFunction());

    // Technique Four (Module Pattern)
    var myFunction04 = new MyFunction04(1, 2);
    $("#techModule").html(myFunction04.nestedFunction());

    var app = new App();
    app.initialize();
});


text:
<?php

namespace FOS\RestBundle\Util;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Negotiation\FormatNegotiator as BaseFormatNegotiator;
use Negotiation\AcceptHeader;

class FormatNegotiator implements MediaTypeNegotiatorInterface
{
    private $map = array();

    public function __construct()
    {
        $this->formatNegotiator = new BaseFormatNegotiator();
    }

    /**
     * @param RequestMatcherInterface $requestMatcher
     * @param array                   $options
     */
    public function add(RequestMatcherInterface $requestMatcher, array $options = array())
    {
        $this->map[] = array($requestMatcher, $options);
    }

    /**
     * Detects the request format based on the priorities and the Accept header.
     *
     * @param Request $request
     *
     * @return null|string
     */
    public function getBestFormat(Request $request)
    {
        $mediaType = $this->getBestMediaType($request);
        if (null === $mediaType) {
            return null;
        }

        return $this->getFormat($mediaType);
    }

    /**
     * Detects the request format based on the priorities and the Accept header.
     *
     * @param Request $request
     *
     * @return null|string
     */
    public function getBestMediaType(Request $request)
    {
        foreach ($this->map as $elements) {
            if (null === $elements[0] || $elements[0]->matches($request)) {
                $options = $elements[1];
            }

            if (empty($options['priorities'])) {
                if (!empty($options['fallback_format'])) {
                    return $request->getMimeType($options['fallback_format']);
                }

                continue;
            }

            $acceptHeader = $request->headers->get('Accept');

            if ($options['prefer_extension']) {
                // ensure we only need to compute $extensionHeader once
                if (!isset($extensionHeader)) {
                    if (preg_match('/.*\.([a-z0-9]+)$/', $request->getPathInfo(), $matches)) {
                        $extension = $matches[1];
                    }

                    // $extensionHeader will now be either a non empty string or an empty string
                    $extensionHeader = isset($extension) ? (string) $request->getMimeType($extension) : '';
                    if ($acceptHeader && $extensionHeader) {
                        $extensionHeader = ','.$extensionHeader;
                    }
                }
                if ($extensionHeader) {
                    $acceptHeader.= $extensionHeader.'; q='.$options['prefer_extension'];
                }
            }

            $mimeTypes = $this->formatNegotiator->normalizePriorities($options['priorities']);
            $mediaType = $this->formatNegotiator->getBest($acceptHeader, $mimeTypes);
            if ($mediaType instanceof AcceptHeader && !$mediaType->isMediaRange()) {
                return $mediaType->getValue();
            }

            if (isset($options['fallback_format'])) {
                // if false === fallback_format then we fail here instead of considering more rules
                if (false === $options['fallback_format']) {
                    return null;
                }

                // stop looking at rules since we have a fallback defined
                return $request->getMimeType($options['fallback_format']);
            }
        }

        return null;
    }

    /**
     * Registers a new format with its mime types.
     *
     * @param string $format
     * @param array  $mimeTypes
     * @param bool   $override
     */
    public function registerFormat($format, array $mimeTypes, $override = false)
    {
        $this->formatNegotiator->registerFormat($format, $mimeTypes, $override);
    }

    /**
     * Returns the format for a given mime type, or null if not found.
     *
     * @param string $mimeType
     *
     * @return string|null
     */
    public function getFormat($mimeType)
    {
        return $this->formatNegotiator->getFormat($mimeType);
    }
}


text:
package net.firejack.platform.generate.service;

import net.firejack.platform.api.registry.model.FieldType;
import net.firejack.platform.core.config.meta.IPackageDescriptor;
import net.firejack.platform.core.config.meta.element.action.ActionElement;
import net.firejack.platform.core.config.meta.element.action.ActionParameterElement;
import net.firejack.platform.core.config.meta.utils.DiffUtils;
import net.firejack.platform.core.model.registry.HTTPMethod;
import net.firejack.platform.generate.beans.ImportString;
import net.firejack.platform.generate.beans.web.broker.Broker;
import net.firejack.platform.generate.beans.web.model.Domain;
import net.firejack.platform.generate.beans.web.model.Model;
import net.firejack.platform.generate.beans.web.report.Report;
import net.firejack.platform.generate.beans.web.store.Method;
import net.firejack.platform.generate.beans.web.store.MethodType;
import net.firejack.platform.generate.beans.web.store.Param;
import net.firejack.platform.generate.beans.web.store.Store;
import net.firejack.platform.generate.structure.Structure;
import net.firejack.platform.generate.tools.Utils;
import net.firejack.platform.model.wsdl.Invoker;
import net.firejack.platform.web.mina.annotations.ProgressStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class BrokerGeneratorService extends BaseGeneratorService implements IBrokerGeneratorService {

    @ProgressStatus(weight = 1, description = "Generate broker objects")
    public void generateBrokerService(IPackageDescriptor descriptor, List<Model> models, Structure structure) throws IOException {
        ActionElement[] elements = descriptor.getActionElements();

        if (elements == null) {
            return;
        }

        for (ActionElement element : elements) {
            Model model = getCacheItem(element.getPath());
            if (model != null && !model.isAbstracts()) {
                Store store = model.getStore();

                Method method = model.findStoreMethod(Utils.fieldFormatting(element.getName()));
                Broker broker = getBroker(element, model, store, method);
                model.addBroker(broker);

                if (model instanceof Report) {
                    if (((Report) model).isBiReport()) {
                        generate(broker, "templates/code/server/report/biReportBroker.vsl", structure.getSrc());
                    } else {
                        generate(broker, "templates/code/server/report/reportBroker.vsl", structure.getSrc());
                    }
                } else {
                    generate(broker, "templates/code/server/service/broker.vsl", structure.getSrc());
                }
            }
        }
    }

    private Broker getBroker(ActionElement element, Model model, Store store, Method method) {
        Broker broker;
        if (method != null) {
            broker = new Broker(model, method.getType());
        } else {
            broker = new Broker(model, element.getName());
        }

        broker.setLookup(DiffUtils.lookup(element.getPath(), element.getName()));
        broker.setMethod(method);
        broker.setWsdl(model.isWsdl());
        broker.setWsdlMethod(element.getSoapMethod());
        broker.setDescription(element.getDescription());
        broker.setHttpMethod(element.getMethod());
        broker.addImport(model.getDomain());
        broker.addImport(model.getKey());
        if (model.isWsdl())
            broker.addImport(new ImportString(Invoker.class));
        if (store != null) {
            broker.addImport(store.getInterface());
        }
        if (model.isSingle()) {
            broker.removeImport(model);
        }

        List<ActionParameterElement> parameters = element.getParameters();
        if (parameters != null) {
            for (ActionParameterElement parameter : parameters) {
                if (!model.isSingle() && parameter.getName().equals("id")) {
                    broker.addParam(new Param("id", model.getKey()));
                } else {
                    broker.addParam(new Param(parameter.getName(), parameter.getType()));
                }
            }
        } else if (!broker.getHttpMethod().equals(HTTPMethod.POST) && broker.getType() != null && !broker.isType(MethodType.readAll)) {
            broker.addParam(new Param("id", model.getKey()));
        }

        if (broker.getHttpMethod().equals(HTTPMethod.POST) || broker.getHttpMethod().equals(HTTPMethod.PUT)) {
            Model request = getCacheItem(element.getInputVOEntityLookup());
            broker.addParam(new Param("data", FieldType.OBJECT, request.getDomain()));

            broker.setRequest(request);
            broker.addImport(request.getDomain());
        }

        if (model instanceof Report && ((Report) model).isBiReport()) {
            Model m = new Model();

            Domain domain = new Domain();
            domain.setProjectPath("net.firejack.platform.api.registry.domain");
            domain.setName("BIReportData");
            m.setDomain(domain);

            broker.setResponse(m);
        }

        addCacheItem(broker.getLookup(), broker);
        return broker;
    }
}


text:
package org.apache.spark.sql.catalyst.json

import java.io.Writer

import com.fasterxml.jackson.core._
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.SpecializedGetters
import org.apache.spark.sql.catalyst.util._
import org.apache.spark.sql.catalyst.util.LegacyDateFormats.FAST_DATE_FORMAT
import org.apache.spark.sql.errors.QueryExecutionErrors
import org.apache.spark.sql.types._

/**
 * `JackGenerator` can only be initialized with a `StructType`, a `MapType` or an `ArrayType`.
 * Once it is initialized with `StructType`, it can be used to write out a struct or an array of
 * struct. Once it is initialized with `MapType`, it can be used to write out a map or an array
 * of map. An exception will be thrown if trying to write out a struct if it is initialized with
 * a `MapType`, and vice verse.
 */
private[sql] class JacksonGenerator(
    dataType: DataType,
    writer: Writer,
    options: JSONOptions) {
  // A `ValueWriter` is responsible for writing a field of an `InternalRow` to appropriate
  // JSON data. Here we are using `SpecializedGetters` rather than `InternalRow` so that
  // we can directly access data in `ArrayData` without the help of `SpecificMutableRow`.
  private type ValueWriter = (SpecializedGetters, Int) => Unit

  // `JackGenerator` can only be initialized with a `StructType`, a `MapType` or a `ArrayType`.
  require(dataType.isInstanceOf[StructType] || dataType.isInstanceOf[MapType]
    || dataType.isInstanceOf[ArrayType],
    s"JacksonGenerator only supports to be initialized with a ${StructType.simpleString}, " +
      s"${MapType.simpleString} or ${ArrayType.simpleString} but got ${dataType.catalogString}")

  // `ValueWriter`s for all fields of the schema
  private lazy val rootFieldWriters: Array[ValueWriter] = dataType match {
    case st: StructType => st.map(_.dataType).map(makeWriter).toArray
    case _ => throw QueryExecutionErrors.initialTypeNotTargetDataTypeError(
      dataType, StructType.simpleString)
  }

  // `ValueWriter` for array data storing rows of the schema.
  private lazy val arrElementWriter: ValueWriter = dataType match {
    case at: ArrayType => makeWriter(at.elementType)
    case _: StructType | _: MapType => makeWriter(dataType)
    case _ => throw QueryExecutionErrors.initialTypeNotTargetDataTypesError(dataType)
  }

  private lazy val mapElementWriter: ValueWriter = dataType match {
    case mt: MapType => makeWriter(mt.valueType)
    case _ => throw QueryExecutionErrors.initialTypeNotTargetDataTypeError(
      dataType, MapType.simpleString)
  }

  private val gen = {
    val generator = new JsonFactory().createGenerator(writer).setRootValueSeparator(null)
    if (options.pretty) {
      generator.setPrettyPrinter(new DefaultPrettyPrinter(""))
    }
    if (options.writeNonAsciiCharacterAsCodePoint) {
      generator.setHighestNonEscapedChar(0x7F)
    }
    generator
  }

  private val lineSeparator: String = options.lineSeparatorInWrite

  private val timestampFormatter = TimestampFormatter(
    options.timestampFormatInWrite,
    options.zoneId,
    options.locale,
    legacyFormat = FAST_DATE_FORMAT,
    isParsing = false)
  private val timestampNTZFormatter = TimestampFormatter(
    options.timestampNTZFormatInWrite,
    options.zoneId,
    legacyFormat = FAST_DATE_FORMAT,
    isParsing = false,
    forTimestampNTZ = true)
  private val dateFormatter = DateFormatter(
    options.dateFormatInWrite,
    options.locale,
    legacyFormat = FAST_DATE_FORMAT,
    isParsing = false)

  private def makeWriter(dataType: DataType): ValueWriter = dataType match {
    case NullType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNull()

    case BooleanType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeBoolean(row.getBoolean(ordinal))

    case ByteType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNumber(row.getByte(ordinal))

    case ShortType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNumber(row.getShort(ordinal))

    case IntegerType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNumber(row.getInt(ordinal))

    case LongType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNumber(row.getLong(ordinal))

    case FloatType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNumber(row.getFloat(ordinal))

    case DoubleType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNumber(row.getDouble(ordinal))

    case StringType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeString(row.getUTF8String(ordinal).toString)

    case TimestampType =>
      (row: SpecializedGetters, ordinal: Int) =>
        val timestampString = timestampFormatter.format(row.getLong(ordinal))
        gen.writeString(timestampString)

    case TimestampNTZType =>
      (row: SpecializedGetters, ordinal: Int) =>
      val timestampString =
        timestampNTZFormatter.format(DateTimeUtils.microsToLocalDateTime(row.getLong(ordinal)))
      gen.writeString(timestampString)

    case DateType =>
      (row: SpecializedGetters, ordinal: Int) =>
        val dateString = dateFormatter.format(row.getInt(ordinal))
        gen.writeString(dateString)

    case CalendarIntervalType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeString(row.getInterval(ordinal).toString)

    case YearMonthIntervalType(start, end) =>
      (row: SpecializedGetters, ordinal: Int) =>
        val ymString = IntervalUtils.toYearMonthIntervalString(
          row.getInt(ordinal),
          IntervalStringStyles.ANSI_STYLE,
          start,
          end)
        gen.writeString(ymString)

    case DayTimeIntervalType(start, end) =>
      (row: SpecializedGetters, ordinal: Int) =>
        val dtString = IntervalUtils.toDayTimeIntervalString(
          row.getLong(ordinal),
          IntervalStringStyles.ANSI_STYLE,
          start,
          end)
        gen.writeString(dtString)

    case BinaryType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeBinary(row.getBinary(ordinal))

    case dt: DecimalType =>
      (row: SpecializedGetters, ordinal: Int) =>
        gen.writeNumber(row.getDecimal(ordinal, dt.precision, dt.scale).toJavaBigDecimal)

    case st: StructType =>
      val fieldWriters = st.map(_.dataType).map(makeWriter)
      (row: SpecializedGetters, ordinal: Int) =>
        writeObject(writeFields(row.getStruct(ordinal, st.length), st, fieldWriters))

    case at: ArrayType =>
      val elementWriter = makeWriter(at.elementType)
      (row: SpecializedGetters, ordinal: Int) =>
        writeArray(writeArrayData(row.getArray(ordinal), elementWriter))

    case mt: MapType =>
      val valueWriter = makeWriter(mt.valueType)
      (row: SpecializedGetters, ordinal: Int) =>
        writeObject(writeMapData(row.getMap(ordinal), mt, valueWriter))

    // For UDT values, they should be in the SQL type's corresponding value type.
    // We should not see values in the user-defined class at here.
    // For example, VectorUDT's SQL type is an array of double. So, we should expect that v is
    // an ArrayData at here, instead of a Vector.
    case t: UserDefinedType[_] =>
      makeWriter(t.sqlType)

    case _ =>
      (row: SpecializedGetters, ordinal: Int) =>
        val v = row.get(ordinal, dataType)
        throw QueryExecutionErrors.failToConvertValueToJsonError(v, v.getClass, dataType)
  }

  private def writeObject(f: => Unit): Unit = {
    gen.writeStartObject()
    f
    gen.writeEndObject()
  }

  private def writeFields(
      row: InternalRow, schema: StructType, fieldWriters: Seq[ValueWriter]): Unit = {
    var i = 0
    while (i < row.numFields) {
      val field = schema(i)
      if (!row.isNullAt(i)) {
        gen.writeFieldName(field.name)
        fieldWriters(i).apply(row, i)
      } else if (!options.ignoreNullFields ||
        (options.writeNullIfWithDefaultValue && field.getExistenceDefaultValue().isDefined)) {
        gen.writeFieldName(field.name)
        gen.writeNull()
      }
      i += 1
    }
  }

  private def writeArray(f: => Unit): Unit = {
    gen.writeStartArray()
    f
    gen.writeEndArray()
  }

  private def writeArrayData(
      array: ArrayData, fieldWriter: ValueWriter): Unit = {
    var i = 0
    while (i < array.numElements()) {
      if (!array.isNullAt(i)) {
        fieldWriter.apply(array, i)
      } else {
        gen.writeNull()
      }
      i += 1
    }
  }

  private def writeMapData(
      map: MapData, mapType: MapType, fieldWriter: ValueWriter): Unit = {
    val keyArray = map.keyArray()
    val valueArray = map.valueArray()
    var i = 0
    while (i < map.numElements()) {
      gen.writeFieldName(keyArray.get(i, mapType.keyType).toString)
      if (!valueArray.isNullAt(i)) {
        fieldWriter.apply(valueArray, i)
      } else {
        gen.writeNull()
      }
      i += 1
    }
  }

  def close(): Unit = gen.close()

  def flush(): Unit = gen.flush()

  /**
   * Transforms a single `InternalRow` to JSON object using Jackson.
   * This api calling will be validated through accessing `rootFieldWriters`.
   *
   * @param row The row to convert
   */
  def write(row: InternalRow): Unit = {
    writeObject(writeFields(
      fieldWriters = rootFieldWriters,
      row = row,
      schema = dataType.asInstanceOf[StructType]))
  }

  /**
   * Transforms multiple `InternalRow`s or `MapData`s to JSON array using Jackson
   *
   * @param array The array of rows or maps to convert
   */
  def write(array: ArrayData): Unit = writeArray(writeArrayData(array, arrElementWriter))

  /**
   * Transforms a single `MapData` to JSON object using Jackson
   * This api calling will will be validated through accessing `mapElementWriter`.
   *
   * @param map a map to convert
   */
  def write(map: MapData): Unit = {
    writeObject(writeMapData(
      fieldWriter = mapElementWriter,
      map = map,
      mapType = dataType.asInstanceOf[MapType]))
  }

  def writeLineEnding(): Unit = {
    // Note that JSON uses writer with UTF-8 charset. This string will be written out as UTF-8.
    gen.writeRaw(lineSeparator)
  }
}


text:
package com.intellij.openapi.ui;

import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.ui.UIUtil;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class ComboBoxWithWidePopup<E> extends JComboBox<E> {

  private boolean myLayingOut = false;
  private int myMinLength = 20;

  public ComboBoxWithWidePopup(final ComboBoxModel<E> aModel) {
    super(aModel);

    if (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel()) setMaximumRowCount(25);
  }

  public ComboBoxWithWidePopup(final E[] items) {
    super(items);

    if (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel()) setMaximumRowCount(25);
  }

  public ComboBoxWithWidePopup(final Vector<E> items) {
    super(items);

    if (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel()) setMaximumRowCount(25);
  }

  public ComboBoxWithWidePopup() {
  }

  @SuppressWarnings("GtkPreferredJComboBoxRenderer")
  @Override
  public void setRenderer(ListCellRenderer renderer) {
    super.setRenderer(new AdjustingListCellRenderer(this, renderer));
  }

  public void setMinLength(int minLength) {
    myMinLength = minLength;
  }

  /**
   * @return min string len to show
   */
  protected int getMinLength() {
    return myMinLength;
  }

  public void doLayout() {
    try {
      myLayingOut = true;
      super.doLayout();
    }
    finally {
      myLayingOut = false;
    }
  }

  public Dimension getSize() {
    Dimension size = super.getSize();
    if (!myLayingOut) {
      size.width = Math.max(size.width, getOriginalPreferredSize().width);
    }
    return size;
  }

  private Dimension _getSuperSize() {
    return super.getSize();
  }

  protected Dimension getOriginalPreferredSize() {
    return getPreferredSize();
  }

  /**
   * @return minimum width of a popup that is wide enough to show all the combobox's items horizontally
   */
  public int getMinimumPopupWidth() {
    // Original preferred size of JComboBox is calculated as max of all pref sizes of combobox's items.
    // See javax.swing.plaf.basic.BasicComboBoxUI#getDisplaySize()
    //
    // Please note that "getPreferredSize().width" cannot be used as getPreferredSize might be overridden
    // to return a value different to "max of all pref sizes of comboBox's items".
    return super.getPreferredSize().width;
  }

  private class AdjustingListCellRenderer implements ListCellRenderer {
    private final ListCellRenderer myOldRenderer;
    private final ComboBoxWithWidePopup myComboBox;

    public AdjustingListCellRenderer(ComboBoxWithWidePopup comboBox, ListCellRenderer oldRenderer) {
      myComboBox = comboBox;
      myOldRenderer = oldRenderer;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      Object _value = value;
      if (index == -1 && _value instanceof String && !myComboBox.isValid()) {
        int minLength = getMinLength();

        Dimension size = myComboBox._getSuperSize();
        String stringValue = (String)_value;

        if (size.width == 0) {
          if (stringValue.length() > minLength) {
            _value = stringValue.substring(0, minLength);
          }
        }
      }

      return myOldRenderer.getListCellRendererComponent(list, _value, index, isSelected, cellHasFocus);
    }
  }
}


text:
package org.ice4j.stack;

import org.ice4j.*;

/**
 * The interface is used for collecting incoming Peer UDP Message messages from
 * the NetAccessManager (and more precisely - MessageProcessors) if it is of no
 * other type. This is our way of keeping scalable network and stun layers.
 *
 * @author Aakash Garg
 */
public interface PeerUdpMessageEventHandler
{
    /**
     * Called when an incoming Peer UDP message has been received, parsed
     * and is ready for delivery.
     *
     * @param messageEvent the event object that encapsulates the newly received
     *                     message.
     */
    public void handleMessageEvent(PeerUdpMessageEvent messageEvent);
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Entity.cs" company="nGratis">
//   The MIT License (MIT)
//
//   Copyright (c) 2014 - 2015 Cahya Ong
//
//   Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
//   associated documentation files (the "Software"), to deal in the Software without restriction, including
//   without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
//   following conditions:
//
//   The above copyright notice and this permission notice shall be included in all copies or substantial
//   portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
//   LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
//   EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
//   THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <author>Cahya Ong - cahya.ong@gmail.com</author>
// <creation_timestamp>Saturday, 1 August 2015 1:49:11 AM UTC</creation_timestamp>
// --------------------------------------------------------------------------------------------------------------------

namespace nGratis.Cop.Gaia.Engine
{
    public class Entity : IEntity
    {
        public Entity(uint id, uint templateId)
            : this(id, 0, templateId)
        {
        }

        public Entity(uint id, uint ownerId, uint templateId)
        {
            this.Id = id;
            this.OwnerId = ownerId;
            this.TemplateId = templateId;
        }

        public uint Id { get; private set; }

        public uint OwnerId { get; set; }

        public uint TemplateId { get; private set; }
    }
}


text:
package org.jtheque.core;

import org.jtheque.utils.annotations.ThreadSafe;
import org.jtheque.utils.bean.IntDate;

/**
 * A core configuration specification.
 *
 * @author Baptiste Wicht
 */
@ThreadSafe
public interface CoreConfiguration {
    /**
     * Indicate if we verify the updates at the application startup.
     *
     * @return true if verify updates on startup else false
     */
    boolean verifyUpdateOnStartup();

    /**
     * Set if we must verify the updates on startup.
     *
     * @param value A boolean tag indicating if we must verify updates on startup.
     */
    void setVerifyUpdateOnStartup(boolean value);

    /**
     * Indicate if we must retain the size of the windows.
     *
     * @return true if we must retain the size of the windows else false
     */
    boolean retainSizeAndPositionOfWindow();

    /**
     * Set if we must retain the size of the window.
     *
     * @param value A boolean tag indicating if we must retain the size of the window.
     */
    void setRetainSizeAndPositionOfWindow(boolean value);

    /**
     * Indicate if there is a proxy or not.
     *
     * @return true if there is a proxy else false
     */
    boolean hasAProxy();

    /**
     * Set if there is a proxy or not.
     *
     * @param value A boolean tag indicating if there is a proxy or not.
     */
    void setHasAProxy(boolean value);

    /**
     * Return the port number of the proxy.
     *
     * @param value The port number of the proxy.
     */
    void setProxyPort(String value);

    /**
     * Return the port number of the proxy.
     *
     * @return The port number of the proxy.
     */
    String getProxyPort();

    /**
     * Set the address of the proxy.
     *
     * @param value The address of the proxy.
     */
    void setProxyAddress(String value);

    /**
     * Return the address of the proxy.
     *
     * @return The address of the proxy.
     */
    String getProxyAddress();

    /**
     * Set the email of the user.
     *
     * @param value The new email to set
     */
    void setUserEmail(String value);

    /**
     * Return the email of the user.
     *
     * @return The email
     */
    String getUserEmail();

    /**
     * Set the SMTP host.
     *
     * @param value The new SMTP host.
     */
    void setSmtpHost(String value);

    /**
     * Return the SMTP host.
     *
     * @return The SMTP host.
     */
    String getSmtpHost();

    /**
     * Set the last used collection.
     *
     * @param value The name of the last collection.
     */
    void setLastCollection(String value);

    /**
     * Return the last used collection.
     *
     * @return The last used collection.
     */
    String getLastCollection();

    /**
     * Return the date of the last reading of the messages.
     *
     * @return The date of the last reading of the messages.
     */
    IntDate getMessagesLastRead();
}


text:
use math;
use math::{Point2, Point3, Point4};
use noise_fns::{MultiFractal, NoiseFn, Perlin, Seedable};
use std;

/// Noise function that outputs heterogenous Multifractal noise.
///
/// This is a multifractal method, meaning that it has a fractal dimension
/// that varies with location.
///
/// The result of this multifractal method is that in areas near zero, higher
/// frequencies will be heavily damped, resulting in the terrain remaining
/// smooth. As the value moves further away from zero, higher frequencies will
/// not be as damped and thus will grow more jagged as iteration progresses.
///
#[derive(Clone, Debug)]
pub struct BasicMulti {
    /// Total number of frequency octaves to generate the noise with.
    ///
    /// The number of octaves control the _amount of detail_ in the noise
    /// function. Adding more octaves increases the detail, with the drawback
    /// of increasing the calculation time.
    pub octaves: usize,

    /// The number of cycles per unit length that the noise function outputs.
    pub frequency: f64,

    /// A multiplier that determines how quickly the frequency increases for
    /// each successive octave in the noise function.
    ///
    /// The frequency of each successive octave is equal to the product of the
    /// previous octave's frequency and the lacunarity value.
    ///
    /// A lacunarity of 2.0 results in the frequency doubling every octave. For
    /// almost all cases, 2.0 is a good value to use.
    pub lacunarity: f64,

    /// A multiplier that determines how quickly the amplitudes diminish for
    /// each successive octave in the noise function.
    ///
    /// The amplitude of each successive octave is equal to the product of the
    /// previous octave's amplitude and the persistence value. Increasing the
    /// persistence produces "rougher" noise.
    pub persistence: f64,

    seed: u32,
    sources: Vec<Perlin>,
}

impl BasicMulti {
    pub const DEFAULT_SEED: u32 = 0;
    pub const DEFAULT_OCTAVES: usize = 6;
    pub const DEFAULT_FREQUENCY: f64 = 2.0;
    pub const DEFAULT_LACUNARITY: f64 = std::f64::consts::PI * 2.0 / 3.0;
    pub const DEFAULT_PERSISTENCE: f64 = 0.5;
    pub const MAX_OCTAVES: usize = 32;

    pub fn new() -> Self {
        BasicMulti {
            seed: Self::DEFAULT_SEED,
            octaves: Self::DEFAULT_OCTAVES,
            frequency: Self::DEFAULT_FREQUENCY,
            lacunarity: Self::DEFAULT_LACUNARITY,
            persistence: Self::DEFAULT_PERSISTENCE,
            sources: super::build_sources(Self::DEFAULT_SEED, Self::DEFAULT_OCTAVES),
        }
    }
}

impl Default for BasicMulti {
    fn default() -> Self {
        Self::new()
    }
}

impl MultiFractal for BasicMulti {
    fn set_octaves(self, mut octaves: usize) -> Self {
        if self.octaves == octaves {
            return self;
        }

        octaves = math::clamp(octaves, 1, Self::MAX_OCTAVES);
        BasicMulti {
            octaves,
            sources: super::build_sources(self.seed, octaves),
            ..self
        }
    }

    fn set_frequency(self, frequency: f64) -> Self {
        BasicMulti { frequency, ..self }
    }

    fn set_lacunarity(self, lacunarity: f64) -> Self {
        BasicMulti { lacunarity, ..self }
    }

    fn set_persistence(self, persistence: f64) -> Self {
        BasicMulti {
            persistence,
            ..self
        }
    }
}

impl Seedable for BasicMulti {
    fn set_seed(self, seed: u32) -> Self {
        if self.seed == seed {
            return self;
        }

        BasicMulti {
            seed,
            sources: super::build_sources(seed, self.octaves),
            ..self
        }
    }

    fn seed(&self) -> u32 {
        self.seed
    }
}

/// 2-dimensional `BasicMulti` noise
impl NoiseFn<Point2<f64>> for BasicMulti {
    fn get(&self, mut point: Point2<f64>) -> f64 {
        // First unscaled octave of function; later octaves are scaled.
        point = math::mul2(point, self.frequency);
        let mut result = self.sources[0].get(point);

        // Spectral construction inner loop, where the fractal is built.
        for x in 1..self.octaves {
            // Raise the spatial frequency.
            point = math::mul2(point, self.lacunarity);

            // Get noise value.
            let mut signal = self.sources[x].get(point);

            // Scale the amplitude appropriately for this frequency.
            signal *= self.persistence.powi(x as i32);

            // Scale the signal by the current 'altitude' of the function.
            signal *= result;

            // Add signal to result.
            result += signal;
        }

        // Scale the result to the [-1,1] range.
        result * 0.5
    }
}

/// 3-dimensional `BasicMulti` noise
impl NoiseFn<Point3<f64>> for BasicMulti {
    fn get(&self, mut point: Point3<f64>) -> f64 {
        // First unscaled octave of function; later octaves are scaled.
        point = math::mul3(point, self.frequency);
        let mut result = self.sources[0].get(point);

        // Spectral construction inner loop, where the fractal is built.
        for x in 1..self.octaves {
            // Raise the spatial frequency.
            point = math::mul3(point, self.lacunarity);

            // Get noise value.
            let mut signal = self.sources[x].get(point);

            // Scale the amplitude appropriately for this frequency.
            signal *= self.persistence.powi(x as i32);

            // Scale the signal by the current 'altitude' of the function.
            signal *= result;

            // Add signal to result.
            result += signal;
        }

        // Scale the result to the [-1,1] range.
        result * 0.5
    }
}

/// 4-dimensional `BasicMulti` noise
impl NoiseFn<Point4<f64>> for BasicMulti {
    fn get(&self, mut point: Point4<f64>) -> f64 {
        // First unscaled octave of function; later octaves are scaled.
        point = math::mul4(point, self.frequency);
        let mut result = self.sources[0].get(point);

        // Spectral construction inner loop, where the fractal is built.
        for x in 1..self.octaves {
            // Raise the spatial frequency.
            point = math::mul4(point, self.lacunarity);

            // Get noise value.
            let mut signal = self.sources[x].get(point);

            // Scale the amplitude appropriately for this frequency.
            signal *= self.persistence.powi(x as i32);

            // Scale the signal by the current 'altitude' of the function.
            signal *= result;

            // Add signal to result.
            result += signal;
        }

        // Scale the result to the [-1,1] range.
        result * 0.5
    }
}


text:
/**
 * generated by Xtext 2.10.0
 */
package com.laegler.stubbr.lang.stubbrLang.impl;

import com.laegler.stubbr.lang.stubbrLang.Element;
import com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

/**
 *
 * An implementation of the model object 'Element'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.ElementImpl#getWidth Width}

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.ElementImpl#getHeight Height}

 *

 *
 * @generated
 */
public class ElementImpl extends UiElementImpl implements Element
{
  /**
   * The default value of the '{@link #getWidth() Width}' attribute.
   *
   *
   * @see #getWidth()
   * @generated
   * @ordered
   */
  protected static final int WIDTH_EDEFAULT = 0;

  /**
   * The cached value of the '{@link #getWidth() Width}' attribute.
   *
   *
   * @see #getWidth()
   * @generated
   * @ordered
   */
  protected int width = WIDTH_EDEFAULT;

  /**
   * The default value of the '{@link #getHeight() Height}' attribute.
   *
   *
   * @see #getHeight()
   * @generated
   * @ordered
   */
  protected static final int HEIGHT_EDEFAULT = 0;

  /**
   * The cached value of the '{@link #getHeight() Height}' attribute.
   *
   *
   * @see #getHeight()
   * @generated
   * @ordered
   */
  protected int height = HEIGHT_EDEFAULT;

  /**
   *
   *
   * @generated
   */
  protected ElementImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return StubbrLangPackage.eINSTANCE.getElement();
  }

  /**
   *
   *
   * @generated
   */
  public int getWidth()
  {
    return width;
  }

  /**
   *
   *
   * @generated
   */
  public void setWidth(int newWidth)
  {
    int oldWidth = width;
    width = newWidth;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ELEMENT__WIDTH, oldWidth, width));
  }

  /**
   *
   *
   * @generated
   */
  public int getHeight()
  {
    return height;
  }

  /**
   *
   *
   * @generated
   */
  public void setHeight(int newHeight)
  {
    int oldHeight = height;
    height = newHeight;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ELEMENT__HEIGHT, oldHeight, height));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ELEMENT__WIDTH:
        return getWidth();
      case StubbrLangPackage.ELEMENT__HEIGHT:
        return getHeight();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ELEMENT__WIDTH:
        setWidth((Integer)newValue);
        return;
      case StubbrLangPackage.ELEMENT__HEIGHT:
        setHeight((Integer)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ELEMENT__WIDTH:
        setWidth(WIDTH_EDEFAULT);
        return;
      case StubbrLangPackage.ELEMENT__HEIGHT:
        setHeight(HEIGHT_EDEFAULT);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ELEMENT__WIDTH:
        return width != WIDTH_EDEFAULT;
      case StubbrLangPackage.ELEMENT__HEIGHT:
        return height != HEIGHT_EDEFAULT;
    }
    return super.eIsSet(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    if (eIsProxy()) return super.toString();

    StringBuffer result = new StringBuffer(super.toString());
    result.append(" (width: ");
    result.append(width);
    result.append(", height: ");
    result.append(height);
    result.append(')');
    return result.toString();
  }

} //ElementImpl


text:
<?php

class TexyRegexp
{
	const ALL = 1;
	const OFFSET_CAPTURE = 2;

	private static $messages = array(
		PREG_INTERNAL_ERROR => 'Internal error',
		PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
		PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
		PREG_BAD_UTF8_ERROR => 'Malformed UTF-8 data',
		5 => 'Offset didn\'t correspond to the begin of a valid UTF-8 code point', // PREG_BAD_UTF8_OFFSET_ERROR
	);

	/**
	 * Splits string by a regular expression.
	 * @param  string
	 * @param  string
	 * @param  int  OFFSET_CAPTURE
	 * @return array
	 */
	public static function split($subject, $pattern, $flags = 0)
	{
		$reFlags = (($flags & self::OFFSET_CAPTURE) ? PREG_SPLIT_OFFSET_CAPTURE : 0) | PREG_SPLIT_DELIM_CAPTURE;
		$res = preg_split($pattern, $subject, -1, $reFlags);
		if (preg_last_error()) { // run-time error
			trigger_error(@self::$messages[preg_last_error()], E_USER_WARNING);
		}
		return $res;
	}

	/**
	 * Performs a regular expression match.
	 * @param  string
	 * @param  string
	 * @param  int  OFFSET_CAPTURE, ALL
	 * @param  int  offset in bytes
	 * @return mixed
	 */
	public static function match($subject, $pattern, $flags = 0, $offset = 0)
	{
		$empty = $flags & self::ALL ? array() : NULL;
		if ($offset > strlen($subject)) {
			return $empty;
		}
		$reFlags = ($flags & self::OFFSET_CAPTURE) ? PREG_OFFSET_CAPTURE : 0;
		if ($flags & self::ALL) {
			$res = preg_match_all($pattern, $subject, $m, $reFlags | PREG_SET_ORDER, $offset);
		} else {
			$res = preg_match($pattern, $subject, $m, $reFlags, $offset);
		}
		if (preg_last_error()) { // run-time error
			trigger_error(@self::$messages[preg_last_error()], E_USER_WARNING);
		} elseif ($res) {
			return $m;
		}
		return $empty;
	}

	/**
	 * Perform a regular expression search and replace.
	 * @param  string
	 * @param  string|array
	 * @param  string|callable
	 * @return string
	 */
	public static function replace($subject, $pattern, $replacement = NULL)
	{
		if (is_object($replacement) || is_array($replacement)) {
			$res = preg_replace_callback($pattern, $replacement, $subject);
			if ($res === NULL && preg_last_error()) { // run-time error
				trigger_error(@self::$messages[preg_last_error()], E_USER_WARNING);
			}
			return $res;

		} elseif ($replacement === NULL && is_array($pattern)) {
			$replacement = array_values($pattern);
			$pattern = array_keys($pattern);
		}

		$res = preg_replace($pattern, $replacement, $subject);
		if (preg_last_error()) { // run-time error
			trigger_error(@self::$messages[preg_last_error()], E_USER_WARNING);
		}
		return $res;
	}

}


text:
interface Fiber {
    reset: () => any;
    run: (param?: any) => any;
    throwInto: (ex: any) => any;
}

declare module "fibers" {

    function Fiber(fn: Function): Fiber;

    namespace Fiber {
        export var current: Fiber;
        export function yield(value?: any): any
    }

    export = Fiber;
}

declare module "fibers/future" {

    class Future {
        constructor();
        detach(): void;
        get(): any;
        isResolved (): boolean;
        proxy(future: Future): void;
        proxyErrors(futureOrList: any): Future;
        resolver(): Function;
        resolve(fn: Function): void;
        resolveSuccess(fn: Function): void;
        return(result?: any): void;
        throw (error: any): void;
        wait (): void;
        static wait(future: Future);
        static wait(future_list: Future[]);
        static wrap(fn: Function): Future
    }

    export = Future;
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel;
using IdentityServer.UnitTests.Common;
using IdentityServer4;
using IdentityServer4.Configuration;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Xunit;

namespace IdentityServer.UnitTests.ResponseHandling.AuthorizeInteractionResponseGenerator
{
    public class AuthorizeInteractionResponseGeneratorTests_Login
    {
        private IdentityServerOptions _options = new IdentityServerOptions();
        private IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator _subject;
        private MockConsentService _mockConsentService = new MockConsentService();
        private StubClock _clock = new StubClock();

        public AuthorizeInteractionResponseGeneratorTests_Login()
        {
            _subject = new IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator(
                _clock,
                TestLogger.Create<IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator>(),
                _mockConsentService,
                new MockProfileService());
        }

        [Fact]
        public async Task Anonymous_User_must_SignIn()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Subject = Principal.Anonymous
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeTrue();
        }

        [Fact]
        public async Task Authenticated_User_must_not_SignIn()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Client = new Client(),
                ValidatedResources = new ResourceValidationResult(),
                Subject = new IdentityServerUser("123")
                {
                    IdentityProvider = IdentityServerConstants.LocalIdentityProvider
                }.CreatePrincipal()
            };

            var result = await _subject.ProcessInteractionAsync(request);

            result.IsLogin.Should().BeFalse();
        }

        [Fact]
        public async Task Authenticated_User_with_allowed_current_Idp_must_not_SignIn()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Subject = new IdentityServerUser("123") {
                    IdentityProvider = IdentityServerConstants.LocalIdentityProvider
                }.CreatePrincipal(),
                Client = new Client
                {
                    IdentityProviderRestrictions = new List<string>
                    {
                        IdentityServerConstants.LocalIdentityProvider
                    }
                }
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeFalse();
        }

        [Fact]
        public async Task Authenticated_User_with_restricted_current_Idp_must_SignIn()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Subject = new IdentityServerUser("123")
                {
                    IdentityProvider = IdentityServerConstants.LocalIdentityProvider
                }.CreatePrincipal(),
                Client = new Client
                {
                    EnableLocalLogin = false,
                    IdentityProviderRestrictions = new List<string>
                    {
                        "some_idp"
                    }
                }
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeTrue();
        }

        [Fact]
        public async Task Authenticated_User_with_allowed_requested_Idp_must_not_SignIn()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Client = new Client(),
                 AuthenticationContextReferenceClasses = new List<string>{
                    "idp:" + IdentityServerConstants.LocalIdentityProvider
                },
                Subject = new IdentityServerUser("123")
                {
                    IdentityProvider = IdentityServerConstants.LocalIdentityProvider
                }.CreatePrincipal()
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeFalse();
        }

        [Fact]
        public async Task Authenticated_User_with_different_requested_Idp_must_SignIn()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Client = new Client(),
                AuthenticationContextReferenceClasses = new List<string>{
                    "idp:some_idp"
                },
                Subject = new IdentityServerUser("123")
                {
                    IdentityProvider = IdentityServerConstants.LocalIdentityProvider
                }.CreatePrincipal()
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeTrue();
        }

        [Fact]
        public async Task Authenticated_User_within_client_user_sso_lifetime_should_not_signin()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Client = new Client() {
                    UserSsoLifetime = 3600 // 1h
                },
                Subject = new IdentityServerUser("123")
                {
                    IdentityProvider = "local",
                    AuthenticationTime = _clock.UtcNow.UtcDateTime.Subtract(TimeSpan.FromSeconds(10))
                }.CreatePrincipal()
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeFalse();
        }

        [Fact]
        public async Task Authenticated_User_beyond_client_user_sso_lifetime_should_signin()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Client = new Client()
                {
                    UserSsoLifetime = 3600 // 1h
                },
                Subject = new IdentityServerUser("123")
                {
                    IdentityProvider = "local",
                    AuthenticationTime = _clock.UtcNow.UtcDateTime.Subtract(TimeSpan.FromSeconds(3700))
                }.CreatePrincipal()
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeTrue();
        }

        [Fact]
        public async Task locally_authenticated_user_but_client_does_not_allow_local_should_sign_in()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Client = new Client()
                {
                    EnableLocalLogin = false
                },
                Subject = new IdentityServerUser("123")
                {
                    IdentityProvider = IdentityServerConstants.LocalIdentityProvider
                }.CreatePrincipal()
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeTrue();
        }

        [Fact]
        public async Task prompt_login_should_sign_in()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Subject = new IdentityServerUser("123").CreatePrincipal(),
                PromptModes = new[] { OidcConstants.PromptModes.Login },
                Raw = new NameValueCollection()
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeTrue();
        }

        [Fact]
        public async Task prompt_select_account_should_sign_in()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Subject = new IdentityServerUser("123").CreatePrincipal(),
                PromptModes = new[] { OidcConstants.PromptModes.SelectAccount },
                Raw = new NameValueCollection()
            };

            var result = await _subject.ProcessLoginAsync(request);

            result.IsLogin.Should().BeTrue();
        }

        [Fact]
        public async Task prompt_for_signin_should_remove_prompt_from_raw_url()
        {
            var request = new ValidatedAuthorizeRequest
            {
                ClientId = "foo",
                Subject = new IdentityServerUser("123").CreatePrincipal(),
                PromptModes = new[] { OidcConstants.PromptModes.Login },
                Raw = new NameValueCollection
                {
                    { OidcConstants.AuthorizeRequest.Prompt, OidcConstants.PromptModes.Login }
                }
            };

            var result = await _subject.ProcessLoginAsync(request);

            request.Raw.AllKeys.Should().NotContain(OidcConstants.AuthorizeRequest.Prompt);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 450 (1898)

#### Original name
Uromyces pontederiae Speg.

### Remarks
null


text:
<?php
namespace Pbc\Bandolier\Exception\Writable;

class LocationDoesExist extends WritableLocation {

    /**
     * @param string $message
     * @param int $code
     * @return void
     */
    public function __construct($message = '', $code = 0) {
        parent::__construct($message, $code);
    }
}


text:
#if !KEYVALUEPAIR_CREATE
namespace System.Collections.Generic
{
    internal static class KeyValuePair
    {
        public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value) => new KeyValuePair<TKey, TValue>(key, value);
    }
}
#endif


text:
package co.edu.uniandes.csw.artwork.api;

import co.edu.uniandes.csw.artwork.entities.QualifyEntity;
import java.util.List;

public interface IQualifyLogic {
    public List<QualifyEntity> getQualifys(Long artworkId);
    public QualifyEntity addQualify(Long artworkId, Long clientId, QualifyEntity entity);
}


text:
require File.dirname(__FILE__) + "/../spec_helper"

describe SiteNode do

  reset_domain_tables :site_nodes, :content_types, :content_nodes,  :site_versions, :site_node_modifiers, :end_user
  before(:each) do
    @version = SiteVersion.create(:name => 'Default')
  end

  it "should be able to create the SiteNode content type" do
    ContentType.count.should == 0
    Editor::AdminController.content_node_type_generate

    ct = ContentType.find_by_content_type('SiteNode')

    ct.content_name.should == 'Static Pages'
    ct.component.should == 'editor'
  end

  it "should create and destroy a content_node when created" do
    Editor::AdminController.content_node_type_generate

    # Should create a site node on create
    lambda {
     @page_node = SiteNode.create(:node_type => 'P', :title => 'test_page',:site_version_id => @version.id)
    }.should change { ContentNode.count }.by(1)

    # And delete it on delete
    lambda {
     @page_node.destroy
    }.should change { ContentNode.count }.by(-1)

  end

  it "should update a content node when a new revision is made real" do
    Editor::AdminController.content_node_type_generate

    # Should create a site node on create
    lambda {
     @page_node = SiteNode.create(:node_type => 'P', :title => 'test_page',:site_version_id => @version.id)
    }.should change { ContentNode.count }.by(1)

    # Cheat to create make sure the time is updated
    ContentNode.update_all(:updated_at => Time.now - 10.minutes)
    @page_node.reload
    node_updated_at = @page_node.content_node.updated_at

    rev = @page_node.active_revisions[0].create_temporary
    rev.make_real

    @page_node.reload
    @page_node.content_node.updated_at.should_not == node_updated_at
  end

  it "should be able to create a new version and get a root node" do

    @version.should be_valid

    # Should be able to get the root node which automatically
    # generates a home page
    nd = @version.root_node
    nd.should be_valid

    nd.parent_id.should be_nil
    nd.children.length.should == 1
  end

  it "should be able to add modifiers to nodes" do
    nd = @version.root_node.add_subpage('about')

    assert_difference('SiteNodeModifier.count', 2) do
      nd.add_modifier('framework')
      nd.add_modifier('template')
    end
  end

  it "should be able to get a menu of nodes" do
    news = @version.root_node.add_subpage('news')
    group = @version.root_node.add_subpage('group', 'G')
    page1 = group.add_subpage('page1')
    page2 = group.add_subpage('page2')
    page3 = group.add_subpage('page3')

    @version.root_node.menu.should == [@version.root_node]
    news.menu.should == [news]
    group.menu.should == [page1, page2, page3]
  end

  it "should be able to get the nested pages" do
    news = @version.root_node.add_subpage('news')
    group = news.add_subpage('group', 'G')
    page1 = group.add_subpage('page1')
    page2 = group.add_subpage('page2')
    page3 = group.add_subpage('page3')
    about = @version.root_node.add_subpage('about')
    home = @version.site_nodes.with_type('P').find_by_title('')

    @version.root_node.child_cache.should == []

    @version.root_node.reload
    @version.root_node.nested_pages [group.id]

    @version.root_node.child_cache.should == [home, news, about]
    @version.root_node.child_cache[0].should == home
    @version.root_node.child_cache[0].child_cache.should == []
    @version.root_node.child_cache[1].should == news
    @version.root_node.child_cache[1].child_cache.should == [group]
    @version.root_node.child_cache[2].should == about
    @version.root_node.child_cache[2].child_cache.should == []

    @version.root_node.child_cache[1].child_cache[0].should == group
    @version.root_node.child_cache[1].child_cache[0].child_cache.should == [page1, page2, page3]
    @version.root_node.child_cache[1].child_cache[0].closed.should be_true

    SiteNode.find_page(group.id).should be_nil
    SiteNode.find_page(about.id).should == about

    SiteNode.node_path(@version.root_node.id).should == 'Domain'
    SiteNode.node_path(group.id).should == '/'
    SiteNode.node_path(about.id).should == '/about'
    SiteNode.node_path(-1, '/missing').should == '/missing'
  end

  it "should be able to create node paths" do
    SiteNode.generate_node_path(' Page   (1)   ...').should == 'page-1'
    SiteNode.generate_node_path(' _Page-_   (1)   ...').should == '-page-1'
  end

  it "should be able to create new revisions" do
    news = @version.root_node.add_subpage('news')
    rv = news.active_revision('en')
    rv.title = 'My News'
    rv.save

    news.new_revision do |rv|
      rv.title = 'Changed News Title'
    end

    news.reload
    news.active_revision('en').title.should == 'Changed News Title'
    news.name.should == 'Changed News Title'
    news.content_description('en').should == 'Site Page - /news'
    news.page_type.should == 'page'
    SiteNode.send(:content_admin_url, news.id).should == {:controller => '/edit', :action => 'page', :path => ['page', news.id]}
    news.send(:content_node_body, 'es').should be_nil
  end

  it "should be able to set group node options" do
    news = @version.root_node.add_subpage('news')
    group = news.add_subpage('group', 'G')

    news.node_options.to_hash.should == {}

    group.node_options.closed.should be_false

    group.set_node_options :closed => true

    group = SiteNode.find_by_id(group.id)

    group.node_options.closed.should be_true
  end

  it "should be able to fetch all paragraphs from frameworks" do
    para1 = nil
    para2 = nil
    news = @version.root_node.add_subpage('news')
    framework = news.add_modifier('framework') do |md|
      md.new_revision do |rv|
        para1 = rv.push_paragraph '/editor/auth', 'login', {}, :zone => 3
      end
    end

    template = news.add_modifier('template')

    @version.root_node.add_modifier('framework') do |md|
      md.new_revision do |rv|
        para2 = rv.push_paragraph '/editor/auth', 'login', {}, :zone => 1
      end
    end

    template = @version.root_node.add_modifier('template')
    template.modifier_data[:clear_frameworks] = 'yes'
    template.save

    news.reload
    news.full_framework_paragraphs('en').should == [para2, para1]
  end
end


text:
FROM java:openjdk-8-jre
ENV TERM=xterm-256color

# Change working directory to /usr/mtdnaserver/
WORKDIR /usr/mtdnaserver

# Download haplocheckCLI.jar
RUN wget https://github.com/leklab/haplocheckCLI/raw/master/haplocheckCLI.jar


text:
package org.hawkular.client.android.util;

import java.util.Random;
import java.util.UUID;

import android.support.annotation.NonNull;

public final class Randomizer {
    private Randomizer() {
    }

    private static final class Limits {
        private Limits() {
        }

        public static final int NUMBER = 42;
    }

    public static long generateNumber() {
        return new Random().nextInt(Limits.NUMBER);
    }

    @NonNull
    public static String generateString() {
        return UUID.randomUUID().toString();
    }
}


text:
<?php

namespace Symfony\Tests\Component\Security\Core\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Role\Role;

class UsernamePasswordTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $this->assertFalse($token->isAuthenticated());

        $token = new UsernamePasswordToken('foo', 'bar', 'key', array('ROLE_FOO'));
        $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
        $this->assertTrue($token->isAuthenticated());
        $this->assertEquals('key', $token->getProviderKey());
    }

    /**
     * @expectedException LogicException
     */
    public function testSetAuthenticatedToTrue()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $token->setAuthenticated(true);
    }

    public function testSetAuthenticatedToFalse()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $token->setAuthenticated(false);
        $this->assertFalse($token->isAuthenticated());
    }

    public function testEraseCredentials()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $token->eraseCredentials();
        $this->assertEquals('', $token->getCredentials());
    }
}


text:
			{group_label}{required}
{fields}
				{field}{label} {fields}

			{description}{error_msg}


text:
import './SunBurst.css';
import { groupBy, map, each } from 'lodash';
import { formatL1, formatType, formatScripture } from '../constants';

// Dimensions of sunburst.
var width = 750;
var height = 600;
var radius = Math.min(width, height) / 2;

// Breadcrumb dimensions: width, height, spacing, width of tip/tail.
var b = {
	w: 150,
	h: 30,
	s: 3,
	t: 10
};

// Mapping of step names to colors.
var colors = {
	"Scriptures": "#193441",
	"Scriptures L2": "#3E606F",
	"Scriptures L3": "#91AA9D",
	"Scriptures L4": "#D1DBBD",
	"General Conference": "#002F2F",
	"General Conference L2": "#046380",
	"General Conference L3": "#EFECCA",
	"Ensign": "#33332D",
	"Ensign L2": "#5B7876",
	"Ensign L3": "#8F9E8B"
};

// Total size of all segments; we set this later, after loading the data.
var totalSize = 0;

var vis = d3.select("#chart").append("svg:svg")
	.attr("width", width)
	.attr("height", height)
	.append("svg:g")
	.attr("id", "container")
	.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var partition = d3.layout.partition()
	.size([2 * Math.PI, radius * radius])
	.value(function(d) {
		return d.size;
	});

var arc = d3.svg.arc()
	.startAngle(function(d) {
		return d.x;
	})
	.endAngle(function(d) {
		return d.x + d.dx;
	})
	.innerRadius(function(d) {
		return Math.sqrt(d.y);
	})
	.outerRadius(function(d) {
		return Math.sqrt(d.y + d.dy);
	});

export function renderSunBurst(content) {
	// Use d3.text and d3.csv.parseRows so that we do not need to have a header
	// row, and can receive the csv as an array of arrays.
	let json = buildStudyHierarchy(content);
	createVisualization(json);
}

function buildStudyHierarchy(content) {
	let heirarch = {
		name: 'root',
		children: []
	};

	// Initially group by content study type
	let groups = groupBy(content, (el) => formatType(el.content_type));

	each(groups, (group, key) => {

		let rootColor = key;

		if (key === 'Scriptures') {
			// Group by primary book type (Book of Mormon)
			let l1Groups = groupBy(group, (el) => formatL1(el.content_l1));
			heirarch.children.push({
				name: key,
				color: rootColor,
				children: map(l1Groups, (l1Group, key) => {
					// Group by sub book type (Alma)
					let l2Groups = groupBy(l1Group, (el) => formatScripture(el.content_l2));
					return {
						name: key,
						color: rootColor + ' L2',
						children: map(l2Groups, (l2Group, key) => {
							return {
								name: key,
								color: rootColor + ' L3',
								children: l2Group.map((el) => {
									// Leaf nodes are book and chapter (Alma 32)
									return {
										name: key + ' ' + el.content_l3,
										color: rootColor + ' L4',
										size: el.total_seconds
									}
								})
							}
						})
					}
				})
			})

		} else {

			// These should currently only be General Conference and Ensign
			// Group by Year - Month
			let l1Groups = groupBy(group, (el) => `${el.content_l1} - ${el.content_l2}`);

			heirarch.children.push({
				name: key,
				color: rootColor,
				children: map(l1Groups, (l1Group, key) => {
					// Group by author name
					let l2Groups = groupBy(l1Group, (el) => el.content_l4);
					return {
						name: key,
						color: rootColor + ' L2',
						children: map(l2Groups, (l2Group, key) => {
							return {
								name: key,
								color: rootColor + ' L3',
								// There could be multiple study entries of the same author, find a total sum
								size: _.reduce(l2Group, (total, el) => total + el.total_seconds, 0)
							}
						})
					}
				})
			});

		}
	})

	return heirarch;
}

// Main function to draw and set up the visualization, once we have the data.
function createVisualization(json) {

	// Basic setup of page elements.
	initializeBreadcrumbTrail();

	// Bounding circle underneath the sunburst, to make it easier to detect
	// when the mouse leaves the parent g.
	vis.append("svg:circle")
		.attr("r", radius)
		.style("opacity", 0);

	// For efficiency, filter nodes to keep only those large enough to see.
	var nodes = partition.nodes(json)
		.filter(function(d) {
			return (d.dx > 0.005); // 0.005 radians = 0.29 degrees
		});

	var path = vis.data([json]).selectAll("path")
		.data(nodes)
		.enter().append("svg:path")
		.attr("display", function(d) {
			return d.depth ? null : "none";
		})
		.attr("d", arc)
		.attr("fill-rule", "evenodd")
		.style("fill", function(d) {
			return colors[d.color];
		})
		.style("opacity", 1)
		.on("mouseover", mouseover);

	// Add the mouseleave handler to the bounding circle.
	d3.select("#container").on("mouseleave", mouseleave);

	// Get total size of the tree = value of root node from partition.
	totalSize = path.node().__data__.value;
};

// Fade all but the current sequence, and show it in the breadcrumb trail.
function mouseover(d) {

	var percentage = (100 * d.value / totalSize).toPrecision(3);
	var percentageString = percentage + "%";
	if (percentage < 0.1) {
		percentageString = "< 0.1%";
	}

	d3.select("#percentage")
		.text(percentageString);

	d3.select("#title")
		.text(d.name)

	d3.select("#explanation")
		.style("visibility", "");

	var sequenceArray = getAncestors(d);
	updateBreadcrumbs(sequenceArray, percentageString);

	// Fade all the segments.
	d3.selectAll("path")
		.style("opacity", 0.3);

	// Then highlight only those that are an ancestor of the current segment.
	vis.selectAll("path")
		.filter(function(node) {
			return (sequenceArray.indexOf(node) >= 0);
		})
		.style("opacity", 1);
}

// Restore everything to full opacity when moving off the visualization.
function mouseleave(d) {

	// Hide the breadcrumb trail
	d3.select("#trail")
		.style("visibility", "hidden");

	// Deactivate all segments during transition.
	d3.selectAll("path").on("mouseover", null);

	// Transition each segment to full opacity and then reactivate it.
	d3.selectAll("path")
		.transition()
		.duration(1000)
		.style("opacity", 1)
		.each("end", function() {
			d3.select(this).on("mouseover", mouseover);
		});

	d3.select("#explanation")
		.style("visibility", "hidden");
}

// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
	var path = [];
	var current = node;
	while (current.parent) {
		path.unshift(current);
		current = current.parent;
	}
	return path;
}

function initializeBreadcrumbTrail() {
	// Add the svg area.
	var trail = d3.select("#sequence").append("svg:svg")
		.attr("width", width)
		.attr("height", 50)
		.attr("id", "trail");
	// Add the label at the end, for the percentage.
	trail.append("svg:text")
		.attr("id", "endlabel")
		.style("fill", "#000");
}

// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
	var points = [];
	points.push("0,0");
	points.push(b.w + ",0");
	points.push(b.w + b.t + "," + (b.h / 2));
	points.push(b.w + "," + b.h);
	points.push("0," + b.h);
	if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
		points.push(b.t + "," + (b.h / 2));
	}
	return points.join(" ");
}

// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {

	// Data join; key function combines name and depth (= position in sequence).
	var g = d3.select("#trail")
		.selectAll("g")
		.data(nodeArray, function(d) {
			return d.name + d.depth;
		});

	// Add breadcrumb and label for entering nodes.
	var entering = g.enter().append("svg:g");

	entering.append("svg:polygon")
		.attr("points", breadcrumbPoints)
		.style("fill", function(d) {
			return colors[d.color];
		});

	entering.append("svg:text")
		.attr("x", (b.w + b.t) / 2)
		.attr("y", b.h / 2)
		.attr("dy", "0.35em")
		.attr("text-anchor", "middle")
		.text(function(d) {
			return d.name;
		});

	// Set position for entering and updating nodes.
	g.attr("transform", function(d, i) {
		return "translate(" + i * (b.w + b.s) + ", 0)";
	});

	// Remove exiting nodes.
	g.exit().remove();

	// Now move and update the percentage at the end.
	d3.select("#trail").select("#endlabel")
		.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
		.attr("y", b.h / 2)
		.attr("dy", "0.35em")
		.attr("text-anchor", "middle")
		.text(percentageString);

	// Make the breadcrumb trail visible, if it's hidden.
	d3.select("#trail")
		.style("visibility", "");

}

function drawLegend() {

	// Dimensions of legend item: width, height, spacing, radius of rounded rect.
	var li = {
		w: 75,
		h: 30,
		s: 3,
		r: 3
	};

	var legend = d3.select("#legend").append("svg:svg")
		.attr("width", li.w)
		.attr("height", d3.keys(colors).length * (li.h + li.s));

	var g = legend.selectAll("g")
		.data(d3.entries(colors))
		.enter().append("svg:g")
		.attr("transform", function(d, i) {
			return "translate(0," + i * (li.h + li.s) + ")";
		});

	g.append("svg:rect")
		.attr("rx", li.r)
		.attr("ry", li.r)
		.attr("width", li.w)
		.attr("height", li.h)
		.style("fill", function(d) {
			return d.value;
		});

	g.append("svg:text")
		.attr("x", li.w / 2)
		.attr("y", li.h / 2)
		.attr("dy", "0.35em")
		.attr("text-anchor", "middle")
		.text(function(d) {
			return d.key;
		});
}

function toggleLegend() {
		var legend = d3.select("#legend");
		if (legend.style("visibility") == "hidden") {
			legend.style("visibility", "");
		} else {
			legend.style("visibility", "hidden");
		}
	}
	// Take a 2-column CSV and transform it into a hierarchical structure suitable
	// for a partition layout. The first column is a sequence of step names, from
	// root to leaf, separated by hyphens. The second column is a count of how
	// often that sequence occurred.

function buildHierarchy(csv) {
	var root = {
		"name": "root",
		"children": []
	};
	for (var i = 0; i < csv.length; i++) {
		var sequence = csv[i][0];
		var size = +csv[i][1];
		if (isNaN(size)) { // e.g. if this is a header row
			continue;
		}
		var parts = sequence.split("-");
		var currentNode = root;
		for (var j = 0; j < parts.length; j++) {
			var children = currentNode["children"];
			var nodeName = parts[j];
			var childNode;
			if (j + 1 < parts.length) {
				// Not yet at the end of the sequence; move down the tree.
				var foundChild = false;
				for (var k = 0; k < children.length; k++) {
					if (children[k]["name"] == nodeName) {
						childNode = children[k];
						foundChild = true;
						break;
					}
				}
				// If we don't already have a child node for this branch, create it.
				if (!foundChild) {
					childNode = {
						"name": nodeName,
						"children": []
					};
					children.push(childNode);
				}
				currentNode = childNode;
			} else {
				// Reached the end of the sequence; create a leaf node.
				childNode = {
					"name": nodeName,
					"size": size
				};
				children.push(childNode);
			}
		}
	}
	return root;
};