text:
import datetime
import os
import uuid
from decimal import Decimal

import django
import pytest
from django.http import QueryDict
from django.utils import timezone

import rest_framework
from rest_framework import serializers

# Tests for field keyword arguments and core functionality.
# ---------------------------------------------------------

class TestEmpty:
    """
    Tests for `required`, `allow_null`, `allow_blank`, `default`.
    """
    def test_required(self):
        """
        By default a field must be included in the input.
        """
        field = serializers.IntegerField()
        with pytest.raises(serializers.ValidationError) as exc_info:
            field.run_validation()
        assert exc_info.value.detail == ['This field is required.']

    def test_not_required(self):
        """
        If `required=False` then a field may be omitted from the input.
        """
        field = serializers.IntegerField(required=False)
        with pytest.raises(serializers.SkipField):
            field.run_validation()

    def test_disallow_null(self):
        """
        By default `None` is not a valid input.
        """
        field = serializers.IntegerField()
        with pytest.raises(serializers.ValidationError) as exc_info:
            field.run_validation(None)
        assert exc_info.value.detail == ['This field may not be null.']

    def test_allow_null(self):
        """
        If `allow_null=True` then `None` is a valid input.
        """
        field = serializers.IntegerField(allow_null=True)
        output = field.run_validation(None)
        assert output is None

    def test_disallow_blank(self):
        """
        By default '' is not a valid input.
        """
        field = serializers.CharField()
        with pytest.raises(serializers.ValidationError) as exc_info:
            field.run_validation('')
        assert exc_info.value.detail == ['This field may not be blank.']

    def test_allow_blank(self):
        """
        If `allow_blank=True` then '' is a valid input.
        """
        field = serializers.CharField(allow_blank=True)
        output = field.run_validation('')
        assert output == ''

    def test_default(self):
        """
        If `default` is set, then omitted values get the default input.
        """
        field = serializers.IntegerField(default=123)
        output = field.run_validation()
        assert output is 123

class TestSource:
    def test_source(self):
        class ExampleSerializer(serializers.Serializer):
            example_field = serializers.CharField(source='other')
        serializer = ExampleSerializer(data={'example_field': 'abc'})
        assert serializer.is_valid()
        assert serializer.validated_data == {'other': 'abc'}

    def test_redundant_source(self):
        class ExampleSerializer(serializers.Serializer):
            example_field = serializers.CharField(source='example_field')
        with pytest.raises(AssertionError) as exc_info:
            ExampleSerializer().fields
        assert str(exc_info.value) == (
            "It is redundant to specify `source='example_field'` on field "
            "'CharField' in serializer 'ExampleSerializer', because it is the "
            "same as the field name. Remove the `source` keyword argument."
        )

    def test_callable_source(self):
        class ExampleSerializer(serializers.Serializer):
            example_field = serializers.CharField(source='example_callable')

        class ExampleInstance(object):
            def example_callable(self):
                return 'example callable value'

        serializer = ExampleSerializer(ExampleInstance())
        assert serializer.data['example_field'] == 'example callable value'

    def test_callable_source_raises(self):
        class ExampleSerializer(serializers.Serializer):
            example_field = serializers.CharField(source='example_callable', read_only=True)

        class ExampleInstance(object):
            def example_callable(self):
                raise AttributeError('method call failed')

        with pytest.raises(ValueError) as exc_info:
            serializer = ExampleSerializer(ExampleInstance())
            serializer.data.items()

        assert 'method call failed' in str(exc_info.value)

class TestReadOnly:
    def setup(self):
        class TestSerializer(serializers.Serializer):
            read_only = serializers.ReadOnlyField()
            writable = serializers.IntegerField()
        self.Serializer = TestSerializer

    def test_validate_read_only(self):
        """
        Read-only serializers.should not be included in validation.
        """
        data = {'read_only': 123, 'writable': 456}
        serializer = self.Serializer(data=data)
        assert serializer.is_valid()
        assert serializer.validated_data == {'writable': 456}

    def test_serialize_read_only(self):
        """
        Read-only serializers.should be serialized.
        """
        instance = {'read_only': 123, 'writable': 456}
        serializer = self.Serializer(instance)
        assert serializer.data == {'read_only': 123, 'writable': 456}

class TestWriteOnly:
    def setup(self):
        class TestSerializer(serializers.Serializer):
            write_only = serializers.IntegerField(write_only=True)
            readable = serializers.IntegerField()
        self.Serializer = TestSerializer

    def test_validate_write_only(self):
        """
        Write-only serializers.should be included in validation.
        """
        data = {'write_only': 123, 'readable': 456}
        serializer = self.Serializer(data=data)
        assert serializer.is_valid()
        assert serializer.validated_data == {'write_only': 123, 'readable': 456}

    def test_serialize_write_only(self):
        """
        Write-only serializers.should not be serialized.
        """
        instance = {'write_only': 123, 'readable': 456}
        serializer = self.Serializer(instance)
        assert serializer.data == {'readable': 456}

class TestInitial:
    def setup(self):
        class TestSerializer(serializers.Serializer):
            initial_field = serializers.IntegerField(initial=123)
            blank_field = serializers.IntegerField()
        self.serializer = TestSerializer()

    def test_initial(self):
        """
        Initial values should be included when serializing a new representation.
        """
        assert self.serializer.data == {
            'initial_field': 123,
            'blank_field': None
        }

class TestLabel:
    def setup(self):
        class TestSerializer(serializers.Serializer):
            labeled = serializers.IntegerField(label='My label')
        self.serializer = TestSerializer()

    def test_label(self):
        """
        A field's label may be set with the `label` argument.
        """
        fields = self.serializer.fields
        assert fields['labeled'].label == 'My label'

class TestInvalidErrorKey:
    def setup(self):
        class ExampleField(serializers.Field):
            def to_native(self, data):
                self.fail('incorrect')
        self.field = ExampleField()

    def test_invalid_error_key(self):
        """
        If a field raises a validation error, but does not have a corresponding
        error message, then raise an appropriate assertion error.
        """
        with pytest.raises(AssertionError) as exc_info:
            self.field.to_native(123)
        expected = (
            'ValidationError raised by `ExampleField`, but error key '
            '`incorrect` does not exist in the `error_messages` dictionary.'
        )
        assert str(exc_info.value) == expected

class TestBooleanHTMLInput:
    def test_empty_html_checkbox(self):
        """
        HTML checkboxes do not send any value, but should be treated
        as `False` by BooleanField.
        """
        class TestSerializer(serializers.Serializer):
            archived = serializers.BooleanField()

        serializer = TestSerializer(data=QueryDict(''))
        assert serializer.is_valid()
        assert serializer.validated_data == {'archived': False}

    def test_empty_html_checkbox_not_required(self):
        """
        HTML checkboxes do not send any value, but should be treated
        as `False` by BooleanField, even if the field is required=False.
        """
        class TestSerializer(serializers.Serializer):
            archived = serializers.BooleanField(required=False)

        serializer = TestSerializer(data=QueryDict(''))
        assert serializer.is_valid()
        assert serializer.validated_data == {'archived': False}

class TestHTMLInput:
    def test_empty_html_charfield(self):
        class TestSerializer(serializers.Serializer):
            message = serializers.CharField(default='happy')

        serializer = TestSerializer(data=QueryDict(''))
        assert serializer.is_valid()
        assert serializer.validated_data == {'message': 'happy'}

    def test_empty_html_integerfield(self):
        class TestSerializer(serializers.Serializer):
            message = serializers.IntegerField(default=123)

        serializer = TestSerializer(data=QueryDict('message='))
        assert serializer.is_valid()
        assert serializer.validated_data == {'message': 123}

    def test_empty_html_uuidfield_with_default(self):
        class TestSerializer(serializers.Serializer):
            message = serializers.UUIDField(default=uuid.uuid4)

        serializer = TestSerializer(data=QueryDict('message='))
        assert serializer.is_valid()
        assert list(serializer.validated_data.keys()) == ['message']

    def test_empty_html_uuidfield_with_optional(self):
        class TestSerializer(serializers.Serializer):
            message = serializers.UUIDField(required=False)

        serializer = TestSerializer(data=QueryDict('message='))
        assert serializer.is_valid()
        assert list(serializer.validated_data.keys()) == []

    def test_empty_html_charfield_allow_null(self):
        class TestSerializer(serializers.Serializer):
            message = serializers.CharField(allow_null=True)

        serializer = TestSerializer(data=QueryDict('message='))
        assert serializer.is_valid()
        assert serializer.validated_data == {'message': None}

    def test_empty_html_datefield_allow_null(self):
        class TestSerializer(serializers.Serializer):
            expiry = serializers.DateField(allow_null=True)

        serializer = TestSerializer(data=QueryDict('expiry='))
        assert serializer.is_valid()
        assert serializer.validated_data == {'expiry': None}

    def test_empty_html_charfield_allow_null_allow_blank(self):
        class TestSerializer(serializers.Serializer):
            message = serializers.CharField(allow_null=True, allow_blank=True)

        serializer = TestSerializer(data=QueryDict('message='))
        assert serializer.is_valid()
        assert serializer.validated_data == {'message': ''}

    def test_empty_html_charfield_required_false(self):
        class TestSerializer(serializers.Serializer):
            message = serializers.CharField(required=False)

        serializer = TestSerializer(data=QueryDict(''))
        assert serializer.is_valid()
        assert serializer.validated_data == {}

    def test_querydict_list_input(self):
        class TestSerializer(serializers.Serializer):
            scores = serializers.ListField(child=serializers.IntegerField())

        serializer = TestSerializer(data=QueryDict('scores=1&scores=3'))
        assert serializer.is_valid()
        assert serializer.validated_data == {'scores': [1, 3]}

    def test_querydict_list_input_only_one_input(self):
        class TestSerializer(serializers.Serializer):
            scores = serializers.ListField(child=serializers.IntegerField())

        serializer = TestSerializer(data=QueryDict('scores=1&'))
        assert serializer.is_valid()
        assert serializer.validated_data == {'scores': [1]}

class TestCreateOnlyDefault:
    def setup(self):
        default = serializers.CreateOnlyDefault('2001-01-01')

        class TestSerializer(serializers.Serializer):
            published = serializers.HiddenField(default=default)
            text = serializers.CharField()
        self.Serializer = TestSerializer

    def test_create_only_default_is_provided(self):
        serializer = self.Serializer(data={'text': 'example'})
        assert serializer.is_valid()
        assert serializer.validated_data == {
            'text': 'example', 'published': '2001-01-01'
        }

    def test_create_only_default_is_not_provided_on_update(self):
        instance = {
            'text': 'example', 'published': '2001-01-01'
        }
        serializer = self.Serializer(instance, data={'text': 'example'})
        assert serializer.is_valid()
        assert serializer.validated_data == {
            'text': 'example',
        }

    def test_create_only_default_callable_sets_context(self):
        """
        CreateOnlyDefault instances with a callable default should set_context
        on the callable if possible
        """
        class TestCallableDefault:
            def set_context(self, serializer_field):
                self.field = serializer_field

            def __call__(self):
                return "success" if hasattr(self, 'field') else "failure"

        class TestSerializer(serializers.Serializer):
            context_set = serializers.CharField(default=serializers.CreateOnlyDefault(TestCallableDefault()))

        serializer = TestSerializer(data={})
        assert serializer.is_valid()
        assert serializer.validated_data['context_set'] == 'success'

