text:
<?php
namespace Sutra\Component\DataStructure\Tests;

use Sutra\Component\DataStructure\Dictionary;
use Sutra\Component\DataStructure\StrictArray;

class StrictArrayTest extends TestCase
{
    const walkCallback = 'Sutra\Component\DataStructure\Tests\StrictArrayTest::walkCallback';
    const filterCallback1 = 'Sutra\Component\DataStructure\Tests\StrictArrayTest::filterCallback1';
    const filterCallback2 = 'Sutra\Component\DataStructure\Tests\StrictArrayTest::filterCallback2';
    const mapCallback = 'Sutra\Component\DataStructure\Tests\StrictArrayTest::mapCallback';
    const walkCallbackRef = 'Sutra\Component\DataStructure\Tests\StrictArrayTest::walkCallbackRef';

    public function testGetData()
    {
        $a = new StrictArray(1, 2, 3);
        $this->assertEquals(array(1, 2, 3), $a->getData());
    }

    public function testCount()
    {
        $a = new StrictArray(1, 2, 3);
        $this->assertEquals(3, $a->count());
        $this->assertEquals(3, count($a));
        $this->assertEquals(3, $a->length);
    }

    public function testArrayAccess()
    {
        $a = new StrictArray(1, 2, 3);
        foreach ($a as $key => $value) {
            $this->assertEquals($value, $a[$key]);
        }
    }

    public function testArraySetting()
    {
        $a = new StrictArray(1, 2, 3);
        $a[0] = 2;
        $this->assertEquals(array(2,2,3), $a->getData());
    }

    /**
     * @expectedException Sutra\Component\DataStructure\Exception\ProgrammerException
     * @expectedExceptionMessage Offsets can only be integer. Given: "1.2"
     */
    public function testOffsetExistsBadArgument()
    {
        $a = new StrictArray(1, 2, 3);
        isset($a[1.2]);
    }

    /**
     * @expectedException Sutra\Component\DataStructure\Exception\ProgrammerException
     * @expectedExceptionMessage Offsets can only be integer. Given: "1.2"
     */
    public function testOffsetGetException()
    {
        $a = new StrictArray(1,2,3);
        $c = $a[1.2];
    }

    public function testOffsetExists()
    {
        $a = new StrictArray(1,2,3);
        $this->assertTrue($a->offsetExists(0));
        $this->assertFalse($a->offsetExists(3));
    }

    public function testOffsetSet()
    {
        $a = new StrictArray(1,2,3);
        $a[] = 2;
        $this->assertEquals(2, $a[3]);
    }

    /**
     * @expectedException Sutra\Component\DataStructure\Exception\ProgrammerException
     * @expectedExceptionMessage Offsets can only be integer. Given: "1.2"
     */
    public function testOffsetUnsetBadArgument()
    {
        $a = new StrictArray(1, 2, 3);
        unset($a[1.2]);
    }

    public function testOffsetUnset()
    {
        $a = new StrictArray(1, 2, 3);
        unset($a[0]);
    }

    public function testPop()
    {
        $a = new StrictArray(1,2,3);
        $this->assertEquals(3, $a->pop());
    }

    public function testPush()
    {
        $a = new StrictArray(1,2);
        $a->push(3);
        $this->assertEquals(3, $a->pop());
    }

    public function testFill()
    {
        $a = new StrictArray(1,2);
        $a->fill(10, 1);
        for ($i = 0; $i < 10; $i++) {
            $offset = $i + 2;
            $this->assertEquals(1, $a[$offset]);
        }
    }

    public function testShift()
    {
        $a = new StrictArray(1,2,3,4);
        $this->assertEquals(1, $a->shift());
        $this->assertEquals(array(2,3,4), $a->getData());
    }

    public function testUnshift()
    {
        $a = new StrictArray(2,3,4);
        $this->assertEquals($a, $a->unshift(1));
        $this->assertEquals(array(1,2,3,4), $a->getData());
    }

    public function testMerge()
    {
        $one = array(1,2,3,4);
        $two = array(45,46,47);
        $three = new StrictArray(100,1000,10000);

        $a = new StrictArray;
        $this->assertEquals($a, $a->merge($one));
        $this->assertEquals($one, $a->getData());

        $a = new StrictArray;
        $a->merge($one, $two);
        $this->assertEquals(array_merge($one, $two), $a->getData());

        $a = new StrictArray;
        $a->merge($one, $three);
        $this->assertEquals(array_merge($one, $three->getData()), $a->getData());
    }

    public static function walkCallback($a, $b, $user_data = NULL) {
        if (is_array($a)) {
            print join(',', $a);
        }
        else {
            print $a;
        }
        print '=>';
        print $b.',';
    }

    public function testWalk()
    {
        $this->expectOutputString('1=>0,2=>1,3=>2,');
        $a = new StrictArray(1,2,3);
        $this->assertEquals($a, $a->walk(self::walkCallback));
    }

    public static function walkCallbackRef(&$value, $key, $user_data = NULL) {
        $value += 3;
    }

    public function testWalkModify()
    {
        $a = new StrictArray(1,2,3);
        $b = array(4,5,6);
        $this->assertEquals($b, $a->walk(self::walkCallbackRef)->getData());
    }

    public function testWalkRecursive()
    {
        $this->expectOutputString('1=>0,2=>1,3=>2,a=>3,a=>0,a,1=>4,a=>0,1=>1,1=>0,[]=>5,[]=>6,');
        $a = new StrictArray(1,2,3, array('a'), new StrictArray('a', array(1)), new ContainerMock(), new ContainerMockInvalid());
        $this->assertEquals($a, $a->walkRecursive(self::walkCallback));
    }

    public function testPrintJSON()
    {
        $this->expectOutputString('[1,2,3]');
        $a = new StrictArray(1,2,3);
        $a->printJSON();
    }

    public function testToJSON()
    {
        $a = new StrictArray(1,2,3);
        $this->assertEquals('[1,2,3]', $a->toJSON());
    }

    public function testSearch()
    {
        $a = new StrictArray(1,2,3);
        $this->assertEquals(0, $a->search(1));
        $this->assertEquals(0, $a->search(TRUE));
        $this->assertFalse($a->search(TRUE, TRUE));
    }

    public function testRand()
    {
        $a = new StrictArray(1,2,3);
        $this->assertInternalType('array', $a->rand());
        $this->assertEquals(1, count($a->rand()));
        $this->assertEquals(2, count($a->rand(2)));
    }

    public function testDiff()
    {
        $a = new StrictArray(1,2,3);
        $b = new StrictArray(4,3,5);
        $diff = $a->diff($b);
        $this->assertInstanceOf('Sutra\Component\DataStructure\StrictArray', $diff);
        $this->assertEquals(array(1,2), $diff->getData());
    }

    public function testReverse()
    {
        $a = new StrictArray(1,2,3);
        $result = array(3,2,1);
        $this->assertEquals($result, $a->reverse()->getData());
    }

    public function testSlice()
    {
        $a = new StrictArray(1,2,3);
        $result = array(2,3);
        $this->assertEquals($result, $a->slice(1)->getData());

        $this->assertEquals(array(2), $a->slice(1, 1)->getData());
    }

    public static function filterCallback1() {
        return TRUE;
    }

    public static function filterCallback2($var) {
        if ($var === 1) {
            return FALSE;
        }
        return TRUE;
    }

    public function testFilter()
    {
        $a = new StrictArray(1,2,3);
        $b = $a->filter(self::filterCallback1);
        $this->assertNotSame($b, $a);
        $this->assertEquals($a->getData(), $b->getData());

        $b = $a->filter(self::filterCallback2);
        $this->assertEquals(array(2,3), $b->getData());
    }

    public static function mapCallback($n) {
        return $n * 2;
    }

    public function testMap()
    {
        $a = new StrictArray(1,2,3);
        $b = $a->map(self::mapCallback);
        $this->assertEquals(array(2,4,6), $b->getData());
    }

    public function testPad()
    {
        $a = new StrictArray(1,2,3);
        $b = $a->pad(10, 0);
        $this->assertEquals(array(1,2,3,0,0,0,0,0,0,0), $b->getData());
    }

    public function testUnique()
    {
        $a = new StrictArray(1,2,3,1,2,3,1,2,3);
        $b = $a->unique(SORT_NUMERIC);
        $this->assertEquals(array(1,2,3), $b->getData());
    }

    public function testValues()
    {
        $a = new StrictArray(1,2,3,1,2,3,1,2,3);
        $this->assertInternalType('array', $a->values());
        $this->assertEquals(array(1,2,3,1,2,3,1,2,3), $a->values());
    }

    public function testFlip()
    {
        $a = new StrictArray('a', 'b', 'c');
        $obj = $a->flip();
        $this->assertInstanceOf('Sutra\Component\DataStructure\Dictionary', $obj);
        $this->assertEquals(0, $obj['a']);
        $this->assertEquals(1, $obj->b);
        $this->assertEquals(2, $obj->c);
    }

    public function testGetUnknownProperty()
    {
        $a = new StrictArray(1, 2, 3);
        $this->assertNull($a->unknown_property);
    }

    public function testSort()
    {
        $a = new StrictArray(10,2,3,1);
        $a->sort(SORT_NUMERIC);
        $this->assertEquals(array(1,2,3,10), $a->getData());
    }

    public function testReverseSort()
    {
        $a = new StrictArray(10,2,3,1);
        $a->reverseSort(SORT_NUMERIC);
        $this->assertEquals(array(10,3,2,1), $a->getData());
    }
}


text:
import re
import json
from functools import reduce

# Django
from django.core.exceptions import FieldError, ValidationError
from django.db import models
from django.db.models import Q
from django.db.models.fields import FieldDoesNotExist
from django.db.models.fields.related import ForeignObjectRel, ManyToManyField, ForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _

# Django REST Framework
from rest_framework.exceptions import ParseError, PermissionDenied
from rest_framework.filters import BaseFilterBackend

# AWX
from awx.main.utils import get_type_for_model, to_python_boolean
from awx.main.utils.db import get_all_field_names
from awx.main.models.credential import CredentialType

class V1CredentialFilterBackend(BaseFilterBackend):
    '''
    For /api/v1/ requests, filter out v2 (custom) credentials
    '''

    def filter_queryset(self, request, queryset, view):
        # TODO: remove in 3.3
        from awx.api.versioning import get_request_version
        if get_request_version(request) == 1:
            queryset = queryset.filter(credential_type__managed_by_tower=True)
        return queryset

