text:
from msrest.pipeline import ClientRawResponse

from .. import models

class LargePersonGroupPersonOperations(object):
    """LargePersonGroupPersonOperations operations.

    You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer

        self.config = config

    def create(
            self, large_person_group_id, name=None, user_data=None, custom_headers=None, raw=False, **operation_config):
        """Create a new person in a specified large person group.

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param name: User defined name, maximum length is 128.
        :type name: str
        :param user_data: User specified data. Length should not exceed 16KB.
        :type user_data: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Person or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.vision.face.models.Person or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        body = models.NameAndUserDataContract(name=name, user_data=user_data)

        # Construct URL
        url = self.create.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'NameAndUserDataContract')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('Person', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    create.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons'}

    def list(
            self, large_person_group_id, start=None, top=None, custom_headers=None, raw=False, **operation_config):
        """List all persons in a large person group, and retrieve person
        information (including personId, name, userData and persistedFaceIds of
        registered faces of the person).

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param start: Starting person id to return (used to list a range of
         persons).
        :type start: str
        :param top: Number of persons to return starting with the person id
         indicated by the 'start' parameter.
        :type top: int
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: list or ClientRawResponse if raw=true
        :rtype: list[~azure.cognitiveservices.vision.face.models.Person] or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        # Construct URL
        url = self.list.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if start is not None:
            query_parameters['start'] = self._serialize.query("start", start, 'str')
        if top is not None:
            query_parameters['top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1)

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('[Person]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    list.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons'}

    def delete(
            self, large_person_group_id, person_id, custom_headers=None, raw=False, **operation_config):
        """Delete an existing person from a large person group. The
        persistedFaceId, userData, person name and face feature in the person
        entry will all be deleted.

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        # Construct URL
        url = self.delete.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
    delete.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}'}

    def get(
            self, large_person_group_id, person_id, custom_headers=None, raw=False, **operation_config):
        """Retrieve a person's name and userData, and the persisted faceIds
        representing the registered person face feature.

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Person or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.vision.face.models.Person or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('Person', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}'}

    def update(
            self, large_person_group_id, person_id, name=None, user_data=None, custom_headers=None, raw=False, **operation_config):
        """Update name or userData of a person.

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param name: User defined name, maximum length is 128.
        :type name: str
        :param user_data: User specified data. Length should not exceed 16KB.
        :type user_data: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        body = models.NameAndUserDataContract(name=name, user_data=user_data)

        # Construct URL
        url = self.update.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'NameAndUserDataContract')

        # Construct and send request
        request = self._client.patch(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
    update.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}'}

    def delete_face(
            self, large_person_group_id, person_id, persisted_face_id, custom_headers=None, raw=False, **operation_config):
        """Delete a face from a person in a large person group by specified
        largePersonGroupId, personId and persistedFaceId.
        <br /> Adding/deleting faces to/from a same person will be processed
        sequentially. Adding/deleting faces to/from different persons are
        processed in parallel.

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param persisted_face_id: Id referencing a particular persistedFaceId
         of an existing face.
        :type persisted_face_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        # Construct URL
        url = self.delete_face.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str'),
            'persistedFaceId': self._serialize.url("persisted_face_id", persisted_face_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
    delete_face.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces/{persistedFaceId}'}

    def get_face(
            self, large_person_group_id, person_id, persisted_face_id, custom_headers=None, raw=False, **operation_config):
        """Retrieve information about a persisted face (specified by
        persistedFaceId, personId and its belonging largePersonGroupId).

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param persisted_face_id: Id referencing a particular persistedFaceId
         of an existing face.
        :type persisted_face_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: PersistedFace or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.vision.face.models.PersistedFace or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        # Construct URL
        url = self.get_face.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str'),
            'persistedFaceId': self._serialize.url("persisted_face_id", persisted_face_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('PersistedFace', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_face.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces/{persistedFaceId}'}

    def update_face(
            self, large_person_group_id, person_id, persisted_face_id, user_data=None, custom_headers=None, raw=False, **operation_config):
        """Update a person persisted face's userData field.

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param persisted_face_id: Id referencing a particular persistedFaceId
         of an existing face.
        :type persisted_face_id: str
        :param user_data: User-provided data attached to the face. The size
         limit is 1KB.
        :type user_data: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        body = models.UpdateFaceRequest(user_data=user_data)

        # Construct URL
        url = self.update_face.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str'),
            'persistedFaceId': self._serialize.url("persisted_face_id", persisted_face_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, 'UpdateFaceRequest')

        # Construct and send request
        request = self._client.patch(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
    update_face.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces/{persistedFaceId}'}

    def add_face_from_url(
            self, large_person_group_id, person_id, url, user_data=None, target_face=None, detection_model="detection_01", custom_headers=None, raw=False, **operation_config):
        """Add a face to a person into a large person group for face
        identification or verification. To deal with an image contains multiple
        faces, input face can be specified as an image with a targetFace
        rectangle. It returns a persistedFaceId representing the added face. No
        image will be stored. Only the extracted face feature will be stored on
        server until [LargePersonGroup PersonFace -
        Delete](https://docs.microsoft.com/rest/api/faceapi/largepersongroupperson/deleteface),
        [LargePersonGroup Person -
        Delete](https://docs.microsoft.com/rest/api/faceapi/largepersongroupperson/delete)
        or [LargePersonGroup -
        Delete](https://docs.microsoft.com/rest/api/faceapi/largepersongroup/delete)
        is called.
        <br /> Note persistedFaceId is different from faceId generated by [Face
        -
        Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl).
        * Higher face image quality means better recognition precision. Please
        consider high-quality faces: frontal, clear, and face size is 200x200
        pixels (100 pixels between eyes) or bigger.
        * Each person entry can hold up to 248 faces.
        * JPEG, PNG, GIF (the first frame), and BMP format are supported. The
        allowed image file size is from 1KB to 6MB.
        * "targetFace" rectangle should contain one face. Zero or multiple
        faces will be regarded as an error. If the provided "targetFace"
        rectangle is not returned from [Face -
        Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl),
        there's no guarantee to detect and add the face successfully.
        * Out of detectable face size (36x36 - 4096x4096 pixels), large
        head-pose, or large occlusions will cause failures.
        * Adding/deleting faces to/from a same person will be processed
        sequentially. Adding/deleting faces to/from different persons are
        processed in parallel.
        * The minimum detectable face size is 36x36 pixels in an image no
        larger than 1920x1080 pixels. Images with dimensions higher than
        1920x1080 pixels will need a proportionally larger minimum face size.
        * Different 'detectionModel' values can be provided. To use and compare
        different detection models, please refer to [How to specify a detection
        model](https://docs.microsoft.com/azure/cognitive-services/face/face-api-how-to-topics/specify-detection-model).

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param url: Publicly reachable URL of an image
        :type url: str
        :param user_data: User-specified data about the face for any purpose.
         The maximum length is 1KB.
        :type user_data: str
        :param target_face: A face rectangle to specify the target face to be
         added to a person in the format of "targetFace=left,top,width,height".
         E.g. "targetFace=10,10,100,100". If there is more than one face in the
         image, targetFace is required to specify which face to add. No
         targetFace means there is only one face detected in the entire image.
        :type target_face: list[int]
        :param detection_model: Name of detection model. Detection model is
         used to detect faces in the submitted image. A detection model name
         can be provided when performing Face - Detect or (Large)FaceList - Add
         Face or (Large)PersonGroup - Add Face. The default value is
         'detection_01', if another model is needed, please explicitly specify
         it. Possible values include: 'detection_01', 'detection_02',
         'detection_03'
        :type detection_model: str or
         ~azure.cognitiveservices.vision.face.models.DetectionModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: PersistedFace or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.vision.face.models.PersistedFace or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        image_url = models.ImageUrl(url=url)

        # Construct URL
        url = self.add_face_from_url.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if user_data is not None:
            query_parameters['userData'] = self._serialize.query("user_data", user_data, 'str', max_length=1024)
        if target_face is not None:
            query_parameters['targetFace'] = self._serialize.query("target_face", target_face, '[int]', div=',')
        if detection_model is not None:
            query_parameters['detectionModel'] = self._serialize.query("detection_model", detection_model, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(image_url, 'ImageUrl')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('PersistedFace', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    add_face_from_url.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces'}

    def add_face_from_stream(
            self, large_person_group_id, person_id, image, user_data=None, target_face=None, detection_model="detection_01", custom_headers=None, raw=False, callback=None, **operation_config):
        """Add a face to a person into a large person group for face
        identification or verification. To deal with an image contains multiple
        faces, input face can be specified as an image with a targetFace
        rectangle. It returns a persistedFaceId representing the added face. No
        image will be stored. Only the extracted face feature will be stored on
        server until [LargePersonGroup PersonFace -
        Delete](https://docs.microsoft.com/rest/api/faceapi/largepersongroupperson/deleteface),
        [LargePersonGroup Person -
        Delete](https://docs.microsoft.com/rest/api/faceapi/largepersongroupperson/delete)
        or [LargePersonGroup -
        Delete](https://docs.microsoft.com/rest/api/faceapi/largepersongroup/delete)
        is called.
        <br /> Note persistedFaceId is different from faceId generated by [Face
        -
        Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl).
        * Higher face image quality means better recognition precision. Please
        consider high-quality faces: frontal, clear, and face size is 200x200
        pixels (100 pixels between eyes) or bigger.
        * Each person entry can hold up to 248 faces.
        * JPEG, PNG, GIF (the first frame), and BMP format are supported. The
        allowed image file size is from 1KB to 6MB.
        * "targetFace" rectangle should contain one face. Zero or multiple
        faces will be regarded as an error. If the provided "targetFace"
        rectangle is not returned from [Face -
        Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl),
        there's no guarantee to detect and add the face successfully.
        * Out of detectable face size (36x36 - 4096x4096 pixels), large
        head-pose, or large occlusions will cause failures.
        * Adding/deleting faces to/from a same person will be processed
        sequentially. Adding/deleting faces to/from different persons are
        processed in parallel.
        * The minimum detectable face size is 36x36 pixels in an image no
        larger than 1920x1080 pixels. Images with dimensions higher than
        1920x1080 pixels will need a proportionally larger minimum face size.
        * Different 'detectionModel' values can be provided. To use and compare
        different detection models, please refer to [How to specify a detection
        model](https://docs.microsoft.com/azure/cognitive-services/face/face-api-how-to-topics/specify-detection-model).

        :param large_person_group_id: Id referencing a particular large person
         group.
        :type large_person_group_id: str
        :param person_id: Id referencing a particular person.
        :type person_id: str
        :param image: An image stream.
        :type image: Generator
        :param user_data: User-specified data about the face for any purpose.
         The maximum length is 1KB.
        :type user_data: str
        :param target_face: A face rectangle to specify the target face to be
         added to a person in the format of "targetFace=left,top,width,height".
         E.g. "targetFace=10,10,100,100". If there is more than one face in the
         image, targetFace is required to specify which face to add. No
         targetFace means there is only one face detected in the entire image.
        :type target_face: list[int]
        :param detection_model: Name of detection model. Detection model is
         used to detect faces in the submitted image. A detection model name
         can be provided when performing Face - Detect or (Large)FaceList - Add
         Face or (Large)PersonGroup - Add Face. The default value is
         'detection_01', if another model is needed, please explicitly specify
         it. Possible values include: 'detection_01', 'detection_02',
         'detection_03'
        :type detection_model: str or
         ~azure.cognitiveservices.vision.face.models.DetectionModel
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param callback: When specified, will be called with each chunk of
         data that is streamed. The callback should take two arguments, the
         bytes of the current chunk of data and the response object. If the
         data is uploading, response will be None.
        :type callback: Callable[Bytes, response=None]
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: PersistedFace or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.vision.face.models.PersistedFace or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        # Construct URL
        url = self.add_face_from_stream.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'largePersonGroupId': self._serialize.url("large_person_group_id", large_person_group_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
            'personId': self._serialize.url("person_id", person_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if user_data is not None:
            query_parameters['userData'] = self._serialize.query("user_data", user_data, 'str', max_length=1024)
        if target_face is not None:
            query_parameters['targetFace'] = self._serialize.query("target_face", target_face, '[int]', div=',')
        if detection_model is not None:
            query_parameters['detectionModel'] = self._serialize.query("detection_model", detection_model, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/octet-stream'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._client.stream_upload(image, callback)

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('PersistedFace', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    add_face_from_stream.metadata = {'url': '/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces'}


text:
package org.overlord.commons.services;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;

/**
 * Implements a service registry by using the standard java {@link ServiceLoader}
 * mechanism.
 *
 * @author eric.wittmann@redhat.com
 */
public class ServiceLoaderServiceRegistry extends AbstractServiceRegistry {

    private Map<Class<?>, Set<?>> servicesCache = new HashMap<Class<?>, Set<?>>();

    /**
     * @see org.overlord.commons.services.ServiceRegistry#getSingleService(java.lang.Class)
     */
    @Override
    public <T> T getSingleService(Class<T> serviceInterface) throws IllegalStateException {
        // Cached single service values are derived from the values cached when checking
        // for multiple services
        T rval = null;
        Set<T> services=getServices(serviceInterface);

        if (services.size() > 1) {
            throw new IllegalStateException(Messages.getString("ServiceLoaderServiceRegistry.MultipleImplsFound") + serviceInterface); //$NON-NLS-1$
        } else if (!services.isEmpty()) {
            rval = services.iterator().next();
        }
        return rval;
    }

    /**
     * @see org.overlord.commons.services.ServiceRegistry#getServices(java.lang.Class)
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> Set<T> getServices(Class<T> serviceInterface) {
        synchronized(servicesCache) {
            if (servicesCache.containsKey(serviceInterface))
                return (Set<T>) servicesCache.get(serviceInterface);

            Set<T> services = new LinkedHashSet<T>();
            try {
                for (T service : ServiceLoader.load(serviceInterface)) {
                    init(service);
                    services.add(service);
                }
            } catch (ServiceConfigurationError sce) {
                // No services found - don't check again.
            }
            servicesCache.put(serviceInterface, services);
            return services;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Proceso.h
 *
 *  Created on: 26/4/2015
 *      Author: mateo
 */

#ifndef PROCESO_H_
#define PROCESO_H_

#include <sys/prctl.h>
#include <iostream>

#include "structures/SIGINT_Handler.h"
#include "structures/SignalHandler.h"

class Proceso {
public:
	Proceso();
	virtual ~Proceso();
	SIGINT_Handler sigint_handler;
	void changeName(std::string name);

};

#endif /* PROCESO_H_ */


text:
import logging

# Import Third-Party

# Import Homebrew
from bitex.formatters.base import Formatter

# Init Logging Facilities
log = logging.getLogger(__name__)

class CcexFormatter(Formatter):

    @staticmethod
    def ticker(data, *args, **kwargs):
        return (data['buy'], data['sell'], data['high'], data['low'], None,
                None, data['lastprice'], None, data['updated'])


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

-->

<merge
    xmlns:latin="http://schemas.android.com/apk/res/com.udmurtlyk.extrainputmethod.latin"
>
    <!-- The table period key which may have different label depending on locale -->
    <!-- Kept as a separate file for cleaner overriding by an overlay.  -->
    <switch>
        <case
            latin:languageCode="hi"
            latin:keyboardLayoutSet="hindi_compact"
        >
            <!-- U+0964: "।" DEVANAGARI DANDA -->
            <Key
                latin:keySpec="\u0964"
                latin:keyLabelFlags="hasPopupHint"
                latin:moreKeys="!autoColumnOrder!8,\\,,.,',#,),(,/,;,@,:,-,",+,\\%,&"
                latin:backgroundType="functional" />
        </case>
        <case
            latin:keyboardLayoutSet="dvorak"
        >
            <Key
                latin:keySpec="\?"
                latin:moreKeys="!text/morekeys_tablet_period,!text/morekeys_question" />
        </case>
        <default>
            <Key
                latin:keySpec="!text/keyspec_tablet_period"
                latin:keyHintLabel="!text/keyhintlabel_tablet_period"
                latin:keyLabelFlags="hasPopupHint"
                latin:moreKeys="!text/morekeys_tablet_period"
                latin:backgroundType="functional"
                latin:keyStyle="hasShiftedLetterHintStyle" />
        </default>
    </switch>
</merge>


text:
class Course::Forum::PostsController < Course::Forum::ComponentController
  before_action :load_topic
  authorize_resource :topic
  skip_authorize_resource :post, only: :toggle_answer
  before_action :authorize_locked_topic, only: [:create]
  before_action :add_topic_breadcrumb

  include Course::Discussion::PostsConcern

  def create
    result = @post.class.transaction do
      raise ActiveRecord::Rollback unless @post.save && create_topic_subscription && update_topic_pending_status
      raise ActiveRecord::Rollback unless @topic.update_column(:latest_post_at, @post.created_at)
      true
    end

    if result
      send_created_notification(@post)
      redirect_to course_forum_topic_path(current_course, @forum, @topic),
                  success: t('course.discussion.posts.create.success')
    else
      redirect_to course_forum_topic_path(current_course, @forum, @topic),
                  danger: t('course.discussion.posts.create.failure',
                            error: @post.errors.full_messages.to_sentence)
    end
  end

  def edit
    # Sanitize input before passing to the form helper for display when editing in case the text
    # has not been sanitized before save.
    @post.text = helpers.format_html(@post.text)
  end

  def update
    if @post.update_attributes(post_params)
      redirect_to course_forum_topic_path(current_course, @forum, @topic),
                  success: t('course.discussion.posts.update.success')
    else
      render 'edit'
    end
  end

  def vote
    @post.cast_vote!(current_user, post_vote_param)
    redirect_to course_forum_topic_path(current_course, @forum, @topic),
                success: t('.success')
  end

  # Mark/unmark the post as the correct answer
  def toggle_answer
    authorize!(:toggle_answer, @topic)
    if @post.toggle_answer
      redirect_to course_forum_topic_path(current_course, @forum, @topic), success: t('.success')
    else
      redirect_to course_forum_topic_path(current_course, @forum, @topic),
                  danger: @post.errors.full_messages.to_sentence
    end
  end

  def destroy
    if @topic.posts.count == 1 && @topic.destroy
      redirect_to course_forum_path(current_course, @forum),
                  success: t('course.forum.topics.destroy.success', title: @topic.title)
    elsif @post.destroy
      @topic.update_column(:latest_post_at, @topic.posts.last&.created_at || @topic.created_at)
      redirect_to course_forum_topic_path(current_course, @forum, @topic),
                  success: t('course.discussion.posts.destroy.success')
    else
      redirect_to course_forum_topic_path(current_course, @forum, @topic),
                  danger: t('course.discussion.posts.destroy.failure',
                            error: @post.errors.full_messages.to_sentence)
    end
  end

  # Render a new post in a separate page
  def reply
    node = @post
    @post_chain = [node]
    # Show up to reply-post + 2 parent posts
    2.times do
      break if node.parent.nil?
      @post_chain << node.parent
      node = node.parent
    end
    @post_chain = @post_chain.reverse
    @reply_post = @post.children.build
  end

  protected

  def create_topic_subscription
    @topic.ensure_subscribed_by(current_user)
  end

  def discussion_topic
    @topic.acting_as
  end

  def skip_update_topic_status
    true
  end

  private

  def topic_id_param
    params.permit(:topic_id)[:topic_id]
  end

  def load_topic
    @topic ||= @forum.topics.friendly.find(topic_id_param)
  end

  def add_topic_breadcrumb
    add_breadcrumb @topic.title, course_forum_topic_path(current_course, @forum, @topic)
  end

  def post_vote_param
    params.permit(:vote)[:vote].to_i
  end

  def send_created_notification(post)
    return unless current_user
    Course::Forum::PostNotifier.post_replied(current_user, current_course_user, post)
  end

  def authorize_locked_topic
    authorize!(:reply, @topic)
  end
end


text:
package com.epimorphics.android.myrivers.models;

import com.epimorphics.android.myrivers.data.CDEPoint;
import com.epimorphics.android.myrivers.helpers.GeoJsonParser;
import com.google.maps.android.data.Geometry;
import com.google.maps.android.data.geojson.GeoJsonFeature;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Consumes an InputStream and converts it to a GeoJsonFeature
 *
 * @see CDEPoint
 * @see GeoJsonFeature
 */
public class InputStreamToCDERiverLine {

    /**
     * Converts InputStream to JsonObject
     *
     * @param inputStream InputStream to be converted
     * @return JSONObject corresponding to the given InputStream
     * @throws JSONException if JSONObject not convertible from StringBuilder
     * @throws IOException if InputStream not convertible to BufferReader
     */
    private static JSONObject inStreamToJSONObject(InputStream inputStream)
            throws IOException, JSONException {

        BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }
        return new JSONObject(responseStrBuilder.toString());
    }

    /**
     * Converts an InputStream to the GeoJsonFeature riverLine and sets it to the given CDEPoint
     *
     * @param inputStream InputStream to be converted
     * @param cdePoint CDEPoint to which a converted river line belongs
     * @throws IOException if InputStream not convertible to JSONObject
     * @throws JSONException if JSONObject not accessed properly
     *
     * @see CDEPoint
     * @see GeoJsonFeature
     */
    public void readJsonStream(InputStream inputStream, CDEPoint cdePoint) throws IOException, JSONException {
        JSONObject jsonObject = inStreamToJSONObject(inputStream);
        Geometry geometry = GeoJsonParser.parseGeometry(jsonObject);
        GeoJsonFeature riverLine = new GeoJsonFeature(geometry, "Feature", null, null);
        cdePoint.setRiverLine(riverLine);
    }
}


text:
from ifcb.io.file import BinFile
import re
from sys import argv

if __name__ == '__main__':
    if(len(argv) < 2):
        print 'usage: roi2images [file] [outdir: .] [format: png]'
    else:
        bin = BinFile(argv[1]) # file
        print 'Converting %d images from %s...' % (bin.length(), bin)
        bin.save_images(*argv[2:4]) # outdir, format


text:
@interface GBUtils : NSObject

- (BOOL)connected;

@end


text:
@import UIKit;
@import MultipeerConnectivity;

@class MCSClient;

@protocol ServerBrowserViewControllerDelegate;

@interface ServerBrowserViewController : UIViewController

@property (nonatomic, strong) MCSClient *multipeerClient;
@property (nonatomic, weak) id<ServerBrowserViewControllerDelegate> delegate;

@end

@protocol ServerBrowserViewControllerDelegate <NSObject>

- (void)serverBrowserViewController:(ServerBrowserViewController *)viewController wantsToJoinPeer:(MCPeerID *)peerID;

@end


text:
using GuiLabs.Canvas.DrawStyle;
using GuiLabs.Canvas.Renderer;
using GuiLabs.Canvas.Shapes;

namespace GuiLabs.Canvas.Renderer
{
	public class Caret : IHasBounds
	{
		public Caret()
		{
			CaretStyle = RendererSingleton.StyleFactory.ProduceNewLineStyleInfo(System.Drawing.Color.Black, 1);
		}

		private ILineStyleInfo mCaretStyle;
		public ILineStyleInfo CaretStyle
		{
			get { return mCaretStyle; }
			set { mCaretStyle = value; }
		}

		private Rect mBounds = new Rect();
		public Rect Bounds
		{
			get { return mBounds; }
			set { mBounds = value; }
		}

		public void SetNewPosition(int x, int y)
		{
			Bounds.Location.X = x;
			Bounds.Location.Y = y;
		}

		public void SetNewSize(int height)
		{
			Bounds.Size.Y = height;
		}

		public void SetNewBounds(int x, int y, int height)
		{
			Bounds.Location.X = x;
			Bounds.Location.Y = y;
			Bounds.Size.Y = height;
		}

		private bool mVisible = false;
		public bool Visible
		{
			get
			{
				return mVisible;
			}
			set
			{
				mVisible = value;
			}
		}
	}
}


text:
package gov.nih.nci.gss.util;

import gov.nih.nci.gss.domain.DataServiceGroup;
import gov.nih.nci.gss.domain.SearchExemplar;

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

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Order;

/**
 * Translates between caB2B representations and their GSS equivalents, and
 * provides a lookup for caB2B-specific values. The purpose of this service is
 * to isolate GSS clients from potential changes in caB2B.
 *
 * @author Konrad Rokicki
 */
public class Cab2bTranslator {

    private static Logger log = Logger.getLogger(Cab2bTranslator.class);

    private List<DataServiceGroup> serviceGroups;
    private HashMap<String, DataServiceGroup> byServiceGroup;
    private Map<String,DataServiceGroup> byModelGroup;

    public Cab2bTranslator(SessionFactory sessionFactory) {

        this.serviceGroups = new ArrayList<DataServiceGroup>();
        this.byServiceGroup = new HashMap<String,DataServiceGroup>();
        this.byModelGroup = new HashMap<String,DataServiceGroup>();

        Session s = sessionFactory.openSession();
        try {
        	log.info("Configuring data service groups:");
            List<DataServiceGroup> groups = s.createCriteria(
                DataServiceGroup.class).addOrder(Order.asc("id")).list();

            for(DataServiceGroup group : groups) {

                log.info(group.getName()+" -> "+group.getCab2bName()+
                        " (primary key: "+group.getDataPrimaryKey()+") ");

            	// Initialize the associations because we'll be closing this session
            	for(SearchExemplar se : group.getExemplarCollection()) {
            	    log.info("    Search exemplar: "+se.getSearchString());
            	}

            	serviceGroups.add(group);
            	byServiceGroup.put(group.getName(), group);
            	byModelGroup.put(group.getCab2bName(), group);
            }
        }
        finally {
        	s.close();
        }
    }

    public List<DataServiceGroup> getServiceGroups() {
        return serviceGroups;
    }

	public DataServiceGroup getServiceGroupForModelGroup(String modelGroup) {
		return byModelGroup.get(modelGroup);
	}

	public DataServiceGroup getServiceGroupByName(String serviceGroupName) {
		return byServiceGroup.get(serviceGroupName);
	}

}


text:
package android.support.v7.widget;

import android.database.DataSetObserver;

// Referenced classes of package android.support.v7.widget:
//            ListPopupWindow

private class <init> extends DataSetObserver
{

    final ListPopupWindow this$0;

    public void onChanged()
    {
        if (isShowing())
        {
            show();
        }
    }

    public void onInvalidated()
    {
        dismiss();
    }

    private ()
    {
        this$0 = ListPopupWindow.this;
        super();
    }

    this._cls0(this._cls0 _pcls0)
    {
        this();
    }
}


text:
namespace content {

bool BrowserMayStartAsynchronously();
void BrowserStartupComplete(int result);

bool RegisterBrowserStartupController(JNIEnv* env);

}  // namespace content
#endif  // CONTENT_BROWSER_ANDROID_BROWSER_STARTUP_CONTROLLER_H_


text:
package eu.qualimaster.base.algorithm;

import java.util.List;

/**
 * Implementation of the switch tuple {@link ISwitchTuple}.
 * @author qin
 *
 */
public class SwitchTuple extends GeneralTuple implements ISwitchTuple {
    private long id;
    private List<Object> values;
    /**
     * Creates a switch tuple with id and values.
     * @param id the tuple id
     * @param values the tuple values
     */
    public SwitchTuple(long id, List<Object> values) {
        super(values);
        this.id = id;
    }

    @Override
    public void setId(long id) {
        this.id = id;
    }

    @Override
    public long getId() {
        return id;
    }

    @Override
    public boolean isGeneralTuple() {
        return false;
    }

}


text:
# Installation manually

## Step 1
- Download the [`natrium binary`](https://github.com/e-sites/Natrium/raw/master/bin/natrium).
- Save it in your project root
- Rename `natrium.dms` to `natrium`
- Open terminal and type: `chmod +x ./natrium`

## Step 2

Create `.natrium.yml` in the root of your project (in the same folder as the .xcproject and .xcworkspace files).
Check the configuration parameters [here](CONFIGURATION.md).

## Step 3

Create a Pre-Action per scheme which runs the following script:

```shell
"${PROJECT_DIR}/natrium" Production
```

The final argument `"Production"` is the actual environment you want to use for that specific scheme.<br>
This way you can create different schemes per environment

![Schemes](../Assets/xcode_scheme_manual.png)

⚠ **Warning:** Don't forget to select your target in the `Provide build settings from...` selectbox

## Step 4
Build your project (`⌘ + B` or `⌘ + R`).
Then open the `.natrium` directory from your project root and:

- Add the `Natrium.swift` files to your project AND target(s).
- Add all the `Natrium.*.xcconfig` files to your project and do NOT add them to your target(s).

## Step 5
*This step can be skipped if you're not using the `xcconfig` keys in the `.natrium.yml` file*

Select the xcconfig files you just added to your project in step 4 in your project settings:

![Project settings](../Assets/project_settings_manual.png?002)

## Step 6
_This step is optional_

Add the `.natrium` directory to your `gitignore` file.
Since the entire contents of that directory will be generated once you run natrium.


text:
The schema files here are pre-fixed with a numeral to ensure their alphanumeric order is the same order that the schema files should be applied to a fresh MySQL installation / container.

This is due to the way the APEL database is deployed as a docker container.

Schema files are mounted into the directory `/docker-entrypoint-initdb.d` within the standard [MySQL Docker Image](https://hub.docker.com/r/library/mysql/) and are automatically executed in alphanumeric order when the container starts for the first time to create the database.

`20-cloud-extra.sql` assumes the presence of tables created in `10-cloud.sql`.

Without these numeral prefixes, `cloud-extra.sql` would be executed first, resulting in a failure to create the database as it would refer to tables that had not yet been created.

Future schema files **must** continue this naming convention when they depend on other schema files present in this directory. Schema files without such dependencies should continue this convention, but can be executed in any order.


text:
cask 'master-pdf-editor' do
  version '5.2.00'
  sha256 'bd17a531ff083d7ed614bf0447bedd2162ce056e0c929a422e9c75ee58986dde'

  url 'https://code-industry.net/public/MasterPDFEditor.dmg'
  appcast 'https://code-industry.net/get-masterpdfeditor/'
  name 'Master PDF Editor'
  homepage 'https://code-industry.net/masterpdfeditor/'

  auto_updates true

  app 'Master PDF Editor.app'

  zap trash: [
               '~/Library/Application Support/Master PDF Editor',
               '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/net.code-industry.masterpdfeditor3.sfl*',
               '~/Library/Preferences/net.code-industry.Master PDF Editor.plist',
               '~/Library/Saved Application State/net.code-industry.MasterPDFEditor3.savedState',
             ]
end


text:
"""
./app.py --dbpedia-data-dir /home/roman/dbpedia --ner-host diufpc54.unifr.ch --types-table typogram --hbase-host diufpc304
"""
import argparse
import os.path

from flask import Flask, jsonify, request

import kilogram
from kilogram.dataset.entity_linking.gerbil import DataSet
from kilogram.entity_linking import syntactic_subsumption
from kilogram.dataset.dbpedia import DBPediaOntology, NgramEntityResolver
from kilogram.entity_types.prediction import NgramTypePredictor
from kilogram import NgramService

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--dbpedia-data-dir', dest='dbpedia_data_dir', action='store', required=True,
                    help='DBpedia data directory')
parser.add_argument('--ner-host', dest='ner_host', action='store', required=True,
                    help='Hostname of the server where Stanford NER is running')
parser.add_argument('--types-table', dest='types_table', action='store', required=True,
                    help='Typed N-gram table in HBase')
parser.add_argument('--hbase-host', dest='hbase_host', action='store', required=True,
                    help='HBase gateway host')
parser.add_argument('--hbase-port', dest='hbase_port', action='store',
                    default='9090', help='HBase gateway host')

args = parser.parse_args()

NgramService.configure(hbase_host=(args.hbase_host, args.hbase_port))
kilogram.NER_HOSTNAME = args.ner_host
ner = NgramEntityResolver(os.path.join(args.dbpedia_data_dir, "dbpedia_data.txt"),
                          os.path.join(args.dbpedia_data_dir, "dbpedia_2015-04.owl"))

dbpedia_ontology = DBPediaOntology(os.path.join(args.dbpedia_data_dir, "dbpedia_2015-04.owl"))
ngram_predictor = NgramTypePredictor(args.types_table, dbpedia_ontology)

app = Flask(__name__)

@app.route('/entity-linking/d2kb/prior', methods=['POST'])
def d2kb_prior():
    result = request.get_json(force=True)
    candidates = DataSet(result['text'], result['mentions'], ner).candidates
    syntactic_subsumption(candidates)
    new_mentions = []
    for mention, candidate in zip(result['mentions'], candidates):
        mention['uri'] = candidate.get_max_uri()
        if mention['uri'] is None:
            mention['uri'] = 'http://unknown.org/unknown/' + mention['name'].replace(' ', '_')
        else:
            mention['uri'] = 'http://dbpedia.org/resource/' + mention['uri']
        print mention
        new_mentions.append(mention)
    return jsonify({'mentions': new_mentions})

@app.route('/entity-linking/d2kb/prior-typed', methods=['POST'])
def d2kb_prior_types():
    result = request.get_json(force=True)
    candidates = DataSet(result['text'], result['mentions'], ner).candidates
    syntactic_subsumption(candidates)
    for candidate in candidates:
        candidate.init_context_types(ngram_predictor)
    new_mentions = []
    for mention, candidate in zip(result['mentions'], candidates):
        context_types_list = [c.context_types for c in candidates
                              if c.context_types and c.cand_string == candidate.cand_string]
        if context_types_list:
            mention['uri'] = candidate.get_max_typed_uri(context_types_list)
        else:
            mention['uri'] = candidate.get_max_uri()
        new_mentions.append(mention)
    return jsonify({'mentions': new_mentions})

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


text:
package com.example.destr.busy_calendar.utils;

        import android.content.Context;
        import android.net.ConnectivityManager;

public class InternetConnection {

    public boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ~ Copyright (c) 2015-2018 Skymind, Inc.
  ~
  ~ This program and the accompanying materials are made available under the
  ~ terms of the Apache License, Version 2.0 which is available at
  ~ https://www.apache.org/licenses/LICENSE-2.0.
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  ~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  ~ License for the specific language governing permissions and limitations
  ~ under the License.
  ~
  ~ SPDX-License-Identifier: Apache-2.0
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->

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

    <artifactId>datavec-data-image</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.datavec</groupId>
            <artifactId>datavec-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.jai-imageio</groupId>
            <artifactId>jai-imageio-core</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.twelvemonkeys.imageio</groupId>
            <artifactId>imageio-jpeg</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.twelvemonkeys.imageio</groupId>
            <artifactId>imageio-tiff</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.twelvemonkeys.imageio</groupId>
            <artifactId>imageio-psd</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.twelvemonkeys.imageio</groupId>
            <artifactId>imageio-bmp</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <version>4.1.1.4</version>
            <exclusions>
                <exclusion>
                    <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacpp</artifactId>
            <version>${javacpp.version}</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv</artifactId>
            <version>${javacv.version}</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>opencv-platform</artifactId>
            <version>${opencv.version}-${javacpp-presets.version}</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>leptonica-platform</artifactId>
            <version>${leptonica.version}-${javacpp-presets.version}</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>hdf5-platform</artifactId>
            <version>${hdf5.version}-${javacpp-presets.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <classpathDependencyExcludes>
                        <classpathDependencyExclude>com.google.android:android</classpathDependencyExclude>
                    </classpathDependencyExcludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>test-nd4j-native</id>
        </profile>
        <profile>
            <id>test-nd4j-cuda-10.2</id>
        </profile>
    </profiles>
</project>


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

package com.google.gerrit.rules;

import com.google.gerrit.server.AnonymousUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.patch.PatchListCache;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.project.ProjectCache;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.Assisted;

import com.googlecode.prolog_cafe.lang.BufferingPrologControl;
import com.googlecode.prolog_cafe.lang.Predicate;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.PrologMachineCopy;

import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Per-thread Prolog interpreter.
 *

 * This class is not thread safe.
 *

 * A single copy of the Prolog interpreter, for the current thread.
 */
public class PrologEnvironment extends BufferingPrologControl {

  private static final Logger log =
    LoggerFactory.getLogger(PrologEnvironment.class);

  static final int MAX_ARITY = 8;

  public static interface Factory {
    /**
     * Construct a new Prolog interpreter.
     *
     * @param src the machine to template the new environment from.
     * @return the new interpreter.
     */
    PrologEnvironment create(PrologMachineCopy src);
  }

  private final Args args;
  private final Map<StoredValue<Object>, Object> storedValues;
  private int reductionLimit;
  private int reductionsRemaining;
  private List<Runnable> cleanup;

  @Inject
  PrologEnvironment(Args a, @Assisted PrologMachineCopy src) {
    super(src);
    setMaxArity(MAX_ARITY);
    setEnabled(EnumSet.allOf(Prolog.Feature.class), false);
    args = a;
    storedValues = new HashMap<>();
    reductionLimit = a.reductionLimit;
    reductionsRemaining = reductionLimit;
    cleanup = new LinkedList<>();
  }

  public Args getArgs() {
    return args;
  }

  @Override
  public boolean isEngineStopped() {
    if (super.isEngineStopped()) {
      return true;
    } else if (--reductionsRemaining <= 0) {
      throw new ReductionLimitException(reductionLimit);
    }
    return false;
  }

  @Override
  public void setPredicate(Predicate goal) {
    super.setPredicate(goal);
    reductionLimit = args.reductionLimit(goal);
    reductionsRemaining = reductionLimit;
  }

  /** @return number of reductions during execution. */
  public int getReductions() {
    return reductionLimit - reductionsRemaining;
  }

  /**
   * Lookup a stored value in the interpreter's hash manager.
   *
   * @param <T> type of stored Java object.
   * @param sv unique key.
   * @return the value; null if not stored.
   */
  @SuppressWarnings("unchecked")
  public <T> T get(StoredValue<T> sv) {
    return (T) storedValues.get(sv);
  }

  /**
   * Set a stored value on the interpreter's hash manager.
   *
   * @param <T> type of stored Java object.
   * @param sv unique key.
   * @param obj the value to store under {@code sv}.
   */
  @SuppressWarnings("unchecked")
  public <T> void set(StoredValue<T> sv, T obj) {
    storedValues.put((StoredValue<Object>) sv, obj);
  }

  /**
   * Copy the stored values from another interpreter to this one.
   * Also gets the cleanup from the child interpreter
   */
  public void copyStoredValues(PrologEnvironment child) {
    storedValues.putAll(child.storedValues);
    setCleanup(child.cleanup);
  }

  /**
   * Assign the environment a cleanup list (in order to use a centralized list)
   * If this enivronment's list is non-empty, append its cleanup tasks to the
   * assigning list.
   */
  public void setCleanup(List<Runnable> newCleanupList) {
    newCleanupList.addAll(cleanup);
    cleanup = newCleanupList;
  }

  /**
   * Adds cleanup task to run when close() is called
   * @param task is run when close() is called
   */
  public void addToCleanup(Runnable task) {
    cleanup.add(task);
  }

  /**
   * Release resources stored in interpreter's hash manager.
   */
  public void close() {
    for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext();) {
      try {
        i.next().run();
      } catch (Throwable err) {
        log.error("Failed to execute cleanup for PrologEnvironment", err);
      }
      i.remove();
    }
  }

  @Singleton
  public static class Args {
    private final ProjectCache projectCache;
    private final GitRepositoryManager repositoryManager;
    private final PatchListCache patchListCache;
    private final PatchSetInfoFactory patchSetInfoFactory;
    private final IdentifiedUser.GenericFactory userFactory;
    private final Provider<AnonymousUser> anonymousUser;
    private final int reductionLimit;
    private final int compileLimit;

    @Inject
    Args(ProjectCache projectCache,
        GitRepositoryManager repositoryManager,
        PatchListCache patchListCache,
        PatchSetInfoFactory patchSetInfoFactory,
        IdentifiedUser.GenericFactory userFactory,
        Provider<AnonymousUser> anonymousUser,
        @GerritServerConfig Config config) {
      this.projectCache = projectCache;
      this.repositoryManager = repositoryManager;
      this.patchListCache = patchListCache;
      this.patchSetInfoFactory = patchSetInfoFactory;
      this.userFactory = userFactory;
      this.anonymousUser = anonymousUser;

      int limit = config.getInt("rules", null, "reductionLimit", 100000);
      reductionLimit = limit <= 0 ? Integer.MAX_VALUE : limit;

      limit = config.getInt("rules", null, "compileReductionLimit",
          (int) Math.min(10L * limit, Integer.MAX_VALUE));
      compileLimit = limit <= 0 ? Integer.MAX_VALUE : limit;
    }

    private int reductionLimit(Predicate goal) {
      if ("com.googlecode.prolog_cafe.builtin.PRED_consult_stream_2"
          .equals(goal.getClass().getName())) {
        return compileLimit;
      }
      return reductionLimit;
    }

    public ProjectCache getProjectCache() {
      return projectCache;
    }

    public GitRepositoryManager getGitRepositoryManager() {
      return repositoryManager;
    }

    public PatchListCache getPatchListCache() {
      return patchListCache;
    }

    public PatchSetInfoFactory getPatchSetInfoFactory() {
      return patchSetInfoFactory;
    }

    public IdentifiedUser.GenericFactory getUserFactory() {
      return userFactory;
    }

    public AnonymousUser getAnonymousUser() {
      return anonymousUser.get();
    }
  }
}


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

<TITLE>
TextAutoNumberSchemeEnum (POI API Documentation)
</TITLE>

<META NAME="date" CONTENT="2012-11-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

org.apache.poi.hslf.record

Enum TextAutoNumberSchemeEnum

java.lang.Object
  java.lang.Enum<TextAutoNumberSchemeEnum>
      org.apache.poi.hslf.record.TextAutoNumberSchemeEnum

All Implemented Interfaces:
java.io.Serializable, java.lang.Comparable<TextAutoNumberSchemeEnum>

public enum TextAutoNumberSchemeEnum
extends java.lang.Enum<TextAutoNumberSchemeEnum>

Enum Constant Summary

ANM_AlphaLcParenBoth

ANM_AlphaLcParenRight

ANM_AlphaLcPeriod

ANM_AlphaUcParenBoth

ANM_AlphaUcParenRight

ANM_AlphaUcPeriod

ANM_Arabic1Minus

ANM_Arabic2Minus

ANM_ArabicDbPeriod

ANM_ArabicDbPlain

ANM_ArabicParenBoth

ANM_ArabicParenRight

ANM_ArabicPeriod

ANM_ArabicPlain

ANM_ChsPeriod

ANM_ChsPlain

ANM_ChtPeriod

ANM_ChtPlain

ANM_CircleNumDBPlain

ANM_CircleNumWDBBlackPlain

ANM_CircleNumWDBWhitePlain

ANM_Hebrew2Minus

ANM_HindiAlpha1Period

ANM_HindiAlphaPeriod

ANM_HindiNumParenRight

ANM_HindiNumPeriod

ANM_JpnChsDBPeriod

ANM_JpnKorPeriod

ANM_JpnKorPlain

ANM_RomanLcParenBoth

ANM_RomanLcParenRight

ANM_RomanLcPeriod

ANM_RomanUcParenBoth

ANM_RomanUcParenRight

ANM_RomanUcPeriod

ANM_ThaiAlphaParenBoth

ANM_ThaiAlphaParenRight

ANM_ThaiAlphaPeriod

ANM_ThaiNumParenBoth

ANM_ThaiNumParenRight

ANM_ThaiNumPeriod

Method Summary

 java.lang.String
getDescription()

static java.lang.String
getDescription(TextAutoNumberSchemeEnum code)

static TextAutoNumberSchemeEnum
valueOf(short autoNumberScheme)

static TextAutoNumberSchemeEnum
valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static TextAutoNumberSchemeEnum[]
values()

          Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

ANM_AlphaLcPeriod

public static final TextAutoNumberSchemeEnum ANM_AlphaLcPeriod

ANM_AlphaUcPeriod

public static final TextAutoNumberSchemeEnum ANM_AlphaUcPeriod

ANM_ArabicParenRight

public static final TextAutoNumberSchemeEnum ANM_ArabicParenRight

ANM_ArabicPeriod

public static final TextAutoNumberSchemeEnum ANM_ArabicPeriod

ANM_RomanLcParenBoth

public static final TextAutoNumberSchemeEnum ANM_RomanLcParenBoth

ANM_RomanLcParenRight

public static final TextAutoNumberSchemeEnum ANM_RomanLcParenRight

ANM_RomanLcPeriod

public static final TextAutoNumberSchemeEnum ANM_RomanLcPeriod

ANM_RomanUcPeriod

public static final TextAutoNumberSchemeEnum ANM_RomanUcPeriod

ANM_AlphaLcParenBoth

public static final TextAutoNumberSchemeEnum ANM_AlphaLcParenBoth

ANM_AlphaLcParenRight

public static final TextAutoNumberSchemeEnum ANM_AlphaLcParenRight

ANM_AlphaUcParenBoth

public static final TextAutoNumberSchemeEnum ANM_AlphaUcParenBoth

ANM_AlphaUcParenRight

public static final TextAutoNumberSchemeEnum ANM_AlphaUcParenRight

ANM_ArabicParenBoth

public static final TextAutoNumberSchemeEnum ANM_ArabicParenBoth

ANM_ArabicPlain

public static final TextAutoNumberSchemeEnum ANM_ArabicPlain

ANM_RomanUcParenBoth

public static final TextAutoNumberSchemeEnum ANM_RomanUcParenBoth

ANM_RomanUcParenRight

public static final TextAutoNumberSchemeEnum ANM_RomanUcParenRight

ANM_ChsPlain

public static final TextAutoNumberSchemeEnum ANM_ChsPlain

ANM_ChsPeriod

public static final TextAutoNumberSchemeEnum ANM_ChsPeriod

ANM_CircleNumDBPlain

public static final TextAutoNumberSchemeEnum ANM_CircleNumDBPlain

ANM_CircleNumWDBWhitePlain

public static final TextAutoNumberSchemeEnum ANM_CircleNumWDBWhitePlain

ANM_CircleNumWDBBlackPlain

public static final TextAutoNumberSchemeEnum ANM_CircleNumWDBBlackPlain

ANM_ChtPlain

public static final TextAutoNumberSchemeEnum ANM_ChtPlain

ANM_ChtPeriod

public static final TextAutoNumberSchemeEnum ANM_ChtPeriod

ANM_Arabic1Minus

public static final TextAutoNumberSchemeEnum ANM_Arabic1Minus

ANM_Arabic2Minus

public static final TextAutoNumberSchemeEnum ANM_Arabic2Minus

ANM_Hebrew2Minus

public static final TextAutoNumberSchemeEnum ANM_Hebrew2Minus

ANM_JpnKorPlain

public static final TextAutoNumberSchemeEnum ANM_JpnKorPlain

ANM_JpnKorPeriod

public static final TextAutoNumberSchemeEnum ANM_JpnKorPeriod

ANM_ArabicDbPlain

public static final TextAutoNumberSchemeEnum ANM_ArabicDbPlain

ANM_ArabicDbPeriod

public static final TextAutoNumberSchemeEnum ANM_ArabicDbPeriod

ANM_ThaiAlphaPeriod

public static final TextAutoNumberSchemeEnum ANM_ThaiAlphaPeriod

ANM_ThaiAlphaParenRight

public static final TextAutoNumberSchemeEnum ANM_ThaiAlphaParenRight

ANM_ThaiAlphaParenBoth

public static final TextAutoNumberSchemeEnum ANM_ThaiAlphaParenBoth

ANM_ThaiNumPeriod

public static final TextAutoNumberSchemeEnum ANM_ThaiNumPeriod

ANM_ThaiNumParenRight

public static final TextAutoNumberSchemeEnum ANM_ThaiNumParenRight

ANM_ThaiNumParenBoth

public static final TextAutoNumberSchemeEnum ANM_ThaiNumParenBoth

ANM_HindiAlphaPeriod

public static final TextAutoNumberSchemeEnum ANM_HindiAlphaPeriod

ANM_HindiNumPeriod

public static final TextAutoNumberSchemeEnum ANM_HindiNumPeriod

ANM_JpnChsDBPeriod

public static final TextAutoNumberSchemeEnum ANM_JpnChsDBPeriod

ANM_HindiNumParenRight

public static final TextAutoNumberSchemeEnum ANM_HindiNumParenRight

ANM_HindiAlpha1Period

public static final TextAutoNumberSchemeEnum ANM_HindiAlpha1Period

Method Detail

values

public static TextAutoNumberSchemeEnum[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (TextAutoNumberSchemeEnum c : TextAutoNumberSchemeEnum.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in
the order they are declared

valueOf

public static TextAutoNumberSchemeEnum valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:
name - the name of the enum constant to be returned.

Returns:
the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

getDescription

public java.lang.String getDescription()

getDescription

public static java.lang.String getDescription(TextAutoNumberSchemeEnum code)

valueOf

public static TextAutoNumberSchemeEnum valueOf(short autoNumberScheme)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

                Copyright 2012 The Apache Software Foundation or
        its licensors, as applicable.


text:
using HaloEzAPI.Model.Response.MetaData.HaloWars2.Views;

namespace HaloEzAPI.Model.Response.MetaData.HaloWars2.Campaign
{
    public class CampaignContentItem : HW2ApiItem<CampaignLevelView>
    {

    }
}


text:
package eff

// Graphics describes the Graphics struct which is used to add graphics to the canvas
type Graphics interface {
	DrawPoints(points []Point, color Color)
	DrawPoint(Point, Color)
	DrawColorPoints([]Point, []Color)

	DrawLine(Point, Point, Color)
	DrawLines([]Point, Color)

	StrokeRect(Rect, Color)
	StrokeRects([]Rect, Color)
	StrokeColorRects([]Rect, []Color)
	FillRect(Rect, Color)
	FillRects([]Rect, Color)
	FillColorRects([]Rect, []Color)

	DrawText(Font, string, Color, Point) error
	GetTextSize(Font, string) (int, int, error)

	DrawImage(Image, Rect) error

	Begin(*Shape)
	End(*Shape)
}


text:
package Dist::Zilla::Plugin::Test::TrailingSpace;

our $VERSION = '0.2.0';

use 5.012;

use Moose;
extends 'Dist::Zilla::Plugin::InlineFiles';
with qw/Dist::Zilla::Role::TextTemplate Dist::Zilla::Role::PrereqSource/;

use namespace::autoclean;

has filename_regex => (
    is => 'ro',
    isa => 'Str',
    default => q/(?:\.(?:t|pm|pl|xs|c|h|txt|pod|PL)|README|Changes|TODO|LICENSE)\z/,
);

around add_file => sub {
    my ($orig, $self, $file) = @_;

    return $self->$orig(
        Dist::Zilla::File::InMemory->new(
            name => $file->name,
            content => $self->fill_in_string($file->content,
                {
                    dist => \($self->zilla),
                    filename_regex => $self->filename_regex,
                }
            )
        )
    );
};

# Register the release test prereq as a "develop requires"
# so it will be listed in "dzil listdeps --author"
sub register_prereqs {
    my ($self) = @_;

    $self->zilla->register_prereqs(
        {
            type  => 'requires',
            phase => 'develop',
        },
        'Test::TrailingSpace'     => '0.0203',
    );

    return;
}

__PACKAGE__->meta->make_immutable;

1;

=pod

=encoding UTF-8

=head1 NAME

Dist::Zilla::Plugin::Test::TrailingSpace - test for trailing whitespace
in files.

=head1 VERSION

version 0.2.0

=head1 SYNOPSIS

1. In the dist.ini:

    [Test::TrailingSpace]

2. From the command line

    $ dzil test --release

=head1 DESCRIPTION

This module tests adds a test for trailing whitespace in the distribution. It
accepts the following parameters:

=head2 filename_regex

The regular expression for input to Test::TrailingSpace for matching the files
to look for trailing space.

Here is an example of how to override it:

    [Test::TrailingSpace]
    filename_regex = \.(?:pm|pod)\z

=head1 SUBROUTINES/METHODS

=head2 register_prereqs()

Needed by L<Dist::Zilla> .

=head1 SEE ALSO

=over 4

=item * L<Dist::Zilla::Plugin::Test::EOL>

Can also check for trailing whitespace.

=item * L<Dist::Zilla::Plugin::EOLTests>

Older and seems less preferable.

=item * L<Test::TrailingSpace>

A standalone test module for trailing whitespace which this is a wrapper
for.

=back

=head1 AUTHOR

Shlomi Fish <shlomif@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2013 by Shlomi Fish.

This is free software, licensed under:

  The MIT (X11) License

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website
http://rt.cpan.org/NoAuth/Bugs.html?Dist=Dist-Zilla-Plugin-Test-TrailingSpa
ce or by email to bug-dist-zilla-plugin-test-trailingspace@rt.cpan.org.

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 SUPPORT

=head2 Perldoc

You can find documentation for this module with the perldoc command.

  perldoc Dist::Zilla::Plugin::Test::TrailingSpace

=head2 Websites

The following websites have more information about this module, and may be of help to you. As always,
in addition to those websites please use your favorite search engine to discover more resources.

=over 4

=item *

MetaCPAN

A modern, open-source CPAN search engine, useful to view POD in HTML format.

L<http://metacpan.org/release/Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

Search CPAN

The default CPAN search engine, useful to view POD in HTML format.

L<http://search.cpan.org/dist/Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

RT: CPAN's Bug Tracker

The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

AnnoCPAN

The AnnoCPAN is a website that allows community annotations of Perl module documentation.

L<http://annocpan.org/dist/Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

CPAN Ratings

The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.

L<http://cpanratings.perl.org/d/Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

CPAN Forum

The CPAN Forum is a web forum for discussing Perl modules.

L<http://cpanforum.com/dist/Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

CPANTS

The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.

L<http://cpants.perl.org/dist/overview/Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

CPAN Testers

The CPAN Testers is a network of smokers who run automated tests on uploaded CPAN distributions.

L<http://www.cpantesters.org/distro/D/Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

CPAN Testers Matrix

The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.

L<http://matrix.cpantesters.org/?dist=Dist-Zilla-Plugin-Test-TrailingSpace>

=item *

CPAN Testers Dependencies

The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.

L<http://deps.cpantesters.org/?module=Dist::Zilla::Plugin::Test::TrailingSpace>

=back

=head2 Bugs / Feature Requests

Please report any bugs or feature requests by email to C<bug-dist-zilla-plugin-test-trailingspace at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Dist-Zilla-Plugin-Test-TrailingSpace>. You will be automatically notified of any
progress on the request by the system.

=head2 Source Code

The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)

L<http://bitbucket.org/shlomif/perl-Dist-Zilla-Plugin-Test-TrailingSpace>

  hg clone ssh://hg@bitbucket.org/shlomif/perl-Dist-Zilla-Plugin-Test-TrailingSpace

=cut

__DATA__
___[ xt/release/trailing-space.t ]___
#!perl

use strict;
use warnings;

use Test::More;

eval "use Test::TrailingSpace";
if ($@)
{
   plan skip_all => "Test::TrailingSpace required for trailing space test.";
}
else
{
   plan tests => 1;
}

# TODO: add .pod, .PL, the README/Changes/TODO/etc. documents and possibly
# some other stuff.
my $finder = Test::TrailingSpace->new(
   {
       root => '.',
       filename_regex => qr#{{ $filename_regex }}#,
   },
);

# TEST
$finder->no_trailing_space(
   "No trailing space was found."
);


text:
UCLASS(config = EditorPerProjectUserSettings)
class UVoreealEditorSettings : public UObject
{
	GENERATED_BODY()

public:
	UVoreealEditorSettings();

	// Background color in the voreeal editor.
	UPROPERTY(config, EditAnywhere, Category = Background, meta = (HideAlphaChannel))
	FColor BackgroundColor;

	// Should the grid be shown by default when the editor is opened?
	UPROPERTY(config, EditAnywhere, Category = Background)
	bool bShowGridByDefault;

	// The default scale all the basic volume actors will spawn with.
	UPROPERTY(config, EditAnywhere, Category = LevelEditor)
	FVector DefaultScale;
};


text:
namespace dh
{
namespace client
{

template <typename T>
class Result : util::NonCopyable
{
public:
	typedef std::experimental::optional<T> ValueType;

	virtual void set(ValueType value) = 0;

protected:
	Result() = default;
	~Result() = default;
};

template <typename T>
class BlockingResult : public Result<T>
{
public:
	using typename Result<T>::ValueType;

	BlockingResult() = default;
	~BlockingResult() = default;

	ValueType wait()
	{
		std::unique_lock<std::mutex> lock(guard_);
		while (!notified_)
			signal_.wait(lock);
		return result_;
	}

private:
	virtual void set(ValueType value)
	{
		{
			std::unique_lock<std::mutex> lock(guard_);
			notified_ = true;
			result_ = value;
		}

		signal_.notify_all();
	}

private:
	ValueType result_;

	std::mutex guard_;
	std::condition_variable signal_;
	bool notified_ = false;
};

template <typename T>
class CallbackResult : public Result<T>
{
public:
	using typename Result<T>::ValueType;
	typedef std::function< void(ValueType) > Handler;

	CallbackResult(const Handler& handler) :
	    handler_(handler)
	{
		DH_VERIFY( handler_ );
	}

	~CallbackResult() = default;

private:
	virtual void set(ValueType value)
	{
		handler_(value);
	}

private:
	const Handler handler_;
};

}
}


text:
<?php

namespace ptlis\SemanticVersion\Comparator;

use ptlis\SemanticVersion\Version\VersionInterface;

/**
 * Version greater than comparator.
 */
final class GreaterThan implements ComparatorInterface
{
    /**
     * Return true if the left version is greater than right version.
     *
     * @param VersionInterface $lVersion
     * @param VersionInterface $rVersion
     *
     * @return boolean
     */
    public function compare(VersionInterface $lVersion, VersionInterface $rVersion)
    {
        return (new LessThan())->compare($rVersion, $lVersion);
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        return '>';
    }
}


text:
import PropTypes from 'prop-types'
import React, { Component } from 'react'

import COLORS from '../utils/colors'
import { card as cardStyle } from '../utils/styles'

const Detail = ({ label, data }) => (

    {label} :
    {data}

)

const AccessToken = ({ token }) => {
  const codeStyle = {
    fontFamily: 'monospace',
    wordWrap: 'break-word',
    margin: '.5em 0',
    padding: '.5em',
    fontSize: '85%',
    backgroundColor: 'rgba(27,31,35,0.05)',
    borderRadius: '3px'
  }

  return (

      Access token :

{token}

  )
}

export default class UserCard extends Component {
  static propTypes = {
    user: PropTypes.shape({
      _profile: PropTypes.object,
      _token: PropTypes.object
    }),
    logout: PropTypes.func
  }

  render () {
    const { user: { _profile, _token }, logout } = this.props
    let expiration = 'unknown'

    if (_token.expiresAt === Infinity) {
      expiration = 'never/unknown (see provider doc)'
    } else if (_token.expiresAt) {
      const date = new Date(_token.expiresAt)
      const year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let hour = date.getHours()
      let minute = date.getMinutes()

      if (month < 10) month = `0${month}`
      if (day < 10) day = `0${day}`
      if (hour < 10) hour = `0${hour}`
      if (minute < 10) minute = `0${minute}`

      expiration = `${month}/${day}/${year} ${hour}:${minute}`
    }

    const styles = {
      container: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        textAlign: 'left'
      },
      avatar: {
        background: COLORS.background,
        boxShadow: '0 0 12px rgba(0,0,0,0.5)',
        border: `5px solid ${COLORS.white}`,
        borderRadius: '50%',
        height: '7em',
        width: '7em',
        zIndex: '1'
      },
      content: {
        ...cardStyle,
        marginTop: '-.75rem'
      },
      dataContainer: {
        padding: '1.5rem 2rem'
      },
      id: {
        fontSize: '.5rem',
        margin: '-.2rem 0'
      },
      name: {
        fontSize: '1.5rem',
        marginBottom: '.5rem'
      },
      button: {
        color: COLORS.red,
        border: 'none',
        width: '100%',
        padding: '.5rem',
        fontSize: '1em',
        textTransform: 'uppercase'
      }
    }

    const avatar = _profile.profilePicURL ||
      'https://maxcdn.icons8.com/Share/icon/p1em/users//gender_neutral_user1600.png'

    return (

ID {_profile.id}

{_profile.name}

            <Detail label='Firstname' data={_profile.firstName} />
            <Detail label='Lastname' data={_profile.lastName} />
            <Detail label='Email' data={_profile.email} />
            <Detail label='Gender' data={_profile.gender} />
            <Detail label='Expiration' data={expiration} />
            <AccessToken token={_token.accessToken} />

          <button style={styles.button} onClick={logout}>Logout</button>

    )
  }
}


text:
netcat-openbsd
==============

netcat from OpenBSD