# Tests for field input and output values.
# ----------------------------------------

def get_items(mapping_or_list_of_two_tuples):
    # Tests accept either lists of two tuples, or dictionaries.
    if isinstance(mapping_or_list_of_two_tuples, dict):
        # {value: expected}
        return mapping_or_list_of_two_tuples.items()
    # [(value, expected), ...]
    return mapping_or_list_of_two_tuples

class FieldValues:
    """
    Base class for testing valid and invalid input values.
    """
    def test_valid_inputs(self):
        """
        Ensure that valid values return the expected validated data.
        """
        for input_value, expected_output in get_items(self.valid_inputs):
            assert self.field.run_validation(input_value) == expected_output

    def test_invalid_inputs(self):
        """
        Ensure that invalid values raise the expected validation error.
        """
        for input_value, expected_failure in get_items(self.invalid_inputs):
            with pytest.raises(serializers.ValidationError) as exc_info:
                self.field.run_validation(input_value)
            assert exc_info.value.detail == expected_failure

    def test_outputs(self):
        for output_value, expected_output in get_items(self.outputs):
            assert self.field.to_representation(output_value) == expected_output

# Boolean types...

class TestBooleanField(FieldValues):
    """
    Valid and invalid values for `BooleanField`.
    """
    valid_inputs = {
        'true': True,
        'false': False,
        '1': True,
        '0': False,
        1: True,
        0: False,
        True: True,
        False: False,
    }
    invalid_inputs = {
        'foo': ['"foo" is not a valid boolean.'],
        None: ['This field may not be null.']
    }
    outputs = {
        'true': True,
        'false': False,
        '1': True,
        '0': False,
        1: True,
        0: False,
        True: True,
        False: False,
        'other': True
    }
    field = serializers.BooleanField()

class TestNullBooleanField(FieldValues):
    """
    Valid and invalid values for `BooleanField`.
    """
    valid_inputs = {
        'true': True,
        'false': False,
        'null': None,
        True: True,
        False: False,
        None: None
    }
    invalid_inputs = {
        'foo': ['"foo" is not a valid boolean.'],
    }
    outputs = {
        'true': True,
        'false': False,
        'null': None,
        True: True,
        False: False,
        None: None,
        'other': True
    }
    field = serializers.NullBooleanField()

# String types...

class TestCharField(FieldValues):
    """
    Valid and invalid values for `CharField`.
    """
    valid_inputs = {
        1: '1',
        'abc': 'abc'
    }
    invalid_inputs = {
        '': ['This field may not be blank.']
    }
    outputs = {
        1: '1',
        'abc': 'abc'
    }
    field = serializers.CharField()

    def test_trim_whitespace_default(self):
        field = serializers.CharField()
        assert field.to_internal_value(' abc ') == 'abc'

    def test_trim_whitespace_disabled(self):
        field = serializers.CharField(trim_whitespace=False)
        assert field.to_internal_value(' abc ') == ' abc '

    def test_disallow_blank_with_trim_whitespace(self):
        field = serializers.CharField(allow_blank=False, trim_whitespace=True)

        with pytest.raises(serializers.ValidationError) as exc_info:
            field.run_validation('   ')
        assert exc_info.value.detail == ['This field may not be blank.']

class TestEmailField(FieldValues):
    """
    Valid and invalid values for `EmailField`.
    """
    valid_inputs = {
        'example@example.com': 'example@example.com',
        ' example@example.com ': 'example@example.com',
    }
    invalid_inputs = {
        'examplecom': ['Enter a valid email address.']
    }
    outputs = {}
    field = serializers.EmailField()

class TestRegexField(FieldValues):
    """
    Valid and invalid values for `RegexField`.
    """
    valid_inputs = {
        'a9': 'a9',
    }
    invalid_inputs = {
        'A9': ["This value does not match the required pattern."]
    }
    outputs = {}
    field = serializers.RegexField(regex='[a-z][0-9]')

class TestSlugField(FieldValues):
    """
    Valid and invalid values for `SlugField`.
    """
    valid_inputs = {
        'slug-99': 'slug-99',
    }
    invalid_inputs = {
        'slug 99': ['Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.']
    }
    outputs = {}
    field = serializers.SlugField()

class TestURLField(FieldValues):
    """
    Valid and invalid values for `URLField`.
    """
    valid_inputs = {
        'http://example.com': 'http://example.com',
    }
    invalid_inputs = {
        'example.com': ['Enter a valid URL.']
    }
    outputs = {}
    field = serializers.URLField()

class TestUUIDField(FieldValues):
    """
    Valid and invalid values for `UUIDField`.
    """
    valid_inputs = {
        '825d7aeb-05a9-45b5-a5b7-05df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'),
        '825d7aeb05a945b5a5b705df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'),
        'urn:uuid:213b7d9b-244f-410d-828c-dabce7a2615d': uuid.UUID('213b7d9b-244f-410d-828c-dabce7a2615d'),
        284758210125106368185219588917561929842: uuid.UUID('d63a6fb6-88d5-40c7-a91c-9edf73283072')
    }
    invalid_inputs = {
        '825d7aeb-05a9-45b5-a5b7': ['"825d7aeb-05a9-45b5-a5b7" is not a valid UUID.']
    }
    outputs = {
        uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'): '825d7aeb-05a9-45b5-a5b7-05df87923cda'
    }
    field = serializers.UUIDField()

    def _test_format(self, uuid_format, formatted_uuid_0):
        field = serializers.UUIDField(format=uuid_format)
        assert field.to_representation(uuid.UUID(int=0)) == formatted_uuid_0
        assert field.to_internal_value(formatted_uuid_0) == uuid.UUID(int=0)

    def test_formats(self):
        self._test_format('int', 0)
        self._test_format('hex_verbose', '00000000-0000-0000-0000-000000000000')
        self._test_format('urn', 'urn:uuid:00000000-0000-0000-0000-000000000000')
        self._test_format('hex', '0' * 32)

class TestIPAddressField(FieldValues):
    """
    Valid and invalid values for `IPAddressField`
    """
    valid_inputs = {
        '127.0.0.1': '127.0.0.1',
        '192.168.33.255': '192.168.33.255',
        '2001:0db8:85a3:0042:1000:8a2e:0370:7334': '2001:db8:85a3:42:1000:8a2e:370:7334',
        '2001:cdba:0:0:0:0:3257:9652': '2001:cdba::3257:9652',
        '2001:cdba::3257:9652': '2001:cdba::3257:9652'
    }
    invalid_inputs = {
        '127001': ['Enter a valid IPv4 or IPv6 address.'],
        '127.122.111.2231': ['Enter a valid IPv4 or IPv6 address.'],
        '2001:::9652': ['Enter a valid IPv4 or IPv6 address.'],
        '2001:0db8:85a3:0042:1000:8a2e:0370:73341': ['Enter a valid IPv4 or IPv6 address.'],
    }
    outputs = {}
    field = serializers.IPAddressField()

class TestIPv4AddressField(FieldValues):
    """
    Valid and invalid values for `IPAddressField`
    """
    valid_inputs = {
        '127.0.0.1': '127.0.0.1',
        '192.168.33.255': '192.168.33.255',
    }
    invalid_inputs = {
        '127001': ['Enter a valid IPv4 address.'],
        '127.122.111.2231': ['Enter a valid IPv4 address.'],
    }
    outputs = {}
    field = serializers.IPAddressField(protocol='IPv4')

class TestIPv6AddressField(FieldValues):
    """
    Valid and invalid values for `IPAddressField`
    """
    valid_inputs = {
        '2001:0db8:85a3:0042:1000:8a2e:0370:7334': '2001:db8:85a3:42:1000:8a2e:370:7334',
        '2001:cdba:0:0:0:0:3257:9652': '2001:cdba::3257:9652',
        '2001:cdba::3257:9652': '2001:cdba::3257:9652'
    }
    invalid_inputs = {
        '2001:::9652': ['Enter a valid IPv4 or IPv6 address.'],
        '2001:0db8:85a3:0042:1000:8a2e:0370:73341': ['Enter a valid IPv4 or IPv6 address.'],
    }
    outputs = {}
    field = serializers.IPAddressField(protocol='IPv6')

class TestFilePathField(FieldValues):
    """
    Valid and invalid values for `FilePathField`
    """

    valid_inputs = {
        __file__: __file__,
    }
    invalid_inputs = {
        'wrong_path': ['"wrong_path" is not a valid path choice.']
    }
    outputs = {
    }
    field = serializers.FilePathField(
        path=os.path.abspath(os.path.dirname(__file__))
    )

# Number types...

class TestIntegerField(FieldValues):
    """
    Valid and invalid values for `IntegerField`.
    """
    valid_inputs = {
        '1': 1,
        '0': 0,
        1: 1,
        0: 0,
        1.0: 1,
        0.0: 0,
        '1.0': 1
    }
    invalid_inputs = {
        0.5: ['A valid integer is required.'],
        'abc': ['A valid integer is required.'],
        '0.5': ['A valid integer is required.']
    }
    outputs = {
        '1': 1,
        '0': 0,
        1: 1,
        0: 0,
        1.0: 1,
        0.0: 0
    }
    field = serializers.IntegerField()

class TestMinMaxIntegerField(FieldValues):
    """
    Valid and invalid values for `IntegerField` with min and max limits.
    """
    valid_inputs = {
        '1': 1,
        '3': 3,
        1: 1,
        3: 3,
    }
    invalid_inputs = {
        0: ['Ensure this value is greater than or equal to 1.'],
        4: ['Ensure this value is less than or equal to 3.'],
        '0': ['Ensure this value is greater than or equal to 1.'],
        '4': ['Ensure this value is less than or equal to 3.'],
    }
    outputs = {}
    field = serializers.IntegerField(min_value=1, max_value=3)

class TestFloatField(FieldValues):
    """
    Valid and invalid values for `FloatField`.
    """
    valid_inputs = {
        '1': 1.0,
        '0': 0.0,
        1: 1.0,
        0: 0.0,
        1.0: 1.0,
        0.0: 0.0,
    }
    invalid_inputs = {
        'abc': ["A valid number is required."]
    }
    outputs = {
        '1': 1.0,
        '0': 0.0,
        1: 1.0,
        0: 0.0,
        1.0: 1.0,
        0.0: 0.0,
    }
    field = serializers.FloatField()