class TypeFilterBackend(BaseFilterBackend):
    '''
    Filter on type field now returned with all objects.
    '''

    def filter_queryset(self, request, queryset, view):
        try:
            types = None
            for key, value in request.query_params.items():
                if key == 'type':
                    if ',' in value:
                        types = value.split(',')
                    else:
                        types = (value,)
            if types:
                types_map = {}
                for ct in ContentType.objects.filter(Q(app_label='main') | Q(app_label='auth', model='user')):
                    ct_model = ct.model_class()
                    if not ct_model:
                        continue
                    ct_type = get_type_for_model(ct_model)
                    types_map[ct_type] = ct.pk
                model = queryset.model
                model_type = get_type_for_model(model)
                if 'polymorphic_ctype' in get_all_field_names(model):
                    types_pks = set([v for k,v in types_map.items() if k in types])
                    queryset = queryset.filter(polymorphic_ctype_id__in=types_pks)
                elif model_type in types:
                    queryset = queryset
                else:
                    queryset = queryset.none()
            return queryset
        except FieldError as e:
            # Return a 400 for invalid field names.
            raise ParseError(*e.args)

def get_field_from_path(model, path):
    '''
    Given a Django ORM lookup path (possibly over multiple models)
    Returns the last field in the line, and also the revised lookup path
    ex., given
        model=Organization
        path='project__timeout'
    returns tuple of field at the end of the line as well as a corrected
    path, for special cases we do substitutions
        (<IntegerField for timeout>, 'project__timeout')
    '''
    # Store of all the fields used to detect repeats
    field_set = set([])
    new_parts = []
    for name in path.split('__'):
        if model is None:
            raise ParseError(_('No related model for field {}.').format(name))
        # HACK: Make project and inventory source filtering by old field names work for backwards compatibility.
        if model._meta.object_name in ('Project', 'InventorySource'):
            name = {
                'current_update': 'current_job',
                'last_update': 'last_job',
                'last_update_failed': 'last_job_failed',
                'last_updated': 'last_job_run',
            }.get(name, name)

        if name == 'type' and 'polymorphic_ctype' in get_all_field_names(model):
            name = 'polymorphic_ctype'
            new_parts.append('polymorphic_ctype__model')
        else:
            new_parts.append(name)

        if name in getattr(model, 'PASSWORD_FIELDS', ()):
            raise PermissionDenied(_('Filtering on password fields is not allowed.'))
        elif name == 'pk':
            field = model._meta.pk
        else:
            name_alt = name.replace("_", "")
            if name_alt in model._meta.fields_map.keys():
                field = model._meta.fields_map[name_alt]
                new_parts.pop()
                new_parts.append(name_alt)
            else:
                field = model._meta.get_field(name)
            if isinstance(field, ForeignObjectRel) and getattr(field.field, '__prevent_search__', False):
                raise PermissionDenied(_('Filtering on %s is not allowed.' % name))
            elif getattr(field, '__prevent_search__', False):
                raise PermissionDenied(_('Filtering on %s is not allowed.' % name))
        if field in field_set:
            # Field traversed twice, could create infinite JOINs, DoSing Tower
            raise ParseError(_('Loops not allowed in filters, detected on field {}.').format(field.name))
        field_set.add(field)
        model = getattr(field, 'related_model', None)

    return field, '__'.join(new_parts)

class FieldLookupBackend(BaseFilterBackend):
    '''
    Filter using field lookups provided via query string parameters.
    '''

    RESERVED_NAMES = ('page', 'page_size', 'format', 'order', 'order_by',
                      'search', 'type', 'host_filter')

    SUPPORTED_LOOKUPS = ('exact', 'iexact', 'contains', 'icontains',
                         'startswith', 'istartswith', 'endswith', 'iendswith',
                         'regex', 'iregex', 'gt', 'gte', 'lt', 'lte', 'in',
                         'isnull', 'search')

    def get_field_from_lookup(self, model, lookup):

        if '__' in lookup and lookup.rsplit('__', 1)[-1] in self.SUPPORTED_LOOKUPS:
            path, suffix = lookup.rsplit('__', 1)
        else:
            path = lookup
            suffix = 'exact'

        if not path:
            raise ParseError(_('Query string field name not provided.'))

        # FIXME: Could build up a list of models used across relationships, use
        # those lookups combined with request.user.get_queryset(Model) to make
        # sure user cannot query using objects he could not view.
        field, new_path = get_field_from_path(model, path)

        new_lookup = new_path
        new_lookup = '__'.join([new_path, suffix])
        return field, new_lookup

    def to_python_related(self, value):
        value = force_text(value)
        if value.lower() in ('none', 'null'):
            return None
        else:
            return int(value)

    def value_to_python_for_field(self, field, value):
        if isinstance(field, models.NullBooleanField):
            return to_python_boolean(value, allow_none=True)
        elif isinstance(field, models.BooleanField):
            return to_python_boolean(value)
        elif isinstance(field, (ForeignObjectRel, ManyToManyField, GenericForeignKey, ForeignKey)):
            try:
                return self.to_python_related(value)
            except ValueError:
                raise ParseError(_('Invalid {field_name} id: {field_id}').format(
                    field_name=getattr(field, 'name', 'related field'),
                    field_id=value)
                )
        else:
            return field.to_python(value)

    def value_to_python(self, model, lookup, value):
        try:
            lookup = lookup.encode("ascii")
        except UnicodeEncodeError:
            raise ValueError("%r is not an allowed field name. Must be ascii encodable." % lookup)

        field, new_lookup = self.get_field_from_lookup(model, lookup)

        # Type names are stored without underscores internally, but are presented and
        # and serialized over the API containing underscores so we remove `_`
        # for polymorphic_ctype__model lookups.
        if new_lookup.startswith('polymorphic_ctype__model'):
            value = value.replace('_','')
        elif new_lookup.endswith('__isnull'):
            value = to_python_boolean(value)
        elif new_lookup.endswith('__in'):
            items = []
            if not value:
                raise ValueError('cannot provide empty value for __in')
            for item in value.split(','):
                items.append(self.value_to_python_for_field(field, item))
            value = items
        elif new_lookup.endswith('__regex') or new_lookup.endswith('__iregex'):
            try:
                re.compile(value)
            except re.error as e:
                raise ValueError(e.args[0])
        elif new_lookup.endswith('__search'):
            related_model = getattr(field, 'related_model', None)
            if not related_model:
                raise ValueError('%s is not searchable' % new_lookup[:-8])
            new_lookups = []
            for rm_field in related_model._meta.fields:
                if rm_field.name in ('username', 'first_name', 'last_name', 'email', 'name', 'description'):
                    new_lookups.append('{}__{}__icontains'.format(new_lookup[:-8], rm_field.name))
            return value, new_lookups
        else:
            value = self.value_to_python_for_field(field, value)
        return value, new_lookup

    def filter_queryset(self, request, queryset, view):
        try:
            # Apply filters specified via query_params. Each entry in the lists
            # below is (negate, field, value).
            and_filters = []
            or_filters = []
            chain_filters = []
            role_filters = []
            search_filters = {}
            # Can only have two values: 'AND', 'OR'
            # If 'AND' is used, an iterm must satisfy all condition to show up in the results.
            # If 'OR' is used, an item just need to satisfy one condition to appear in results.
            search_filter_relation = 'OR'
            for key, values in request.query_params.lists():
                if key in self.RESERVED_NAMES:
                    continue

                # HACK: Make job event filtering by host name mostly work even
                # when not capturing job event hosts M2M.
                if queryset.model._meta.object_name == 'JobEvent' and key.startswith('hosts__name'):
                    key = key.replace('hosts__name', 'or__host__name')
                    or_filters.append((False, 'host__name__isnull', True))

                # Custom __int filter suffix (internal use only).
                q_int = False
                if key.endswith('__int'):
                    key = key[:-5]
                    q_int = True

                # RBAC filtering
                if key == 'role_level':
                    role_filters.append(values[0])
                    continue

                # Search across related objects.
                if key.endswith('__search'):
                    if values and ',' in values[0]:
                        search_filter_relation = 'AND'
                        values = reduce(lambda list1, list2: list1 + list2, [i.split(',') for i in values])
                    for value in values:
                        search_value, new_keys = self.value_to_python(queryset.model, key, force_text(value))
                        assert isinstance(new_keys, list)
                        search_filters[search_value] = new_keys
                    continue

                # Custom chain__ and or__ filters, mutually exclusive (both can
                # precede not__).
                q_chain = False
                q_or = False
                if key.startswith('chain__'):
                    key = key[7:]
                    q_chain = True
                elif key.startswith('or__'):
                    key = key[4:]
                    q_or = True

                # Custom not__ filter prefix.
                q_not = False
                if key.startswith('not__'):
                    key = key[5:]
                    q_not = True

                # Make legacy v1 Job/Template fields work for backwards compatability
                # TODO: remove after API v1 deprecation period
                if queryset.model._meta.object_name in ('JobTemplate', 'Job') and key in (
                        'credential', 'vault_credential', 'cloud_credential', 'network_credential'
                ) or queryset.model._meta.object_name in ('InventorySource', 'InventoryUpdate') and key == 'credential':
                    key = 'credentials'

                # Make legacy v1 Credential fields work for backwards compatability
                # TODO: remove after API v1 deprecation period
                #
                # convert v1 `Credential.kind` queries to `Credential.credential_type__pk`
                if queryset.model._meta.object_name == 'Credential' and key == 'kind':
                    key = key.replace('kind', 'credential_type')

                    if 'ssh' in values:
                        # In 3.2, SSH and Vault became separate credential types, but in the v1 API,
                        # they're both still "kind=ssh"
                        # under the hood, convert `/api/v1/credentials/?kind=ssh` to
                        # `/api/v1/credentials/?or__credential_type=<ssh_pk>&or__credential_type=<vault_pk>`
                        values = set(values)
                        values.add('vault')
                        values = list(values)
                        q_or = True

                    for i, kind in enumerate(values):
                        if kind == 'vault':
                            type_ = CredentialType.objects.get(kind=kind)
                        else:
                            type_ = CredentialType.from_v1_kind(kind)
                        if type_ is None:
                            raise ParseError(_('cannot filter on kind %s') % kind)
                        values[i] = type_.pk

                # Convert value(s) to python and add to the appropriate list.
                for value in values:
                    if q_int:
                        value = int(value)
                    value, new_key = self.value_to_python(queryset.model, key, value)
                    if q_chain:
                        chain_filters.append((q_not, new_key, value))
                    elif q_or:
                        or_filters.append((q_not, new_key, value))
                    else:
                        and_filters.append((q_not, new_key, value))

            # Now build Q objects for database query filter.
            if and_filters or or_filters or chain_filters or role_filters or search_filters:
                args = []
                for n, k, v in and_filters:
                    if n:
                        args.append(~Q(**{k:v}))
                    else:
                        args.append(Q(**{k:v}))
                for role_name in role_filters:
                    if not hasattr(queryset.model, 'accessible_pk_qs'):
                        raise ParseError(_(
                            'Cannot apply role_level filter to this list because its model '
                            'does not use roles for access control.'))
                    args.append(
                        Q(pk__in=queryset.model.accessible_pk_qs(request.user, role_name))
                    )
                if or_filters:
                    q = Q()
                    for n,k,v in or_filters:
                        if n:
                            q |= ~Q(**{k:v})
                        else:
                            q |= Q(**{k:v})
                    args.append(q)
                if search_filters and search_filter_relation == 'OR':
                    q = Q()
                    for term, constrains in search_filters.iteritems():
                        for constrain in constrains:
                            q |= Q(**{constrain: term})
                    args.append(q)
                elif search_filters and search_filter_relation == 'AND':
                    for term, constrains in search_filters.iteritems():
                        q_chain = Q()
                        for constrain in constrains:
                            q_chain |= Q(**{constrain: term})
                        queryset = queryset.filter(q_chain)
                for n,k,v in chain_filters:
                    if n:
                        q = ~Q(**{k:v})
                    else:
                        q = Q(**{k:v})
                    queryset = queryset.filter(q)
                queryset = queryset.filter(*args).distinct()
            return queryset
        except (FieldError, FieldDoesNotExist, ValueError, TypeError) as e:
            raise ParseError(e.args[0])
        except ValidationError as e:
            raise ParseError(json.dumps(e.messages, ensure_ascii=False))

