text:
import binascii
import hashlib
import pytest

from api.base.settings.defaults import API_BASE
from django.contrib.auth.models import Permission

from osf.models import RegistrationSchema
from osf_tests.factories import (
    ProjectFactory,
    DraftRegistrationFactory,
    AuthUserFactory,
    RegistrationFactory,
)
from osf.utils.permissions import WRITE, READ
from rest_framework import exceptions
from api_tests.nodes.views.test_node_draft_registration_list import DraftRegistrationTestCase

SCHEMA_VERSION = 2

@pytest.mark.django_db
class TestDraftRegistrationDetail(DraftRegistrationTestCase):

    @pytest.fixture()
    def schema(self):
        return RegistrationSchema.objects.get(
            name='OSF-Standard Pre-Data Collection Registration',
            schema_version=SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration(self, user, project_public, schema):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema,
            branched_from=project_public
        )

    @pytest.fixture()
    def project_other(self, user):
        return ProjectFactory(creator=user)

    @pytest.fixture()
    def url_draft_registrations(self, project_public, draft_registration):
        return '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration._id)

    def test_admin_can_view_draft(
            self, app, user, draft_registration, project_public,
            schema, url_draft_registrations, group_mem):
        res = app.get(url_draft_registrations, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert schema._id in data['relationships']['registration_schema']['links']['related']['href']
        assert data['id'] == draft_registration._id
        assert data['attributes']['registration_metadata'] == {}

    #   test_group_mem_admin_can_view
        res = app.get(url_draft_registrations, auth=group_mem.auth)
        assert res.status_code == 200

    def test_cannot_view_draft(
            self, app, user_write_contrib, project_public,
            user_read_contrib, user_non_contrib,
            url_draft_registrations, group, group_mem):

        #   test_read_only_contributor_cannot_view_draft
        res = app.get(
            url_draft_registrations,
            auth=user_read_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_read_write_contributor_cannot_view_draft
        res = app.get(
            url_draft_registrations,
            auth=user_write_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_logged_in_non_contributor_cannot_view_draft
        res = app.get(
            url_draft_registrations,
            auth=user_non_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_unauthenticated_user_cannot_view_draft
        res = app.get(url_draft_registrations, expect_errors=True)
        assert res.status_code == 401

    #   test_group_mem_read_cannot_view
        project_public.remove_osf_group(group)
        project_public.add_osf_group(group, READ)
        res = app.get(url_draft_registrations, auth=group_mem.auth, expect_errors=True)
        assert res.status_code == 403

    def test_cannot_view_deleted_draft(
            self, app, user, url_draft_registrations):
        res = app.delete_json_api(url_draft_registrations, auth=user.auth)
        assert res.status_code == 204

        res = app.get(
            url_draft_registrations,
            auth=user.auth,
            expect_errors=True)
        assert res.status_code == 410

    def test_draft_must_be_branched_from_node_in_kwargs(
            self, app, user, project_other, draft_registration):
        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_other._id, draft_registration._id)
        res = app.get(url, auth=user.auth, expect_errors=True)
        assert res.status_code == 400
        errors = res.json['errors'][0]
        assert errors['detail'] == 'This draft registration is not created from the given node.'

    def test_reviewer_can_see_draft_registration(
            self, app, schema, draft_registration, url_draft_registrations):
        user = AuthUserFactory()
        administer_permission = Permission.objects.get(
            codename='administer_prereg')
        user.user_permissions.add(administer_permission)
        user.save()
        res = app.get(url_draft_registrations, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert schema._id in data['relationships']['registration_schema']['links']['related']['href']
        assert data['id'] == draft_registration._id
        assert data['attributes']['registration_metadata'] == {}

@pytest.mark.django_db
class TestDraftRegistrationUpdate(DraftRegistrationTestCase):

    @pytest.fixture()
    def schema(self):
        return RegistrationSchema.objects.get(
            name='OSF-Standard Pre-Data Collection Registration',
            schema_version=SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration(self, user, project_public, schema):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema,
            branched_from=project_public
        )

    @pytest.fixture()
    def schema_prereg(self):
        return RegistrationSchema.objects.get(
            name='Prereg Challenge',
            schema_version=SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration_prereg(self, user, project_public, schema_prereg):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema_prereg,
            branched_from=project_public
        )

    @pytest.fixture()
    def metadata_registration(
            self, prereg_metadata,
            draft_registration_prereg):
        return prereg_metadata(draft_registration_prereg)

    @pytest.fixture()
    def project_other(self, user):
        return ProjectFactory(creator=user)

    @pytest.fixture()
    def url_draft_registrations(self, project_public, draft_registration):
        return '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration._id)

    @pytest.fixture()
    def payload(self, draft_registration):
        return {
            'data': {
                'id': draft_registration._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'datacompletion': {
                            'value': 'No, data collection has not begun'
                        },
                        'looked': {
                            'value': 'No'
                        },
                        'comments': {
                            'value': 'This is my first registration.'
                        }
                    }
                }
            }
        }

    @pytest.fixture()
    def administer_permission(self):
        return Permission.objects.get(codename='administer_prereg')

    def test_id_required_in_payload(self, app, user, url_draft_registrations):
        payload = {
            'data': {
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {}
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations, payload,
            auth=user.auth, expect_errors=True)
        assert res.status_code == 400
        errors = res.json['errors'][0]
        assert errors['source']['pointer'] == '/data/id'
        assert errors['detail'] == 'This field may not be null.'

    def test_admin_can_update_draft(
            self, app, user, schema, project_public,
            payload, url_draft_registrations):
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert schema._id in data['relationships']['registration_schema']['links']['related']['href']
        assert data['attributes']['registration_metadata'] == payload['data']['attributes']['registration_metadata']

    def test_draft_must_be_branched_from_node(
            self, app, user, project_other, draft_registration, payload):
        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_other._id, draft_registration._id)
        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        errors = res.json['errors'][0]
        assert errors['detail'] == 'This draft registration is not created from the given node.'

    def test_cannot_update_draft(
            self, app, user_write_contrib, project_public,
            user_read_contrib, user_non_contrib,
            payload, url_draft_registrations, group, group_mem):

        #   test_read_only_contributor_cannot_update_draft
        res = app.put_json_api(
            url_draft_registrations,
            payload,
            auth=user_read_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_read_write_contributor_cannot_update_draft
        res = app.put_json_api(
            url_draft_registrations,
            payload,
            auth=user_write_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_logged_in_non_contributor_cannot_update_draft
        res = app.put_json_api(
            url_draft_registrations,
            payload,
            auth=user_non_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_unauthenticated_user_cannot_update_draft
        res = app.put_json_api(
            url_draft_registrations,
            payload, expect_errors=True)
        assert res.status_code == 401

    #   test_osf_group_member_admin_cannot_update_draft
        res = app.put_json_api(
            url_draft_registrations,
            payload, expect_errors=True,
            auth=group_mem.auth
        )
        assert res.status_code == 403

    #   test_osf_group_member_write_cannot_update_draft
        project_public.remove_osf_group(group)
        project_public.add_osf_group(group, WRITE)
        res = app.put_json_api(
            url_draft_registrations,
            payload, expect_errors=True,
            auth=group_mem.auth
        )
        assert res.status_code == 403

    def test_registration_metadata_must_be_supplied(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes'] = {}

        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        errors = res.json['errors'][0]
        assert res.status_code == 400
        assert errors['source']['pointer'] == '/data/attributes/registration_metadata'
        assert errors['detail'] == 'This field is required.'

    def test_registration_metadata_must_be_a_dictionary(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata'] = 'Registration data'

        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        errors = res.json['errors'][0]
        assert res.status_code == 400
        assert errors['source']['pointer'] == '/data/attributes/registration_metadata'
        assert errors['detail'] == 'Expected a dictionary of items but got type "unicode".'

    def test_registration_metadata_question_values_must_be_dictionaries(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['datacompletion'] = 'No, data collection has not begun'

        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        errors = res.json['errors'][0]
        assert res.status_code == 400
        assert errors['detail'] == 'For your registration your response to the \'Has data collection begun for this project?\'' \
                                   ' field is invalid, your response must be one of the provided options.'

    def test_registration_metadata_question_keys_must_be_value(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['datacompletion'] = {
            'incorrect_key': 'No, data collection has not begun'}

        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        errors = res.json['errors'][0]
        assert res.status_code == 400
        assert errors['detail'] == 'For your registration your response to the \'Has data collection begun for this project?\'' \
                                   ' field is invalid, your response must be one of the provided options.'

    def test_question_in_registration_metadata_must_be_in_schema(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q11'] = {
            'value': 'No, data collection has not begun'
        }

        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        errors = res.json['errors'][0]
        assert res.status_code == 400
        assert errors['detail'] == 'For your registration the \'datacompletion\' field is extraneous and not' \
                                   ' permitted in your response.'

    def test_multiple_choice_question_value_must_match_value_in_schema(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['datacompletion'] = {
            'value': 'Nope, data collection has not begun'}

        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        errors = res.json['errors'][0]
        assert res.status_code == 400
        assert errors['detail'] == 'For your registration your response to the \'Has data collection begun for this project?\' field' \
                                   ' is invalid, your response must be one of the provided options.'

    def test_cannot_update_registration_schema(
            self, app, user, schema, payload,
            schema_prereg, url_draft_registrations):
        payload['data']['relationships'] = {
            'registration_schema': {
                'data': {
                    'id': schema_prereg._id,
                    'type': 'registration_schema'
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 200
        assert schema._id in res.json['data']['relationships']['registration_schema']['links']['related']['href']

    def test_required_metaschema_questions_not_required_on_update(
            self, app, user, project_public,
            draft_registration_prereg,
            metadata_registration):

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        del metadata_registration['q1']
        draft_registration_prereg.metadata_registration = metadata_registration
        draft_registration_prereg.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q2': {
                            'value': 'New response'
                        }
                    }
                }
            }
        }

        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q2']['value'] == 'New response'
        assert 'q1' not in res.json['data']['attributes']['registration_metadata']

    def test_reviewer_can_update_draft_registration(
            self, app, project_public,
            draft_registration_prereg,
            administer_permission):
        user = AuthUserFactory()
        user.user_permissions.add(administer_permission)
        user.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q2': {
                            'comments': [{'value': 'This is incomplete.'}]
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        res = app.put_json_api(
            url, payload,
            auth=user.auth,
            expect_errors=True)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q2']['comments'][0]['value'] == 'This is incomplete.'
        assert 'q1' not in res.json['data']['attributes']['registration_metadata']

    def test_reviewer_can_only_update_comment_fields_draft_registration(
            self, app, project_public, draft_registration_prereg, administer_permission):
        user = AuthUserFactory()
        user.user_permissions.add(administer_permission)
        user.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q2': {
                            'value': 'Test response'
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0][
            'detail'] == 'For your registration your response to the \'Authors\' field is invalid.'

    def test_reviewer_can_update_nested_comment_fields_draft_registration(
            self, app, project_public, draft_registration_prereg, administer_permission):
        user = AuthUserFactory()
        user.user_permissions.add(administer_permission)
        user.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q7': {
                            'value': {
                                'question': {
                                    'comments': [{'value': 'Add some clarity here.'}]
                                }
                            }
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q7'][
            'value']['question']['comments'][0]['value'] == 'Add some clarity here.'

    def test_reviewer_cannot_update_nested_value_fields_draft_registration(
            self, app, project_public, draft_registration_prereg, administer_permission):
        user = AuthUserFactory()
        user.user_permissions.add(administer_permission)
        user.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q7': {
                            'value': {
                                'question': {
                                    'value': 'This is the answer'
                                }
                            }
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0][
            'detail'] == 'For your registration your response to the \'Data collection procedures\' field is invalid.'

@pytest.mark.django_db
class TestDraftRegistrationPatch(DraftRegistrationTestCase):

    @pytest.fixture()
    def schema(self):
        return RegistrationSchema.objects.get(
            name='OSF-Standard Pre-Data Collection Registration',
            schema_version=SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration(self, user, project_public, schema):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema,
            branched_from=project_public
        )

    @pytest.fixture()
    def schema_prereg(self):
        return RegistrationSchema.objects.get(
            name='Prereg Challenge',
            schema_version=SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration_prereg(self, user, project_public, schema_prereg):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema_prereg,
            branched_from=project_public
        )

    @pytest.fixture()
    def metadata_registration(
            self, prereg_metadata,
            draft_registration_prereg):
        return prereg_metadata(draft_registration_prereg)

    @pytest.fixture()
    def project_other(self, user):
        return ProjectFactory(creator=user)

    @pytest.fixture()
    def url_draft_registrations(self, project_public, draft_registration):
        return '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration._id)

    @pytest.fixture()
    def payload(self, draft_registration):
        return {
            'data': {
                'id': draft_registration._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'datacompletion': {
                            'value': 'No, data collection has not begun'
                        },
                        'looked': {
                            'value': 'No'
                        },
                        'comments': {
                            'value': 'This is my first registration.'
                        }
                    }
                }
            }
        }

    def test_admin_can_update_draft(
            self, app, user, schema, payload,
            url_draft_registrations):
        res = app.patch_json_api(
            url_draft_registrations,
            payload, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert schema._id in data['relationships']['registration_schema']['links']['related']['href']
        assert data['attributes']['registration_metadata'] == payload['data']['attributes']['registration_metadata']

    def test_cannot_update_draft(
            self, app, user_write_contrib,
            user_read_contrib, user_non_contrib,
            payload, url_draft_registrations, group_mem):

        #   test_read_only_contributor_cannot_update_draft
        res = app.patch_json_api(
            url_draft_registrations,
            payload,
            auth=user_read_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_read_write_contributor_cannot_update_draft
        res = app.patch_json_api(
            url_draft_registrations,
            payload,
            auth=user_write_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_logged_in_non_contributor_cannot_update_draft
        res = app.patch_json_api(
            url_draft_registrations,
            payload,
            auth=user_non_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_unauthenticated_user_cannot_update_draft
        res = app.patch_json_api(
            url_draft_registrations,
            payload, expect_errors=True)
        assert res.status_code == 401

        # group admin cannot update draft
        res = app.patch_json_api(
            url_draft_registrations,
            payload,
            auth=group_mem.auth,
            expect_errors=True)
        assert res.status_code == 403

@pytest.mark.django_db
class TestDraftRegistrationDelete(DraftRegistrationTestCase):

    @pytest.fixture()
    def schema(self):
        return RegistrationSchema.objects.get(
            name='OSF-Standard Pre-Data Collection Registration',
            schema_version=SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration(self, user, project_public, schema):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema,
            branched_from=project_public
        )

    @pytest.fixture()
    def project_other(self, user):
        return ProjectFactory(creator=user)

    @pytest.fixture()
    def url_draft_registrations(self, project_public, draft_registration):
        return '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration._id)

    def test_admin_can_delete_draft(self, app, user, url_draft_registrations, project_public):
        res = app.delete_json_api(url_draft_registrations, auth=user.auth)
        assert res.status_code == 204

    def test_cannot_delete_draft(
            self, app, user_write_contrib, project_public,
            user_read_contrib, user_non_contrib,
            url_draft_registrations, group, group_mem):

        #   test_read_only_contributor_cannot_delete_draft
        res = app.delete_json_api(
            url_draft_registrations,
            auth=user_read_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_read_write_contributor_cannot_delete_draft
        res = app.delete_json_api(
            url_draft_registrations,
            auth=user_write_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_logged_in_non_contributor_cannot_delete_draft
        res = app.delete_json_api(
            url_draft_registrations,
            auth=user_non_contrib.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_unauthenticated_user_cannot_delete_draft
        res = app.delete_json_api(url_draft_registrations, expect_errors=True)
        assert res.status_code == 401

    #   test_group_member_admin_cannot_delete_draft
        res = app.delete_json_api(url_draft_registrations, expect_errors=True, auth=group_mem.auth)
        assert res.status_code == 403

    #   test_group_member_write_cannot_delete_draft
        project_public.remove_osf_group(group)
        project_public.add_osf_group(group, WRITE)
        res = app.delete_json_api(url_draft_registrations, expect_errors=True, auth=group_mem.auth)
        assert res.status_code == 403

    def test_draft_that_has_been_registered_cannot_be_deleted(
            self, app, user, project_public, draft_registration, url_draft_registrations):
        reg = RegistrationFactory(project=project_public)
        draft_registration.registered_node = reg
        draft_registration.save()
        res = app.delete_json_api(
            url_draft_registrations,
            auth=user.auth,
            expect_errors=True)
        assert res.status_code == 403
        assert res.json['errors'][0]['detail'] == 'This draft has already been registered and cannot be modified.'

    def test_reviewer_cannot_delete_draft_registration(
            self, app, url_draft_registrations):
        user = AuthUserFactory()
        administer_permission = Permission.objects.get(
            codename='administer_prereg')
        user.user_permissions.add(administer_permission)
        user.save()

        res = app.delete_json_api(
            url_draft_registrations,
            auth=user.auth, expect_errors=True)
        assert res.status_code == 403
        assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail

@pytest.mark.django_db
class TestDraftPreregChallengeRegistrationMetadataValidation(
        DraftRegistrationTestCase):

    @pytest.fixture()
    def schema_prereg(self):
        return RegistrationSchema.objects.get(
            name='Prereg Challenge',
            schema_version=SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration_prereg(self, user, project_public, schema_prereg):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema_prereg,
            branched_from=project_public
        )

    @pytest.fixture()
    def project_other(self, user):
        return ProjectFactory(creator=user)

    @pytest.fixture()
    def url_draft_registrations(
            self, project_public,
            draft_registration_prereg):
        return '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

    @pytest.fixture()
    def payload(self, draft_registration_prereg):
        return {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {}
                }
            }
        }

    def test_first_level_open_ended_answers(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q1'] = {
            'value': 'This is my answer.'
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q1']['value'] == 'This is my answer.'

    def test_first_level_open_ended_answer_must_have_correct_key(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q1'] = {
            'values': 'This is my answer.'
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0][
            'detail'] == 'For your registration your response to the \'Title\' field is invalid.'

    def test_first_level_open_ended_answer_must_be_of_correct_type(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q1'] = {
            'value': 12345
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'For your registration your response to the \'Title\' field is invalid.'

    def test_first_level_open_ended_answer_not_expecting_more_nested_data(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q1'] = {
            'value': {
                'question': {
                    'value': 'This is my answer.'
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'For your registration your response to the \'Title\' field is invalid.'

    def test_second_level_answers(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q7'] = {
            'value': {
                'question': {
                    'value': 'This is my answer.'
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q7']['value']['question']['value'] == 'This is my answer.'

    def test_second_level_open_ended_answer_must_have_correct_key(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q7'] = {
            'value': {
                'questions': {
                    'value': 'This is my answer.'
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0][
            'detail'] == 'For your registration your response to the \'Data collection procedures\' field is invalid.'

    def test_third_level_open_ended_answer_must_have_correct_key(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q7'] = {
            'value': {
                'question': {
                    'values': 'This is my answer.'
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == \
               'For your registration your response to the \'Data collection procedures\' field is invalid.'

    def test_second_level_open_ended_answer_must_have_correct_type(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q7'] = {
            'value': {
                'question': 'This is my answer'
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'For your registration your response to the \'Data collection procedures\'' \
                                                  ' field is invalid.'

    def test_third_level_open_ended_answer_must_have_correct_type(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q7'] = {
            'value': {
                'question': {
                    'value': True
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'For your registration your response to the \'Data collection procedures\'' \
                                                  ' field is invalid.'

    def test_uploader_metadata(
            self, app, user, project_public,
            draft_registration_prereg,
            payload, url_draft_registrations):
        sha256 = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
        payload['data']['attributes']['registration_metadata']['q7'] = {
            'value': {
                'uploader': {
                    'value': 'Screen Shot 2016-03-30 at 7.02.05 PM.png',
                    'extra': [{
                        'data': {},
                        'nodeId': project_public._id,
                        'viewUrl': '/project/{}/files/osfstorage/{}'.format(project_public._id, draft_registration_prereg._id),
                        'selectedFileName': 'Screen Shot 2016-03-30 at 7.02.05 PM.png',
                        'sha256': binascii.hexlify(sha256)
                    }]
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q7']['value'][
            'uploader']['value'] == 'Screen Shot 2016-03-30 at 7.02.05 PM.png'

    def test_uploader_metadata_incorrect_key(
            self, app, user, project_public,
            draft_registration_prereg,
            payload, url_draft_registrations):
        sha256 = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
        payload['data']['attributes']['registration_metadata']['q7'] = {
            'value': {
                'uploader': {
                    'value': 'Screen Shot 2016-03-30 at 7.02.05 PM.png',
                    'extra': [{
                        'data': {},
                        'nodeId': project_public._id,
                        'viewUrl': '/project/{}/files/osfstorage/{}'.format(project_public._id, draft_registration_prereg._id),
                        'selectedFileNames': 'Screen Shot 2016-03-30 at 7.02.05 PM.png',
                        'sha256': binascii.hexlify(sha256)
                    }]
                }
            }
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0][
            'detail'] == 'For your registration your response to the \'Data collection procedures\' field is invalid.'

    def test_multiple_choice_questions_incorrect_choice(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q15'] = {
            'value': ['This is my answer.']
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'For your registration your response to the \'Blinding\' field is invalid, your ' \
                                                  'response must be one of the provided options.'

    def test_multiple_choice_questions(
            self, app, user, payload, url_draft_registrations):
        payload['data']['attributes']['registration_metadata']['q15'] = {
            'value': ['No blinding is involved in this study.']
        }
        res = app.put_json_api(
            url_draft_registrations,
            payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q15']['value'] == ['No blinding is involved in this study.']


text:
"""
Integrate a surface field
"""

from __future__ import print_function
import argparse
import time
import os
import re
import sys

from icqsol.shapes.icqShapeManager import ShapeManager
from icqsol import util

# time stamp
tid = re.sub(r'\.', '', str(time.time()))

parser = argparse.ArgumentParser(description='Color surface field')

parser.add_argument('--input', dest='input', default='',
                    help='VTK input file')

parser.add_argument('--name', dest='name', default='',
                    help='Set the name of the field')

parser.add_argument('--component', dest='component', type=int, default=0,
                    help='Set the component of the field')

parser.add_argument('--ascii', dest='ascii', action='store_true',
                    help='Save data in ASCII format (default is binary)')

args = parser.parse_args()

if not args.input:
    print('ERROR: must specify input file: --input <file>')
    sys.exit(3)

if not os.path.exists(args.input):
    print('ERROR: file {0} does not exist'.format(args.input))
    sys.exit(2)

file_format = util.getFileFormat(args.input)

if file_format != util.VTK_FORMAT:
    print('ERROR: file {0} must be VTK format'.format(args.input))
    sys.exit(2)

vtk_dataset_type = util.getVtkDatasetType(args.input)

if vtk_dataset_type not in util.VTK_DATASET_TYPES:
    print('ERROR: invalid VTK dataset type {0}'.format(vtk_dataset_type))
    sys.exit(2)

shape_mgr = ShapeManager(file_format=util.VTK_FORMAT, vtk_dataset_type=vtk_dataset_type)
pDataInput = shape_mgr.loadAsVtkPolyData(args.input)
integral = shape_mgr.integrateSurfaceField(pDataInput,
                                           field_name=args.name,
                                           field_component=args.component)

print('integral = {0}'.format(integral))

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eas.util;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mg
 */
public class CollectionEditingSupport<C, V> {

    protected C collection;
    protected Set<CollectionListener<C, V>> listeners = new HashSet<>();

    public CollectionEditingSupport(C aCollection) {
        super();
        collection = aCollection;
    }

    public void addListener(CollectionListener aListener) {
        listeners.add(aListener);
    }

    public boolean removeListener(CollectionListener aListener) {
        return listeners.remove(aListener);
    }

    public void fireElementAdded(V element) {
        try {
            for (CollectionListener l : listeners) {
                l.added(collection, element);
            }
        } catch (Exception ex) {
            Logger.getLogger(CollectionEditingSupport.class.getName()).log(Level.SEVERE, "While firering an event \"fireElementAdded\"", ex);
        }
    }

    public void fireElementsAdded(Collection<V> elements) {
        try {
            for (CollectionListener l : listeners) {
                l.added(collection, elements);
            }
        } catch (Exception ex) {
            Logger.getLogger(CollectionEditingSupport.class.getName()).log(Level.SEVERE, "While firering an event \"fireElementsAdded\"", ex);
        }
    }

    public void fireElementRemoved(V element) {
        try {
            for (CollectionListener l : listeners) {
                l.removed(collection, element);
            }
        } catch (Exception ex) {
            Logger.getLogger(CollectionEditingSupport.class.getName()).log(Level.SEVERE, "While firering an event \"fireElementRemoved\"", ex);
        }
    }

    public void fireElementsRemoved(Collection<V> elements) {
        try {
            for (CollectionListener l : listeners) {
                l.removed(collection, elements);
            }
        } catch (Exception ex) {
            Logger.getLogger(CollectionEditingSupport.class.getName()).log(Level.SEVERE, "While firering an event \"fireElementsRemoved\"", ex);
        }
    }

    public void fireCleared() {
        try {
            for (CollectionListener l : listeners) {
                l.cleared(collection);
            }
        } catch (Exception ex) {
            Logger.getLogger(CollectionEditingSupport.class.getName()).log(Level.SEVERE, "While firering an event \"fireCleared\"", ex);
        }
    }

    public void fireReodered() {
        try {
            for (CollectionListener l : listeners) {
                l.reodered(collection);
            }
        } catch (Exception ex) {
            Logger.getLogger(CollectionEditingSupport.class.getName()).log(Level.SEVERE, "While firering an event \"fireReodered\"", ex);
        }
    }
}


text:
exports.tomarTareasOrdenadasPorPrioridadParaEstadoFinalizadas = function() {
    var estados = JSON.parse(Ti.App.Properties.getString("ListaDeEstados"));
    Alloy.Collections.tareas.fetch({
        query: 'SELECT * from tareas where estado="' + estados[0].finalizada + '" order by prioridad ASC'
    });
    return Alloy.Collections.tareas;
};

exports.tomarTareasOrdenadasPorPrioridadParaEstado = function(strEstado) {
    Alloy.Collections.tareas.fetch({
        query: 'SELECT * from tareas where estado="' + strEstado + '" and usuario="' + strUsuarioActual + '" order by prioridad ASC'
    });
    return Alloy.Collections.tareas;
};

exports.tomarTextoTareaParaID = function(strID) {
    Alloy.Collections.tareas.fetch({
        query: 'SELECT * from tareas where alloy_id="' + strID + '"'
    });
    return Alloy.Collections.tareas.at(0).get("texto");
};

exports.agregaTarea = function(strTexto, intPrioridad, strEstado) {
    var tareaModel = Alloy.createModel("Tareas", {
        texto: strTexto,
        prioridad: intPrioridad,
        estado: strEstado,
        usuario: strUsuarioActual
    });
    Alloy.Collections.tareas.add(tareaModel);
    tareaModel.save();
};

exports.eliminiarTareaParaID = function(idTareaActualEdicion) {
    var tarea = Alloy.Collections.tareas.get(idTareaActualEdicion);
    tarea.destroy();
};

exports.editaTextoTareaParaID = function(strID, strTexto, intPrioridad, strEstado) {
    var tareaModel = Alloy.createModel("Tareas", {
        alloy_id: strID,
        texto: strTexto,
        prioridad: intPrioridad,
        estado: strEstado,
        usuario: strUsuarioActual
    });
    Alloy.Collections.tareas.add(tareaModel);
    tareaModel.save();
};

exports.controlLogin = function(strUsuario, strClave) {
    var usuarios = JSON.parse(Ti.App.Properties.getString("ListaDeUsuarios"));
    for (i in usuarios) if (strUsuario == usuarios[i].usuario && strClave == usuarios[i].pass) return true;
    return false;
};

exports.cargaDataEjemplar = function() {
    var tareaModel = Alloy.createModel("Tareas", {
        texto: "comprar carne p3 carlos",
        prioridad: 3,
        estado: "Pendiente",
        usuario: "carlos"
    });
    Alloy.Collections.tareas.add(tareaModel);
    tareaModel.save();
    var tareaModel = Alloy.createModel("Tareas", {
        texto: "comprar carne p1 carlos",
        prioridad: 1,
        estado: "Pendiente",
        usuario: "carlos"
    });
    Alloy.Collections.tareas.add(tareaModel);
    tareaModel.save();
    var tareaModel = Alloy.createModel("Tareas", {
        texto: "comprar carne p2 cefe",
        prioridad: 2,
        estado: "Pendiente",
        usuario: "cefe"
    });
    Alloy.Collections.tareas.add(tareaModel);
    tareaModel.save();
    tareaModel = Alloy.createModel("Tareas", {
        texto: "comprar leña cefe",
        prioridad: 2,
        estado: "Finalizada",
        usuario: "cefe"
    });
    Alloy.Collections.tareas.add(tareaModel);
    tareaModel.save();
    tareaModel = Alloy.createModel("Tareas", {
        texto: "comprar pan carlos",
        prioridad: 1,
        estado: "En Progreso",
        usuario: "carlos"
    });
    Alloy.Collections.tareas.add(tareaModel);
    tareaModel.save();
};


text:
namespace Leafly.Types
{
    public class StrainDetailsFlavorsListItem : StrainDetailsListItemBase{}
}


text:
import enum
import itertools
import os.path
import shutil

from typing import Dict, List

import lib.aur as aur
import lib.pacman.sync as sync
import lib.pacman.upgrade as upgrade
import packager.path
from manager.models import Package, Build, Artifact
from packager.manager import BuilderManager
from packager.path import build_to_path
from packager.settings import BUILD_ROOT_DIR

class OperationError(Exception):
    def __init__(self, reason):
        self.reason = reason

    def __str__(self):
        return repr(self.reason)

class RegisterStatus(enum.Enum):
    package = 1
    artifact = 2
    not_registered = 3

def _is_registered(name: str) -> bool:
    return not _register_status(name)[0] == RegisterStatus.not_registered

def _register_status(name: str) -> (RegisterStatus, str):
    if Package.objects.filter(name=name).exists():
        return RegisterStatus.package, name
    else:
        a = Artifact.objects.filter(name=name)
        if a.exists():
            return RegisterStatus.artifact, a[0].package.name
        else:
            return RegisterStatus.not_registered, ''

# TODO: Refactor too naive implementation
def register(name: str, server: str, with_depend: bool = False) -> Dict[str, List[str]]:
    (is_registered, registered_name) = _register_status(name)
    if is_registered == RegisterStatus.package:
        raise OperationError('{} has already registered'.format(name))
    elif is_registered == RegisterStatus.artifact:
        raise OperationError('{} has already registered as Artifact of {}'.format(name, registered_name))

    info = aur.detail_info(name, server)
    native = []
    foreign = []
    if with_depend:
        depends = []
        if hasattr(info, 'Depends'):
            depends.append(info.Depends)
        if hasattr(info, 'MakeDepends'):
            depends.append(info.MakeDepends)
        for depend in itertools.chain(*depends):
            depend_name = depend.translate(str.maketrans('>=', '<<')).split('<')[0]
            if sync.exist(depend_name):
                native.append(depend_name)
            elif aur.exist(depend_name, Package.OFFICIAL):
                foreign.append(depend_name)
            else:
                raise OperationError('{} not found'.format(depend_name))
        sync.system_upgrade()
        sync.install(native, asdeps=True)
        for package in foreign:
            if not _is_registered(package):
                # Dependent package will register from official server
                r = register(package, Package.OFFICIAL, with_depend=True)
                native.extend(r['native'])
                foreign.extend(r['foreign'])

    for duplicate in (set(foreign) & set(info.pkgnames)):
        d = Package.objects.filter(name=duplicate)
        if d.exists():
            d.delete()
    package = Package(name=name, server=server)
    package.save()
    for pkgname in info.pkgnames:
        artifact = Artifact(package=package, name=pkgname)
        artifact.save()
    ret = dict()
    ret['native'] = list(set(native))
    ret['foreign'] = list(set(foreign))
    return ret

def remove_package(name, cleanup=False):
    if not _is_registered(name):
        raise OperationError('{} has not registered'.format(name))

    if cleanup:
        shutil.rmtree(os.path.join(BUILD_ROOT_DIR, name), ignore_errors=True)

    package = Package.objects.get(name=name)
    package.delete()

def _remove_build(build_: Build) -> None:
    path = build_to_path(build_)
    shutil.rmtree(path.build_dir, ignore_errors=True)
    build_.delete()

def remove_build(name: str, build_number: int) -> None:
    if not _is_registered(name):
        raise OperationError('{} has not registered'.format(name))
    try:
        build_ = Build.objects.filter(package__name=name).order_by('-id')[build_number - 1]
        _remove_build(build_)
    except IndexError:
        raise OperationError('{} build {} is not existed'.format(name, build_number))

def cleanup(name: str) -> None:
    if not _is_registered(name):
        raise OperationError('{} has not registered'.format(name))
    for build_ in Build.objects.filter(package__name=name, status=Build.FAILURE):
        _remove_build(build_)
    try:
        for build_ in Build.objects.filter(package__name=name, status=Build.SUCCESS).order_by('-id')[1:]:
            _remove_build(build_)
    except IndexError:
        pass

def cleanup_all() -> None:
    for package in Package.objects.all():
        cleanup(package.name)

def build(name):
    if not _is_registered(name):
        raise OperationError('{} has not registered'.format(name))

    package = Package.objects.get(name=name)
    sync.system_upgrade()
    BuilderManager().register(package.id)

def build_all():
    packages = Package.objects.all()
    sync.system_upgrade()
    for package in packages:
        BuilderManager().register(package.id)

def build_update():
    packages = Package.objects.all()
    sync.system_upgrade()
    # dict of server tag to list of Build
    need_check: Dict[str, List[Build]] = {}
    for package in packages:
        if package.ignore:
            continue
        try:
            latest = Build.objects.filter(package_id=package.id).order_by('-id')[0]
        except IndexError:
            BuilderManager().register(package.id)
        else:
            if latest.status == Build.FAILURE:
                BuilderManager().register(package.id)
            elif latest.status == Build.SUCCESS:
                if latest.package.server in need_check:
                    need_check[latest.package.server].append(latest)
                else:
                    need_check[latest.package.server] = [latest]
    if need_check:
        for k, v in need_check.items():
            multiple_info_ = aur.multiple_info([x.package.name for x in v], k)
            for p in v:
                package_name = p.package.name
                if multiple_info_[package_name] and multiple_info_[package_name].Version != p.version:
                    BuilderManager().register(p.package.id)

def install(name):
    if not _is_registered(name):
        raise OperationError('{} has not registered'.format(name))

    package = Package.objects.get(name=name)
    try:
        build_ = Build.objects.filter(package_id=package.id).order_by('-id')[0]
    except IndexError:
        raise OperationError('{} has no build'.format(name))
    if build_.status == Build.SUCCESS:
        try:
            path = packager.path.build_to_path(build_)
            sync.system_upgrade()
            completed = upgrade.install(path.artifact_file(name))
            if completed.returncode:
                raise OperationError(
                    'stdout:\n{}\n\nstderr\n:{}'.format(completed.stdout.decode(), completed.stderr.decode()))
        except FileNotFoundError as e:
            raise OperationError from e
    else:
        raise OperationError('{} latest build has not succeeded'.format(name))

def toggle_ignore(name):
    if not _is_registered(name):
        raise OperationError('{} has not registered'.format(name))

    package = Package.objects.get(name=name)
    package.ignore = not package.ignore
    package.save()
    return package.ignore


text:
package aos.camel;

import org.apache.camel.builder.RouteBuilder;

/**
 * A route which exposes a ping service over HTTP.
 *
 * @version $Revision: 51 $
 */
public class PingService extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("jetty:http://0.0.0.0:8080/ping").transform(constant("PONG\n"));
    }

}


text:
// Bz2Handler.cpp

#include "StdAfx.h"

#include "../../Common/ComTry.h"

#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamUtils.h"

#include "../Compress/BZip2Decoder.h"
#include "../Compress/BZip2Encoder.h"
#include "../Compress/CopyCoder.h"

#include "Common/DummyOutStream.h"
#include "Common/HandlerOut.h"

using namespace NWindows;

namespace NArchive {
namespace NBz2 {

class CHandler:
  public IInArchive,
  public IArchiveOpenSeq,
  public IOutArchive,
  public ISetProperties,
  public CMyUnknownImp
{
  CMyComPtr<IInStream> _stream;
  CMyComPtr<ISequentialInStream> _seqStream;

  bool _isArc;
  bool _needSeekToStart;
  bool _dataAfterEnd;
  bool _needMoreInput;

  bool _packSize_Defined;
  bool _unpackSize_Defined;
  bool _numStreams_Defined;
  bool _numBlocks_Defined;

  UInt64 _packSize;
  UInt64 _unpackSize;
  UInt64 _numStreams;
  UInt64 _numBlocks;

  CSingleMethodProps _props;

public:
  MY_UNKNOWN_IMP4(
      IInArchive,
      IArchiveOpenSeq,
      IOutArchive,
      ISetProperties)
  INTERFACE_IInArchive(;)
  INTERFACE_IOutArchive(;)
  STDMETHOD(OpenSeq)(ISequentialInStream *stream);
  STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, UInt32 numProps);

  CHandler() { }
};

static const Byte kProps[] =
{
  kpidSize,
  kpidPackSize
};

static const Byte kArcProps[] =
{
  kpidNumStreams,
  kpidNumBlocks
};

IMP_IInArchive_Props
IMP_IInArchive_ArcProps

STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
  NCOM::CPropVariant prop;
  switch (propID)
  {
    case kpidPhySize: if (_packSize_Defined) prop = _packSize; break;
    case kpidUnpackSize: if (_unpackSize_Defined) prop = _unpackSize; break;
    case kpidNumStreams: if (_numStreams_Defined) prop = _numStreams; break;
    case kpidNumBlocks: if (_numBlocks_Defined) prop = _numBlocks; break;
    case kpidErrorFlags:
    {
      UInt32 v = 0;
      if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;;
      if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd;
      if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd;
      prop = v;
    }
  }
  prop.Detach(value);
  return S_OK;
}

STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
  *numItems = 1;
  return S_OK;
}

STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)
{
  NCOM::CPropVariant prop;
  switch (propID)
  {
    case kpidPackSize: if (_packSize_Defined) prop = _packSize; break;
    case kpidSize: if (_unpackSize_Defined) prop = _unpackSize; break;
  }
  prop.Detach(value);
  return S_OK;
}

static const unsigned kSignatureCheckSize = 10;

API_FUNC_static_IsArc IsArc_BZip2(const Byte *p, size_t size)
{
  if (size < kSignatureCheckSize)
    return k_IsArc_Res_NEED_MORE;
  if (p[0] != 'B' || p[1] != 'Z' || p[2] != 'h' || p[3] < '1' || p[3] > '9')
    return k_IsArc_Res_NO;
  p += 4;
  if (NCompress::NBZip2::IsBlockSig(p))
    return k_IsArc_Res_YES;
  if (NCompress::NBZip2::IsEndSig(p))
    return k_IsArc_Res_YES;
  return k_IsArc_Res_NO;
}
}

STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)
{
  COM_TRY_BEGIN
  Close();
  {
    Byte buf[kSignatureCheckSize];
    RINOK(ReadStream_FALSE(stream, buf, kSignatureCheckSize));
    if (IsArc_BZip2(buf, kSignatureCheckSize) == k_IsArc_Res_NO)
      return S_FALSE;
    _isArc = true;
    _stream = stream;
    _seqStream = stream;
    _needSeekToStart = true;
  }
  return S_OK;
  COM_TRY_END
}

STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
{
  Close();
  _isArc = true;
  _seqStream = stream;
  return S_OK;
}

STDMETHODIMP CHandler::Close()
{
  _isArc = false;
  _needSeekToStart = false;
  _dataAfterEnd = false;
  _needMoreInput = false;

  _packSize_Defined = false;
  _unpackSize_Defined = false;
  _numStreams_Defined = false;
  _numBlocks_Defined = false;

  _packSize = 0;

  _seqStream.Release();
  _stream.Release();
  return S_OK;
}

STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
    Int32 testMode, IArchiveExtractCallback *extractCallback)
{
  COM_TRY_BEGIN
  if (numItems == 0)
    return S_OK;
  if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0))
    return E_INVALIDARG;

  if (_packSize_Defined)
    extractCallback->SetTotal(_packSize);

  // RINOK(extractCallback->SetCompleted(&packSize));

  CMyComPtr<ISequentialOutStream> realOutStream;
  Int32 askMode = testMode ?
      NExtract::NAskMode::kTest :
      NExtract::NAskMode::kExtract;
  RINOK(extractCallback->GetStream(0, &realOutStream, askMode));
  if (!testMode && !realOutStream)
    return S_OK;

  extractCallback->PrepareOperation(askMode);

  if (_needSeekToStart)
  {
    if (!_stream)
      return E_FAIL;
    RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL));
  }
  else
    _needSeekToStart = true;

  Int32 opRes;

  try
  {

  NCompress::NBZip2::CDecoder *decoderSpec = new NCompress::NBZip2::CDecoder;
  CMyComPtr<ICompressCoder> decoder = decoderSpec;
  decoderSpec->SetInStream(_seqStream);

  #ifndef _7ZIP_ST
  RINOK(decoderSpec->SetNumberOfThreads(_props._numThreads));
  #endif

  CDummyOutStream *outStreamSpec = new CDummyOutStream;
  CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
  outStreamSpec->SetStream(realOutStream);
  outStreamSpec->Init();

  realOutStream.Release();

  CLocalProgress *lps = new CLocalProgress;
  CMyComPtr<ICompressProgressInfo> progress = lps;
  lps->Init(extractCallback, true);

  UInt64 packSize = 0;
  UInt64 unpackedSize = 0;
  UInt64 numStreams = 0;

  decoderSpec->InitNumBlocks();

  HRESULT result = S_OK;

  for (;;)
  {
    lps->InSize = packSize;
    lps->OutSize = unpackedSize;

    RINOK(lps->SetCur());

    result = decoderSpec->CodeResume(outStream, progress);

    if (result != S_FALSE && result != S_OK)
      return result;

    if (decoderSpec->IsBz)
      numStreams++;
    else if (numStreams == 0)
    {
      _isArc = false;
      result = S_FALSE;
      break;
    }

    unpackedSize = outStreamSpec->GetSize();
    UInt64 streamSize = decoderSpec->GetStreamSize();

    if (streamSize == packSize)
    {
      // no new bytes in input stream, So it's good end of archive.
      result = S_OK;
      break;
    }

    if (!decoderSpec->IsBz)
    {
      _dataAfterEnd = true;
      result = S_FALSE;
      break;
    }

    if (decoderSpec->Base.BitDecoder.ExtraBitsWereRead())
    {
      _needMoreInput = true;
      packSize = streamSize;
      result = S_FALSE;
      break;
    }

    packSize = decoderSpec->GetInputProcessedSize();

    if (packSize > streamSize)
      return E_FAIL;

    if (result != S_OK)
      break;
  }

  if (numStreams != 0)
  {
    _packSize = packSize;
    _unpackSize = unpackedSize;
    _numStreams = numStreams;
    _numBlocks = decoderSpec->GetNumBlocks();

    _packSize_Defined = true;
    _unpackSize_Defined = true;
    _numStreams_Defined = true;
    _numBlocks_Defined = true;
  }

  decoderSpec->ReleaseInStream();
  outStream.Release();

  if (!_isArc)
    opRes = NExtract::NOperationResult::kIsNotArc;
  else if (_needMoreInput)
    opRes = NExtract::NOperationResult::kUnexpectedEnd;
  else if (decoderSpec->CrcError)
    opRes = NExtract::NOperationResult::kCRCError;
  else if (_dataAfterEnd)
    opRes = NExtract::NOperationResult::kDataAfterEnd;
  else if (result == S_FALSE)
    opRes = NExtract::NOperationResult::kDataError;
  else if (result == S_OK)
    opRes = NExtract::NOperationResult::kOK;
  else
    return result;

  }
  catch(const CInBufferException &e)  { return e.ErrorCode; }

  return extractCallback->SetOperationResult(opRes);

  COM_TRY_END
}

static HRESULT UpdateArchive(
    UInt64 unpackSize,
    ISequentialOutStream *outStream,
    const CProps &props,
    IArchiveUpdateCallback *updateCallback)
{
  RINOK(updateCallback->SetTotal(unpackSize));
  CMyComPtr<ISequentialInStream> fileInStream;
  RINOK(updateCallback->GetStream(0, &fileInStream));
  CLocalProgress *localProgressSpec = new CLocalProgress;
  CMyComPtr<ICompressProgressInfo> localProgress = localProgressSpec;
  localProgressSpec->Init(updateCallback, true);
  NCompress::NBZip2::CEncoder *encoderSpec = new NCompress::NBZip2::CEncoder;
  CMyComPtr<ICompressCoder> encoder = encoderSpec;
  RINOK(props.SetCoderProps(encoderSpec, NULL));
  RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, localProgress));
  return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK);
}

STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type)
{
  *type = NFileTimeType::kUnix;
  return S_OK;
}

STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
    IArchiveUpdateCallback *updateCallback)
{
  if (numItems != 1)
    return E_INVALIDARG;

  Int32 newData, newProps;
  UInt32 indexInArchive;
  if (!updateCallback)
    return E_FAIL;
  RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive));

  if (IntToBool(newProps))
  {
    {
      NCOM::CPropVariant prop;
      RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop));
      if (prop.vt == VT_BOOL)
      {
        if (prop.boolVal != VARIANT_FALSE)
          return E_INVALIDARG;
      }
      else if (prop.vt != VT_EMPTY)
        return E_INVALIDARG;
    }
  }

  if (IntToBool(newData))
  {
    UInt64 size;
    {
      NCOM::CPropVariant prop;
      RINOK(updateCallback->GetProperty(0, kpidSize, &prop));
      if (prop.vt != VT_UI8)
        return E_INVALIDARG;
      size = prop.uhVal.QuadPart;
    }
    return UpdateArchive(size, outStream, _props, updateCallback);
  }
  if (indexInArchive != 0)
    return E_INVALIDARG;
  if (_stream)
    RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL));
  return NCompress::CopyStream(_stream, outStream, NULL);
}

STDMETHODIMP CHandler::SetProperties(const wchar_t **names, const PROPVARIANT *values, UInt32 numProps)
{
  return _props.SetProperties(names, values, numProps);
}

IMP_CreateArcIn
IMP_CreateArcOut

static CArcInfo g_ArcInfo =
  { "bzip2", "bz2 bzip2 tbz2 tbz", "* * .tar .tar", 2,
  3, { 'B', 'Z', 'h' },
  0,
  NArcInfoFlags::kKeepName,
  REF_CreateArc_Pair, IsArc_BZip2 };

REGISTER_ARC(BZip2)

}}


text:
/*
 * FRC 4931 (http://www.evilletech.com)
 *
 * Open source software. Licensed under the FIRST BSD license file in the
 * root directory of this project's Git repository.
 */
package org.frc4931.robot.system.mock;

import org.fest.assertions.Delta;
import org.frc4931.robot.component.DriveTrain;

import static org.fest.assertions.Assertions.assertThat;

/**
 *
 */
public class MockDrive implements DriveTrain {
    private double leftSpeed;
    private double rightSpeed;

    @Override
    public void drive(double leftSpeed, double rightSpeed) {
        this.leftSpeed = leftSpeed;
        this.rightSpeed = rightSpeed;
    }

    public void assertDrivingForward() {
        assertThat(leftSpeed).isGreaterThan(0);
        assertThat(rightSpeed).isGreaterThan(0);
    }

    public void assertDrivingBackwards() {
        assertThat(leftSpeed).isLessThan(0);
        assertThat(rightSpeed).isLessThan(0);
    }

    public void assertNotTranslating() {
        assertThat(leftSpeed+rightSpeed).isEqualTo(0, Delta.delta(0.01));
    }

    public void assertTurningLeft() {
        assertThat(rightSpeed).isGreaterThan(leftSpeed);
    }

    public void assertTurningRight() {
        assertThat(leftSpeed).isGreaterThan(rightSpeed);
    }

    public void assertNotTurning() {
        assertThat(leftSpeed).isEqualTo(rightSpeed, Delta.delta(0.01));
    }

    public void assertStopped() {
        assertThat(leftSpeed).isEqualTo(0, Delta.delta(0.01));
        assertThat(rightSpeed).isEqualTo(0, Delta.delta(0.01));
    }
}


text:
package org.projectfloodlight.openflow.protocol.ver15;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import com.google.common.collect.ImmutableList;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;

class OFBsnGentableEntryStatsEntryVer15 implements OFBsnGentableEntryStatsEntry {
    private static final Logger logger = LoggerFactory.getLogger(OFBsnGentableEntryStatsEntryVer15.class);
    // version: 1.5
    final static byte WIRE_VERSION = 6;
    final static int MINIMUM_LENGTH = 4;

        private final static List<OFBsnTlv> DEFAULT_KEY = ImmutableList.<OFBsnTlv>of();
        private final static List<OFBsnTlv> DEFAULT_STATS = ImmutableList.<OFBsnTlv>of();

    // OF message fields
    private final List<OFBsnTlv> key;
    private final List<OFBsnTlv> stats;
//
    // Immutable default instance
    final static OFBsnGentableEntryStatsEntryVer15 DEFAULT = new OFBsnGentableEntryStatsEntryVer15(
        DEFAULT_KEY, DEFAULT_STATS
    );

    // package private constructor - used by readers, builders, and factory
    OFBsnGentableEntryStatsEntryVer15(List<OFBsnTlv> key, List<OFBsnTlv> stats) {
        if(key == null) {
            throw new NullPointerException("OFBsnGentableEntryStatsEntryVer15: property key cannot be null");
        }
        if(stats == null) {
            throw new NullPointerException("OFBsnGentableEntryStatsEntryVer15: property stats cannot be null");
        }
        this.key = key;
        this.stats = stats;
    }

    // Accessors for OF message fields
    @Override
    public List<OFBsnTlv> getKey() {
        return key;
    }

    @Override
    public List<OFBsnTlv> getStats() {
        return stats;
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

    public OFBsnGentableEntryStatsEntry.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFBsnGentableEntryStatsEntry.Builder {
        final OFBsnGentableEntryStatsEntryVer15 parentMessage;

        // OF message fields
        private boolean keySet;
        private List<OFBsnTlv> key;
        private boolean statsSet;
        private List<OFBsnTlv> stats;

        BuilderWithParent(OFBsnGentableEntryStatsEntryVer15 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public List<OFBsnTlv> getKey() {
        return key;
    }

    @Override
    public OFBsnGentableEntryStatsEntry.Builder setKey(List<OFBsnTlv> key) {
        this.key = key;
        this.keySet = true;
        return this;
    }
    @Override
    public List<OFBsnTlv> getStats() {
        return stats;
    }

    @Override
    public OFBsnGentableEntryStatsEntry.Builder setStats(List<OFBsnTlv> stats) {
        this.stats = stats;
        this.statsSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

        @Override
        public OFBsnGentableEntryStatsEntry build() {
                List<OFBsnTlv> key = this.keySet ? this.key : parentMessage.key;
                if(key == null)
                    throw new NullPointerException("Property key must not be null");
                List<OFBsnTlv> stats = this.statsSet ? this.stats : parentMessage.stats;
                if(stats == null)
                    throw new NullPointerException("Property stats must not be null");

                //
                return new OFBsnGentableEntryStatsEntryVer15(
                    key,
                    stats
                );
        }

    }

    static class Builder implements OFBsnGentableEntryStatsEntry.Builder {
        // OF message fields
        private boolean keySet;
        private List<OFBsnTlv> key;
        private boolean statsSet;
        private List<OFBsnTlv> stats;

    @Override
    public List<OFBsnTlv> getKey() {
        return key;
    }

    @Override
    public OFBsnGentableEntryStatsEntry.Builder setKey(List<OFBsnTlv> key) {
        this.key = key;
        this.keySet = true;
        return this;
    }
    @Override
    public List<OFBsnTlv> getStats() {
        return stats;
    }

    @Override
    public OFBsnGentableEntryStatsEntry.Builder setStats(List<OFBsnTlv> stats) {
        this.stats = stats;
        this.statsSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

//
        @Override
        public OFBsnGentableEntryStatsEntry build() {
            List<OFBsnTlv> key = this.keySet ? this.key : DEFAULT_KEY;
            if(key == null)
                throw new NullPointerException("Property key must not be null");
            List<OFBsnTlv> stats = this.statsSet ? this.stats : DEFAULT_STATS;
            if(stats == null)
                throw new NullPointerException("Property stats must not be null");

            return new OFBsnGentableEntryStatsEntryVer15(
                    key,
                    stats
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFBsnGentableEntryStatsEntry> {
        @Override
        public OFBsnGentableEntryStatsEntry readFrom(ByteBuf bb) throws OFParseError {
            int start = bb.readerIndex();
            int length = U16.f(bb.readShort());
            if(length < MINIMUM_LENGTH)
                throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length);
            if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
                // Buffer does not have all data yet
                bb.readerIndex(start);
                return null;
            }
            if(logger.isTraceEnabled())
                logger.trace("readFrom - length={}", length);
            int keyLength = U16.f(bb.readShort());
            List<OFBsnTlv> key = ChannelUtils.readList(bb, keyLength, OFBsnTlvVer15.READER);
            List<OFBsnTlv> stats = ChannelUtils.readList(bb, length - (bb.readerIndex() - start), OFBsnTlvVer15.READER);

            OFBsnGentableEntryStatsEntryVer15 bsnGentableEntryStatsEntryVer15 = new OFBsnGentableEntryStatsEntryVer15(
                    key,
                      stats
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", bsnGentableEntryStatsEntryVer15);
            return bsnGentableEntryStatsEntryVer15;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFBsnGentableEntryStatsEntryVer15Funnel FUNNEL = new OFBsnGentableEntryStatsEntryVer15Funnel();
    static class OFBsnGentableEntryStatsEntryVer15Funnel implements Funnel<OFBsnGentableEntryStatsEntryVer15> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFBsnGentableEntryStatsEntryVer15 message, PrimitiveSink sink) {
            // FIXME: skip funnel of length
            // FIXME: skip funnel of keyLength
            FunnelUtils.putList(message.key, sink);
            FunnelUtils.putList(message.stats, sink);
        }
    }

    public void writeTo(ByteBuf bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFBsnGentableEntryStatsEntryVer15> {
        @Override
        public void write(ByteBuf bb, OFBsnGentableEntryStatsEntryVer15 message) {
            int startIndex = bb.writerIndex();
            // length is length of variable message, will be updated at the end
            int lengthIndex = bb.writerIndex();
            bb.writeShort(U16.t(0));

            // keyLength is length indicator for key, will be
            // udpated when key has been written
            int keyLengthIndex = bb.writerIndex();
            bb.writeShort(0);
            int keyStartIndex = bb.writerIndex();
            ChannelUtils.writeList(bb, message.key);
            // update field length member keyLength
            int keyLength = bb.writerIndex() - keyStartIndex;
            bb.setShort(keyLengthIndex, keyLength);
            ChannelUtils.writeList(bb, message.stats);

            // update length field
            int length = bb.writerIndex() - startIndex;
            bb.setShort(lengthIndex, length);

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFBsnGentableEntryStatsEntryVer15(");
        b.append("key=").append(key);
        b.append(", ");
        b.append("stats=").append(stats);
        b.append(")");
        return b.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OFBsnGentableEntryStatsEntryVer15 other = (OFBsnGentableEntryStatsEntryVer15) obj;

        if (key == null) {
            if (other.key != null)
                return false;
        } else if (!key.equals(other.key))
            return false;
        if (stats == null) {
            if (other.stats != null)
                return false;
        } else if (!stats.equals(other.stats))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;

        result = prime * result + ((key == null) ? 0 : key.hashCode());
        result = prime * result + ((stats == null) ? 0 : stats.hashCode());
        return result;
    }

}


text:
<?php
require_once('./BDD.php');

global $link;
$query =  "DELETE from Stagiaire WHERE id=" . $_GET['id'];
// Exécution de la requête
$result = mysql_query($query, $link);

// Vérification du résultat
// Ceci montre la requête envoyée à MySQL ainsi que l'erreur. Utile pour déboguer.
if (!$result) {
	$message  = 'Requête invalide : ' . mysql_error() . "\n";
	$message .= 'Requête complète : ' . $query;
	die($message);
}

echo '{}';
?>


text:
<?php declare(strict_types=1);

namespace Propel\Common\Config;

use Propel\Common\Config\Exception\InvalidArgumentException;
use Propel\Common\Config\Loader\DelegatingLoader;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Config\Definition\Processor;

/**
 * Class ConfigurationManager
 *
 * Class to load and process configuration files. Supported formats are: php, ini (or .properties), yaml, xml, json.
 *
 * @author Cristiano Cinotti
 */
class ConfigurationManager
{
    const CONFIG_FILE_NAME = 'propel';

    /**
     * Array of configuration values
     *
     * @var array
     */
    private $config = [];

    /**
     * Load and validate configuration values from a file.
     *
     * @param string $filename  Configuration file name or directory in which resides the configuration file.
     * @param array  $extraConf Array of configuration properties, to be merged with those loaded from file.
     *                          It's useful when passing configuration parameters from command line.
     */
    public function __construct(string $filename = './', array $extraConf = [])
    {
        if ('' !== $filename) {
            $this->load($filename, $extraConf);
        }

        $this->process();
    }

    /**
     * Return the whole configuration array
     *
     * @return array
     */
    public function get(): array
    {
        return $this->config;
    }

    /**
     * Return a specific section of the configuration array.
     * It ca be useful to get, in example, only 'buildtime' values.
     *
     * @param  string $section the section to be returned
     * @return array
     */
    public function getSection(string $section): array
    {
        if (!array_key_exists($section, $this->config)) {
            return null;
        }

        return $this->config[$section];
    }

    /**
     * Return a specific configuration property.
     * The name of the requested property must be given as a string, representing its hierarchy in the configuration
     * array, with each level separated by a dot. I.e.:
     *  $config['database']['adapter']['mysql']['tableType']
     * is expressed by:
     * 'database.adapter.mysql.tableType'
     *
     * @param string $name The name of property, expressed as a dot separated level hierarchy
     * @throws \Propel\Common\Config\Exception\InvalidArgumentException
     * @return mixed The configuration property
     */
    public function getConfigProperty(string $name)
    {
        $keys = explode('.', $name);
        $output = $this->get();
        foreach ($keys as $key) {
            if (!array_key_exists($key, $output)) {
                return null;
            }
            $output = $output[$key];
        }

        return $output;
    }

    /**
     * Return an array of parameters relative to configured connections, for `runtime` or `generator` section.
     * It's useful for \Propel\Generator\Command\ConfigConvertCommand class
     *
     * @param  string     $section `runtime` or `generator` section
     * @return array|null
     */
    public function getConnectionParametersArray(string $section = 'runtime'):? array
    {
        if (!in_array($section, ['runtime', 'generator'])) {
            return null;
        }

        $output = [];
        foreach ($this->config[$section]['connections'] as $connection) {
            $output[$connection] = $this->config['database']['connections'][$connection];
        }

        return $output;
    }

    /**
     * Find a configuration file and loads it.
     * Default configuration file is named 'propel' and is expected to be found in the current directory
     * or a subdirectory named '/conf' or '/config'. It can have one of the supported extensions (.ini, .properties,
     * .json, .yaml, .yml, .xml, .php, .inc).
     * Only one configuration file is supposed to be found.
     * This method also looks for a '.dist' configuration file and loads it.
     *
     * @param string $fileName  Configuration file name or directory in which resides the configuration file.
     * @param array  $extraConf Array of configuration properties, to be merged with those loaded from file.
     */
    protected function load(string $fileName = '', array $extraConf): void
    {
        $currentDir = getcwd();

        if ('' == $fileName) {
            $fileName = self::CONFIG_FILE_NAME;
        }

        if (is_dir($fileName)) {
            $currentDir = $fileName;
            $fileName = 'propel';
        }

        if (null === $extraConf) {
            $extraConf = [];
        }

        if ('propel' === $fileName) {
            $dirs[] = $currentDir;
            if (is_dir($currentDir . '/conf')) {
                $dirs[] = $currentDir . '/conf';
            }
            if (is_dir($currentDir . '/config')) {
                $dirs[] = $currentDir . '/config';
            }

            $finder = new Finder();
            $finder->in($dirs)->depth(0)->files()->name($fileName . '.{php,inc,ini,properties,yaml,yml,xml,json}');
            $files = iterator_to_array($finder);

            $distFinder = new Finder();
            $distFinder->in($dirs)->depth(0)->files()->name($fileName . '.{php,inc,ini,properties,yaml,yml,xml,json}.dist');
            $distFiles = iterator_to_array($distFinder);

            $numFiles = count($files);
            $numDistFiles = count($distFiles);

            //allow to load only .dist file
            if (0 === $numFiles && 1 === $numDistFiles) {
                $files = $distFiles;
                $numFiles = 1;
            }

            if ($numFiles > 1) {
                $realPath = realpath($fileName);
                throw new InvalidArgumentException(
                    sprintf(
                        'Propel expects only one configuration file in %s. Found %s',
                    $realPath,
                    implode(', ', $files)
                )
                );
            } elseif ($numFiles === 0) {
                $this->config = $extraConf;
                return;
            } else {
                $file = current($files);
                $fileName = $file->getPathName();
            }
        }

        $delegatingLoader = new DelegatingLoader();

        $conf = $delegatingLoader->load($fileName);

        $distConf = [];
        if (file_exists($fileName . '.dist')) {
            $distDelegatingLoader = new DelegatingLoader();
            $distConf = $distDelegatingLoader->load($fileName . '.dist');
        }

        $this->config = array_replace_recursive($distConf, $conf, $extraConf);
    }

    /**
     * Validate the configuration array via Propel\Common\Config\PropelConfiguration class
     * and add default values.
     *
     * @param array $extraConf Extra configuration to merge before processing. It's useful when a child class overwrite
     *                         the constructor to pass a built-in array of configuration, without load it from file. I.e.
     *                         Propel\Generator\Config\QuickGeneratorConfig class.
     */
    protected function process(array $extraConf = null): void
    {
        $processor = new Processor();
        $configuration = new PropelConfiguration();

        if (is_array($extraConf)) {
            $this->config = array_replace_recursive($this->config, $extraConf);
        }

        $this->config = $processor->processConfiguration($configuration, $this->config);

        //Workaround to remove empty `slaves` array from database.connections
        foreach ($this->config['database']['connections'] as $name => $connection) {
            if (count($connection['slaves']) <= 0) {
                unset($this->config['database']['connections'][$name]['slaves']);
            }
        }

        foreach (['runtime', 'generator'] as $section) {
            if (!isset($this->config[$section]['connections']) || count($this->config[$section]['connections']) === 0) {
                $this->config[$section]['connections'] = array_keys($this->config['database']['connections']);
            }

            if (!isset($this->config[$section]['defaultConnection'])) {
                $this->config[$section]['defaultConnection'] = key($this->config['database']['connections']);
            }
        }
    }
}


text:
//
//  LogTableViewController.m
//  Spoiler_Test
//
//  Created by Tausif Ahmed on 4/20/15.
//  Copyright (c) 2015 Tausif. All rights reserved.
//

#import "LogTableViewController.h"
#import "LogViewController.h"

static NSString* const SEGUE_LOGVIEW = @"LogSegue";

@interface LogTableViewController() @end

@implementation LogTableViewController

#pragma mark - View & Misc.

- (void) viewDidLoad {
    [super viewDidLoad];

	if (!self.sharedData) {
		self.sharedData = [[SharedData alloc] init];
	}

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_data) name:@"reload_data" object:nil];

	[self.navigationController.navigationBar.topItem setTitle: @"Logs"];

    NSFileManager* manager = [NSFileManager defaultManager];
    self.logData = [manager contentsOfDirectoryAtPath:self.sharedData.log_path error:NULL];

    self.logData = [[self.logData reverseObjectEnumerator] allObjects];

    self.tableView = [[UITableView alloc] init];
	[self loadViewGraphics];
    }

- (void) loadViewGraphics {
	[self.tableView setFrame: CGRectMake(0, self.navigationController.navigationBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - self.tabBarController.tabBar.frame.size.height - self.navigationController.navigationBar.frame.size.height)];
	[self.tableView setDataSource: self];
	[self.tableView setDelegate: self];
	[self.tableView setBackgroundColor: [UIColor colorWithWhite: 235/255.0 alpha:1]];
	[self.tableView setSeparatorColor: [UIColor colorWithWhite: 235/255.0 alpha:1]];
	[self.tableView setAutoresizingMask: UIViewAutoresizingFlexibleHeight |
	 UIViewAutoresizingFlexibleWidth];
	[self.tableView reloadData];
	[self.view setBackgroundColor: [UIColor colorWithWhite:235.255/0 alpha:1]];

}

- (void) didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)handle_data {

    NSFileManager* manager = [NSFileManager defaultManager];
    self.logData = [manager contentsOfDirectoryAtPath: self.sharedData.log_path error:NULL];

    self.logData = [[self.logData reverseObjectEnumerator] allObjects];

    [self.tableView reloadData];
}

#pragma mark - Table Data View

// Function to retrieve # of sections
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView {
    return 1;
}

// Function to retrieve # of rows in table
- (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section {
    return [self.logData count];
}
/*
// Function to format the file name of the Log File
- (NSString *) parseFileName: (NSString*) name {
    // Copy of original input
    NSString *format = [NSString stringWithFormat:@"%@", name];

    // Format the string to show a proper log name
    format = [format stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
    format = [format substringWithRange:NSMakeRange(0, 19)];
    NSString *date = [format substringWithRange:NSMakeRange(0, 10)];
    NSString *time = [format substringWithRange:NSMakeRange(11, 8)];
    time = [time stringByReplacingOccurrencesOfString:@"/" withString:@"."];
    format = [date stringByAppendingFormat:@" %@", time];

    return format;
}

// Function to undo the format of the Log File Name
- (NSString *) unparseFileName: (NSString *) name {
    NSString * format = [NSString stringWithFormat:@"%@", name];

    format = [format stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    format = [format stringByReplacingOccurrencesOfString:@" " withString:@"_"];
    format = [format stringByReplacingOccurrencesOfString:@"." withString:@"_"];
    format = [format stringByAppendingFormat:@".log"];

    return format;
}*/

- (void) tableView: (UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath {
    self.selected_file = [self.logData objectAtIndex: indexPath.row];
	[self performSegueWithIdentifier: SEGUE_LOGVIEW sender:self];

}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString: SEGUE_LOGVIEW]) {
        LogViewController *log = [segue destinationViewController];
		//log.file_name = self.selected_file;
		[log setUpLogView:self.selected_file];
    }
}

#pragma mark - Table View

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *log = @"LogItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:log];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:log];
    }

    // Format the name of the table element
    NSString *format = [self.logData objectAtIndex:indexPath.row];

    format  = [self.sharedData parseFileName:format];

    // Set the cell's text to the log name
    cell.textLabel.text = format;
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

@end


text:
package ariba.ui.widgets;

import ariba.ui.aribaweb.core.AWRequestContext;
import ariba.ui.aribaweb.core.AWComponent;

public final class HasSidebarNotchConditionHandler extends ConditionHandler
{
    public boolean evaluateCondition (AWRequestContext requestContext)
    {
        // defer to binding, if one was passed on the <BasicPageWrapper>
        AWComponent parent = requestContext.getCurrentComponent().parent();
        if (parent.hasBinding(BindingNames.hasSidebarNotch)) {
            return parent.booleanValueForBinding(BindingNames.hasSidebarNotch);
        }
        if (requestContext.session(false) != null) {
            WidgetsSessionState state = WidgetsSessionState.get(requestContext);
            return state.hasSidebarNotch();
        }
        return true;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Smash_Forge
{
    public class FormBase : Form
    {

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            /*this.BackColor = System.Drawing.Color.Black;
            this.ForeColor = System.Drawing.Color.Wheat;

            foreach (Control c in Controls)
            {
                c.BackColor = System.Drawing.Color.Black;
                c.ForeColor = System.Drawing.Color.Wheat;
            }*/
        }

    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="JobEventModel.cs" company="Nima Shahri">
// Copyright (c) Nima Shahri. All rights reserved.
// </copyright>
// <summary>
//   Defines the JobEventModel type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace AtomicClock.Services.Events
{
    using AtomicClock.Asserts;
    using AtomicClock.Jobs;
    using AtomicClock.Schedulers;

    /// <summary>
    /// The job event model.
    /// </summary>
    public class JobEventModel : IJobEventModel
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="JobEventModel"/> class.
        /// </summary>
        /// <param name="jobInfo">
        /// The job info.
        /// </param>
        /// <param name="jobScheduler">
        /// The job scheduler.
        /// </param>
        public JobEventModel(IJobInfo jobInfo, IJobScheduler jobScheduler)
        {
            ArgumentAssert.NotNull(nameof(jobInfo), jobInfo);
            ArgumentAssert.NotNull(nameof(jobScheduler), jobScheduler);

            this.JobInfo = jobInfo;
            this.JobScheduler = jobScheduler;
        }

        /// <summary>
        /// Gets the job info.
        /// </summary>
        public IJobInfo JobInfo { get; private set; }

        /// <summary>
        /// Gets the job scheduler.
        /// </summary>
        public IJobScheduler JobScheduler { get; private set; }
    }
}


text:
package com.ibm.kdd.core;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class SparseEvent extends HashMap<String,String> implements Event  {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public SparseEvent() {

	}

	public SparseEvent(SparseEvent another) {
		Set<String> attrNames = another.getAttrNames();
		for (String attrName: attrNames) {
			this.setValue(attrName, another.getStr(attrName));
		}
	}

	public Set<String> getAttrNames() {
		return this.keySet();
	}

	@Override
	public double getDouble(String attrName) {
		// TODO Auto-generated method stub
		return Double.parseDouble(getStr(attrName));
	}

	@Override
	public int getInt(String attrName) {
		// TODO Auto-generated method stub
		return Integer.parseInt(getStr(attrName));
	}

	@Override
	public String getStr(String attrName) {
		// TODO Auto-generated method stub
		return this.get(attrName);
	}

	@Override
	public String getValue(String attrName) {
		// TODO Auto-generated method stub
		return this.get(attrName);
	}

	@Override
	public void setValue(String attrName, double value) {
		// TODO Auto-generated method stub
		this.put(attrName, value+"");
	}

	@Override
	public void setValue(String attrName, int value) {
		// TODO Auto-generated method stub
		this.put(attrName, value+"");
	}

	@Override
	public void setValue(String attrName, String value) {
		// TODO Auto-generated method stub
		this.put(attrName, value);
	}

	@Override
	public Event clone() {
		return new SparseEvent(this);
	}

	@Override
	public Event createNew() {
		// TODO Auto-generated method stub
		return new SparseEvent();
	}

	@Override
	public boolean hasAttribute(String attrName) {
		// TODO Auto-generated method stub
		return this.getAttrNames().contains(attrName);
	}

}