class TestMinMaxFloatField(FieldValues):
    """
    Valid and invalid values for `FloatField` with min and max limits.
    """
    valid_inputs = {
        '1': 1,
        '3': 3,
        1: 1,
        3: 3,
        1.0: 1.0,
        3.0: 3.0,
    }
    invalid_inputs = {
        0.9: ['Ensure this value is greater than or equal to 1.'],
        3.1: ['Ensure this value is less than or equal to 3.'],
        '0.0': ['Ensure this value is greater than or equal to 1.'],
        '3.1': ['Ensure this value is less than or equal to 3.'],
    }
    outputs = {}
    field = serializers.FloatField(min_value=1, max_value=3)

class TestDecimalField(FieldValues):
    """
    Valid and invalid values for `DecimalField`.
    """
    valid_inputs = {
        '12.3': Decimal('12.3'),
        '0.1': Decimal('0.1'),
        10: Decimal('10'),
        0: Decimal('0'),
        12.3: Decimal('12.3'),
        0.1: Decimal('0.1'),
        '2E+1': Decimal('20'),
    }
    invalid_inputs = (
        ('abc', ["A valid number is required."]),
        (Decimal('Nan'), ["A valid number is required."]),
        (Decimal('Inf'), ["A valid number is required."]),
        ('12.345', ["Ensure that there are no more than 3 digits in total."]),
        (200000000000.0, ["Ensure that there are no more than 3 digits in total."]),
        ('0.01', ["Ensure that there are no more than 1 decimal places."]),
        (123, ["Ensure that there are no more than 2 digits before the decimal point."]),
        ('2E+2', ["Ensure that there are no more than 2 digits before the decimal point."])
    )
    outputs = {
        '1': '1.0',
        '0': '0.0',
        '1.09': '1.1',
        '0.04': '0.0',
        1: '1.0',
        0: '0.0',
        Decimal('1.0'): '1.0',
        Decimal('0.0'): '0.0',
        Decimal('1.09'): '1.1',
        Decimal('0.04'): '0.0'
    }
    field = serializers.DecimalField(max_digits=3, decimal_places=1)

class TestMinMaxDecimalField(FieldValues):
    """
    Valid and invalid values for `DecimalField` with min and max limits.
    """
    valid_inputs = {
        '10.0': Decimal('10.0'),
        '20.0': Decimal('20.0'),
    }
    invalid_inputs = {
        '9.9': ['Ensure this value is greater than or equal to 10.'],
        '20.1': ['Ensure this value is less than or equal to 20.'],
    }
    outputs = {}
    field = serializers.DecimalField(
        max_digits=3, decimal_places=1,
        min_value=10, max_value=20
    )

class TestNoStringCoercionDecimalField(FieldValues):
    """
    Output values for `DecimalField` with `coerce_to_string=False`.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = {
        1.09: Decimal('1.1'),
        0.04: Decimal('0.0'),
        '1.09': Decimal('1.1'),
        '0.04': Decimal('0.0'),
        Decimal('1.09'): Decimal('1.1'),
        Decimal('0.04'): Decimal('0.0'),
    }
    field = serializers.DecimalField(
        max_digits=3, decimal_places=1,
        coerce_to_string=False
    )

# Date & time serializers...

class TestDateField(FieldValues):
    """
    Valid and invalid values for `DateField`.
    """
    valid_inputs = {
        '2001-01-01': datetime.date(2001, 1, 1),
        datetime.date(2001, 1, 1): datetime.date(2001, 1, 1),
    }
    invalid_inputs = {
        'abc': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].'],
        '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].'],
        datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'],
    }
    outputs = {
        datetime.date(2001, 1, 1): '2001-01-01',
        '2001-01-01': '2001-01-01',
        None: None,
        '': None,
    }
    field = serializers.DateField()

class TestCustomInputFormatDateField(FieldValues):
    """
    Valid and invalid values for `DateField` with a cutom input format.
    """
    valid_inputs = {
        '1 Jan 2001': datetime.date(2001, 1, 1),
    }
    invalid_inputs = {
        '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY.']
    }
    outputs = {}
    field = serializers.DateField(input_formats=['%d %b %Y'])

class TestCustomOutputFormatDateField(FieldValues):
    """
    Values for `DateField` with a custom output format.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = {
        datetime.date(2001, 1, 1): '01 Jan 2001'
    }
    field = serializers.DateField(format='%d %b %Y')

class TestNoOutputFormatDateField(FieldValues):
    """
    Values for `DateField` with no output format.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = {
        datetime.date(2001, 1, 1): datetime.date(2001, 1, 1)
    }
    field = serializers.DateField(format=None)

class TestDateTimeField(FieldValues):
    """
    Valid and invalid values for `DateTimeField`.
    """
    valid_inputs = {
        '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        # Django 1.4 does not support timezone string parsing.
        '2001-01-01T14:00+01:00' if (django.VERSION > (1, 4)) else '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC())
    }
    invalid_inputs = {
        'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
        '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
        datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'],
    }
    outputs = {
        datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00',
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z'
    }
    field = serializers.DateTimeField(default_timezone=timezone.UTC())

class TestCustomInputFormatDateTimeField(FieldValues):
    """
    Valid and invalid values for `DateTimeField` with a cutom input format.
    """
    valid_inputs = {
        '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=timezone.UTC()),
    }
    invalid_inputs = {
        '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY.']
    }
    outputs = {}
    field = serializers.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y'])

class TestCustomOutputFormatDateTimeField(FieldValues):
    """
    Values for `DateTimeField` with a custom output format.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = {
        datetime.datetime(2001, 1, 1, 13, 00): '01:00PM, 01 Jan 2001',
    }
    field = serializers.DateTimeField(format='%I:%M%p, %d %b %Y')

class TestNoOutputFormatDateTimeField(FieldValues):
    """
    Values for `DateTimeField` with no output format.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = {
        datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00),
    }
    field = serializers.DateTimeField(format=None)

class TestNaiveDateTimeField(FieldValues):
    """
    Valid and invalid values for `DateTimeField` with naive datetimes.
    """
    valid_inputs = {
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00),
        '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00),
    }
    invalid_inputs = {}
    outputs = {}
    field = serializers.DateTimeField(default_timezone=None)

class TestTimeField(FieldValues):
    """
    Valid and invalid values for `TimeField`.
    """
    valid_inputs = {
        '13:00': datetime.time(13, 00),
        datetime.time(13, 00): datetime.time(13, 00),
    }
    invalid_inputs = {
        'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'],
        '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'],
    }
    outputs = {
        datetime.time(13, 00): '13:00:00'
    }
    field = serializers.TimeField()

class TestCustomInputFormatTimeField(FieldValues):
    """
    Valid and invalid values for `TimeField` with a custom input format.
    """
    valid_inputs = {
        '1:00pm': datetime.time(13, 00),
    }
    invalid_inputs = {
        '13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM].'],
    }
    outputs = {}
    field = serializers.TimeField(input_formats=['%I:%M%p'])

class TestCustomOutputFormatTimeField(FieldValues):
    """
    Values for `TimeField` with a custom output format.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = {
        datetime.time(13, 00): '01:00PM'
    }
    field = serializers.TimeField(format='%I:%M%p')