class OrderByBackend(BaseFilterBackend):
    '''
    Filter to apply ordering based on query string parameters.
    '''

    def filter_queryset(self, request, queryset, view):
        try:
            order_by = None
            for key, value in request.query_params.items():
                if key in ('order', 'order_by'):
                    order_by = value
                    if ',' in value:
                        order_by = value.split(',')
                    else:
                        order_by = (value,)
            if order_by:
                order_by = self._validate_ordering_fields(queryset.model, order_by)

                # Special handling of the type field for ordering. In this
                # case, we're not sorting exactly on the type field, but
                # given the limited number of views with multiple types,
                # sorting on polymorphic_ctype.model is effectively the same.
                new_order_by = []
                if 'polymorphic_ctype' in get_all_field_names(queryset.model):
                    for field in order_by:
                        if field == 'type':
                            new_order_by.append('polymorphic_ctype__model')
                        elif field == '-type':
                            new_order_by.append('-polymorphic_ctype__model')
                        else:
                            new_order_by.append(field)
                else:
                    for field in order_by:
                        if field not in ('type', '-type'):
                            new_order_by.append(field)
                queryset = queryset.order_by(*new_order_by)
            return queryset
        except FieldError as e:
            # Return a 400 for invalid field names.
            raise ParseError(*e.args)

    def _validate_ordering_fields(self, model, order_by):
        for field_name in order_by:
            # strip off the negation prefix `-` if it exists
            prefix = ''
            path = field_name
            if field_name[0] == '-':
                prefix = field_name[0]
                path = field_name[1:]
            try:
                field, new_path = get_field_from_path(model, path)
                new_path = '{}{}'.format(prefix, new_path)
            except (FieldError, FieldDoesNotExist) as e:
                raise ParseError(e.args[0])
            yield new_path

redpajama_set_name: RedPajamaGithub


text:
namespace rx
{

ProgramPipelineVk::ProgramPipelineVk(const gl::ProgramPipelineState &state)
    : ProgramPipelineImpl(state)
{}

ProgramPipelineVk::~ProgramPipelineVk() {}

}  // namespace rx


text:
package org.opensmartgridplatform.domain.microgrids.valueobjects;

import java.io.Serializable;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import org.joda.time.DateTime;

public class Measurement extends NodeIdentifier implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 3315719218127525093L;

    private final int qualifier;
    private final DateTime time;
    private final double value;

    public Measurement(final int id, final String node, final int qualifier, final DateTime time, final double value) {
        super(id, node);
        this.qualifier = qualifier;
        this.time = time;
        this.value = this.roundValue(value);
    }

    public int getQualifier() {
        return this.qualifier;
    }

    public DateTime getTime() {
        return this.time;
    }

    public double getValue() {
        return this.value;
    }

    private double roundValue(final double value) {
        final DecimalFormat df = new DecimalFormat("#.#####");
        df.setRoundingMode(RoundingMode.HALF_UP);
        return Double.parseDouble(df.format(value));
    }
}


text:
class RemoveWorkflowRunDagVersion < ActiveRecord::Migration[5.2]
  def change
    remove_column :workflow_runs, :dag_version
  end
end


text:
package org.apache.myfaces.trinidadinternal.image.util;

import java.awt.Polygon;
import java.awt.Rectangle;

import org.apache.myfaces.trinidad.util.IntegerUtils;

/**
 * MapArea describes an area of an image map.
 *
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/image/util/MapArea.java#0 $) $Date: 10-nov-2005.19:04:49 $
 */
public class MapArea
{
  /**
   * Shape for rectangles
   */
  public static final String RECTANGLE_SHAPE = "rect";

  /**
   * Shape for polygons
   */
  public static final String POLYGON_SHAPE  = "poly";

  /**
   * Crates a MapArea.
   * @param shape The shape of the area.  This is one of the *_SHAPE constants
   *   defined by MapArea.
   * @param coordinates The coordinates of the area.
   */
  public MapArea(String shape, int[] coordinates)
  {
    _init(shape, coordinates);
  }

  /**
   * Creates a MapArea.
   * @param shape The shape of the area.  This is one of the *_SHAPE constants
   *   defined by MapArea.
   * @param coordinates The String representing the coordinates of the area.
   */
  public MapArea(String shape, String coordinatesString)
  {
    _shape = shape;
    _coords = coordinatesString;
  }

  /**
   * Creates a rectangle MapArea.
   */
  public MapArea(Rectangle rectangle)
  {
    int[] coords = null;

    if (rectangle != null)
    {
      coords = new int[4];
      coords[0] = rectangle.x;
      coords[1] = rectangle.y;
      coords[2] = rectangle.x + rectangle.width;
      coords[3] = rectangle.y + rectangle.height;
    }

    _init(RECTANGLE_SHAPE, coords);
  }

  /**
   * Creates a polygon MapArea
   */
  public MapArea(Polygon polygon)
  {
    int[] coords = null;

    if ((polygon != null) && (polygon.npoints != 0))
    {
      coords = new int[polygon.npoints * 2];
      for (int i = 0; i < polygon.npoints; i++)
      {
        coords[i*2] = polygon.xpoints[i];
        coords[i*2+1] = polygon.ypoints[i];
      }
    }

    _init(POLYGON_SHAPE, coords);
  }

  /**
   * Returns a String indicating the shape of the MapArea,
   * suitable for use in an HTML image map.
   */
  public String getShape()
  {
    return _shape;
  }

  /**
   * Returns a String representing the area's coordinates, suitable
   * for inclusion in an HTML image map.
   */
  public String getCoordinatesString()
  {
    return _coords;
  }

  // Initializes the MapArea
  private void _init(String shape, int[] coordinates)
  {
    _shape = shape;

    if (coordinates == null)
      return;

    StringBuffer buffer = new StringBuffer(coordinates.length*4);
    for (int i = 0; i < coordinates.length; i++)
    {
      buffer.append(IntegerUtils.getString(coordinates[i]));

      if (i < (coordinates.length - 1))
        buffer.append(_SEPARATOR);
    }

    _coords = buffer.toString();
  }

  private String _shape;
  private String _coords;

  private static final char _SEPARATOR = ',';
}


text:
package com.librethinking.simmodsys.exceptions;

/**
 * This Exception represents a problem with the type of Parameters to
 * be assigned to States.
 *
 * @author Christian Vielma <cvielma@librethinking.com>
 */
public class InvalidParameterException extends RuntimeException{

    public InvalidParameterException(){
        super("Tried to assign invalid Parameter. Check Reference.");
    }

    public InvalidParameterException(String err) {
        super(err);
    }

}


text:
package seedu.stask.commons.events.ui;

import seedu.stask.commons.events.BaseEvent;
import seedu.stask.model.Model;

//@@author A0143884W
/**
 * Indicates a request to update the list count
 */
public class UpdateListCountEvent extends BaseEvent {

	public final Model model;

	public UpdateListCountEvent(Model model){
		this.model = model;
	}

	@Override
	public String toString() {
		return this.getClass().getSimpleName();
	}

}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<Stromx version="0.1.0">
    <Stream>
        <Operator id="0" package="runtime" type="Counter" version="0.1.0"/>
        <Operator id="1" package="runtime" type="PeriodicDelay" version="0.1.0">
            <Parameter id="0">
                <Data type="UInt32" package="runtime" version="0.1.0">1000</Data>
            </Parameter>
            <Input id="0" operator="0" output="0"/>
        </Operator>
        <Thread name="Thread">
            <InputConnector operator="1" input="0"/>
        </Thread>
    </Stream>
</Stromx>


text:
package apps

import (
	imageutils "k8s.io/kubernetes/test/utils/image"
)

// NOTE(claudiub): These constants should NOT be used as Pod Container Images.
const (
	WebserverImageName = "httpd"
	AgnhostImageName   = "agnhost"
)

var (
	// WebserverImage is the fully qualified URI to the Httpd image
	WebserverImage = imageutils.GetE2EImage(imageutils.Httpd)

	// NewWebserverImage is the fully qualified URI to the HttpdNew image
	NewWebserverImage = imageutils.GetE2EImage(imageutils.HttpdNew)

	// AgnhostImage is the fully qualified URI to the Agnhost image
	AgnhostImage = imageutils.GetE2EImage(imageutils.Agnhost)
)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anal. Mus. nac. B. Aires, Ser. 2 6: 305 (1899)

#### Original name
Ciboria poronioides Speg.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<screen xmlns="http://www.scons.org/dbxsd/v1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.scons.org/dbxsd/v1.0 http://www.scons.org/dbxsd/v1.0/scons.xsd">% <userinput>scons -Q foo.o</userinput>
cc -o foo.o -c -DCONFIG_FILE="/etc/my_config" foo.c
% <userinput>scons -Q CONFIG=/usr/local/etc/other_config foo.o</userinput>
scons: `foo.o' is up to date.
</screen>


text:
DEFAULT_BAUDRATE = 38400
import sys

if (hasattr(sys, 'implementation') and
            sys.implementation.name == 'micropython'):
    # if using pyBoard
    from pyb import UART as uart_base
else:
    from serial import Serial as uart_base

from obdlib.logging import logger

class UART(object):
    def __init__(self):
        self.bus_name = uart_base.__name__
        self.bus = None
        self.map = {}

    def connection(self, port, baudrate=DEFAULT_BAUDRATE):
        try:
            self.bus = uart_base(port, baudrate)
            self._mapping()
        except Exception as err:
            # logging exception
            logger.error(err)
            return None

        return self

    def __getattr__(self, item):
        def args_wrapper(*args, **kwargs):
            try:
                response = getattr(self.bus, item)(*args, **kwargs)
            except AttributeError:
                response = self._invoke_mapping(item, *args, **kwargs)
            return response

        return args_wrapper

    def _invoke_mapping(self, method, *args, **kwargs):
        try:
            item = self.map[self.bus_name][method]
            return getattr(self.bus, item)(*args, **kwargs) if item else None
        except KeyError:
            raise Exception(
                "Unregistered method or attribute {}".format(method))

    def _mapping(self):
        self.map = {
            "UART": {
                "close": "deinit",
                "flushInput": "",
                "flushOutput": ""
            },
        }


text:
var should = require('should');
var util = require('util');
var testUtils = require('../util/util');
var sinon = require('sinon');
var crypto = require('crypto');
var CLITest = require('../framework/cli-test');
var vmTestUtil = require('../util/asmVMTestUtil');

var suite;
var vmPrefix = 'clitestvm';
var createdVms = [];
var testPrefix = 'cli.vm.create_comm-tests';

var requiredEnvironment = [{
  name: 'AZURE_VM_TEST_LOCATION',
  defaultValue: 'West US'
}, {
  name: 'AZURE_COMMUNITY_IMAGE_ID',
  defaultValue: null,
  secure: true
}];

var currentRandom = 0;

describe('cli', function() {
  describe('vm', function() {
    var location,
      communityImageId,
      timeout,
      retry,
      customVmName,
      username = 'azureuser',
      password = 'Pa$$word@123';
    testUtils.TIMEOUT_INTERVAL = 5000;
    var vmUtil = new vmTestUtil();

    var vmToUse = {
      Name: null,
      Created: false,
      Delete: false
    };

    before(function(done) {
      suite = new CLITest(this, testPrefix, requiredEnvironment);
      location = process.env.AZURE_VM_TEST_LOCATION;
      communityImageId = process.env.AZURE_COMMUNITY_IMAGE_ID;
      customVmName = suite.generateId(vmPrefix, createdVms);
      timeout = suite.isPlayback() ? 0 : testUtils.TIMEOUT_INTERVAL;
      retry = 5;
      if (suite.isMocked) {
        sinon.stub(crypto, 'randomBytes', function() {
          return (++currentRandom).toString();
        });
      }
      suite.setupSuite(done);
    });

    after(function(done) {
      if (suite.isMocked) {
        crypto.randomBytes.restore();
      }
      suite.teardownSuite(done);
    });

    beforeEach(function(done) {
      suite.setupTest(done);
    });

    afterEach(function(done) {
      vmUtil.deleteUsedVM(vmToUse, timeout, suite, function() {
        suite.teardownTest(done);
      });
    });

    //Create vm with custom data
    describe('Create:', function() {
      //this tests only runs live, because it downloads data from a live site, taking 4 minutes
      if (process.env.NOCK_OFF) {
        it('with community data', function(done) {
          var cmd = util.format('vm create -o %s %s %s %s --json --verbose',
            customVmName, communityImageId, username, password).split(' ');
          cmd.push('-l');
          cmd.push(location);
          testUtils.executeCommand(suite, retry, cmd, function(result) {
            result.exitStatus.should.equal(0);
            vmToUse.Name = customVmName;
            vmToUse.Created = true;
            vmToUse.Delete = true;
            done();
          });
        });
      }
    });
  });
});


text:
SVG.Rect = SVG.invent({
  // Initialize node
  create: 'rect'

  // Inherit from
, inherit: SVG.Shape

  // Add parent method
, construct: {
    // Create a rect element
    rect: function(width, height) {
      return this.put(new SVG.Rect().size(width, height))
    }
  }
})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SharedResourceHolder.Resource (grpc-core 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2015-03-22">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

io.grpc

Interface SharedResourceHolder.Resource<T>

Enclosing class:

SharedResourceHolder

public static interface SharedResourceHolder.Resource<T>

Defines a resource, and the way to create and destroy instances of it.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
close(T instance)

Destroy the given instance.

T
create()

Create a new instance of the resource.

Method Detail

create

T create()

Create a new instance of the resource.

close

void close(T instance)

Destroy the given instance.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@interface Hero : NSManagedObject

@property (nonatomic, retain, readonly) NSNumber * age;
@property (nonatomic, retain) NSDate * birthdate;
@property (nonatomic, retain) UIColor * favoriteColor;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * secretIdentity;
@property (nonatomic, retain) NSString * sex;

@end


text: from .runners import Noun  # ?


text:
package com.BibleQuote.dal;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.BibleQuote.dal.repository.bookmarks.BookmarksTags;
import com.BibleQuote.dal.repository.migration.Migration;
import com.BibleQuote.dal.repository.migration.Migration_1_2;
import com.BibleQuote.dal.repository.migration.Migration_2_3;
import com.BibleQuote.domain.entity.Bookmark;
import com.BibleQuote.domain.entity.Tag;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Yakushev V.V. / ru.phoenix@gmail.com
 * @since 02.05.13
 */
public final class DbLibraryHelper {

    public static final String DB_NAME = "library.db";
    public static final String TAGS_TABLE = "tags";
    public static final String BOOKMARKS_TAGS_TABLE = "bookmarks_tags";
    public static final String BOOKMARKS_TABLE = "bookmarks";

    private static final String[] CREATE_DATABASE = new String[]{
            "create table " + BOOKMARKS_TABLE + " ("
                    + Bookmark.KEY_ID + " integer primary key autoincrement, "
                    + Bookmark.OSIS + " text unique not null, "
                    + Bookmark.LINK + " text not null, "
                    + Bookmark.DATE + " text not null"
                    + ");",
            "create table " + BOOKMARKS_TAGS_TABLE + " ("
                    + BookmarksTags.BOOKMARKSTAGS_KEY_ID + " integer primary key autoincrement, "
                    + BookmarksTags.BOOKMARKSTAGS_BM_ID + " integer not null, "
                    + BookmarksTags.BOOKMARKSTAGS_TAG_ID + " integer not null"
                    + ");",
            "create table " + TAGS_TABLE + " ("
                    + Tag.KEY_ID + " integer primary key autoincrement, "
                    + Tag.NAME + " text unique not null"
                    + ");"
    };
    private static final List<Migration> MIGRATIONS = Arrays.asList(new Migration_1_2(), new Migration_2_3());
    private static final int VERSION = 3;

    private final Context mContext;
    private SQLiteDatabase database;

    public DbLibraryHelper(Context context) {
        mContext = context;
    }

    public SQLiteDatabase getDatabase() {
        if (database == null) {
            database = openOrCreateDatabase();
        }
        return database;
    }

    private void onCreate(SQLiteDatabase db) {
        for (String command : CREATE_DATABASE) {
            db.execSQL(command);
        }
    }

    private void onUpgrade(SQLiteDatabase db, final int oldVersion) {
        if (oldVersion == DbLibraryHelper.VERSION) {
            // миграция не требуется
            return;
        }

        Collections.sort(MIGRATIONS);
        int currVersion = oldVersion;
        for (Migration migration : MIGRATIONS) {
            // ищем миграцию для текущей версии БД
            if (migration.oldVersion != currVersion) {
                continue;
            }

            // выполняем миграцию и обновляем текущую версию
            migration.migrate(db);
            currVersion = migration.newVersion;

            // если достигли требуемой версии БД, то прерываем миграцию
            if (currVersion == DbLibraryHelper.VERSION) {
                break;
            }
        }
    }

    private SQLiteDatabase openOrCreateDatabase() {
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mContext.getDatabasePath(DB_NAME), null);
        int oldVersion = db.getVersion();
        if (oldVersion < VERSION) {
            db.beginTransaction();
            try {
                if (oldVersion == 0) {
                    onCreate(db);
                    oldVersion = 1;
                }
                onUpgrade(db, oldVersion);
                db.setVersion(VERSION);
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }

        return db;
    }
}


text:
		{{percentChange}}% <fa name="play" rotate="{{rotation}}"></fa>

		{{data.currentSatisfaction}}

		<fa name="line-chart" class="icon"></fa>
		Not enough data to render graph


text:
#region License
// https://github.com/TheBerkin/Rant.Demos
//
// Copyright (c) 2017 Nicholas Fleck
//
// 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.
#endregion

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

using Rant;

namespace BookCoverDemo
{
	public class BookModel
	{
		public const int CoverHeight = 700;
		public const int CoverWidth = 500;
		public const int CoverHeightFifth = CoverHeightInMargins / 5;
		public const int CoverHeightSixth = CoverHeightInMargins / 6;
		public const int CoverHeightQuarter = CoverHeightInMargins / 4;
		public const int CoverHeightEighth = CoverHeightInMargins / 8;
		public const int CoverHeightInMargins = CoverHeight - Margin * 2;
		public const int CoverWidthInMargins = CoverWidth - Margin * 2;
		public const int Margin = 15;
		public const int LargeMargin = CoverWidth / 5;

		private const StringFormatFlags StringDrawFlags = StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox;

		private static readonly PrivateFontCollection pfc;

		private readonly RantEngine rant;
		private readonly RantProgram pgmCover;

		private readonly RNG rand;

		static BookModel()
		{
			pfc = new PrivateFontCollection();
			foreach (var fontPath in Directory.GetFiles("fonts", "*.ttf"))
			{
				pfc.AddFontFile(fontPath);
			}

			AppDomain.CurrentDomain.ProcessExit += BookModelDestructor;
		}

		private static void BookModelDestructor(object sender, EventArgs eventArgs)
		{
			pfc.Dispose();
		}

		struct BookColorScheme
		{
			public readonly Color BackgroundColor;
			public readonly Color ForegroundColor;
			public readonly Color BorderColor;
			public readonly Color InnerBorderColor;

			public BookColorScheme(Color backgroundColor, Color foregroundColor, Color borderColor, Color innerBorderColor)
			{
				BackgroundColor = backgroundColor;
				ForegroundColor = foregroundColor;
				BorderColor = borderColor;
				InnerBorderColor = innerBorderColor;
			}
		}

		static readonly BookColorScheme[] BookColorSchemes =
		{
			new BookColorScheme(Color.Blue, Color.White, Color.Black, Color.Transparent),
			new BookColorScheme(Color.DarkBlue, Color.White, Color.LightGray, Color.Transparent),
			new BookColorScheme(Color.DarkRed, Color.WhiteSmoke, Color.Black, Color.Transparent),
			new BookColorScheme(Color.DarkGreen, Color.WhiteSmoke, Color.DarkGoldenrod, Color.Transparent),
			new BookColorScheme(Color.FromArgb(23, 141, 141), Color.LightGoldenrodYellow, Color.White, Color.Transparent),
			new BookColorScheme(Color.OrangeRed, Color.White, Color.Transparent, Color.Transparent),
			new BookColorScheme(Color.DarkMagenta, Color.FromArgb(255, 97, 182), Color.Black, Color.Transparent),
			new BookColorScheme(Color.WhiteSmoke, Color.IndianRed, Color.IndianRed, Color.DarkRed),
			new BookColorScheme(Color.DarkSlateBlue, Color.WhiteSmoke, Color.Black, Color.LightGray),
			new BookColorScheme(Color.DarkSlateGray, Color.WhiteSmoke, Color.Black, Color.Transparent),
			new BookColorScheme(Color.FromArgb(47, 30, 11), Color.FromArgb(218, 148, 32), Color.Black, Color.Gold),
			new BookColorScheme(Color.FromArgb(13, 13, 19), Color.LightGray, Color.DimGray, Color.Transparent),
			new BookColorScheme(Color.DarkSlateGray, Color.Gold, Color.Transparent, Color.LightGray),
			new BookColorScheme(Color.FromArgb(43, 42, 73), Color.FromArgb(226, 160, 51), Color.Transparent, Color.DarkGray),
		};

		public BookModel()
		{
			rant = new RantEngine();
			foreach (var path in Directory.GetFiles("rant", "*.rantpkg"))
			{
				rant.LoadPackage(path);
			}

#if SPICY
			rant.Dictionary.IncludeHiddenClass("nsfw");
#endif

			pgmCover = RantProgram.CompileFile("rant/cover.rant");
			rand = new RNG();
		}

		public Image GenerateCover(long seed, out string title)
		{
			var bmp = new Bitmap(CoverWidth, CoverHeight);
			using (var g = Graphics.FromImage(bmp))
			{
				g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
				// Generate data for cover
				var output = rant.Do(pgmCover, seed);
				title = output["title"].Normalize(NormalizationForm.FormC);
				var fontTitle = output["title-font"];
				var author = output["author"];
				var subtext = output["subtext"];
				var titleSize = float.Parse(output["title-size"]) / 7.5f;
				var authorSize = float.Parse(output["author-size"]) / 7.5f;
				var authorFlags = output["author-flags"];
				var titleBannerFlags = output["title-banner-flags"];
				bool stretchAuthorName = authorFlags.Contains("s");
				var titleHorizontalAlign = Util.ParseEnum<StringAlignment>(output["title-align"]);
				var authorHorizontalAlign = Util.ParseEnum<StringAlignment>(output["author-align"]);

				float titleFontSize = CoverHeight * 0.045f * titleSize;
				float authorFontSize = CoverHeight * 0.045f * authorSize;
				var titleFont = new Font(fontTitle, titleFontSize, Util.ParseEnum<FontStyle>(output["title-style"]));
				var authorFont = new Font(fontTitle, authorFontSize, Util.ParseEnum<FontStyle>(output["author-style"]));

				// Generate color scheme
				var colorScheme = BookColorSchemes[rand.Next(BookColorSchemes.Length)];

				// Create BG
				g.Clear(colorScheme.BackgroundColor);

				var searchQuery = new string(title.ToLower().Where(c => Char.IsLetterOrDigit(c) || c == ' ').ToArray());
#if SPICY
				if (rand.Next(0, 3) == 0) searchQuery += " nsfw";
#endif
				var searchedImage = NetUtils.GoogleImagesPickRandom(searchQuery, rand);
				if (searchedImage != null)
				{
					var searchedBitmap = new Bitmap(searchedImage);
					int scaledW, scaledH;
					float ratio;

					// Image must be fill-scaled to avoid stretching.
					// The shortest dimension must be scaled to fit the same dimension of the screen.
					// So there are two cases:
					// Width is shorter or image is square: Scale until width matches screen.
					// Height is shorter: Scale until height matches screen.

					// Width is shorter / image is square
					if (searchedBitmap.Width <= searchedBitmap.Height)
					{
						ratio = (float)searchedBitmap.Height / searchedBitmap.Width;
						scaledW = CoverWidth;
						scaledH = (int)(CoverWidth * ratio);
						g.DrawImage(searchedBitmap, new Rectangle(0, -(scaledH - CoverHeight) / 2, scaledW, scaledH));
					}
					// Height is shorter
					else
					{
						ratio = (float)searchedBitmap.Width / searchedBitmap.Height;
						scaledW = (int)(CoverHeight * ratio);
						scaledH = CoverHeight;
						g.DrawImage(searchedBitmap, new Rectangle(-(scaledW - CoverWidth) / 2, 0, scaledW, scaledH));
					}
					searchedBitmap.Dispose();
					searchedImage.Dispose();
				}

				// Background postprocessing
				using (var editor = new ImageEditor(bmp))
				{
					editor.FillColor(editor.Average(10), BlendMode.Multiply);
					editor.Blur(7);
				}

				bool hasSubtext = !string.IsNullOrWhiteSpace(output["subtext"]);

				StringAlignment titleVerticalAlign, authorVertialAlign;
				var rectTitle = Layout.GetLayoutRect(Util.ParseEnum<LayoutPosition>(output["title-pos"]), out titleVerticalAlign);
				var rectAuthor = Layout.GetLayoutRect(Util.ParseEnum<LayoutPosition>(output["author-pos"]), out authorVertialAlign);

				// Gradient (Horrible)
				if (rand.NextBoolean())
				{
					var gradientBrush = new LinearGradientBrush(
						new PointF(CoverWidth, 0),
						new PointF(CoverWidth, CoverHeight),
						Color.Black,
						Color.Transparent)
					{
						Blend = new Blend
						{
							Factors = new[] { 0.0f, 1.0f },
							Positions = new[] { 0.0f, 1.0f }
						}
					};

					g.FillRectangle(gradientBrush, 0, 0, CoverWidth, CoverHeight);
				}

				// Borders and banners
				DrawBanner(g, rectTitle, titleBannerFlags, colorScheme);
				DrawBookBorder(g, CoverWidth, CoverHeight, colorScheme, Margin * 0.6f, Margin * 0.05f);

				// Title
				DrawString(g, title, titleFont, colorScheme.ForegroundColor, rectTitle, titleHorizontalAlign, titleVerticalAlign, true, false);

				// Author
				DrawString(g, author, authorFont, colorScheme.ForegroundColor, rectAuthor, authorHorizontalAlign, authorVertialAlign, true, stretchAuthorName);

				// Subtext
				if (hasSubtext)
				{
					StringAlignment subtextVerticalAlign;
					var rectSubtext = Layout.GetLayoutRect(Util.ParseEnum<LayoutPosition>(output["subtext-pos"]), out subtextVerticalAlign);
					DrawString(g, subtext, titleFont, colorScheme.ForegroundColor, rectSubtext,
						Util.ParseEnum<StringAlignment>(output["subtext-align"]),
						subtextVerticalAlign, true, false);
				}

			}
			return bmp;
		}

		private static void DrawBanner(Graphics g, RectangleF rect, string bannerFlags, BookColorScheme colorScheme)
		{
			bool fill = bannerFlags.Contains("f");
			bool verticalLines = bannerFlags.Contains("v");
			bool horizontalLines = bannerFlags.Contains("h");
			bool stretchVertical = bannerFlags.Contains("V");
			bool stretchHorizontal = bannerFlags.Contains("H");

			var bannerFillRect = rect;

			// Calculate banner area
			if (stretchHorizontal)
			{
				bannerFillRect.X = 0;
				bannerFillRect.Width = CoverWidth;
			}

			if (stretchVertical)
			{
				bannerFillRect.Y = 0;
				bannerFillRect.Height = CoverHeight;
			}

			if (verticalLines) bannerFillRect.Inflate(Margin * 0.5f, 0);
			if (horizontalLines) bannerFillRect.Inflate(0, Margin * 0.5f);

			// Draw banner background
			if (fill)
			{
				g.FillRectangle(new SolidBrush(colorScheme.BackgroundColor), bannerFillRect);
			}

			// Draw banner lines
			var pen = new Pen(colorScheme.ForegroundColor, 1.5f);

			if (verticalLines)
			{
				g.DrawLine(pen, bannerFillRect.Left, bannerFillRect.Top, bannerFillRect.Left, bannerFillRect.Bottom);
				g.DrawLine(pen, bannerFillRect.Right, bannerFillRect.Top, bannerFillRect.Right, bannerFillRect.Bottom);
			}

			if (horizontalLines)
			{
				g.DrawLine(pen, bannerFillRect.Left, bannerFillRect.Top, bannerFillRect.Right, bannerFillRect.Top);
				g.DrawLine(pen, bannerFillRect.Left, bannerFillRect.Bottom, bannerFillRect.Right, bannerFillRect.Bottom);
			}
		}

		private static void DrawBookBorder(Graphics g, int w, int h, BookColorScheme colorScheme, float borderThickness, float innerBorderThickness)
		{
			var penOuter = new Pen(colorScheme.BorderColor, borderThickness)
			{
				LineJoin = LineJoin.MiterClipped,
				Alignment = PenAlignment.Inset
			};
			var penInner = new Pen(colorScheme.InnerBorderColor, innerBorderThickness)
			{
				LineJoin = LineJoin.MiterClipped,
				Alignment = PenAlignment.Center
			};
			g.DrawRectangle(penOuter, 0, 0, w, h);
			g.DrawRectangle(penInner, borderThickness / 2, borderThickness / 2, w - borderThickness, h - borderThickness);
		}

		private static void DrawString(Graphics g, string text, Font font, Color color, RectangleF rect, StringAlignment halign, StringAlignment valign, bool shadow, bool stretch)
		{
			const StringFormatFlags stretchFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
			const float stretchFontSize = CoverWidthInMargins;
			var fmt = new StringFormat
			{
				Alignment = halign,
				Trimming = StringTrimming.Word,
				LineAlignment = valign,
				FormatFlags = StringDrawFlags
			};
			var shadowRect = rect;
			float shadowOffset = Margin * 0.2f;
			shadowRect.Offset(shadowOffset, shadowOffset);

			// Stretch mode
			if (stretch)
			{
				var stretchFormat = new StringFormat
				{
					Alignment = StringAlignment.Center,
					LineAlignment = valign,
					Trimming = StringTrimming.None,
					FormatFlags = stretchFlags
				};
				var stretchFont = new Font(font.FontFamily, stretchFontSize, font.Style == FontStyle.Italic ? FontStyle.Regular : font.Style);
				var stretchSize = g.MeasureString(text, stretchFont);

				// First the text is drawn onto a separate bitmap, then it is scaled and applied to the cover.
				using (var stretchImage = new Bitmap((int)stretchSize.Width, (int)stretchSize.Height, PixelFormat.Format32bppArgb))
				using (var gs = Graphics.FromImage(stretchImage))
				{
					gs.Clear(Color.Transparent);
					var stretchRect = new RectangleF(0, 0, stretchSize.Width, stretchSize.Height);

					// Draw shadow
					if (shadow)
					{
						gs.DrawString(text, stretchFont, Brushes.Black, stretchRect, stretchFormat);
						g.DrawImage(stretchImage, shadowRect);
						gs.Clear(Color.Transparent);
					}

					gs.DrawString(text, stretchFont, new SolidBrush(color), stretchRect, stretchFormat);
					g.DrawImage(stretchImage, rect);
				}

				return;
			}

			// If the text won't all fit in the allotted space, reduce the font size.
			int fitted, lines;
			g.MeasureString(text, font, new SizeF(rect.Width, rect.Height), fmt, out fitted, out lines);
			if (fitted < text.Length) font = new Font(font.FontFamily, font.Size * (fitted / (float)text.Length), font.Style);

			// Draw shadow
			if (shadow)
			{
				g.DrawString(text, font, Brushes.Black, shadowRect, fmt);
			}

			g.DrawString(text, font, new SolidBrush(color), rect, fmt);
		}
	}
}


text:
// Copyright (c) Copyright (c) The University of Edinburgh, Universidad Politecnica de Madrid, 2009-2012.
//
// LICENCE-START
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// LICENCE-END

package es.upm.fi.dia.oeg.ogsadai.sparql.federation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import uk.org.ogsadai.converters.databaseschema.ColumnMetaData;
import uk.org.ogsadai.converters.databaseschema.KeyMetaData;
import uk.org.ogsadai.converters.databaseschema.TableMetaData;
import uk.org.ogsadai.dqp.common.EvaluationNode;
import uk.org.ogsadai.dqp.common.TableSchema;
import uk.org.ogsadai.dqp.common.simple.SimpleDataDictionary;
import uk.org.ogsadai.dqp.lqp.Attribute;
import uk.org.ogsadai.dqp.lqp.AttributeImpl;
import uk.org.ogsadai.dqp.lqp.Heading;
import uk.org.ogsadai.dqp.lqp.HeadingImpl;
import uk.org.ogsadai.dqp.lqp.exceptions.TableNotFoundException;
import uk.org.ogsadai.dqp.lqp.udf.FunctionRepository;

/**
 * Simple implementation of a data dictionary which stores the table schemas in
 * memory.
 *
 * TODO: doc
 *
 * @author The OGSA-DAI Project Team.
 */
public class SimpleRDFDataDictionary extends SimpleDataDictionary //implements DataDictionary
{
    /** Copyright notice. */
    private static final String COPYRIGHT_NOTICE =
            "Copyright (c) The University of Edinburgh, 2008, Universidad Politecnica de Madrid, 2011";

    private final Set<TableSchema> mLogicalSchemas = new HashSet<TableSchema>();

    private final Map<String, TableSchema> mTableMetadata = new HashMap<String, TableSchema>();

    private FunctionRepository mFunctionRepository;

    private final List<String> mServerList = new ArrayList<String>();

    private Set<EvaluationNode> mEvaluationNodes;

    public Set<TableSchema> getTableSchemas()
    {
        return mLogicalSchemas;
    }

    /**
     * Add a new schema to the data dictionary.
     *
     * @param schema
     *            table schema to add
     */
    public synchronized void add(TableSchema schema)
    {
        mLogicalSchemas.add(schema);
        mTableMetadata.put(schema.getTableName(), schema);
    }

    /**
     * Remove a schema from the data dictionary.
     *
     * @param schema
     *            table schema to remove
     */
    public synchronized void remove(TableSchema schema)
    {
        mLogicalSchemas.remove(schema);
        mTableMetadata.remove(schema.getTableName());
    }

    public Heading getHeading(String tableName) throws TableNotFoundException
    {
        TableSchema schema = mTableMetadata.get(tableName);
        if (schema == null)
        {
            throw new TableNotFoundException(tableName);
        }

        Set<String> keyColumnNameSet = new HashSet<String>();
        TableMetaData metadata = schema.getSchema();
        String[] primaryKeys = metadata.getPrimaryKeys();
        if (primaryKeys.length == 1)
        {
            // we can use only non composite key for attributes
            keyColumnNameSet.add(primaryKeys[0]);
        }

        KeyMetaData[] kmdArray = metadata.getImportedKeys();
        if (kmdArray != null)
        {
            for (KeyMetaData kmd : kmdArray)
            {
                keyColumnNameSet.add(kmd.getPrimaryKeyColumnName());
            }
        }

        List<Attribute> attribList = new ArrayList<Attribute>();
        for (int i = 1; i <= metadata.getColumnCount(); i++)
        {
            ColumnMetaData column = metadata.getColumn(i);
            int type = column.getTupleType();

            boolean isPrimaryKey = column.isPrimaryKey() ? true
                    : keyColumnNameSet.contains(column.getName());

            attribList.add(new AttributeImpl(column.getName(), type, tableName,
                    isPrimaryKey));
        }

        return new HeadingImpl(attribList);
    }

    public TableSchema getTableSchema(String tableName)
            throws TableNotFoundException
    {
        TableSchema schema = mTableMetadata.get(tableName);
        if (schema == null)
        {
            throw new TableNotFoundException(tableName);
        }
        return schema;
    }

    /**
     * Sets the function repository of this data dictionary.
     *
     * @param functionRepository
     *            repository
     */
    public void setFunctionRepository(FunctionRepository functionRepository)
    {
        mFunctionRepository = functionRepository;
    }

    public FunctionRepository getFunctionRepository()
    {
        return mFunctionRepository;
    }

    public void addEvaluationNodes(Set<EvaluationNode> evaluationNodes)
    {
        mEvaluationNodes = evaluationNodes;
    }

    public Set<EvaluationNode> getEvaluationNodes()
    {
        return mEvaluationNodes;
    }

}


text:
package io.kubernetes.client.admissionreview.models;

import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;

/** AdmissionReview describes an admission review request/response. */
@ApiModel(description = "AdmissionReview describes an admission review request/response.")
@javax.annotation.Generated(
    value = "org.openapitools.codegen.languages.JavaClientCodegen",
    date = "2021-07-01T14:30:02.888Z[Etc/UTC]")
public class AdmissionReview {
  public static final String SERIALIZED_NAME_API_VERSION = "apiVersion";

  @SerializedName(SERIALIZED_NAME_API_VERSION)
  private String apiVersion;

  public static final String SERIALIZED_NAME_KIND = "kind";

  @SerializedName(SERIALIZED_NAME_KIND)
  private String kind;

  public static final String SERIALIZED_NAME_REQUEST = "request";

  @SerializedName(SERIALIZED_NAME_REQUEST)
  private AdmissionRequest request;

  public static final String SERIALIZED_NAME_RESPONSE = "response";

  @SerializedName(SERIALIZED_NAME_RESPONSE)
  private AdmissionResponse response;

  public AdmissionReview apiVersion(String apiVersion) {

    this.apiVersion = apiVersion;
    return this;
  }

  /**
   * APIVersion defines the versioned schema of this representation of an object. Servers should
   * convert recognized schemas to the latest internal value, and may reject unrecognized values.
   * More info:
   * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
   *
   * @return apiVersion
   */
  @javax.annotation.Nullable
  @ApiModelProperty(
      value =
          "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources")
  public String getApiVersion() {
    return apiVersion;
  }

  public void setApiVersion(String apiVersion) {
    this.apiVersion = apiVersion;
  }

  public AdmissionReview kind(String kind) {

    this.kind = kind;
    return this;
  }

  /**
   * Kind is a string value representing the REST resource this object represents. Servers may infer
   * this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More
   * info:
   * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
   *
   * @return kind
   */
  @javax.annotation.Nullable
  @ApiModelProperty(
      value =
          "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds")
  public String getKind() {
    return kind;
  }

  public void setKind(String kind) {
    this.kind = kind;
  }

  public AdmissionReview request(AdmissionRequest request) {

    this.request = request;
    return this;
  }

  /**
   * Get request
   *
   * @return request
   */
  @javax.annotation.Nullable
  @ApiModelProperty(value = "")
  public AdmissionRequest getRequest() {
    return request;
  }

  public void setRequest(AdmissionRequest request) {
    this.request = request;
  }

  public AdmissionReview response(AdmissionResponse response) {

    this.response = response;
    return this;
  }

  /**
   * Get response
   *
   * @return response
   */
  @javax.annotation.Nullable
  @ApiModelProperty(value = "")
  public AdmissionResponse getResponse() {
    return response;
  }

  public void setResponse(AdmissionResponse response) {
    this.response = response;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    AdmissionReview admissionReview = (AdmissionReview) o;
    return Objects.equals(this.apiVersion, admissionReview.apiVersion)
        && Objects.equals(this.kind, admissionReview.kind)
        && Objects.equals(this.request, admissionReview.request)
        && Objects.equals(this.response, admissionReview.response);
  }

  @Override
  public int hashCode() {
    return Objects.hash(apiVersion, kind, request, response);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class AdmissionReview {\n");
    sb.append("    apiVersion: ").append(toIndentedString(apiVersion)).append("\n");
    sb.append("    kind: ").append(toIndentedString(kind)).append("\n");
    sb.append("    request: ").append(toIndentedString(request)).append("\n");
    sb.append("    response: ").append(toIndentedString(response)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
.. _sam_v71_xplained_ultra:

SAM V71(B) Xplained Ultra
#########################

Overview
********

The SAM V71 Xplained Ultra evaluation kit is a development platform to
evaluate the Atmel SAM V71 series microcontrollers. The current version
allows to use both IC variations ATSAMV71Q21A(B).

.. image:: img/sam_v71_xult.jpg
     :align: center
     :alt: SAM V71 Xplained Ultra

Hardware
********

- ATSAMV71Q21A(B) ARM Cortex-M7 Processor
- 12 MHz crystal oscillator
- 32.768 kHz crystal oscillator
- Supercap backup
- AT24MAC402 EEPROM
- IS42S16100E 16 Mb SDRAM
- S25FL116K 16 Mb QSPI
- WM8904 low power stereo audio codec
- ATA6561 CAN Transceiver
- SD card connector with SDIO support
- Camera interface connector
- MediaLB connector
- Ethernet port
- Micro-AB USB device
- Micro-AB USB debug interface supporting CMSIS-DAP, Virtual COM Port and Data
  Gateway Interface (DGI)
- JTAG interface connector
- One reset and two user pushbuttons
- Two yellow user LEDs

Supported Features
==================

The sam_v71_xplained_ultra board configuration supports the following hardware
features:

+-----------+------------+-------------------------------------+
| Interface | Controller | Driver/Component                    |
+===========+============+=====================================+
| NVIC      | on-chip    | nested vector interrupt controller  |
+-----------+------------+-------------------------------------+
| SYSTICK   | on-chip    | systick                             |
+-----------+------------+-------------------------------------+
| UART      | on-chip    | serial port                         |
+-----------+------------+-------------------------------------+
| USART     | on-chip    | serial port                         |
+-----------+------------+-------------------------------------+
| I2C       | on-chip    | i2c                                 |
+-----------+------------+-------------------------------------+
| SPI       | on-chip    | spi                                 |
+-----------+------------+-------------------------------------+
| ETHERNET  | on-chip    | ethernet                            |
+-----------+------------+-------------------------------------+
| WATCHDOG  | on-chip    | watchdog                            |
+-----------+------------+-------------------------------------+
| GPIO      | on-chip    | gpio                                |
+-----------+------------+-------------------------------------+
| ADC       | on-chip    | ADC via AFEC                        |
+-----------+------------+-------------------------------------+
| USB       | on-chip    | USB device                          |
+-----------+------------+-------------------------------------+
| PWM       | on-chip    | pwm                                 |
+-----------+------------+-------------------------------------+
| CAN-FD    | on-chip    | can                                 |
+-----------+------------+-------------------------------------+
| HWINFO    | on-chip    | Unique device serial number         |
+-----------+------------+-------------------------------------+

Other hardware features are not currently supported by Zephyr.

The default configuration can be found in the Kconfig
:zephyr_file:`boards/arm/sam_v71_xult/sam_v71_xult_defconfig`.

Connections and IOs
===================

The `SAMV71-XULT User Guide`_ has detailed information about board
connections.

System Clock
============

The SAM V71 MCU is configured to use the 12 MHz external oscillator on the
board with the on-chip PLL to generate a 300 MHz system clock.

Serial Port
===========

The ATSAMV71Q21 MCU has five UARTs and three USARTs. USART1 is configured
for the console and is available as a Virtual COM Port via EDBG USB chip.

Programming and Debugging
*************************

Flashing the Zephyr project onto SAM V71 MCU requires the `OpenOCD tool`_.
By default a factory new SAM V71 chip will boot the `SAM-BA`_ boot loader
located in the ROM, not the flashed image. This is determined by the value
of GPNVM1 (General-Purpose NVM bit 1). The flash procedure will ensure that
GPNVM1 is set to 1 changing the default behavior to boot from Flash.

If your chip has a security bit GPNVM0 set you will be unable to program flash
memory or connect to it via a debug interface. The only way to clear GPNVM0
is to perform a chip erase procedure that will erase all GPNVM bits and the
full contents of the SAM V71 flash memory:

- With the board power off, set a jumper on the J200 header.
- Turn the board power on. The jumper can be removed soon after the power is
  on (flash erasing procedure is started when the erase line is asserted for
  at least 230ms)

Flashing
========

#. Run your favorite terminal program to listen for output. Under Linux the
   terminal should be :code:`/dev/ttyACM0`. For example:

   .. code-block:: console

      $ minicom -D /dev/ttyACM0 -o

   The -o option tells minicom not to send the modem initialization
   string. Connection should be configured as follows:

   - Speed: 115200
   - Data: 8 bits
   - Parity: None
   - Stop bits: 1

#. Connect the SAM V71 Xplained Ultra board to your host computer using the
   USB debug port. Then build and flash the :ref:`hello_world`
   application.

   .. zephyr-app-commands::
      :zephyr-app: samples/hello_world
      :board: sam_v71_xult
      :goals: build flash

   You should see "Hello World! arm" in your terminal.

#. To use the SoC variation B IC, you need type "sam_v71b_xult".

   .. zephyr-app-commands::
      :zephyr-app: samples/hello_world
      :board: sam_v71b_xult
      :goals: build flash

   You should see "Hello World! arm" in your terminal.

You can flash the image using an external debug adapter such as J-Link
or ULINK, connected to the 20-pin JTAG header. Supply the name of the
debug adapter (e.g., ``jlink``) via an OPENOCD_INTERFACE environment
variable. OpenOCD will look for the appropriate interface
configuration in an ``interface/$(OPENOCD_INTERFACE).cfg`` file on its
internal search path.

Debugging
=========

You can debug an application in the usual way.  Here is an example for the
:ref:`hello_world` application.

.. zephyr-app-commands::
   :zephyr-app: samples/hello_world
   :board: sam_v71_xult
   :maybe-skip-config:
   :goals: debug

References
**********

SAM V71 Product Page:
    https://www.microchip.com/design-centers/32-bit/sam-32-bit-mcus/sam-v-mcus

.. _SAMV71-XULT User Guide:
    http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42408-SAMV71-Xplained-Ultra_User-Guide.pdf

.. _OpenOCD tool:
    http://openocd.org/

.. _SAM-BA:
    https://www.microchip.com/developmenttools/ProductDetails/PartNO/SAM-BA%20In-system%20Programmer


text:
package edu.harvard.hul.ois.fits.tools.ffident;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.apache.log4j.Logger;

import edu.harvard.hul.ois.fits.Fits;
import edu.harvard.hul.ois.fits.exceptions.FitsToolException;
import edu.harvard.hul.ois.fits.tools.ToolBase;
import edu.harvard.hul.ois.fits.tools.ToolInfo;
import edu.harvard.hul.ois.fits.tools.ToolOutput;

/** The main class of the FFIdent tool, adapted for use under FITS.
 *  Uses tools/ffident/formats.txt
 */
public class FFIdent extends ToolBase {

    private final static String TOOL_NAME = "ffident";
    private final static String TOOL_VERSION = "0.2";
    private final static String TOOL_DATE = "2005-10-21";

	private FormatIdentification identifier = null;
	public final static String xslt =Fits.FITS_XML+"/ffident/ffident_to_fits.xslt";
	private boolean enabled = true;

    private static final Logger logger = Logger.getLogger(FFIdent.class);

	public FFIdent() throws FitsToolException{

        logger.debug ("Initializing FFIdent");
		info = new ToolInfo(TOOL_NAME, TOOL_VERSION, TOOL_DATE);

		try {
			File config = new File(Fits.FITS_TOOLS+"ffident/formats.txt");
			identifier = new FormatIdentification(config.getPath());
		} catch (FileNotFoundException e) {
			throw new FitsToolException(Fits.FITS_TOOLS+"ffident/formats.txt could not be found",e);
		}
	}

	public ToolOutput extractInfo(File file) throws FitsToolException {
	    logger.debug ("FFIdent.extractInfo starting on " + file.getName());
		long startTime = System.currentTimeMillis();
		FormatDescription desc = identifier.identify(file);
		//FileIdentity identity = null;
		Document rawOut = null;
		Document fitsXml = null;
		//if (desc != null) {
			//desc.getShortName();
			//desc.getMimeTypes();
			//identity = new FileIdentity(desc.getMimeType(),desc.getShortName(),null);
			rawOut = createXml(desc);
			fitsXml = transform(xslt,rawOut);
		//}
		output = new ToolOutput(this,fitsXml,rawOut);
		duration = System.currentTimeMillis()-startTime;
		runStatus = RunStatus.SUCCESSFUL;
        logger.debug ("FFIdent.extractInfo finished on " + file.getName());
		return output;
	}

   private Document createXml(FormatDescription desc) throws FitsToolException {
    	StringWriter out = new StringWriter();

    	String shortname;
    	String longname;
    	String group;
    	List<String> mimetypes = new ArrayList<String>();
    	List<String> exts = new ArrayList<String>();

    	if(desc == null) {
    		shortname = "";
    		longname = "Unknown Binary";
    		group = "";
    		mimetypes.add("application/octet-stream");
    	}
    	else {
    		shortname = desc.getShortName();
    		longname = desc.getLongName();
    		group = desc.getGroup();
    		mimetypes = desc.getMimeTypes();
    		exts = desc.getFileExtensions();
    	}

        out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.write("\n");
        out.write("<ffidentOutput>");
        out.write("\n");
        out.write("  <shortName>"+shortname+"</shortName>");
        out.write("\n");
        out.write("  <longName>"+longname+"</longName>");
        out.write("\n");
        out.write("  <group>"+group+"</group>");
        out.write("\n");
        out.write("  <mimetypes>");
        out.write("\n");
        for(String mime : mimetypes) {
        	out.write("    <mimetype>"+mime+"</mimetype>");
        	out.write("\n");
        }
        out.write("  </mimetypes>");
        out.write("\n");

        out.write("  <fileExtensions>");
        out.write("\n");
        for(String ext : exts) {
        	out.write("    <extension>"+ext+"</extension>");
        	out.write("\n");
        }
        out.write("  </fileExtensions>");
        out.write("\n");
        out.write("</ffidentOutput>");
        out.write("\n");
        out.flush();
        try {
			out.close();
		} catch (IOException e) {
		    logger.debug ("Error closing ffident XML output stream: " + e.getClass().getName());
			throw new FitsToolException("Error closing ffident XML output stream",e);
		}

        Document doc = null;
		try {
			doc = saxBuilder.build(new StringReader(out.toString()));
		} catch (Exception e) {
		    logger.debug("Error parsing ffident XML Output: " + e.getClass().getName());
			throw new FitsToolException("Error parsing ffident XML Output",e);
		}
        return doc;
    }

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean value) {
		enabled = value;
	}

}


text: Live version at [从零开始学习Ruby课程](http://rubybasic.herokuapp.com)


text:
using System;
using BetterModules.Core.Exceptions;

namespace BetterModules.Core.Web.Exceptions.Host
{
    [Serializable]
    public class RestartApplicationException : CoreException
    {
        public RestartApplicationException(string message)
            : base(message)
        {
        }

        public RestartApplicationException(string message, Exception innerException)
            : base(message, innerException)
        {
        }
    }
}


text:
"""
Implements logic for day1 oprations.
"""
from ruamel import yaml
import re
import subprocess
import os
from time import sleep

def create_configs(payload, socketio):
    """
    Accepts configuration parameters in json format.
    And store them in there respective configuration files(vdx.conf, nsx.conf).
    """
    vdx_params = ["vip", "username", "password", "overlay_gateway_name"]
    nsx_params = ["nsx_mgr_ip", "nsx_mgr_user", "nsx_mgr_pass", "lswitch_name", "switch_name", "hardware_gateway_name"]

    vdx_dict = {}
    nsx_dict = {}
    for key in payload:
        if key in vdx_params:
            vdx_dict[key] = payload[key]

        if key in nsx_params:
            nsx_dict[key] = payload[key]

    with open('/opt/stackstorm/configs/vdx_vtep.yaml', 'w') as outfile:
        yaml.safe_dump(vdx_dict, outfile, default_flow_style=False, explicit_start=True, indent=4)

    with open('/opt/stackstorm/configs/nsx_vtep.yaml', 'w') as outfile:
        yaml.safe_dump(nsx_dict, outfile, default_flow_style=False, explicit_start=True, indent=4)

    socketio.emit('day1_log', "Data submitted successfully", namespace='/submit')
    return True

def reload_configs():
    """
        Reloads configuration parameters in stackstorm database from configuration files.
    """
    os.system("st2ctl reload --register-configs")

def run_workflow(lswitch, vlan, port):
    """
        Execute day1 workflow which will configure VNI to VLAN mapping.
    """
    workflow_cmd = "st2 run vdx_vtep.attach_vlan_to_gw_workflow lswitch_name=%s vlan=%s port=%s" % (lswitch, vlan, port)
    subprocess.Popen(workflow_cmd, shell=True)

def configure_mapping(payload):
    """
        Calls day1 workflow for each VNI to VLAN mapping.
        If there are n number of mappings then it will call workflow n times.
    """
    flag = True
    for k, v in payload.iteritems():
        if re.search("mapping[1-9]", k):
            lswitch = v.pop('lswitch', None)
            vlan = v.pop('vlan', None)
            port = v.pop('port', None)
            run_workflow(lswitch, vlan, port)
            sleep(10)

def vni_mapping(payload, socketio):
    """
        Main function of this module.
            1. Accepts configuration parameters in json format.
            2. Creates configuration files.
            3. Execute workflow.
    """
    create_configs(payload, socketio)
    reload_configs()
    configure_mapping(payload)


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/sol_margin_olcu_onbes"
    android:paddingTop="@dimen/sol_margin_olcu_onbes"
    android:background="@color/beyaz_renk">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center_vertical">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/sol_margin_olcu_onbes"
                android:textStyle="bold"
                android:text="@string/baslik"
                />

            <TextView
                android:id="@+id/tvbaslik"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/margin_bes"
                android:text=""
                />

        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="10dp">
            <TextView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/sol_margin_olcu_onbes"
                android:textStyle="bold"
                android:text="@string/icerik"
                />
            <TextView
                android:id="@+id/tvicerik"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/margin_bes"
                android:text=""
                />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
using UnityEngine;
using System.Collections;

/// <summary>
/// Server manager handles the hosting and connecting to the game server. Provides a basic GUI for starting, finding, and connecting to games.
/// </summary>
public class ServerManager : MonoBehaviour
{
	string registeredName = "somekindofuniquename";
	float refreshRequestLength = 3.0f;
	HostData[] hostData;
	public string chosenGameName = "";

	private void StartServer ()
	{
		Network.InitializeServer (16, Random.Range (2000, 2500), !Network.HavePublicAddress ());
		MasterServer.RegisterHost (registeredName, chosenGameName);
	}

	private IEnumerator RefreshHostList ()
	{
		MasterServer.RequestHostList (registeredName);
		float timeEnd = Time.time + refreshRequestLength;
		while (Time.time < timeEnd) {
			hostData = MasterServer.PollHostList ();
			yield return new WaitForEndOfFrame ();
		}
	}

	public void OnGUI ()
	{
		if (Network.isClient || Network.isServer) {
			return;
		}
		if (chosenGameName == "") {
			GUI.Label (new Rect (Screen.width / 2 - Screen.width / 10, Screen.height / 2 - Screen.height / 20, Screen.width / 5, Screen.height / 20), "Game Name");
		}
		chosenGameName = GUI.TextField (new Rect (Screen.width / 2 - Screen.width / 10, Screen.height / 2 - Screen.height / 20, Screen.width / 5, Screen.height / 20), chosenGameName, 25);
		if (GUI.Button (new Rect (Screen.width / 2 - Screen.width / 10, Screen.height / 2, Screen.width / 5, Screen.height / 10), "Start New Server")) {
			StartServer ();
		}
		if (GUI.Button (new Rect (Screen.width / 2 - Screen.width / 10, Screen.height / 2 + Screen.height / 10, Screen.width / 5, Screen.height / 10), "Find Servers")) {
			StartCoroutine (RefreshHostList ());
		}
		if (hostData != null) {
			for (int i = 0; i < hostData.Length; i++) {
				if (GUI.Button (new Rect (Screen.width / 2 - Screen.width / 10, Screen.height / 2 + ((Screen.height / 20) * (i + 4)), Screen.width / 5, Screen.height / 20), hostData [i].gameName)) {
					Network.Connect (hostData [i]);
				}
			}
		}
	}
}


text:
Finance
=======

Ariah Finance


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BrightcoveMapiWrapper.Model;
using BrightcoveMapiWrapper.Model.Items;
using NUnit.Framework;
using BrightcoveMapiWrapper.Model.Containers;
using BrightcoveMapiWrapper.Api;

namespace BrightcoveOS.NET_MAPI_Wrapper.Tests.IntegrationTests.AudioTrackPlaylistWrite
{
	[TestFixture]
	public class CreateAudioTrackPlaylistTests : AudioTrackPlaylistWriteTestBase
	{
		[Test]
		public void CreateAudioTrackPlaylist_Test_Basic()
		{
			BrightcoveItemCollection<BrightcoveAudioTrack> audioTracks = _api.FindAllAudioTracks(4, 0);
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-5" + RandomString(8),
				// Get a list of random audio tracks to add to the playlist.
				AudioTrackIds = audioTracks.Select(x => x.Id).ToList(),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.Explicit,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			BrightcoveAudioTrackPlaylist newPlaylist = _api.FindAudioTrackPlaylistById(newId);

			Assert.AreEqual(playlist.Name, newPlaylist.Name);
			Assert.AreEqual(playlist.ReferenceId, newPlaylist.ReferenceId);
			Assert.AreEqual(playlist.ShortDescription, newPlaylist.ShortDescription);
			Assert.AreEqual(audioTracks.Count, newPlaylist.AudioTrackIds.Count);
			Assert.AreEqual(audioTracks.Count, newPlaylist.AudioTracks.Count);
			Assert.AreEqual(audioTracks.Count, newPlaylist.AudioTracks.Count(o => o != null));
		}

		[Test]
		[ExpectedException(typeof(BrightcoveApiException))]
		public void CreateAudioTrackPlaylist_Test_PlaylistType_PlaysTotal()
		{
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-6" + RandomString(8),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.PlaysTotal,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			Assert.Greater(newId, 0);
		}

		[Test]
		[ExpectedException(typeof(BrightcoveApiException))]
		public void CreateAudioTrackPlaylist_Test_PlaylistType_PlaysTrailingWeek()
		{
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-6" + RandomString(8),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.PlaysTrailingWeek,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			Assert.Greater(newId, 0);
		}

		[Test]
		[ExpectedException(typeof(BrightcoveApiException))]
		public void CreateAudioTrackPlaylist_Test_PlaylistType_StartDateNewestToOldest()
		{
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-7" + RandomString(8),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.StartDateNewestToOldest,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			Assert.Greater(newId, 0);
		}

		[Test]
		[ExpectedException(typeof(BrightcoveApiException))]
		public void CreateAudioTrackPlaylist_Test_PlaylistType_StartDateOldestToNewest()
		{
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-8" + RandomString(8),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.StartDateOldestToNewest,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			Assert.Greater(newId, 0);
		}

		[Test]
		public void CreateAudioTrackPlaylist_Test_PlaylistType_Alphabetical()
		{
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-9" + RandomString(8),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.Alphabetical,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			Assert.Greater(newId, 0);
		}

		[Test]
		public void CreateAudioTrackPlaylist_Test_PlaylistType_NewestToOldest()
		{
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-10" + RandomString(8),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.NewestToOldest,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			Assert.Greater(newId, 0);
		}

		[Test]
		public void CreateAudioTrackPlaylist_Test_PlaylistType_OldestToNewest()
		{
			BrightcoveAudioTrackPlaylist playlist = new BrightcoveAudioTrackPlaylist
			{
				Name = "Test Audio Playlist",
				ReferenceId = "new-reference-id-11" + RandomString(8),
				ShortDescription = "This is a playlist's short description",
				PlaylistType = PlaylistType.OldestToNewest,
				FilterTags = new[] { "president" }
			};

			long newId = _api.CreateAudioTrackPlaylist(playlist);
			Assert.Greater(newId, 0);
		}
	}
}


text:
body {padding: 0px; margin: 0px; background-color: #fff; line-height: 24px}
body, div, td, input {font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; }

h1 {color: #888; margin: 0px 0px 30px 0px; border-bottom: 1px dotted #888; padding-bottom: 10px; font-size: 32px}
h2 {color: #303030; margin: 0px 0px 10px 0px; font-size: 18px}

div#ccm-logo {border-top: 3px solid #222; background: url(../images/bg_header.png) repeat-x; }
div#ccm-theme-wrapper {width: 640px; margin: 0px auto 0px auto; background: #fff; padding: 20px; }

a {color: #538AC4}
p {color: #333}
div.ccm-spacer {clear: both; line-height: 0px; margin-right: 0px}

.ccm-error {color: #f00; font-weight: bold}
ul.ccm-error {font-size: 12px; list-style-type: none; padding: 0px; margin: 0px 0px 30px 0px}
ul.ccm-error li {margin-bottom: 8px}

div.ccm-form {width: 300px; margin: 0px auto 0px auto}

div.ccm-form label {font-size: 14px; color: #333}
div.ccm-form-sub {color: #888; font-size: 12px}
div.ccm-form input.ccm-input-text, div.ccm-form input.uak-text, div.ccm-form input.ccm-input-password, div.ccm-form input.ccm-input-captcha {width: 300px; font-size: 18px; color: #444; padding: 4px}
div.ccm-form input.ccm-input-openid {background: #fff url(../images/icons/openid.gif) no-repeat scroll 2px 6px; width: 284px; font-size: 18px; color: #444; padding: 4px 4px 4px 20px}

input.ccm-input-submit, input.ccm-input-button {font-size: 18px;}
div.ccm-button {margin-top: 12px; text-align: right}

/* install check */

div#ccm-install-check {width: 300px; float: left; margin-right: 40px}
div#ccm-install-form {width: 300px; float: left}

div#ccm-install-check-items {background: #ebebeb url(../images/bg_default_pane.jpg) repeat-x scroll; padding: 10px; border: 1px solid #ddd; -webkit-border-radius: 10px; -moz-border-radius: 10px}
div#ccm-install-check-items div.test {padding: 2px 30px 4px 0px; position: relative;  background-attachment: scroll; background-position: right 7px; background-repeat: no-repeat}
div#ccm-install-check-items div.passed {background-image: url(../images/icons/success.png); color: #666}
div#ccm-install-check-items div.loading {background-image: url(../images/dashboard/sitemap/loading.gif);}
div#ccm-install-check-items div.warning {background-image: url(../images/icons/warning.png); font-weight: bold}
div#ccm-install-check-items div.fail {background-image: url(../images/icons/error.png); font-weight: bold}
div#ccm-install-check-items h2 {margin-bottom: 3px; margin-top: 20px}
div#ccm-install-note a {text-decoration: none}
div#ccm-install-note a:hover {text-decoration: underline}
div#ccm-install-note {font-size: 12px; margin-top: 10px; text-align: center; line-height: 18px}
div.ccm-install-info {display: none; font-size: 12px; font-weight: normal; color: #000; line-height: 18px; margin-bottom: 20px}
a.ccm-install-tooltip img {position: absolute; top: 7px; right: 21px}
div#ccm-install-check-items div.passed a.ccm-install-tooltip {display: none}
div#ccm-install-check-items div.loading a.ccm-install-tooltip {display: none}