class TestNoOutputFormatTimeField(FieldValues):
    """
    Values for `TimeField` with a no output format.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = {
        datetime.time(13, 00): datetime.time(13, 00)
    }
    field = serializers.TimeField(format=None)

@pytest.mark.skipif(django.VERSION < (1, 8),
                    reason='DurationField is only available for django1.8+')
class TestDurationField(FieldValues):
    """
    Valid and invalid values for `DurationField`.
    """
    valid_inputs = {
        '13': datetime.timedelta(seconds=13),
        '3 08:32:01.000123': datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123),
        '08:01': datetime.timedelta(minutes=8, seconds=1),
        datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123),
    }
    invalid_inputs = {
        'abc': ['Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].'],
        '3 08:32 01.123': ['Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].'],
    }
    outputs = {
        datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): '3 08:32:01.000123',
    }
    if django.VERSION >= (1, 8):
        field = serializers.DurationField()

# Choice types...

class TestChoiceField(FieldValues):
    """
    Valid and invalid values for `ChoiceField`.
    """
    valid_inputs = {
        'poor': 'poor',
        'medium': 'medium',
        'good': 'good',
    }
    invalid_inputs = {
        'amazing': ['"amazing" is not a valid choice.']
    }
    outputs = {
        'good': 'good',
        '': '',
        'amazing': 'amazing',
    }
    field = serializers.ChoiceField(
        choices=[
            ('poor', 'Poor quality'),
            ('medium', 'Medium quality'),
            ('good', 'Good quality'),
        ]
    )

    def test_allow_blank(self):
        """
        If `allow_blank=True` then '' is a valid input.
        """
        field = serializers.ChoiceField(
            allow_blank=True,
            choices=[
                ('poor', 'Poor quality'),
                ('medium', 'Medium quality'),
                ('good', 'Good quality'),
            ]
        )
        output = field.run_validation('')
        assert output == ''

    def test_allow_null(self):
        """
        If `allow_null=True` then '' on HTML forms is treated as None.
        """
        field = serializers.ChoiceField(
            allow_null=True,
            choices=[
                1, 2, 3
            ]
        )
        field.field_name = 'example'
        value = field.get_value(QueryDict('example='))
        assert value is None
        output = field.run_validation(None)
        assert output is None

    def test_iter_options(self):
        """
        iter_options() should return a list of options and option groups.
        """
        field = serializers.ChoiceField(
            choices=[
                ('Numbers', ['integer', 'float']),
                ('Strings', ['text', 'email', 'url']),
                'boolean'
            ]
        )
        items = list(field.iter_options())

        assert items[0].start_option_group
        assert items[0].label == 'Numbers'
        assert items[1].value == 'integer'
        assert items[2].value == 'float'
        assert items[3].end_option_group

        assert items[4].start_option_group
        assert items[4].label == 'Strings'
        assert items[5].value == 'text'
        assert items[6].value == 'email'
        assert items[7].value == 'url'
        assert items[8].end_option_group

        assert items[9].value == 'boolean'

class TestChoiceFieldWithType(FieldValues):
    """
    Valid and invalid values for a `Choice` field that uses an integer type,
    instead of a char type.
    """
    valid_inputs = {
        '1': 1,
        3: 3,
    }
    invalid_inputs = {
        5: ['"5" is not a valid choice.'],
        'abc': ['"abc" is not a valid choice.']
    }
    outputs = {
        '1': 1,
        1: 1
    }
    field = serializers.ChoiceField(
        choices=[
            (1, 'Poor quality'),
            (2, 'Medium quality'),
            (3, 'Good quality'),
        ]
    )

class TestChoiceFieldWithListChoices(FieldValues):
    """
    Valid and invalid values for a `Choice` field that uses a flat list for the
    choices, rather than a list of pairs of (`value`, `description`).
    """
    valid_inputs = {
        'poor': 'poor',
        'medium': 'medium',
        'good': 'good',
    }
    invalid_inputs = {
        'awful': ['"awful" is not a valid choice.']
    }
    outputs = {
        'good': 'good'
    }
    field = serializers.ChoiceField(choices=('poor', 'medium', 'good'))

class TestChoiceFieldWithGroupedChoices(FieldValues):
    """
    Valid and invalid values for a `Choice` field that uses a grouped list for the
    choices, rather than a list of pairs of (`value`, `description`).
    """
    valid_inputs = {
        'poor': 'poor',
        'medium': 'medium',
        'good': 'good',
    }
    invalid_inputs = {
        'awful': ['"awful" is not a valid choice.']
    }
    outputs = {
        'good': 'good'
    }
    field = serializers.ChoiceField(
        choices=[
            (
                'Category',
                (
                    ('poor', 'Poor quality'),
                    ('medium', 'Medium quality'),
                ),
            ),
            ('good', 'Good quality'),
        ]
    )

class TestChoiceFieldWithMixedChoices(FieldValues):
    """
    Valid and invalid values for a `Choice` field that uses a single paired or
    grouped.
    """
    valid_inputs = {
        'poor': 'poor',
        'medium': 'medium',
        'good': 'good',
    }
    invalid_inputs = {
        'awful': ['"awful" is not a valid choice.']
    }
    outputs = {
        'good': 'good'
    }
    field = serializers.ChoiceField(
        choices=[
            (
                'Category',
                (
                    ('poor', 'Poor quality'),
                ),
            ),
            'medium',
            ('good', 'Good quality'),
        ]
    )

class TestMultipleChoiceField(FieldValues):
    """
    Valid and invalid values for `MultipleChoiceField`.
    """
    valid_inputs = {
        (): set(),
        ('aircon',): set(['aircon']),
        ('aircon', 'manual'): set(['aircon', 'manual']),
    }
    invalid_inputs = {
        'abc': ['Expected a list of items but got type "str".'],
        ('aircon', 'incorrect'): ['"incorrect" is not a valid choice.']
    }
    outputs = [
        (['aircon', 'manual', 'incorrect'], set(['aircon', 'manual', 'incorrect']))
    ]
    field = serializers.MultipleChoiceField(
        choices=[
            ('aircon', 'AirCon'),
            ('manual', 'Manual drive'),
            ('diesel', 'Diesel'),
        ]
    )

    def test_against_partial_and_full_updates(self):
        field = serializers.MultipleChoiceField(choices=(('a', 'a'), ('b', 'b')))
        field.partial = False
        assert field.get_value(QueryDict({})) == []
        field.partial = True
        assert field.get_value(QueryDict({})) == rest_framework.fields.empty

class TestEmptyMultipleChoiceField(FieldValues):
    """
    Invalid values for `MultipleChoiceField(allow_empty=False)`.
    """
    valid_inputs = {
    }
    invalid_inputs = (
        ([], ['This selection may not be empty.']),
    )
    outputs = [
    ]
    field = serializers.MultipleChoiceField(
        choices=[
            ('consistency', 'Consistency'),
            ('availability', 'Availability'),
            ('partition', 'Partition tolerance'),
        ],
        allow_empty=False
    )

# File serializers...

class MockFile:
    def __init__(self, name='', size=0, url=''):
        self.name = name
        self.size = size
        self.url = url

    def __eq__(self, other):
        return (
            isinstance(other, MockFile) and
            self.name == other.name and
            self.size == other.size and
            self.url == other.url
        )

class TestFileField(FieldValues):
    """
    Values for `FileField`.
    """
    valid_inputs = [
        (MockFile(name='example', size=10), MockFile(name='example', size=10))
    ]
    invalid_inputs = [
        ('invalid', ['The submitted data was not a file. Check the encoding type on the form.']),
        (MockFile(name='example.txt', size=0), ['The submitted file is empty.']),
        (MockFile(name='', size=10), ['No filename could be determined.']),
        (MockFile(name='x' * 100, size=10), ['Ensure this filename has at most 10 characters (it has 100).'])
    ]
    outputs = [
        (MockFile(name='example.txt', url='/example.txt'), '/example.txt'),
        ('', None)
    ]
    field = serializers.FileField(max_length=10)

class TestFieldFieldWithName(FieldValues):
    """
    Values for `FileField` with a filename output instead of URLs.
    """
    valid_inputs = {}
    invalid_inputs = {}
    outputs = [
        (MockFile(name='example.txt', url='/example.txt'), 'example.txt')
    ]
    field = serializers.FileField(use_url=False)

# Stub out mock Django `forms.ImageField` class so we don't *actually*
# call into it's regular validation, or require PIL for testing.
class FailImageValidation(object):
    def to_python(self, value):
        raise serializers.ValidationError(self.error_messages['invalid_image'])

class PassImageValidation(object):
    def to_python(self, value):
        return value

class TestInvalidImageField(FieldValues):
    """
    Values for an invalid `ImageField`.
    """
    valid_inputs = {}
    invalid_inputs = [
        (MockFile(name='example.txt', size=10), ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.'])
    ]
    outputs = {}
    field = serializers.ImageField(_DjangoImageField=FailImageValidation)

class TestValidImageField(FieldValues):
    """
    Values for an valid `ImageField`.
    """
    valid_inputs = [
        (MockFile(name='example.txt', size=10), MockFile(name='example.txt', size=10))
    ]
    invalid_inputs = {}
    outputs = {}
    field = serializers.ImageField(_DjangoImageField=PassImageValidation)

# Composite serializers...

class TestListField(FieldValues):
    """
    Values for `ListField` with IntegerField as child.
    """
    valid_inputs = [
        ([1, 2, 3], [1, 2, 3]),
        (['1', '2', '3'], [1, 2, 3]),
        ([], [])
    ]
    invalid_inputs = [
        ('not a list', ['Expected a list of items but got type "str".']),
        ([1, 2, 'error'], ['A valid integer is required.'])
    ]
    outputs = [
        ([1, 2, 3], [1, 2, 3]),
        (['1', '2', '3'], [1, 2, 3])
    ]
    field = serializers.ListField(child=serializers.IntegerField())

class TestEmptyListField(FieldValues):
    """
    Values for `ListField` with allow_empty=False flag.
    """
    valid_inputs = {}
    invalid_inputs = [
        ([], ['This list may not be empty.'])
    ]
    outputs = {}
    field = serializers.ListField(child=serializers.IntegerField(), allow_empty=False)

class TestUnvalidatedListField(FieldValues):
    """
    Values for `ListField` with no `child` argument.
    """
    valid_inputs = [
        ([1, '2', True, [4, 5, 6]], [1, '2', True, [4, 5, 6]]),
    ]
    invalid_inputs = [
        ('not a list', ['Expected a list of items but got type "str".']),
    ]
    outputs = [
        ([1, '2', True, [4, 5, 6]], [1, '2', True, [4, 5, 6]]),
    ]
    field = serializers.ListField()

class TestDictField(FieldValues):
    """
    Values for `ListField` with CharField as child.
    """
    valid_inputs = [
        ({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}),
    ]
    invalid_inputs = [
        ({'a': 1, 'b': None}, ['This field may not be null.']),
        ('not a dict', ['Expected a dictionary of items but got type "str".']),
    ]
    outputs = [
        ({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}),
    ]
    field = serializers.DictField(child=serializers.CharField())

class TestUnvalidatedDictField(FieldValues):
    """
    Values for `ListField` with no `child` argument.
    """
    valid_inputs = [
        ({'a': 1, 'b': [4, 5, 6], 1: 123}, {'a': 1, 'b': [4, 5, 6], '1': 123}),
    ]
    invalid_inputs = [
        ('not a dict', ['Expected a dictionary of items but got type "str".']),
    ]
    outputs = [
        ({'a': 1, 'b': [4, 5, 6]}, {'a': 1, 'b': [4, 5, 6]}),
    ]
    field = serializers.DictField()

# Tests for FieldField.
# ---------------------

class MockRequest:
    def build_absolute_uri(self, value):
        return 'http://example.com' + value

class TestFileFieldContext:
    def test_fully_qualified_when_request_in_context(self):
        field = serializers.FileField(max_length=10)
        field._context = {'request': MockRequest()}
        obj = MockFile(name='example.txt', url='/example.txt')
        value = field.to_representation(obj)
        assert value == 'http://example.com/example.txt'

# Tests for SerializerMethodField.
# --------------------------------

class TestSerializerMethodField:
    def test_serializer_method_field(self):
        class ExampleSerializer(serializers.Serializer):
            example_field = serializers.SerializerMethodField()

            def get_example_field(self, obj):
                return 'ran get_example_field(%d)' % obj['example_field']

        serializer = ExampleSerializer({'example_field': 123})
        assert serializer.data == {
            'example_field': 'ran get_example_field(123)'
        }

    def test_redundant_method_name(self):
        class ExampleSerializer(serializers.Serializer):
            example_field = serializers.SerializerMethodField('get_example_field')

        with pytest.raises(AssertionError) as exc_info:
            ExampleSerializer().fields
        assert str(exc_info.value) == (
            "It is redundant to specify `get_example_field` on "
            "SerializerMethodField 'example_field' in serializer "
            "'ExampleSerializer', because it is the same as the default "
            "method name. Remove the `method_name` argument."
        )


text:
#include "Interpreter.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include <cstring>
using namespace llvm;

namespace {

static struct RegisterInterp {
  RegisterInterp() { Interpreter::Register(); }
} InterpRegistrator;

}

extern "C" void LLVMLinkInInterpreter() { }

/// create - Create a new interpreter object.  This can never fail.
///
ExecutionEngine *Interpreter::create(Module *M, std::string* ErrStr) {
  // Tell this Module to materialize everything and release the GVMaterializer.
  if (M->MaterializeAllPermanently(ErrStr))
    // We got an error, just return 0
    return 0;

  return new Interpreter(M);
}

//===----------------------------------------------------------------------===//
// Interpreter ctor - Initialize stuff
//
Interpreter::Interpreter(Module *M)
  : ExecutionEngine(M), TD(M) {

  memset(&ExitValue.Untyped, 0, sizeof(ExitValue.Untyped));
  setTargetData(&TD);
  // Initialize the "backend"
  initializeExecutionEngine();
  initializeExternalFunctions();
  emitGlobals();

  IL = new IntrinsicLowering(TD);
}

Interpreter::~Interpreter() {
  delete IL;
}

void Interpreter::runAtExitHandlers () {
  while (!AtExitHandlers.empty()) {
    callFunction(AtExitHandlers.back(), std::vector<GenericValue>());
    AtExitHandlers.pop_back();
    run();
  }
}

/// run - Start execution with the specified function and arguments.
///
GenericValue
Interpreter::runFunction(Function *F,
                         const std::vector<GenericValue> &ArgValues) {
  assert (F && "Function *F was null at entry to run()");

  // Try extra hard not to pass extra args to a function that isn't
  // expecting them.  C programmers frequently bend the rules and
  // declare main() with fewer parameters than it actually gets
  // passed, and the interpreter barfs if you pass a function more
  // parameters than it is declared to take. This does not attempt to
  // take into account gratuitous differences in declared types,
  // though.
  std::vector<GenericValue> ActualArgs;
  const unsigned ArgCount = F->getFunctionType()->getNumParams();
  for (unsigned i = 0; i < ArgCount; ++i)
    ActualArgs.push_back(ArgValues[i]);

  // Set up the function call.
  callFunction(F, ActualArgs);

  // Start executing the function.
  run();

  return ExitValue;
}

redpajama_set_name: RedPajamaGithub


text:
package net.sf.antcontrib.logic;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.taskdefs.MacroDef;
import org.apache.tools.ant.taskdefs.MacroInstance;
import org.apache.tools.ant.taskdefs.Parallel;
import org.apache.tools.ant.types.DirSet;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.TaskLogger;

import java.io.File;
import java.lang.reflect.Method;
import java.util.*;

/***
 * Task definition for the for task.  This is based on
 * the foreach task but takes a sequential element
 * instead of a target and only works for ant >= 1.6Beta3
 * @author Peter Reilly
 */
public class ForDelegate  {

    private String     list;
    private String     param;
    private String     delimiter = ",";
    private Path       currPath;
    private boolean    trim;
    private boolean    keepgoing = false;
    private MacroDef   macroDef;
    private List       hasIterators = new ArrayList();
    private boolean    parallel = false;
    private Integer    threadCount;
    private Parallel   parallelTasks;
    private TaskLogger logger;

    private Project project;
    private Target owningTarget;

    /**
     * Creates a new For instance.
     * This checks if the ant version is correct to run this task.
     */
    public ForDelegate() {
    }

    public void setOwningTarget(Target owningTarget)
    {
        this.owningTarget = owningTarget;
    }

    public void setProject(Project project)
    {
        this.project = project;
    }

    /**
     * Attribute whether to execute the loop in parallel or in sequence.
     * @param parallel if true execute the tasks in parallel. Default is false.
     */
    public void setParallel(boolean parallel) {
        this.parallel = parallel;
    }

    /***
     * Set the maximum amount of threads we're going to allow
     * to execute in parallel
     * @param threadCount the number of threads to use
     */
    public void setThreadCount(int threadCount) {
        if (threadCount < 1) {
            throw new BuildException("Illegal value for threadCount " + threadCount
                                     + " it should be > 0");
        }
        this.threadCount = new Integer(threadCount);
    }

    /**
     * Set the trim attribute.
     *
     * @param trim if true, trim the value for each iterator.
     */
    public void setTrim(boolean trim) {
        this.trim = trim;
    }

    /**
     * Set the keepgoing attribute, indicating whether we
     * should stop on errors or continue heedlessly onward.
     *
     * @param keepgoing a boolean, if true then we act in
     * the keepgoing manner described.
     */
    public void setKeepgoing(boolean keepgoing) {
        this.keepgoing = keepgoing;
    }

    /**
     * Set the list attribute.
     *
     * @param list a list of delimiter separated tokens.
     */
    public void setList(String list) {
        this.list = list;
    }

    /**
     * Set the delimiter attribute.
     *
     * @param delimiter the delimiter used to separate the tokens in
     *        the list attribute. The default is ",".
     */
    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }

    /**
     * Set the param attribute.
     * This is the name of the macrodef attribute that
     * gets set for each iterator of the sequential element.
     *
     * @param param the name of the macrodef attribute.
     */
    public void setParam(String param) {
        this.param = param;
    }

    private Path getOrCreatePath() {
        if (currPath == null) {
            currPath = new Path(project);
        }
        return currPath;
    }

    /**
     * This is a path that can be used instread of the list
     * attribute to interate over. If this is set, each
     * path element in the path is used for an interator of the
     * sequential element.
     *
     * @param path the path to be set by the ant script.
     */
    public void addConfigured(Path path) {
        getOrCreatePath().append(path);
    }

    /**
     * This is a path that can be used instread of the list
     * attribute to interate over. If this is set, each
     * path element in the path is used for an interator of the
     * sequential element.
     *
     * @param path the path to be set by the ant script.
     */
    public void addConfiguredPath(Path path) {
        addConfigured(path);
    }

    /**
     * @return a MacroDef#NestedSequential object to be configured
     */
    public Object createSequential() {
        macroDef = new MacroDef();
        macroDef.setProject(project);
        return macroDef.createSequential();
    }

    /**
     * Run the for task.
     * This checks the attributes and nested elements, and
     * if there are ok, it calls doTheTasks()
     * which constructes a macrodef task and a
     * for each interation a macrodef instance.
     */
    public void execute() {
        if (parallel) {
            parallelTasks = (Parallel) project.createTask("parallel");
            if (threadCount != null) {
                parallelTasks.setThreadCount(threadCount.intValue());
            }
        }
        if (list == null && currPath == null && hasIterators.size() == 0) {
            throw new BuildException(
                "You must have a list or path to iterate through");
        }
        if (param == null) {
            throw new BuildException(
                "You must supply a property name to set on"
                + " each iteration in param");
        }
        if (macroDef == null) {
            throw new BuildException(
                "You must supply an embedded sequential "
                + "to perform");
        }
        doTheTasks();
        if (parallel) {
            parallelTasks.perform();
        }
    }

    private void doSequentialIteration(String val) {
        MacroInstance instance = new MacroInstance();
        instance.setProject(project);
        instance.setOwningTarget(owningTarget);
        instance.setMacroDef(macroDef);
        instance.setDynamicAttribute(param.toLowerCase(),
                                     val);
        if (!parallel) {
            instance.execute();
        } else {
            parallelTasks.addTask(instance);
        }
    }

    private void doTheTasks() {
        int errorCount = 0;
        int taskCount = 0;

        // Create a macro attribute
        MacroDef.Attribute attribute = new MacroDef.Attribute();
        attribute.setName(param);
        macroDef.addConfiguredAttribute(attribute);
        // Take Care of the list attribute
        if (list != null) {
            StringTokenizer st = new StringTokenizer(list, delimiter);

            while (st.hasMoreTokens()) {
                String tok = st.nextToken();
                if (trim) {
                    tok = tok.trim();
                }
                try {
                    taskCount++;
                    doSequentialIteration(tok);
                } catch (BuildException bx) {
                    if (keepgoing) {
                        if (logger != null) {
                            logger.error(tok + ": " + bx.getMessage());
                        }
                        errorCount++;
                    } else {
                        throw bx;
                    }
                }
            }
        }
        if (keepgoing && (errorCount != 0)) {
            throw new BuildException(
                "Keepgoing execution: " + errorCount
                + " of " + taskCount + " iterations failed.");
        }

        // Take Care of the path element
        String[] pathElements = new String[0];
        if (currPath != null) {
            pathElements = currPath.list();
        }
        for (int i = 0; i < pathElements.length; i++) {
            File nextFile = new File(pathElements[i]);
            try {
                taskCount++;
                doSequentialIteration(nextFile.getAbsolutePath());
            } catch (BuildException bx) {
                if (keepgoing) {
                    if (logger != null) {
                        logger.error(nextFile + ": " + bx.getMessage());
                    }
                    errorCount++;
                } else {
                    throw bx;
                }
            }
        }
        if (keepgoing && (errorCount != 0)) {
            throw new BuildException(
                "Keepgoing execution: " + errorCount
                + " of " + taskCount + " iterations failed.");
        }

        // Take care of iterators
        for (Iterator i = hasIterators.iterator(); i.hasNext();) {
            Iterator it = ((HasIterator) i.next()).iterator();
            while (it.hasNext()) {
                try {
                    taskCount++;
                    doSequentialIteration(it.next().toString());
                } catch (BuildException bx) {
                    if (keepgoing) {
                        if (logger != null) {
                            logger.error(it.next().toString() + ": " + bx.getMessage());
                        }
                        errorCount++;
                    } else {
                        throw bx;
                    }
                }
            }
        }
        if (keepgoing && (errorCount != 0)) {
            throw new BuildException(
                "Keepgoing execution: " + errorCount
                + " of " + taskCount + " iterations failed.");
        }
    }

    /** Specify a logger to be used for passing along messages.
     */
    public void setLogger (TaskLogger logger) {
        this.logger = logger;
    }

    /**
     * Add a Map, iterate over the values
     *
     * @param map a Map object - iterate over the values.
     */
    public void add(Map map) {
        hasIterators.add(new MapIterator(map));
    }

    /**
     * Add a fileset to be iterated over.
     *
     * @param fileset a FileSet value
     */
    public void add(FileSet fileset) {
        getOrCreatePath().addFileset(fileset);
    }

    /**
     * Add a fileset to be iterated over.
     *
     * @param fileset a FileSet value
     */
    public void addFileSet(FileSet fileset) {
        add(fileset);
    }

    /**
     * Add a dirset to be iterated over.
     *
     * @param dirset a DirSet value
     */
    public void add(DirSet dirset) {
        getOrCreatePath().addDirset(dirset);
    }

    /**
     * Add a dirset to be iterated over.
     *
     * @param dirset a DirSet value
     */
    public void addDirSet(DirSet dirset) {
        add(dirset);
    }

    /**
     * Add a collection that can be iterated over.
     *
     * @param collection a Collection value.
     */
    public void add(Collection collection) {
        hasIterators.add(new ReflectIterator(collection));
    }

    /**
     * Add an iterator to be iterated over.
     *
     * @param iterator an Iterator value
     */
    public void add(Iterator iterator) {
        hasIterators.add(new IteratorIterator(iterator));
    }

    /**
     * Add an object that has an Iterator iterator() method
     * that can be iterated over.
     *
     * @param obj An object that can be iterated over.
     */
    public void add(Object obj) {
        hasIterators.add(new ReflectIterator(obj));
    }

    /**
     * Interface for the objects in the iterator collection.
     */
    private interface HasIterator {
        Iterator iterator();
    }

    private static class IteratorIterator implements HasIterator {
        private Iterator iterator;
        public IteratorIterator(Iterator iterator) {
            this.iterator = iterator;
        }
        public Iterator iterator() {
            return this.iterator;
        }
    }

    private static class MapIterator implements HasIterator {
        private Map map;
        public MapIterator(Map map) {
            this.map = map;
        }
        public Iterator iterator() {
            return map.values().iterator();
        }
    }

    private static class ReflectIterator implements HasIterator {
        private Object  obj;
        private Method  method;
        public ReflectIterator(Object obj) {
            this.obj = obj;
            try {
                method = obj.getClass().getMethod(
                    "iterator", new Class[] {});
            } catch (Throwable t) {
                throw new BuildException(
                    "Invalid type " + obj.getClass() + " used in For task, it does"
                    + " not have a public iterator method");
            }
        }

        public Iterator iterator() {
            try {
                return (Iterator) method.invoke(obj, new Object[] {});
            } catch (Throwable t) {
                throw new BuildException(t);
            }
        }
    }
}


text:
package com.datatorrent.bufferserver.packet;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.datatorrent.bufferserver.packet.PublishRequestTuple;
import com.datatorrent.bufferserver.packet.Tuple;

/**
 *
 */
public class PublishRequestTupleTest
{
  public PublishRequestTupleTest()
  {
  }

  @Test
  public void testGetSerializedRequest()
  {
    String pubId = "TestPublisher";
    long windowId = 0xcafebabe000000ffL;
    byte[] serial = PublishRequestTuple.getSerializedRequest(null, pubId, windowId);
    PublishRequestTuple request = (PublishRequestTuple)Tuple.getTuple(serial, 0, serial.length);

    Assert.assertEquals(request.identifier, pubId, "Identifier");
    Assert.assertEquals(Long.toHexString((long)request.baseSeconds << 32 | request.windowId), Long.toHexString(windowId), "Window");
  }

}


text:
static int buttonText(lua_State *L)
{
    assert(yalulCheckControl(L, 1, YALUL_BUTTON_LIB));
    char *text = uiButtonText(CAST_ARG(1, Button));
    lua_pushstring(L, text);
    uiFreeText(text);
    return 1;
}

static int buttonSetText(lua_State *L)
{
    assert(yalulCheckControl(L, 1, YALUL_BUTTON_LIB));
    uiButtonSetText(CAST_ARG(1, Button), luaL_checkstring(L, 2));
    RETURN_SELF;
}

static void callback_onclicked(uiButton *bt, void *p)
{
    lua_State *L = (lua_State*)p;

    yalulDoCallback(L, bt, YALUL_ONCLICKED, 0);
}

static int buttonOnClicked(lua_State *L)
{
    assert(yalulCheckControl(L, 1, YALUL_BUTTON_LIB));
    uiButton *bt = CAST_ARG(1, Button);

    yalulRegisterCallback(L, bt, YALUL_ONCLICKED);

    uiButtonOnClicked(bt, callback_onclicked, L);

    RETURN_SELF;
}

static struct luaL_Reg meta_Button[] = {
    { "text",                 buttonText },
    { "setText",              buttonSetText },
    { "onClicked",            buttonOnClicked },
    { NULL }
};

int yalulSetButton(lua_State *L)
{
    lua_newtable(L);
    luaL_setfuncs(L, meta_Button, 0);

    yalulSetSubControl(L, YALUL_BUTTON_LIB);

    lua_pop(L, 1);
    return 0;
}


text:
class ComplaintCaseUpdaterService < CaseUpdaterService
  attr_reader :result

  def call
    reset_status_on_complaint_type_change
    super
  end

  private

  def reset_status_on_complaint_type_change
    if current_case_type_doesnt_match_selected_case_type
      reset_case_status_to_default_state
    end
  end

  def reset_case_status_to_default_state
    @kase.state_machine.reset_to_initial_state!(acting_user: @user, acting_team: @team)
  end

  def current_case_type_doesnt_match_selected_case_type
    case_type = @kase.complaint_type_in_database
    params_case_type = @params['complaint_type']

    case_type != params_case_type && params_case_type.present?
  end
end


text:
<head>
  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <meta property="og:site_name" content="{{ site.title }}" />
  <meta property="og:description" content="{{ site.tagline }}" />
  <meta property="og:url" content="{{ site.url }}" />
  {% if page.title == "Home" %}
    <meta property="og:title" content="{{ site.title }}" />
  {% else %}
    <meta property="og:title" content="{{ page.title }}" />
  {% endif %}
  <meta property="og:image" content="{{ site.url }}/public/apple-touch-icon-144-precomposed.png" />

  <meta name="description" content="{{ site.tagline }}">
  <meta name="author" content="{{ site.title }}">

  <title>
    {% if page.title == "Home" %}
      {{ site.title }} · {{ site.tagline }}
    {% else %}
      {{ page.title }} · {{ site.title }}
    {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/lanyon.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700|PT+Sans:400">
  <link rel="stylesheet" href='http://mmwebfonts.comquas.com/fonts/?font=myanmar3' />

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>


text:
<?php

class Product extends BasicObject {
	private $_old_price;
	/**
	 * Used by BasicObject to determine the table name.
	 * @returns the table name for the database relation.
	 */
	protected static function table_name() {
		return 'products';
	}

	public static function from_ean($ean) {
		return self::from_field('ean', $ean);
	}

	public function sell($count) {
		$this->count -= $count;
		foreach(ProductPackage::selection(array('package' => $this->id)) as $package) {
			$product = $package->Product();
			$product->sell($count * $package->count);
		}
		$this->commit();
	}

	public function __toString() {
		return $this->name;
	}

	public function __set($key, $value) {
		switch($key) {
			case 'price':
				if($this->_exists && !isset($this->_old_price)) {
					$this->_old_price = $this->price;
				}
		}
		if($value === '') {
			$value = null;
		}
		return parent::__set($key, $value);
	}

	public function commit() {
		global $db;
		$ac = $db->is_autocommit();
		if($ac) {
			$db->autocommit(false);
		}
		if(isset($this->_old_price) && $this->_old_price != $this->price) {
			$log = new ProductLog();
			$log->user_id = $_SESSION['login'];
			$log->old_price = $this->_old_price;
			$log->new_price = $this->price;
			$log->product_id = $this->id;
			$log->commit();
		}
		parent::commit();
		if($ac) {
			$db->commit();
			$db->autocommit(true);
		}
	}
}
?>


text:
<!DOCTYPE html>

      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta name="description" content="">
      <meta name="author" content="">
      <title>Haydn Richards - Portfolio</title>

      <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

      <link href="../css/freelancer.css" rel="stylesheet">

      <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
      <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
      <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

               <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
               Toggle navigation Menu
               </button>
               Chapter 8

                     Assembler

					Translation

					More on compilation

					Back to Theory

                     Application Generation

Machine Code and Assemblers

Machine Code

Processors only understand machine code, the binary sequence that represent data and the instructions.  Remember these instructions sets vary between processors.  In one brand the 1's and 0's that mean ADD won't be the same in other brands processor.  The sequence that makes up the instructions are called the opcodes.

In the early days the only way to give a processor instructions was to write the opcode (1's and 0's).  This took a long time and was prone to errors.  Remember this would need to be done for different processors as well.  If you wanted the program to run on different machines you would have to rewrite the opcode for that processor.

Assembler

Processors only understand machine code, the binary sequence that represent data and the instructions.  Remember these instructions sets vary between processors.  In one brand the 1's and 0's that mean ADD won't be the same in other brands processor.  The sequence that makes up the instructions are called the opcodes.

In the early days the only way to give a processor instructions was to write the opcode (1's and 0's).  This took a long time and was prone to errors.  Remember this would need to be done for different processors as well.  If you wanted the program to run on different machines you would have to rewrite the opcode for that processor.

Compilers and Interpreters

While high level languages are easier for humans to understand, we need a way of converting them into a form a CPU can use. There are two types of translator program used to do this, interpreters and compilers.

Interpreter

An interpreter takes each line of high-level language program, converts it into machine code and runs it.  This is useful when debugging a program as the program can start running straight away and will stop at a line if it finds an error. The downside of this is that an interpreted program runs slowly. Every time the program is run, the user has to wait for the translation of each line as well as the execution. When iterating through a loop, the interpreter may have to translate the same line many times.

Compiler

A compiler is a program that takes a program written in high level language and converts it into object code. This object code can then be distributed to anyone with compatible system without the need for any additional programs. Once the code is compiled, it can run as often as needed and much faster speed than an interpreted program. Also, if the source code were distributed commercially, people could amend it, removing anti piracy measures, debrand the product and sell it on and copy any innovative ideas into their own product, stealing the original creators hard work.  As machine code is not human readable doing any of these things is much harder.

How does a Compiler works?

There are various steps involved in compilation of code.

Lexical Analysis

All comments and whitespace are removed from the program.  Remember comments are just there for the programmers but are no use to the computer.

Syntax Analysis

Syntax analysis checks that the code has been written to the rules of the the language.  Syntax analysis will produce an abstract syntax tree (AST) that will represent the program.

Code Generation

By this stage, the program is represented as an abstract syntax tree and the compiler has all the data it needs. Code generation is when the compiler converts this into object code.

Optimisation

The optimiser for the language will have a number of tricks that could remove lines of code that are not required, the optimiser can remove these lines and the program will run.  It will also look at groups of instructions to see if they can be made smaller.

Libraries

We use libraries all the time when we are programing.  When you download the latest version of Python it comes with its standard libraries that allow you to print to screen using the print function and perform IF statements as well as a thousand more things you can do with a standard install of Python.  Sometimes you might want to use a specialist random function, so you would need to import the random library (module).

Linkers

The linker will bring in the external code from the libraries we looked at above into place holders that you wrote in your source code for example random.randint would be a place holder where the linker would look for the randint code from the random library that you imported.

School Location

North Halifax Grammar School

Moorbottom Road

Halifax

HX2 9SU

                     Copyright © Your Website 2016


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;

namespace LibGit2Sharp
{
    /// <summary>
    /// Holds summary information for a diff.
    /// <para>The individual patches for each file can be accessed through the indexer of this class.</para>
    /// </summary>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class PatchStats : IEnumerable<ContentChangeStats>
    {
        private readonly IDictionary<FilePath, ContentChangeStats> changes = new Dictionary<FilePath, ContentChangeStats>();
        private readonly int totalLinesAdded;
        private readonly int totalLinesDeleted;

        /// <summary>
        /// For mocking.
        /// </summary>
        protected PatchStats()
        { }

        internal PatchStats(DiffSafeHandle diff)
        {
            int count = Proxy.git_diff_num_deltas(diff);
            for (int i = 0; i < count; i++)
            {
                using (var patch = Proxy.git_patch_from_diff(diff, i))
                {
                    var delta = Proxy.git_diff_get_delta(diff, i);
                    var pathPtr = delta.NewFile.Path != IntPtr.Zero ? delta.NewFile.Path : delta.OldFile.Path;
                    var newFilePath = LaxFilePathMarshaler.FromNative(pathPtr);

                    var stats = Proxy.git_patch_line_stats(patch);
                    int added = stats.Item1;
                    int deleted = stats.Item2;
                    changes.Add(newFilePath, new ContentChangeStats(added, deleted));
                    totalLinesAdded += added;
                    totalLinesDeleted += deleted;
                }

            }
        }

        #region IEnumerable<ContentChanges> Members

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns>
        public virtual IEnumerator<ContentChangeStats> GetEnumerator()
        {
            return changes.Values.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        /// <summary>
        /// Gets the <see cref="ContentChangeStats"/> corresponding to the specified <paramref name="path"/>.
        /// </summary>
        /// <param name="path"></param>
        public virtual ContentChangeStats this[string path]
        {
            get { return this[(FilePath) path]; }
        }

        private ContentChangeStats this[FilePath path]
        {
            get
            {
                ContentChangeStats stats;
                if (changes.TryGetValue(path, out stats))
                {
                    return stats;
                }
                return null;
            }
        }

        /// <summary>
        /// The total number of lines added in this diff.
        /// </summary>
        public virtual int TotalLinesAdded
        {
            get { return totalLinesAdded; }
        }

        /// <summary>
        /// The total number of lines deleted in this diff.
        /// </summary>
        public virtual int TotalLinesDeleted
        {
            get { return totalLinesDeleted; }
        }

        private string DebuggerDisplay
        {
            get
            {
                return string.Format(CultureInfo.InvariantCulture, "+{0} -{1}",
                    TotalLinesAdded, TotalLinesDeleted);
            }
        }
    }
}


text:
package com.hack23.cia.service.impl.action.admin;

import java.util.EnumMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.model.internal.application.system.impl.ApplicationOperationType;
import com.hack23.cia.model.internal.application.user.impl.UserAccount;
import com.hack23.cia.model.internal.application.user.impl.UserAccount_;
import com.hack23.cia.model.internal.application.user.impl.UserLockStatus;
import com.hack23.cia.service.api.action.admin.ManageUserAccountRequest;
import com.hack23.cia.service.api.action.admin.ManageUserAccountResponse;
import com.hack23.cia.service.api.action.application.CreateApplicationEventRequest;
import com.hack23.cia.service.api.action.common.ServiceResponse.ServiceResult;
import com.hack23.cia.service.data.api.RemoveDataManager;
import com.hack23.cia.service.impl.action.common.AbstractBusinessServiceImpl;

/**
 * The Class ManageUserAccountService.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED)
public final class ManageUserAccountService
		extends AbstractBusinessServiceImpl<ManageUserAccountRequest, ManageUserAccountResponse> {

	/** The remove data manager. */
	@Autowired
	private RemoveDataManager removeDataManager;

	/** The user command map. */
	private final Map<ManageUserAccountRequest.AccountOperation,UserCommand> userCommandMap = new EnumMap<>(ManageUserAccountRequest.AccountOperation.class);

	/**
	 * Instantiates a new update application configuration service.
	 */
	public ManageUserAccountService() {
		super(ManageUserAccountRequest.class);
	}

	/**
	 * Inits the user command map.
	 */
	@PostConstruct
	public void initUserCommandMap() {
		userCommandMap.put(ManageUserAccountRequest.AccountOperation.DELETE, account -> {
			removeDataManager.removeUserAccountApplicationHistory(account.getUserId());
			getUserDAO().delete(account);
			return new ManageUserAccountResponse(ServiceResult.SUCCESS);
		});

		userCommandMap.put(ManageUserAccountRequest.AccountOperation.UNLOCK, account -> {
			account.setUserLockStatus(UserLockStatus.UNLOCKED);
			getUserDAO().persist(account);
			return new ManageUserAccountResponse(ServiceResult.SUCCESS);
		});

		userCommandMap.put(ManageUserAccountRequest.AccountOperation.LOCK, account -> {
			account.setUserLockStatus(UserLockStatus.LOCKED);
			getUserDAO().persist(account);
			return new ManageUserAccountResponse(ServiceResult.SUCCESS);
		});

	}

	@Override
	@Secured({ "ROLE_ADMIN" })
	public ManageUserAccountResponse processService(final ManageUserAccountRequest serviceRequest) {
		final ManageUserAccountResponse inputValidation = inputValidation(serviceRequest);
		if (inputValidation != null) {
			return inputValidation;
		}

		final CreateApplicationEventRequest eventRequest = createApplicationEventForService(serviceRequest);

		final ManageUserAccountResponse response = performOperation(serviceRequest, eventRequest);
		createApplicationEventService.processService(eventRequest);

		return response;

	}

	/**
	 * Perform operation.
	 *
	 * @param serviceRequest
	 *            the service request
	 * @param eventRequest
	 *            the event request
	 * @return the manage user account response
	 */
	private ManageUserAccountResponse performOperation(final ManageUserAccountRequest serviceRequest,
			final CreateApplicationEventRequest eventRequest) {
		ManageUserAccountResponse response;
		eventRequest.setElementId(serviceRequest.getUserAcountId());
		eventRequest.setApplicationMessage(serviceRequest.getAccountOperation().toString());

		final UserAccount accountToModify = getUserDAO().findFirstByProperty(UserAccount_.userId,
				serviceRequest.getUserAcountId());

		final UserCommand userCommand = userCommandMap.get(serviceRequest.getAccountOperation());
		if (accountToModify != null && userCommand != null) {
			response = userCommand.execute(accountToModify);
		} else {
			response = new ManageUserAccountResponse(ServiceResult.FAILURE);
		}

		eventRequest.setApplicationMessage(response.getResult().toString());
		return response;
	}

	@Override
	protected CreateApplicationEventRequest createApplicationEventForService(final ManageUserAccountRequest serviceRequest) {
		final CreateApplicationEventRequest eventRequest = createBaseApplicationEventRequest();
		eventRequest.setEventGroup(ApplicationEventGroup.ADMIN);
		eventRequest.setApplicationOperation(ApplicationOperationType.UPDATE);
		eventRequest.setActionName(ManageUserAccountRequest.class.getSimpleName());
		eventRequest.setSessionId(serviceRequest.getSessionId());
		return eventRequest;
	}

	@Override
	protected ManageUserAccountResponse createErrorResponse() {
		return new ManageUserAccountResponse(ServiceResult.FAILURE);
	}

	/**
	 * The Interface UserCommand.
	 */
	interface UserCommand {

		/**
		 * Execute.
		 *
		 * @param account
		 *            the account
		 * @return the manage user account response
		 */
		ManageUserAccountResponse execute(UserAccount account);
	}

}


text:
/**
 * @type    Basic Polyfill
 * @use     same as ES5 Array.prototype.map
 * @caveats sparse Arrays are not looped properly
 *          we should not deal with sparse Arrays anyway
 */
[].map || (Array.prototype.map = function (f, c) {
  for (var r = [], i = 0; i < this.length; i++) {
    r[i] = f.call(c, this[i], i, this);
  }
  return r;
});


text:
using System;
using System.Collections.Generic;
using Server;

namespace Server.Mobiles
{
	public class Farmer : BaseVendor
	{
		private List<SBInfo> m_SBInfos = new List<SBInfo>();
		protected override List<SBInfo> SBInfos{ get { return m_SBInfos; } }

		[Constructable]
		public Farmer() : base( "le Fermier", "la Fermiere" )
		{
			SetSkill( SkillName.Lumberjacking, 36.0, 68.0 );
			SetSkill( SkillName.TasteID, 36.0, 68.0 );
			SetSkill( SkillName.Cooking, 36.0, 68.0 );
		}

		public override void InitSBInfo()
		{
			m_SBInfos.Add( new SBFarmer() );
		}

		public override VendorShoeType ShoeType
		{
			get{ return VendorShoeType.ThighBoots; }
		}

		public override int GetShoeHue()
		{
			return 0;
		}

		public override void InitOutfit()
		{
			base.InitOutfit();

			AddItem( new Server.Items.WideBrimHat( Utility.RandomNeutralHue() ) );
		}

		public Farmer( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}
}


text:
class RubyMQ::IncomingFrame
  INITIAL_OCTETS = 12

  attr_reader :sequence_number, :response_to, :payload_length, :payload

  def initialize initial_octets
    @sequence_number, @response_to, @payload_length = initial_octets.unpack("NNN")
    @payload_stream = RubyMQ::Stream.new(initial_octets[8,4])
  end

  def payload= payload
    @payload_stream << payload
    @payload = RubyMQ::Types::Struct32.unpack(@payload_stream)
  end
end


text:
var root = require('./_root'),
    toString = require('./toString');

/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;

/** Used to detect hexadecimal string values. */
var reHasHexPrefix = /^0x/i;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeParseInt = root.parseInt;

/**
 * Converts `string` to an integer of the specified radix. If `radix` is
 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
 * in which case a `radix` of `16` is used.
 *
 * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#x15.1.2.2)
 * of `parseInt`.
 *
 * @static
 * @memberOf _
 * @category String
 * @param {string} string The string to convert.
 * @param {number} [radix] The radix to interpret `value` by.
 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.parseInt('08');
 * // => 8
 *
 * _.map(['6', '08', '10'], _.parseInt);
 * // => [6, 8, 10]
 */
function parseInt(string, radix, guard) {
  // Chrome fails to trim leading <BOM> whitespace characters.
  // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
  if (guard || radix == null) {
    radix = 0;
  } else if (radix) {
    radix = +radix;
  }
  string = toString(string).replace(reTrim, '');
  return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
}

module.exports = parseInt;


text:
package edu.gemini.qpt.ui.view.problem;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collections;
import java.util.Set;

import edu.gemini.qpt.core.Marker;
import edu.gemini.qpt.core.Schedule;
import edu.gemini.qpt.core.util.MarkerManager;
import edu.gemini.ui.gface.GTableController;
import edu.gemini.ui.gface.GViewer;

public class ProblemController implements GTableController<Schedule, Marker, ProblemAttribute>, PropertyChangeListener {

	private GViewer<Schedule, Marker> viewer;
	private MarkerManager manager;
	private Marker[] markers;

	public Object getSubElement(Marker element, ProblemAttribute subElement) {
		if (element != null) {
			switch (subElement) {
			case Description: return element.getText();
			case Resource: return element.getTarget();
			case Severity: return element.getSeverity();
			}
		}
		return null;
	}

	public Marker getElementAt(int row) {
		return row < markers.length ? markers[row] : null;
	}

	public int getElementCount() {
		return markers == null ? 0 : markers.length;
	}

	public void modelChanged(GViewer<Schedule, Marker> viewer, Schedule oldModel, Schedule newModel) {
		this.viewer = viewer;
		if (manager != null) manager.removePropertyChangeListener(this);
		manager = newModel == null ? null : newModel.getMarkerManager();
		if (manager != null) manager.addPropertyChangeListener(this);
		fetchMarkers();
	}

	public void propertyChange(PropertyChangeEvent evt) {
		fetchMarkers();
		viewer.refresh();
	}

	private synchronized void fetchMarkers() {
		Set<Marker> set = manager == null ? Collections.<Marker>emptySet() : manager.getMarkers();
		markers = set.toArray(new Marker[set.size()]);
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of advmod:eval in UD_Komi_Zyrian-IKDP</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Komi_Zyrian-IKDP: Relations: advmod:eval

This relation is a language-specific subtype of <tt>advmod</tt>.
There are also 6 other language-specific subtypes of advmod: <tt>advmod:deg</tt>, <tt>advmod:lfrom</tt>, <tt>advmod:lmod</tt>, <tt>advmod:lto</tt>, <tt>advmod:mmod</tt>, <tt>advmod:tmod</tt>.

8 nodes (0%) are attached to their parents as advmod:eval.

6 instances of advmod:eval (75%) are right-to-left (child precedes parent).
Average distance between parent and child is 1.875.

The following 4 pairs of parts of speech are connected with advmod:eval: <tt>VERB</tt>-<tt>ADV</tt> (3; 38% instances), <tt>ADV</tt>-<tt>ADV</tt> (2; 25% instances), <tt>NOUN</tt>-<tt>ADV</tt> (2; 25% instances), <tt>ADV</tt>-<tt>PART</tt> (1; 13% instances).

# visual-style 3	bgColor:blue
# visual-style 3	fgColor:white
# visual-style 6	bgColor:blue
# visual-style 6	fgColor:white
# visual-style 6 3 advmod:eval	color:blue
1	А	а	CCONJ	CC	_	6	cc	_	GTtags=CC
2	важен	важ	ADJ	A	Case=Ins|Number=Sing	6	obl	_	GTtags=A,Sg,Ins
3	вед	вед	ADV	Adv	_	6	advmod:eval	_	GTtags=Adv,Parenthetic|OrigLang=ru
4	вина	вина	NOUN	N	Case=Nom|Number=Sing	6	obj	_	GTtags=N,Sg,Nom|OrigLang=ru
5	из	оз	AUX	V	Mood=Ind|Number=Sing|Person=3|Polarity=Neg|Tense=Past	6	aux:neg	_	GTtags=V,Neg,Ind,Prt1,Sg3
6	юныс	юны	VERB	V	Connegative=Yes|Number=Plur	0	root	_	GTtags=V,TV,ConNeg|SpaceAfter=No
7	.	.	PUNCT	CLB	_	6	punct	_	GTtags=CLB

# visual-style 4	bgColor:blue
# visual-style 4	fgColor:white
# visual-style 3	bgColor:blue
# visual-style 3	fgColor:white
# visual-style 3 4 advmod:eval	color:blue
1	И	и	CCONJ	CC	_	5	cc	_	OrigLang=ru
2	ӧні	ӧні	ADV	Adv	_	5	advmod:tmod	_	_
3	бара	бара	ADV	Adv	_	5	advmod:tmod	_	_
4	же	жӧ	ADV	Adv	_	3	advmod:eval	_	OrigLang=ru
5	мӧдісныс	мӧдны	VERB	V	Mood=Ind|Number=Plur|Person=3|Tense=Past	0	root	_	_
6	вӧрзёоны	вӧрзьыны	VERB	V	VerbForm=Inf	5	xcomp	_	SpaceAfter=No
7	.	.	PUNCT	CLB	_	5	punct	_	_

# visual-style 5	bgColor:blue
# visual-style 5	fgColor:white
# visual-style 8	bgColor:blue
# visual-style 8	fgColor:white
# visual-style 8 5 advmod:eval	color:blue
1	Нёль	нёль	NUM	Num	Case=Nom|Number=Sing|NumType=Card	3	nummod	_	GTtags=Card,Sg,Nom
2	кынь	кынь	NOUN	N	Case=Nom|Number=Sing	3	nmod	_	GTtags=Sg,Nom
3	рожа	рожа	NOUN	N	Case=Nom|Number=Sing	4	nmod	_	GTtags=Sg,Nom
4	видзысь	видзысь	NOUN	N	Case=Nom|Number=Sing	8	nsubj	_	GTtags=Sg,Nom
5	вед	вед	ADV	Adv	_	8	advmod:eval	_	GTtags=Parenthetic
6	пыр	пыр	ADV	Adv	_	8	advmod	_	_
7	на	на	ADV	Adv	_	8	advmod	_	_
8	лооя	ловъя	NOUN	N	Case=Nom|Number=Sing	0	root	_	GTtags=Sg,Nom|SpaceAfter=No
9	,	,	PUNCT	PUNCT	_	10	punct	_	_
10	ветлалэ	ветлыны	VERB	V	Derivation=Al|Mood=Ind|Number=Sing|Person=3|Tense=Pres	8	conj	_	GTtags=Der/ал,Ind,Prs,Err/Dial,Sg3|SpaceAfter=No
11	!	!	PUNCT	PUNCT	_	8	punct	_	_

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
import lib.record_rate
import lib.getconfig
import lib.puylogger
import lib.commonclient
import lib.basecheck
import json

riak_url = lib.getconfig.getparam('Riak', 'stats')
check_type = 'riak'

class Check(lib.basecheck.CheckBase):

    def precheck(self):

        try:
            stats_json = json.loads(lib.commonclient.httpget(__name__, riak_url))
            metrics= ('sys_process_count', 'memory_processes', 'memory_processes_used', 'mem_allocated',
                      'node_gets', 'node_puts', 'vnode_gets', 'vnode_puts', 'read_repairs', 'vnode_set_update')
            for metric in metrics:
                if metric is 'node_gets':
                    myvalue = stats_json[metric]/60
                elif metric is 'node_puts':
                    myvalue = stats_json[metric]/60
                elif metric is 'vnode_gets':
                    myvalue = stats_json[metric]/60
                elif metric is 'vnode_puts':
                    myvalue = stats_json[metric]/60
                else:
                    myvalue = stats_json[metric]
                self.local_vars.append({'name': 'riak_'+metric, 'timestamp': self.timestamp, 'value': myvalue, 'check_type': check_type, 'chart_type': 'Rate'})
        except Exception as e:
            lib.puylogger.print_message(__name__ + ' Error : ' + str(e))
            pass


text:
function onClick() {
    var divCounter = document.getElementsByTagName("div").length;

    appendDiv(divCounter);
}

function appendDiv(message) {
    var element = document.createElement('div');
    element.innerHTML = message;
    document.body.appendChild(element);
}


text: ${value.data}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.ta4j</groupId>
        <artifactId>ta4j-parent</artifactId>
        <version>0.10-SNAPSHOT</version>
    </parent>
    <artifactId>ta4j-core</artifactId>

    <name>Ta4j Core</name>
    <description>ta4j is a Java library providing a simple API for technical analysis.</description>

    <dependencies>

        <!-- Logging facade -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>3.6.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
package com.dong.design.mediator;

public abstract class Mediator {

	public abstract void componentChanged(Component component);

}


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using Dapper;
using Elasticsearch.Net.Connection;
using Elasticsearch.Net;
using Newtonsoft.Json;

namespace Logger.Library
{
    public class LoggerService
    {
        public void MoveToElasticSearch(bool shouldSave, string logType, string startString, string endString)
        {
            var request = new SearchRequest {
                DateStart = DateTime.Parse(startString),
                DateEnd = DateTime.Parse(endString)
            };

            var logs = GetLogs(logType, request);

            if (shouldSave)
            {
                SendLogToElastic(logs, logType);
            }
            else
            {
                Console.WriteLine(JsonConvert.SerializeObject(logs.First(l => !string.IsNullOrEmpty(l.ApplicationName)), Formatting.Indented));
            }

            Console.WriteLine("{0} {1} sending count: {2}", request.DateStart.ToString(), request.DateEnd.ToString(), logs.Count().ToString());
        }

        private void SendLogToElastic(IEnumerable<LogItem> logs, string logType)
        {
            var node = new Uri("http://10.3.29.129:9200");
            var config = new ConnectionConfiguration(node);
            var elastic = new ElasticsearchClient(config);

            foreach (var item in logs)
            {
                var guid = Guid.NewGuid().ToString();
                var error = JsonConvert.SerializeObject(item);
                var response = elastic.Index("error_log", "log", guid, error);
                Console.WriteLine("Pushed {2} {0}  was successful: {1}", guid, response.SuccessOrKnownError, logType);
            }
        }

        private IEnumerable<LogItem> GetLogs(string logType, SearchRequest request)
        {
            string logCommand = string.Empty;

            switch (logType)
            {
                case "ResponseLog":
                    logCommand = ResponseLog;
                    break;
                case "RequestLog":
                    logCommand = RequestLog;
                    break;
                case "ErrorLog":
                    logCommand = ErrorLog;
                    break;
                default:
                    break;
            }

            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Logging"].ConnectionString))
            {
                return conn.Query<LogItem>(logCommand, request);
            }
        }

        private string ResponseLog = @"SELECT YOUR DATA HERE";

        private string RequestLog = @"SELECT YOUR DATA HERE";

        private string ErrorLog = @"SELECT YOUR DATA HERE";
    }
}


text:
/**
 * New node file
 */

function MsgDeviceIdentifierResponse(){
	this.deviceId = undefined;
};

MsgDeviceIdentifierResponse.prototype.setDeviceId = function setDeviceId(value){
	this.deviceId = value;
};

MsgDeviceIdentifierResponse.prototype.getDeviceId = function getDeviceId(){
	return this.deviceId;
};

MsgDeviceIdentifierResponse.prototype.write = function write(buffer) {
	buffer.writeUInt8String(this.deviceId);
};

MsgDeviceIdentifierResponse.prototype.getSize = function getSize(){
	return  this.deviceId.length+1;
};

MsgDeviceIdentifierResponse.prototype.toString = function toString(){
	var str = "";
	str+="Device-ID: "+this.deviceId+"\n";
	return str;
};

MsgDeviceIdentifierResponse.parse = function parse(buffer) {
	var message = new MsgDeviceIdentifierResponse();
	message.setDeviceId(buffer.readUInt8String());

	return message;
};

module.exports = MsgDeviceIdentifierResponse;


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using SF.Maths;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SF.Sys.Drawing
{

	[Flags]
	public enum ExecuteFlag
	{
		None=0,
		StrictSize=1
	}
	public interface ITransformContext
	{
		IImageBuffer GetTarget(Size Size, bool force=false);
		IDrawContext NewGraphics(IImageBuffer image);
		ExecuteFlag Flags { get; }
		T Execute<T>(Transform<T> Transform, ImageContext src, ExecuteFlag flags= ExecuteFlag.None);
	}
	public class ImageMemoryBuffer
	{
		public byte[] Data { get; set; }
		public string Mime { get; set; }
		public Size Size { get; set; }
	}

	public class ImageContext
	{
		public IImage Image { get; set; }
		public Size Size { get; set; }
	}

	public delegate T Transform<T>(ImageContext src, ITransformContext ctx);

}