text:
@interface MHGroupAvatarsItemViewModel ()

/// user
@property (nonatomic, readwrite, strong) MHUser *user;

/// frame
@property (nonatomic, readwrite, assign) CGRect frame;

@end
@implementation MHGroupAvatarsItemViewModel
- (instancetype)initWithUser:(MHUser *)user frame:(CGRect)frame
{
    self = [super init];
    if (self) {
        self.user = user;
        self.frame = frame;
    }
    return self;
}
@end

redpajama_set_name: RedPajamaGithub


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
module: aws_waf_condition
short_description: create and delete WAF Conditions
description:
  - Read the AWS documentation for WAF
    U(https://aws.amazon.com/documentation/waf/)
version_added: "2.5"

author:
  - Will Thames (@willthames)
  - Mike Mochan (@mmochan)
extends_documentation_fragment:
  - aws
  - ec2
options:
    name:
        description: Name of the Web Application Firewall condition to manage.
        required: yes
    type:
        description: the type of matching to perform.
        choices:
        - byte
        - geo
        - ip
        - regex
        - size
        - sql
        - xss
    filters:
        description:
        - A list of the filters against which to match.
        - For I(type)=C(byte), valid keys are C(field_to_match), C(position), C(header), C(transformation).
        - For I(type)=C(geo), the only valid key is C(country).
        - For I(type)=C(ip), the only valid key is C(ip_address).
        - For I(type)=C(regex), valid keys are C(field_to_match), C(transformation) and C(regex_pattern).
        - For I(type)=C(size), valid keys are C(field_to_match), C(transformation), C(comparison) and C(size).
        - For I(type)=C(sql), valid keys are C(field_to_match) and C(transformation).
        - For I(type)=C(xss), valid keys are C(field_to_match) and C(transformation).
        - I(field_to_match) can be one of C(uri), C(query_string), C(header) C(method) and C(body).
        - If I(field_to_match) is C(header), then C(header) must also be specified.
        - I(transformation) can be one of C(none), C(compress_white_space), C(html_entity_decode), C(lowercase), C(cmd_line), C(url_decode).
        - I(position), can be one of C(exactly), C(starts_with), C(ends_with), C(contains), C(contains_word).
        - I(comparison) can be one of C(EQ), C(NE), C(LE), C(LT), C(GE), C(GT).
        - I(target_string) is a maximum of 50 bytes.
        - I(regex_pattern) is a dict with a C(name) key and C(regex_strings) list of strings to match.
    purge_filters:
        description:
        - Whether to remove existing filters from a condition if not passed in I(filters).
        default: False
        type: bool
    state:
        description: Whether the condition should be C(present) or C(absent).
        choices:
        - present
        - absent
        default: present

'''

EXAMPLES = '''
  - name: create WAF byte condition
    aws_waf_condition:
      name: my_byte_condition
      filters:
      - field_to_match: header
        position: STARTS_WITH
        target_string: Hello
        header: Content-type
      type: byte

  - name: create WAF geo condition
    aws_waf_condition:
      name: my_geo_condition
      filters:
        - country: US
        - country: AU
        - country: AT
      type: geo

  - name: create IP address condition
    aws_waf_condition:
      name: "{{ resource_prefix }}_ip_condition"
      filters:
        - ip_address: "10.0.0.0/8"
        - ip_address: "192.168.0.0/24"
      type: ip

  - name: create WAF regex condition
    aws_waf_condition:
      name: my_regex_condition
      filters:
        - field_to_match: query_string
          regex_pattern:
            name: greetings
            regex_strings:
              - '[hH]ello'
              - '^Hi there'
              - '.*Good Day to You'
      type: regex

  - name: create WAF size condition
    aws_waf_condition:
      name: my_size_condition
      filters:
        - field_to_match: query_string
          size: 300
          comparison: GT
      type: size

  - name: create WAF sql injection condition
    aws_waf_condition:
      name: my_sql_condition
      filters:
        - field_to_match: query_string
          transformation: url_decode
      type: sql

  - name: create WAF xss condition
    aws_waf_condition:
      name: my_xss_condition
      filters:
        - field_to_match: query_string
          transformation: url_decode
      type: xss

'''

RETURN = '''
condition:
  description: condition returned by operation
  returned: always
  type: complex
  contains:
    condition_id:
      description: type-agnostic ID for the condition
      returned: when state is present
      type: str
      sample: dd74b1ff-8c06-4a4f-897a-6b23605de413
    byte_match_set_id:
      description: ID for byte match set
      returned: always
      type: str
      sample: c4882c96-837b-44a2-a762-4ea87dbf812b
    byte_match_tuples:
      description: list of byte match tuples
      returned: always
      type: complex
      contains:
        field_to_match:
          description: Field to match
          returned: always
          type: complex
          contains:
            data:
              description: Which specific header (if type is header)
              type: str
              sample: content-type
            type:
              description: Type of field
              type: str
              sample: HEADER
        positional_constraint:
          description: Position in the field to match
          type: str
          sample: STARTS_WITH
        target_string:
          description: String to look for
          type: str
          sample: Hello
        text_transformation:
          description: Transformation to apply to the field before matching
          type: str
          sample: NONE
    geo_match_constraints:
      description: List of geographical constraints
      returned: when type is geo and state is present
      type: complex
      contains:
        type:
          description: Type of geo constraint
          type: str
          sample: Country
        value:
          description: Value of geo constraint (typically a country code)
          type: str
          sample: AT
    geo_match_set_id:
      description: ID of the geo match set
      returned: when type is geo and state is present
      type: str
      sample: dd74b1ff-8c06-4a4f-897a-6b23605de413
    ip_set_descriptors:
      description: list of IP address filters
      returned: when type is ip and state is present
      type: complex
      contains:
        type:
          description: Type of IP address (IPV4 or IPV6)
          returned: always
          type: str
          sample: IPV4
        value:
          description: IP address
          returned: always
          type: str
          sample: 10.0.0.0/8
    ip_set_id:
      description: ID of condition
      returned: when type is ip and state is present
      type: str
      sample: 78ad334a-3535-4036-85e6-8e11e745217b
    name:
      description: Name of condition
      returned: when state is present
      type: str
      sample: my_waf_condition
    regex_match_set_id:
      description: ID of the regex match set
      returned: when type is regex and state is present
      type: str
      sample: 5ea3f6a8-3cd3-488b-b637-17b79ce7089c
    regex_match_tuples:
      description: List of regex matches
      returned: when type is regex and state is present
      type: complex
      contains:
        field_to_match:
          description: Field on which the regex match is applied
          type: complex
          contains:
            type:
              description: The field name
              returned: when type is regex and state is present
              type: str
              sample: QUERY_STRING
        regex_pattern_set_id:
          description: ID of the regex pattern
          type: str
          sample: 6fdf7f2d-9091-445c-aef2-98f3c051ac9e
        text_transformation:
          description: transformation applied to the text before matching
          type: str
          sample: NONE
    size_constraint_set_id:
      description: ID of the size constraint set
      returned: when type is size and state is present
      type: str
      sample: de84b4b3-578b-447e-a9a0-0db35c995656
    size_constraints:
      description: List of size constraints to apply
      returned: when type is size and state is present
      type: complex
      contains:
        comparison_operator:
          description: Comparison operator to apply
          type: str
          sample: GT
        field_to_match:
          description: Field on which the size constraint is applied
          type: complex
          contains:
            type:
              description: Field name
              type: str
              sample: QUERY_STRING
        size:
          description: size to compare against the field
          type: int
          sample: 300
        text_transformation:
          description: transformation applied to the text before matching
          type: str
          sample: NONE
    sql_injection_match_set_id:
      description: ID of the SQL injection match set
      returned: when type is sql and state is present
      type: str
      sample: de84b4b3-578b-447e-a9a0-0db35c995656
    sql_injection_match_tuples:
      description: List of SQL injection match sets
      returned: when type is sql and state is present
      type: complex
      contains:
        field_to_match:
          description: Field on which the SQL injection match is applied
          type: complex
          contains:
            type:
              description: Field name
              type: str
              sample: QUERY_STRING
        text_transformation:
          description: transformation applied to the text before matching
          type: str
          sample: URL_DECODE
    xss_match_set_id:
      description: ID of the XSS match set
      returned: when type is xss and state is present
      type: str
      sample: de84b4b3-578b-447e-a9a0-0db35c995656
    xss_match_tuples:
      description: List of XSS match sets
      returned: when type is xss and state is present
      type: complex
      contains:
        field_to_match:
          description: Field on which the XSS match is applied
          type: complex
          contains:
            type:
              description: Field name
              type: str
              sample: QUERY_STRING
        text_transformation:
          description: transformation applied to the text before matching
          type: str
          sample: URL_DECODE
'''

try:
    import botocore
except ImportError:
    pass  # handled by AnsibleAWSModule

from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import boto3_conn, get_aws_connection_info, ec2_argument_spec
from ansible.module_utils.ec2 import camel_dict_to_snake_dict, AWSRetry, compare_policies
from ansible.module_utils.aws.waf import run_func_with_change_token_backoff, MATCH_LOOKUP
from ansible.module_utils.aws.waf import get_rule_with_backoff, list_rules_with_backoff

class Condition(object):

    def __init__(self, client, module):
        self.client = client
        self.module = module
        self.type = module.params['type']
        self.method_suffix = MATCH_LOOKUP[self.type]['method']
        self.conditionset = MATCH_LOOKUP[self.type]['conditionset']
        self.conditionsets = MATCH_LOOKUP[self.type]['conditionset'] + 's'
        self.conditionsetid = MATCH_LOOKUP[self.type]['conditionset'] + 'Id'
        self.conditiontuple = MATCH_LOOKUP[self.type]['conditiontuple']
        self.conditiontuples = MATCH_LOOKUP[self.type]['conditiontuple'] + 's'
        self.conditiontype = MATCH_LOOKUP[self.type]['type']

    def format_for_update(self, condition_set_id):
        # Prep kwargs
        kwargs = dict()
        kwargs['Updates'] = list()

        for filtr in self.module.params.get('filters'):
            # Only for ip_set
            if self.type == 'ip':
                # there might be a better way of detecting an IPv6 address
                if ':' in filtr.get('ip_address'):
                    ip_type = 'IPV6'
                else:
                    ip_type = 'IPV4'
                condition_insert = {'Type': ip_type, 'Value': filtr.get('ip_address')}

            # Specific for geo_match_set
            if self.type == 'geo':
                condition_insert = dict(Type='Country', Value=filtr.get('country'))

            # Common For everything but ip_set and geo_match_set
            if self.type not in ('ip', 'geo'):

                condition_insert = dict(FieldToMatch=dict(Type=filtr.get('field_to_match').upper()),
                                        TextTransformation=filtr.get('transformation', 'none').upper())

                if filtr.get('field_to_match').upper() == "HEADER":
                    if filtr.get('header'):
                        condition_insert['FieldToMatch']['Data'] = filtr.get('header').lower()
                    else:
                        self.module.fail_json(msg=str("DATA required when HEADER requested"))

            # Specific for byte_match_set
            if self.type == 'byte':
                condition_insert['TargetString'] = filtr.get('target_string')
                condition_insert['PositionalConstraint'] = filtr.get('position')

            # Specific for size_constraint_set
            if self.type == 'size':
                condition_insert['ComparisonOperator'] = filtr.get('comparison')
                condition_insert['Size'] = filtr.get('size')

            # Specific for regex_match_set
            if self.type == 'regex':
                condition_insert['RegexPatternSetId'] = self.ensure_regex_pattern_present(filtr.get('regex_pattern'))['RegexPatternSetId']

            kwargs['Updates'].append({'Action': 'INSERT', self.conditiontuple: condition_insert})

        kwargs[self.conditionsetid] = condition_set_id
        return kwargs

    def format_for_deletion(self, condition):
        return {'Updates': [{'Action': 'DELETE', self.conditiontuple: current_condition_tuple}
                            for current_condition_tuple in condition[self.conditiontuples]],
                self.conditionsetid: condition[self.conditionsetid]}

    @AWSRetry.exponential_backoff()
    def list_regex_patterns_with_backoff(self, **params):
        return self.client.list_regex_pattern_sets(**params)

    @AWSRetry.exponential_backoff()
    def get_regex_pattern_set_with_backoff(self, regex_pattern_set_id):
        return self.client.get_regex_pattern_set(RegexPatternSetId=regex_pattern_set_id)

    def list_regex_patterns(self):
        # at time of writing(2017-11-20) no regex pattern paginator exists
        regex_patterns = []
        params = {}
        while True:
            try:
                response = self.list_regex_patterns_with_backoff(**params)
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                self.module.fail_json_aws(e, msg='Could not list regex patterns')
            regex_patterns.extend(response['RegexPatternSets'])
            if 'NextMarker' in response:
                params['NextMarker'] = response['NextMarker']
            else:
                break
        return regex_patterns

    def get_regex_pattern_by_name(self, name):
        existing_regex_patterns = self.list_regex_patterns()
        regex_lookup = dict((item['Name'], item['RegexPatternSetId']) for item in existing_regex_patterns)
        if name in regex_lookup:
            return self.get_regex_pattern_set_with_backoff(regex_lookup[name])['RegexPatternSet']
        else:
            return None

    def ensure_regex_pattern_present(self, regex_pattern):
        name = regex_pattern['name']

        pattern_set = self.get_regex_pattern_by_name(name)
        if not pattern_set:
            pattern_set = run_func_with_change_token_backoff(self.client, self.module, {'Name': name},
                                                             self.client.create_regex_pattern_set)['RegexPatternSet']
        missing = set(regex_pattern['regex_strings']) - set(pattern_set['RegexPatternStrings'])
        extra = set(pattern_set['RegexPatternStrings']) - set(regex_pattern['regex_strings'])
        if not missing and not extra:
            return pattern_set
        updates = [{'Action': 'INSERT', 'RegexPatternString': pattern} for pattern in missing]
        updates.extend([{'Action': 'DELETE', 'RegexPatternString': pattern} for pattern in extra])
        run_func_with_change_token_backoff(self.client, self.module,
                                           {'RegexPatternSetId': pattern_set['RegexPatternSetId'], 'Updates': updates},
                                           self.client.update_regex_pattern_set, wait=True)
        return self.get_regex_pattern_set_with_backoff(pattern_set['RegexPatternSetId'])['RegexPatternSet']

    def delete_unused_regex_pattern(self, regex_pattern_set_id):
        try:
            regex_pattern_set = self.client.get_regex_pattern_set(RegexPatternSetId=regex_pattern_set_id)['RegexPatternSet']
            updates = list()
            for regex_pattern_string in regex_pattern_set['RegexPatternStrings']:
                updates.append({'Action': 'DELETE', 'RegexPatternString': regex_pattern_string})
            run_func_with_change_token_backoff(self.client, self.module,
                                               {'RegexPatternSetId': regex_pattern_set_id, 'Updates': updates},
                                               self.client.update_regex_pattern_set)

            run_func_with_change_token_backoff(self.client, self.module,
                                               {'RegexPatternSetId': regex_pattern_set_id},
                                               self.client.delete_regex_pattern_set, wait=True)
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            if e.response['Error']['Code'] == 'WAFNonexistentItemException':
                return
            self.module.fail_json_aws(e, msg='Could not delete regex pattern')

    def get_condition_by_name(self, name):
        all_conditions = [d for d in self.list_conditions() if d['Name'] == name]
        if all_conditions:
            return all_conditions[0][self.conditionsetid]

    @AWSRetry.exponential_backoff()
    def get_condition_by_id_with_backoff(self, condition_set_id):
        params = dict()
        params[self.conditionsetid] = condition_set_id
        func = getattr(self.client, 'get_' + self.method_suffix)
        return func(**params)[self.conditionset]

    def get_condition_by_id(self, condition_set_id):
        try:
            return self.get_condition_by_id_with_backoff(condition_set_id)
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            self.module.fail_json_aws(e, msg='Could not get condition')

    def list_conditions(self):
        method = 'list_' + self.method_suffix + 's'
        try:
            paginator = self.client.get_paginator(method)
            func = paginator.paginate().build_full_result
        except botocore.exceptions.OperationNotPageableError:
            # list_geo_match_sets and list_regex_match_sets do not have a paginator
            func = getattr(self.client, method)
        try:
            return func()[self.conditionsets]
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            self.module.fail_json_aws(e, msg='Could not list %s conditions' % self.type)

    def tidy_up_regex_patterns(self, regex_match_set):
        all_regex_match_sets = self.list_conditions()
        all_match_set_patterns = list()
        for rms in all_regex_match_sets:
            all_match_set_patterns.extend(conditiontuple['RegexPatternSetId']
                                          for conditiontuple in self.get_condition_by_id(rms[self.conditionsetid])[self.conditiontuples])
        for filtr in regex_match_set[self.conditiontuples]:
            if filtr['RegexPatternSetId'] not in all_match_set_patterns:
                self.delete_unused_regex_pattern(filtr['RegexPatternSetId'])

    def find_condition_in_rules(self, condition_set_id):
        rules_in_use = []
        try:
            all_rules = list_rules_with_backoff(self.client)
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            self.module.fail_json_aws(e, msg='Could not list rules')
        for rule in all_rules:
            try:
                rule_details = get_rule_with_backoff(self.client, rule['RuleId'])
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                self.module.fail_json_aws(e, msg='Could not get rule details')
            if condition_set_id in [predicate['DataId'] for predicate in rule_details['Predicates']]:
                rules_in_use.append(rule_details['Name'])
        return rules_in_use

    def find_and_delete_condition(self, condition_set_id):
        current_condition = self.get_condition_by_id(condition_set_id)
        in_use_rules = self.find_condition_in_rules(condition_set_id)
        if in_use_rules:
            rulenames = ', '.join(in_use_rules)
            self.module.fail_json(msg="Condition %s is in use by %s" % (current_condition['Name'], rulenames))
        if current_condition[self.conditiontuples]:
            # Filters are deleted using update with the DELETE action
            func = getattr(self.client, 'update_' + self.method_suffix)
            params = self.format_for_deletion(current_condition)
            try:
                # We do not need to wait for the conditiontuple delete because we wait later for the delete_* call
                run_func_with_change_token_backoff(self.client, self.module, params, func)
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                self.module.fail_json_aws(e, msg='Could not delete filters from condition')
        func = getattr(self.client, 'delete_' + self.method_suffix)
        params = dict()
        params[self.conditionsetid] = condition_set_id
        try:
            run_func_with_change_token_backoff(self.client, self.module, params, func, wait=True)
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            self.module.fail_json_aws(e, msg='Could not delete condition')
        # tidy up regex patterns
        if self.type == 'regex':
            self.tidy_up_regex_patterns(current_condition)
        return True, {}

    def find_missing(self, update, current_condition):
        missing = []
        for desired in update['Updates']:
            found = False
            desired_condition = desired[self.conditiontuple]
            current_conditions = current_condition[self.conditiontuples]
            for condition in current_conditions:
                if not compare_policies(condition, desired_condition):
                    found = True
            if not found:
                missing.append(desired)
        return missing

    def find_and_update_condition(self, condition_set_id):
        current_condition = self.get_condition_by_id(condition_set_id)
        update = self.format_for_update(condition_set_id)
        missing = self.find_missing(update, current_condition)
        if self.module.params.get('purge_filters'):
            extra = [{'Action': 'DELETE', self.conditiontuple: current_tuple}
                     for current_tuple in current_condition[self.conditiontuples]
                     if current_tuple not in [desired[self.conditiontuple] for desired in update['Updates']]]
        else:
            extra = []
        changed = bool(missing or extra)
        if changed:
            update['Updates'] = missing + extra
            func = getattr(self.client, 'update_' + self.method_suffix)
            try:
                result = run_func_with_change_token_backoff(self.client, self.module, update, func, wait=True)
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                self.module.fail_json_aws(e, msg='Could not update condition')
        return changed, self.get_condition_by_id(condition_set_id)

    def ensure_condition_present(self):
        name = self.module.params['name']
        condition_set_id = self.get_condition_by_name(name)
        if condition_set_id:
            return self.find_and_update_condition(condition_set_id)
        else:
            params = dict()
            params['Name'] = name
            func = getattr(self.client, 'create_' + self.method_suffix)
            try:
                condition = run_func_with_change_token_backoff(self.client, self.module, params, func)
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                self.module.fail_json_aws(e, msg='Could not create condition')
            return self.find_and_update_condition(condition[self.conditionset][self.conditionsetid])

    def ensure_condition_absent(self):
        condition_set_id = self.get_condition_by_name(self.module.params['name'])
        if condition_set_id:
            return self.find_and_delete_condition(condition_set_id)
        return False, {}

def main():
    filters_subspec = dict(
        country=dict(),
        field_to_match=dict(choices=['uri', 'query_string', 'header', 'method', 'body']),
        header=dict(),
        transformation=dict(choices=['none', 'compress_white_space',
                                     'html_entity_decode', 'lowercase',
                                     'cmd_line', 'url_decode']),
        position=dict(choices=['exactly', 'starts_with', 'ends_with',
                               'contains', 'contains_word']),
        comparison=dict(choices=['EQ', 'NE', 'LE', 'LT', 'GE', 'GT']),
        target_string=dict(),  # Bytes
        size=dict(type='int'),
        ip_address=dict(),
        regex_pattern=dict(),
    )
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            type=dict(required=True, choices=['byte', 'geo', 'ip', 'regex', 'size', 'sql', 'xss']),
            filters=dict(type='list'),
            purge_filters=dict(type='bool', default=False),
            state=dict(default='present', choices=['present', 'absent']),
        ),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[['state', 'present', ['filters']]])
    state = module.params.get('state')

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
    client = boto3_conn(module, conn_type='client', resource='waf', region=region, endpoint=ec2_url, **aws_connect_kwargs)

    condition = Condition(client, module)

    if state == 'present':
        (changed, results) = condition.ensure_condition_present()
        # return a condition agnostic ID for use by aws_waf_rule
        results['ConditionId'] = results[condition.conditionsetid]
    else:
        (changed, results) = condition.ensure_condition_absent()

    module.exit_json(changed=changed, condition=camel_dict_to_snake_dict(results))

if __name__ == '__main__':
    main()


text:
var World = {
	tracker: null,

	init: function initFn() {
		this.createTracker();
		this.createOverlays();
	},

	/*
		First an AR.CloudTracker needs to be created in order to start the recognition engine.
		It is initialized with your cloud identification token and the id of one of your target collections.
		Optional parameters are passed as object in the last argument. In this case callback functions for the onLoaded and onError triggers are set.
		Once the tracker is fully loaded the function worldLoaded() is called, should there be an error initializing the CloudTracker the
		function trackerError() is called instead.
	*/
	createTracker: function createTrackerFn() {
		World.tracker = new AR.CloudTracker("b277eeadc6183ab57a83b07682b3ceba", "54e4b9fe6134bb74351b2aa3", {
			onLoaded: this.trackerLoaded,
			onError: this.trackerError
		});
	},

	/*
		Callback function to handle CloudTracker initializition errors.
	*/
	trackerError: function trackerErrorFn(errorMessage) {
		alert(errorMessage);
	},

	createOverlays: function createOverlaysFn() {
		/*
			To display a banner containing information about the current target as an augmentation an image resource is created and passed to the
			AR.ImageDrawable. A drawable is a visual component that can be connected to an IR target (AR.Trackable2DObject) or a geolocated
			object (AR.GeoObject). The AR.ImageDrawable is initialized by the image and its size. Optional parameters allow to position it
			relative to the recognized target.
		*/
		this.bannerImg = new AR.ImageResource("assets/banner.jpg");
		this.bannerImgOverlay = new AR.ImageDrawable(this.bannerImg, 0.4, {
			offsetX: 0,
			offsetY: -0.6,
		});
	},

	/*
		The onRecognition callback function defines two parameters. The first parameter is a boolean value which indicates if the server was able
		to detect the target, it's value will be 0 or 1 depending on the outcome. The second parameter a JSON Object will contain metadata about
		the recognized target, if no target was recognized the JSON object will be empty.
	*/
	onRecognition: function onRecognitionFn(recognized, response) {
		if (recognized) {
			/*
				Clean Resources from previous recognitions.
			*/
			if (World.wineLabel !== undefined) {
				World.wineLabel.destroy();
			}

			if (World.wineLabelOverlay !== undefined) {
				World.wineLabelOverlay.destroy();
			}

			/*
				To display the label of the recognized wine on top of the previously created banner, another overlay is defined. From the response
				object returned from the server the 'targetInfo.name' property is read to load the equally named image file.
				The zOrder property (defaults to 0) is set to 1 to make sure it will be positioned on top of the banner.
			*/
			World.wineLabel = new AR.ImageResource("assets/" + response.targetInfo.name + ".jpg");
			World.wineLabelOverlay = new AR.ImageDrawable(World.wineLabel, 0.3, {
				offsetX: -0.5,
				offsetY: -0.6,
				zOrder: 1
			});

			if (World.wineLabelAugmentation !== undefined) {
				World.wineLabelAugmentation.destroy();
			}

			/*
				The following combines everything by creating an AR.Trackable2DObject using the Cloudtracker, the name of the image target and
				the drawables that should augment the recognized image.
			*/
			World.wineLabelAugmentation = new AR.Trackable2DObject(World.tracker, response.targetInfo.name , {
				drawables: {
					cam: [World.bannerImgOverlay, World.wineLabelOverlay]
				}
			});
		} else {
			/*
				Image recognition failed. An error message will be displayed to the user.
			*/
			document.getElementById('errorMessage').innerHTML = "
Recognition failed, please try again!
";

			setTimeout(function() {
				var e = document.getElementById('errorMessage');
				e.removeChild(e.firstChild);
			}, 3000);
		}
	},

	onRecognitionError: function onRecognitionError(errorCode, errorMessage) {
		alert("error code: " + errorCode + " error message: " + JSON.stringify(errorMessage));
	},

	/*
		In this function the recognition will be started, it is triggered by the onClick event of the scanButton.
	*/
	scan: function scanFn() {
		/*
			The tracker recognize function is passed two callback functions. The first callback function will be called by the server after each
			recognition cycle. The second callback defines an on error callback function. It will be called if there is something wrong in
			your cloud archive.
		*/
		World.tracker.recognize(this.onRecognition, this.onRecognitionError);
	},

	trackerLoaded: function trackerLoadedFn() {
		World.showUserInstructions();
	},

	showUserInstructions: function showUserInstructionsFn() {
		var cssDivLeft = " style='display: table-cell;vertical-align: middle; text-align: right; width: 20%; padding-right: 15px;'";
		var cssDivRight = " style='display: table-cell;vertical-align: middle; text-align: center;'";
		var img = "style='margin-right:5px'";

		document.getElementById('messageBox').innerHTML =
			"
Scan:
" +
			"
" +
				"" +
				"" +
				"" +
				"" +
				"" +
			"
";

		setTimeout(function() {
			var e = document.getElementById('messageBox');
			e.parentElement.removeChild(e);
		}, 10000);
	}
};

World.init();


text:
DSP::DSP()
: _active(false),
  _numChannels(0)
{
    connect(this, SIGNAL(message(QString)), Logger::getInstance(), SLOT(message(QString)));
    connect(this, SIGNAL(warn(QString)), Logger::getInstance(), SLOT(warn(QString)));
    connect(this, SIGNAL(error(QString)), Logger::getInstance(), SLOT(error(QString)));

    _inbuffer.init(DSP_RINGSIZE);
    _readbuffer = 0;
    _writebuffer = 0;
    allocBuffers();
}
DSP::~DSP()
{
    disconnect(this, SIGNAL(message(QString)), Logger::getInstance(), SLOT(message(QString)));
    disconnect(this, SIGNAL(warn(QString)), Logger::getInstance(), SLOT(warn(QString)));
    disconnect(this, SIGNAL(error(QString)), Logger::getInstance(), SLOT(error(QString)));

    disable();
    {
        ProcessorChain::iterator it = _processorChain.begin();
        while (it != _processorChain.end()) {
            delete *it;
            it++;
        }
        _processorChain.clear();
    }
    {
        OutputList::iterator it = _outputList.begin();
        while (it != _outputList.end()) {
            delete *it;
            it++;
        }
        _outputList.clear();
    }
    delete[] _readbuffer;
    delete[] _writebuffer;
}
void DSP::reset()
{
    disable();
    {
        ProcessorChain::iterator it = _processorChain.begin();
        while (it != _processorChain.end()) {
            delete *it;
            it++;
        }
        _processorChain.clear();
    }
    {
        OutputList::iterator it = _outputList.begin();
        while (it != _outputList.end()) {
            delete *it;
            it++;
        }
        _outputList.clear();
    }
}
void DSP::allocBuffers()
{
    if (_readbuffer) {
        delete[] _readbuffer;
        _readbuffer = 0;
    }
    if (_writebuffer) {
        delete[] _writebuffer;
        _writebuffer = 0;
    }
    _readbuffer = new sample_t[DSP_RINGSIZE];
    _writebuffer = new sample_t[DSP_RINGSIZE];
    assert(_readbuffer && _writebuffer);
}
void DSP::addProcessor(Processor* p)
{
    QMutexLocker ml(&_processorLock);
    _processorChain.push_back(p);
}
void DSP::removeProcessor(Processor* p)
{
    QMutexLocker ml(&_processorLock);
    _processorChain.remove(p);
    delete p;
}
void DSP::addOutput(Output* o)
{
    QMutexLocker ml(&_outputLock);
    _outputList.push_back(o);
}
void DSP::removeOutput(Output* o)
{
    QMutexLocker ml(&_outputLock);
    _outputList.remove(o);
    delete o;
}
void DSP::run()
{
    _active = true;
    while (_active) {
        _work.lock();
        while (_inbuffer.getFillLevel() < DSP_BLOCKSIZE) {
            _workCondition.wait(&_work);
            if (!_active) {
                _work.unlock();
                return;
            }
        }

        // data available -> take a block & process it
        uint32_t read = _inbuffer.read(_readbuffer, DSP_RINGSIZE);
        assert(read >= DSP_BLOCKSIZE);
        _work.unlock();
        // process signal chain
        {
            QMutexLocker ml(&_processorLock);
            ProcessorChain::iterator it = _processorChain.begin();
            while (it != _processorChain.end()) {
                (*it)->process(_readbuffer, _writebuffer, read);
                if ((*it)->getType() == Processor::METER) {
                    MeterProcessor* p = static_cast<MeterProcessor*>(*it);
                    emit newPeaks(p->getValues());
                }
                else {
                    // now reuse/swap buffers for next processor
                    sample_t* tmp = _readbuffer;
                    _readbuffer = _writebuffer;
                    _writebuffer = tmp;
                }
                it++;
            }
        }
        // send buffer to output
        {
            // outputs can be modified on runtime
            QMutexLocker ml(&_outputLock);
            OutputList::iterator it = _outputList.begin();
            while (it != _outputList.end()) {
                (*it)->feed(_readbuffer, read);
                it++;
            }
        }
        //FileLogger::instance().log(_readbuffer, read, _numChannels);
    }
}
void DSP::disable()
{
    if (_active) {
        _active = false;
        _workCondition.wakeAll();
        wait();
        OutputList::iterator it = _outputList.begin();
        while (it != _outputList.end()) {
            (*it)->disable();
            it++;
        }
    }
}
void DSP::feed(const sample_t* buffer, uint32_t samples)
{
    if (!_active)
        return;
    // FIXME waittime should be based on the current samplerate
    if (_work.tryLock(5)) {
        _inbuffer.write(buffer, samples);

        if (_inbuffer.getFillLevel() >= DSP_BLOCKSIZE) {
            _work.unlock();
            _workCondition.wakeOne();
        }
        else
            _work.unlock();
    }
    else {
        emit message(QString("Dropping frames. DSP appears too busy."));
    }
}


text:
package ru.job4j;

import java.util.*;

/**
 * Created by Anton on 17.04.2017.
 */
public class SpeedCollection {
    /**
     * Start program.
     * @param args args
     */
    public static void main(String[] args) {
        SpeedCollection speedCollection = new SpeedCollection();
        speedCollection.speedTest(new ArrayList<String>(), new LinkedList<String>(), new TreeSet<String>());
    }

    /**
     * Analysing speed collections.
     * @param collection collections
     */
    public void speedTest(Collection<String>... collection) {
        int n; //для удаления первых 1000 строк
        String[] strings = new String[1000000];
        for (int i = 0; i < strings.length; i++) { //генерация строк
            strings[i] = i + "";
        }

        System.out.println("Замер времени вставки: ");
        for (Collection<String> iter : collection) {
            System.out.println(iter.getClass().getName());
            Date date1 = new Date();
            for (int i = 0; i < strings.length; i++) {
                iter.add(strings[i]);
            }
            Date date2 = new Date();
            System.out.println((int) (date2.getTime() - date1.getTime()) + " Миллисекунд");
        }

        System.out.println("");
        System.out.println("Замер времени удаления: ");
        for (Collection<String> iter : collection) {
            n = 10000;
            System.out.println(iter.getClass().getName());
            Iterator<String> iterator = iter.iterator();
            Date date1 = new Date();
            while (iterator.hasNext() && n > -1) {
                iterator.next();
                iterator.remove();
                n--;
            }
            Date date2 = new Date();
            System.out.println((int) (date2.getTime() - date1.getTime()) + " Миллисекунд");
        }
    }
}


text:
import {
  getKey,
  fromKey,
  hash,
  withinExtentAndZ
} from '../../../src/ol/tilecoord.js';
import TileGrid from '../../../src/ol/tilegrid/TileGrid.js';

describe('ol.TileCoord', function() {

  describe('create', function() {
    it('sets x y z properties as expected', function() {
      const tileCoord = [1, 2, 3];
      expect(tileCoord[0]).to.eql(1);
      expect(tileCoord[1]).to.eql(2);
      expect(tileCoord[2]).to.eql(3);
    });
  });

  describe('getKey()', function() {
    it('returns a key for a tile coord', function() {
      const key = getKey([1, 2, 3]);
      expect(key).to.eql('1/2/3');
    });
  });

  describe('fromKey()', function() {
    it('returns a tile coord given a key', function() {
      const tileCoord = [1, 2, 3];
      const key = getKey(tileCoord);

      const returned = fromKey(key);
      expect(returned).to.eql(tileCoord);
    });
  });

  describe('hash', function() {
    it('produces different hashes for different tile coords', function() {
      const tileCoord1 = [3, 2, 1];
      const tileCoord2 = [3, 1, 1];
      expect(hash(tileCoord1)).not.to.eql(
        hash(tileCoord2));
    });
  });

  describe('withinExtentAndZ', function() {

    it('restricts by z', function() {
      const tileGrid = new TileGrid({
        extent: [10, 20, 30, 40],
        tileSize: 10,
        resolutions: [2, 1],
        minZoom: 1
      });
      expect(withinExtentAndZ([0, 0, 0], tileGrid)).to.be(false);
      expect(withinExtentAndZ([1, 0, 0], tileGrid)).to.be(true);
      expect(withinExtentAndZ([2, 0, 0], tileGrid)).to.be(false);
    });

    it('restricts by extent when extent defines tile ranges', function() {
      const tileGrid = new TileGrid({
        extent: [10, 20, 30, 40],
        sizes: [[3, -3]],
        tileSize: 10,
        resolutions: [1]
      });
      expect(withinExtentAndZ([0, 1, 1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 2, 0], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 0, 2], tileGrid)).to.be(false);
    });

    it('restricts by extent when sizes define tile ranges', function() {
      const tileGrid = new TileGrid({
        origin: [10, 20],
        sizes: [[3, 3]],
        tileSize: 10,
        resolutions: [1]
      });
      expect(withinExtentAndZ([0, 0, 0], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 1, 0], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 2, 0], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 0, 1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 1, 1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 2, 1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 0, 2], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 1, 2], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 2, 2], tileGrid)).to.be(true);

      expect(withinExtentAndZ([0, 0, -1], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 1, -1], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 2, -1], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, -1, 0], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 3, 0], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, -1, 1], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 3, 1], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, -1, 2], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 3, 2], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 0, 3], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 1, 3], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 2, 3], tileGrid)).to.be(false);
    });

    it('restricts by extent when sizes (neg y) define tile ranges', function() {
      const tileGrid = new TileGrid({
        origin: [10, 40],
        sizes: [[3, -3]],
        tileSize: 10,
        resolutions: [1]
      });
      expect(withinExtentAndZ([0, 0, -1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 1, -1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 2, -1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 0, -2], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 1, -2], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 2, -2], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 0, -3], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 1, -3], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 2, -3], tileGrid)).to.be(true);

      expect(withinExtentAndZ([0, 0, 0], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 1, 0], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 2, 0], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, -1, -1], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 3, -1], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, -1, -2], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 3, -2], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, -1, -3], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 3, -3], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 0, -4], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 1, -4], tileGrid)).to.be(false);
      expect(withinExtentAndZ([0, 2, -4], tileGrid)).to.be(false);
    });

    it('does not restrict by extent with no extent or sizes', function() {
      const tileGrid = new TileGrid({
        origin: [10, 20],
        tileSize: 10,
        resolutions: [1]
      });
      expect(withinExtentAndZ([0, Infinity, -1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 0, Infinity], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, -Infinity, -1], tileGrid)).to.be(true);
      expect(withinExtentAndZ([0, 0, Infinity], tileGrid)).to.be(true);
    });
  });

});


text:
package com.smartsync.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @author Jack Meyer (jackcmeyer@gmail.com)
 *
 * Tthe Household User Lookup table, this will store information about what users belong to the household.
 */
@Entity
public class HouseholdUserLookup {

    @Id @GeneratedValue
    private Long id;

    /**
     * The user id
     */
    private Long userId;

    /**
     * The household id
     */
    private Long householdId;

    public HouseholdUserLookup(Long userId, Long householdId) {
        this.userId = userId;
        this.householdId = householdId;
    }

    public HouseholdUserLookup() {
        // default constructor
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getUserId() {
        return this.userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Long getHouseholdId() {
        return householdId;
    }

    public void setHouseholdId(Long householdId) {
        this.householdId = householdId;
    }
}


text:
/* global describe, it */

var assert = require('chai').assert,
    resolveSshKey = require('../'),
    path = require('path');

describe('#resolve-ssh-key', function () {

  describe('filePathToKeyName()', function () {
    it('should find the right key name from a correct file path', function () {
      var keyName = resolveSshKey._filePathToKeyName('sample/path/to/key/hello-key.pem');

      assert.strictEqual(keyName, 'hello-key');
    });

    it('should return undefined from an invalid filePath', function () {
      var keyName = resolveSshKey._filePathToKeyName('sample/path/to/key/');

      assert.strictEqual(keyName, undefined);
    });
  });

  describe('isSshKey()', function () {
    var validKey = path.resolve(__dirname, 'fixtures/keys/some_key.pem'),
        invalidKey = path.resolve(__dirname, 'fixtures/keys/invalid_key.pem');

    assert.ok(resolveSshKey._isSshKey(validKey));
    assert.notOk(resolveSshKey._isSshKey(invalidKey));
  });

  it('should find the correct ssh key from its name', function () {
    var keyPath = resolveSshKey(__dirname + '/fixtures/keys', 'some_key');

    assert.strictEqual(keyPath, path.resolve(__dirname, 'fixtures/keys/some_key.pem'));
  });

  it('should return undefined when the key does not exist', function () {
    var keyPath = resolveSshKey(__dirname + '/fixtures/keys', 'some_unexisting_key');

    assert.strictEqual(keyPath, undefined);
  });
});


text:
namespace cc {
class DisplayItemList;
class DrawImage;
class ImageDecodeController;

class CC_EXPORT RasterSource : public base::RefCountedThreadSafe<RasterSource> {
 public:
  struct CC_EXPORT PlaybackSettings {
    PlaybackSettings();

    // If set to true, this indicates that the canvas has already been
    // rasterized into. This means that the canvas cannot be cleared safely.
    bool playback_to_shared_canvas;

    // If set to true, none of the images will be rasterized.
    bool skip_images;

    // If set to true, we will use an image hijack canvas, which enables
    // compositor image caching.
    bool use_image_hijack_canvas;
  };

  static scoped_refptr<RasterSource> CreateFromRecordingSource(
      const RecordingSource* other,
      bool can_use_lcd_text);

  // TODO(trchen): Deprecated.
  void PlaybackToCanvas(SkCanvas* canvas,
                        const gfx::Rect& canvas_bitmap_rect,
                        const gfx::Rect& canvas_playback_rect,
                        float contents_scale,
                        const PlaybackSettings& settings) const;

  // Raster this RasterSource into the given canvas. Canvas states such as
  // CTM and clip region will be respected. This function will replace pixels
  // in the clip region without blending. It is assumed that existing pixels
  // may be uninitialized and will be cleared before playback.
  //
  // Virtual for testing.
  //
  // Note that this should only be called after the image decode controller has
  // been set, which happens during commit.
  virtual void PlaybackToCanvas(SkCanvas* canvas,
                                const PlaybackSettings& settings) const;

  // Returns whether the given rect at given scale is of solid color in
  // this raster source, as well as the solid color value.
  bool PerformSolidColorAnalysis(const gfx::Rect& content_rect,
                                 float contents_scale,
                                 SkColor* color) const;

  // Returns true iff the whole raster source is of solid color.
  bool IsSolidColor() const;

  // Returns the color of the raster source if it is solid color. The results
  // are unspecified if IsSolidColor returns false.
  SkColor GetSolidColor() const;

  // Returns the size of this raster source.
  gfx::Size GetSize() const;

  // Populate the given list with all images that may overlap the given
  // rect in layer space. The returned draw images' matrices are modified as if
  // they were being using during raster at scale |raster_scale|.
  void GetDiscardableImagesInRect(const gfx::Rect& layer_rect,
                                  float raster_scale,
                                  std::vector<DrawImage>* images) const;

  // Return true iff this raster source can raster the given rect in layer
  // space.
  bool CoversRect(const gfx::Rect& layer_rect) const;

  // Returns true if this raster source has anything to rasterize.
  virtual bool HasRecordings() const;

  // Valid rectangle in which everything is recorded and can be rastered from.
  virtual gfx::Rect RecordedViewport() const;

  // Informs the raster source that it should attempt to use distance field text
  // during rasterization.
  virtual void SetShouldAttemptToUseDistanceFieldText();

  // Return true iff this raster source would benefit from using distance
  // field text.
  virtual bool ShouldAttemptToUseDistanceFieldText() const;

  // Tracing functionality.
  virtual void DidBeginTracing();
  virtual void AsValueInto(base::trace_event::TracedValue* array) const;
  virtual sk_sp<SkPicture> GetFlattenedPicture();
  virtual size_t GetPictureMemoryUsage() const;

  // Return true if LCD anti-aliasing may be used when rastering text.
  virtual bool CanUseLCDText() const;

  scoped_refptr<RasterSource> CreateCloneWithoutLCDText() const;

  // Image decode controller should be set once. Its lifetime has to exceed that
  // of the raster source, since the raster source will access it during raster.
  void set_image_decode_controller(
      ImageDecodeController* image_decode_controller) {
    DCHECK(image_decode_controller);
    image_decode_controller_ = image_decode_controller;
  }

  // Returns the ImageDecodeController, currently only used by
  // GpuRasterBufferProvider in order to create its own ImageHijackCanvas.
  // Because of the MultiPictureDraw approach used by GPU raster, it does not
  // integrate well with the use of the ImageHijackCanvas internal to this
  // class. See gpu_raster_buffer_provider.cc for more information.
  // TODO(crbug.com/628394): Redesign this to avoid exposing
  // ImageDecodeController from the raster source.
  ImageDecodeController* image_decode_controller() const {
    return image_decode_controller_;
  }

 protected:
  friend class base::RefCountedThreadSafe<RasterSource>;

  RasterSource(const RecordingSource* other, bool can_use_lcd_text);
  RasterSource(const RasterSource* other, bool can_use_lcd_text);
  virtual ~RasterSource();

  // These members are const as this raster source may be in use on another
  // thread and so should not be touched after construction.
  const scoped_refptr<DisplayItemList> display_list_;
  const size_t painter_reported_memory_usage_;
  const SkColor background_color_;
  const bool requires_clear_;
  const bool can_use_lcd_text_;
  const bool is_solid_color_;
  const SkColor solid_color_;
  const gfx::Rect recorded_viewport_;
  const gfx::Size size_;
  const bool clear_canvas_with_debug_color_;
  const int slow_down_raster_scale_factor_for_debug_;
  // TODO(enne/vmiura): this has a read/write race between raster and compositor
  // threads with multi-threaded Ganesh.  Make this const or remove it.
  bool should_attempt_to_use_distance_field_text_;

  // In practice, this is only set once before raster begins, so it's ok with
  // respect to threading.
  ImageDecodeController* image_decode_controller_;

 private:
  void RasterCommon(SkCanvas* canvas, SkPicture::AbortCallback* callback) const;

  void PrepareForPlaybackToCanvas(SkCanvas* canvas) const;

  DISALLOW_COPY_AND_ASSIGN(RasterSource);
};

}  // namespace cc

#endif  // CC_PLAYBACK_RASTER_SOURCE_H_


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

<title>org.apache.poi (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.poi

Class Summary

Class
Description

POIDocument

This holds the common functionality for all POI
  Document classes.

POIOLE2TextExtractor

Common Parent for OLE2 based Text Extractors
  of POI Documents, such as .doc, .xls
 You will typically find the implementation of
  a given format's text extractor under
  org.apache.poi.

POITextExtractor

Common Parent for Text Extractors
  of POI Documents.

POIXMLDocument

POIXMLDocumentPart

Represents an entry of a OOXML package.

POIXMLFactory

Defines a factory API that enables sub-classes to create instances of POIXMLDocumentPart

POIXMLProperties

Wrapper around the two different kinds of OOXML properties
  a document can have

POIXMLPropertiesTextExtractor

A POITextExtractor for returning the textual
  content of the OOXML file properties, eg author
  and title.

POIXMLRelation

Represents a descriptor of a OOXML relation.

POIXMLTextExtractor

Exception Summary

Exception
Description

EncryptedDocumentException

OldFileFormatException

Base class of all the exceptions that POI throws in the event
 that it's given a file that's older than currently supported.

POIXMLException

Indicates a generic OOXML error.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

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


text:
[![Build Status](https://ci.eulerproject.io/job/euler-common-latest-jdk8/badge/icon)](https://ci.eulerproject.io/job/euler-common-latest-jdk8)
[![GitHub issues](https://img.shields.io/github/issues/euler-projects/euler-common.svg)](https://github.com/euler-projects/euler-common/issues)
[![GitHub release](https://img.shields.io/github/release/euler-projects/euler-common.svg)](https://github.com/euler-projects/euler-common/releases)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.eulerframework/euler-common/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.eulerframework/euler-common)
[![GitHub license](https://img.shields.io/github/license/euler-projects/euler-common.svg)](https://raw.githubusercontent.com/euler-projects/euler-common/master/LICENSE)
## About
A useful code collection

Visit [eulerproject.io][] for more info.

## License
This project is released under version 2.0 of the [Apache License][].

[Apache License]: http://www.apache.org/licenses/LICENSE-2.0
[eulerproject.io]: https://eulerproject.io


text:
package com.yuyh.sprintnba.mvp.model;

import com.yuyh.sprintnba.retrofit.bean.player.Teams;
import com.yuyh.sprintnba.retrofit.api.RequestCallback;

public interface TeamsListBiz {

    void getAllTeams(RequestCallback<Teams> callback);
}


text:
<?php

namespace Box\Mod\Servicemembership;
class Service implements \Box\InjectionAwareInterface
{
    protected $di;

    /**
     * @param mixed $di
     */
    public function setDi($di)
    {
        $this->di = $di;
    }

    /**
     * @return mixed
     */
    public function getDi()
    {
        return $this->di;
    }

    public function validateOrderData(array &$data)
    {
        return true;
    }

    /**
     * @param \Model_ClientOrder $order
     * @return void
     */
    public function action_create(\Model_ClientOrder $order)
    {
        $orderService = $this->di['mod_service']('order');
        $c = $orderService->getConfig($order);

        $this->validateOrderData($c);

        $model = $this->di['db']->dispense('ServiceMembership');
        $model->client_id = $order->client_id;
        $model->config = $order->config;

        $model->created_at = date('c');
        $model->updated_at = date('c');

        $this->di['db']->store($model);

        return $model;
    }

    /**
     * @param \Model_ClientOrder $order
     * @return boolean
     */
    public function action_activate(\Model_ClientOrder $order)
    {
        return true;
    }

    /**
     *
     * @todo
     * @param \Model_ClientOrder $order
     * @return boolean
     */
    public function action_renew(\Model_ClientOrder $order)
    {
        return true;
    }

    /**
     *
     * @todo
     * @param \Model_ClientOrder $order
     * @return boolean
     */
    public function action_suspend(\Model_ClientOrder $order)
    {
        return true;
    }

    /**
     *
     * @todo
     * @param \Model_ClientOrder $order
     * @return boolean
     */
    public function action_unsuspend(\Model_ClientOrder $order)
    {
        return true;
    }

    /**
     *
     * @todo
     * @param \Model_ClientOrder $order
     * @return boolean
     */
    public function action_cancel(\Model_ClientOrder $order)
    {
        return true;
    }

    /**
     *
     * @param \Model_ClientOrder $order
     * @return boolean
     */
    public function action_uncancel(\Model_ClientOrder $order)
    {
        return true;
    }

    /**
     * @param \Model_ClientOrder $order
     * @return void
     */
    public function action_delete(\Model_ClientOrder $order)
    {
        $orderService = $this->di['mod_service']('order');
        $service = $orderService->getOrderService($order);

        if($service instanceof \Model_ServiceMembership) {
            $this->di['db']->trash($service);
        }
    }

    public function toApiArray(\Model_ServiceMembership $model, $deep = false, $identity = null)
    {
        $result = $this->di['db']->toArray($model);
        return $result;
    }

}


text:
#ifndef GEOS_LINEARREF_LINEARLOCATION_H
#define GEOS_LINEARREF_LINEARLOCATION_H

#include <string>
#include <memory> // for std::auto_ptr

#include <geos/geom/Coordinate.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/LineSegment.h>

namespace geos {
namespace linearref { // geos::linearref

/** \brief
 * Represents a location along a {@link LineString} or {@link MultiLineString}.
 *
 * The referenced geometry is not maintained within
 * this location, but must be provided for operations which require it.
 * Various methods are provided to manipulate the location value
 * and query the geometry it references.
 */
class LinearLocation
{
private:
	unsigned int componentIndex;
	unsigned int segmentIndex;
	double segmentFraction;

	/**
	 * Ensures the individual values are locally valid.
	 * Does not ensure that the indexes are valid for
	 * a particular linear geometry.
	 *
	 * @see clamp
	 */
	void normalize();

public:
	/**
	 * Gets a location which refers to the end of a linear {@link Geometry}.
	 * @param linear the linear geometry
	 * @return a new <tt>LinearLocation</tt>
	 */
	static LinearLocation getEndLocation(const geom::Geometry* linear);

	/**
	 * Computes the {@link Coordinate} of a point a given fraction
	 * along the line segment <tt>(p0, p1)</tt>.
	 * If the fraction is greater than 1.0 the last
	 * point of the segment is returned.
	 * If the fraction is less than or equal to 0.0 the first point
	 * of the segment is returned.
	 * The Z ordinate is interpolated from the Z-ordinates of
	 * the given points, if they are specified.
	 *
	 * @param p0 the first point of the line segment
	 * @param p1 the last point of the line segment
	 * @param frac the length to the desired point
	 * @return the <tt>Coordinate</tt> of the desired point
	 */
	static geom::Coordinate pointAlongSegmentByFraction(const geom::Coordinate& p0, const geom::Coordinate& p1, double frac);

	/**
	 * Creates a location referring to the start of a linear geometry
	 */
	LinearLocation(unsigned int segmentIndex = 0, double segmentFraction = 0.0);

	LinearLocation(unsigned int componentIndex, unsigned int segmentIndex, double segmentFraction);

	/**
	 * Ensures the indexes are valid for a given linear {@link Geometry}.
	 *
	 * @param linear a linear geometry
	 */
	void clamp(const geom::Geometry* linear);

	/**
	 * Snaps the value of this location to
	 * the nearest vertex on the given linear {@link Geometry},
	 * if the vertex is closer than <tt>minDistance</tt>.
	 *
	 * @param linearGeom a linear geometry
	 * @param minDistance the minimum allowable distance to a vertex
	 */
	void snapToVertex(const geom::Geometry* linearGeom, double minDistance);

	/**
	 * Gets the length of the segment in the given
	 * Geometry containing this location.
	 *
	 * @param linearGeom a linear geometry
	 * @return the length of the segment
	 */
	double getSegmentLength(const geom::Geometry* linearGeom) const;

	/**
	 * Sets the value of this location to
	 * refer the end of a linear geometry
	 *
	 * @param linear the linear geometry to set
	 */
	void setToEnd(const geom::Geometry* linear);

	/**
	 * Gets the component index for this location.
	 *
	 * @return the component index
	 */
	unsigned int getComponentIndex() const;

	/**
	 * Gets the segment index for this location
	 *
	 * @return the segment index
	 */
	unsigned int getSegmentIndex() const;

	/**
	 * Gets the segment fraction for this location
	 *
	 * @return the segment fraction
	 */
	double getSegmentFraction() const;

	/**
	 * Tests whether this location refers to a vertex
	 *
	 * @return true if the location is a vertex
	 */
	bool isVertex() const;

	/**
	 * Gets the {@link Coordinate} along the
	 * given linear {@link Geometry} which is
	 * referenced by this location.
	 *
	 * @param linearGeom the linear geometry referenced by this location
	 * @return the <tt>Coordinate</tt> at the location
	 */
	geom::Coordinate getCoordinate(const geom::Geometry* linearGeom) const;

	/**
	 * Gets a {@link LineSegment} representing the segment of the
	 * given linear {@link Geometry} which contains this location.
	 *
	 * @param linearGeom a linear geometry
	 * @return the <tt>LineSegment</tt> containing the location
	 */
	std::auto_ptr<geom::LineSegment> getSegment(const geom::Geometry* linearGeom) const;

	/**
	 * Tests whether this location refers to a valid
	 * location on the given linear {@link Geometry}.
	 *
	 * @param linearGeom a linear geometry
	 * @return true if this location is valid
	 */
	bool isValid(const geom::Geometry* linearGeom) const;

	/**
	 *  Compares this object with the specified object for order.
	 *
	 *@param  o  the LineStringLocation with which this Coordinate
	 *      is being compared
	 *@return    a negative integer, zero, or a positive integer as this LineStringLocation
	 *      is less than, equal to, or greater than the specified LineStringLocation
	 */
	int compareTo(const LinearLocation& other) const;

	/**
	 *  Compares this object with the specified index values for order.
	 *
	 * @param componentIndex1 a component index
	 * @param segmentIndex1 a segment index
	 * @param segmentFraction1 a segment fraction
	 * @return    a negative integer, zero, or a positive integer as this LineStringLocation
	 *      is less than, equal to, or greater than the specified locationValues
	 */
	int compareLocationValues(unsigned int componentIndex1, unsigned int segmentIndex1, double segmentFraction1) const;

	/**
	 *  Compares two sets of location values for order.
	 *
	 * @param componentIndex0 a component index
	 * @param segmentIndex0 a segment index
	 * @param segmentFraction0 a segment fraction
	 * @param componentIndex1 another component index
	 * @param segmentIndex1 another segment index
	 * @param segmentFraction1 another segment fraction
	 *@return    a negative integer, zero, or a positive integer
	 *      as the first set of location values
	 *      is less than, equal to, or greater than the second set of locationValues
	 */
	static int compareLocationValues(
		unsigned int componentIndex0, unsigned int segmentIndex0, double segmentFraction0,
		unsigned int componentIndex1, unsigned int segmentIndex1, double segmentFraction1);

	/**
	 * Tests whether two locations
	 * are on the same segment in the parent {@link Geometry}.
	 *
	 * @param loc a location on the same geometry
	 * @return true if the locations are on the same segment of the parent geometry
	 */
	bool isOnSameSegment(const LinearLocation& loc) const;

	/**
	 * \brief
	 * Tests whether this location is an endpoint of
	 * the linear component it refers to.
	 *
	 * @param linearGeom the linear geometry referenced by this location
	 * @return true if the location is a component endpoint
	 */
	bool isEndpoint(const geom::Geometry& linearGeom) const;

	friend std::ostream& operator<< (std::ostream& out, const LinearLocation& obj );

};

} // namespace geos.linearref
} // namespace geos

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

using NUnit.Framework;
using Shouldly;

using Mulder.Base.Domain;

namespace Mulder.Tests.Base.Domain
{
	public class RuleTests
	{
		[TestFixture]
		public class when_checking_if_rule_is_applicable_to_item
		{
			[Test]
			public void should_be_applicable_with_just_string_for_pattern()
			{
				var applicableItem = CreateItem("/a/");

				var rule = new Rule("a");

				rule.ApplicableTo(applicableItem).ShouldBe(true);
			}

			[Test]
			public void should_all_be_applicable_with_just_a_star_wild_card_for_pattern()
			{
				var applicableItems = new List<Item> {
					CreateItem("/"),
					CreateItem("/a/"),
					CreateItem("/a/b/"),
					CreateItem("/a/b/c/"),
					CreateItem("/a/b/c/d/"),
					CreateItem("/a/b/c/d/e/")
				};

				var rule = new Rule("*");

				applicableItems.ForEach(item => rule.ApplicableTo(item).ShouldBe(true));
			}

			[Test]
			public void should_be_applicable_with_star_wild_card_and_specific_directory_for_pattern()
			{
				var applicableItems = new List<Item> {
					CreateItem("/a/b/c/"),
					CreateItem("/a/foo/c/")
				};

				var rule = new Rule("a/*/c");

				applicableItems.ForEach(item => rule.ApplicableTo(item).ShouldBe(true));
			}

			[Test]
			public void should_not_be_applicable_for_star_wild_card_and_specific_directory_for_pattern()
			{
				var nonApplicableItems = new List<Item> {
					CreateItem("/a/"),
					CreateItem("/a/b/"),
					CreateItem("/a/b/c/d/"),
					CreateItem("/a/b/c/d/e/")
				};

				var rule = new Rule("a/*/c");

				nonApplicableItems.ForEach(item => rule.ApplicableTo(item).ShouldBe(false));
			}

			[Test]
			public void should_all_be_applicable_for_plus_wild_card_with_string()
			{
				var applicableItems = new List<Item> {
					CreateItem("/foobar/images/bar/"),
					CreateItem("/foosoap/scripts/bar/"),
					CreateItem("/fooreallylongfoo/")
				};

				var rule = new Rule("foo+");

				applicableItems.ForEach(item => rule.ApplicableTo(item).ShouldBe(true));
			}

			[Test]
			public void should_not_be_applicable_for_plus_wild_card_with_string()
			{
				var nonApplicableItems = new List<Item> {
					CreateItem("/barfoo/"),
					CreateItem("/barfoos/"),
					CreateItem("/reallylongbar/foos/")
				};

				var rule = new Rule("foo+");

				nonApplicableItems.ForEach(item => rule.ApplicableTo(item).ShouldBe(false));
			}

			[Test]
			public void should_be_able_to_use_star_and_plus_wild_card_together()
			{
				var item = CreateItem("/a/b/c/foobar/");

				var rule = new Rule("a/*/c/foo+");

				rule.ApplicableTo(item).ShouldBe(true);
			}

			static Item CreateItem(string identifier)
			{
				return new Item(identifier, false, "", new Dictionary<string, object>(), DateTime.Now);
			}
		}
	}
}


text:
/*
 *
 *  Somado (System Optymalizacji Małych Dostaw)
 *  Optymalizacja dostaw towarów, dane OSM, problem VRP
 *
 *  Autor: Maciej Kawecki 2016 (praca inż. EE PW)
 *
 */
package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import javax.swing.JLabel;

import javax.swing.JPanel;

/**
 *
 * Szablon obiektu pustego centralnego panelu
 *
 * @author Maciej Kawecki
 * @version 1.0
 *
 */
@SuppressWarnings("serial")
public class EmptyPanel extends JPanel {

  /** Szerokosc calego ekranu */
  final static public int SCREEN_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;

  /** Czy wyswietlane dane musza byc odswiezone ? */
  private boolean changed;

  /** Wewnetrzna klasa - etykieta bez pogrubienia, opcjonalnie kolor */
  public class NormLabel extends JLabel {

    NormLabel(String text, boolean redCol) {

       super(text);
       if (redCol) setForeground(new Color(0x990000));
       Font f = getFont();
       setFont(f.deriveFont(f.getStyle() & ~Font.BOLD));

    }

    NormLabel(String text) {

      this(text, false);

    }

  }

  public EmptyPanel() {

    super();
    changed = false;
    setLayout(new FlowLayout(FlowLayout.LEFT));
    setBackground(new Color(0xe3, 0xf1, 0xff));
    setPreferredSize(new Dimension(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT));

  }

  public boolean isChanged() {
      return changed;
  }

  public void setChanged(boolean changed) {
      this.changed = changed;
  }

}


text:
"use strict";

var UI = require("lazuli-ui/index.js");

module.exports = UI.SearchPage.clone({
    id              : "ac_export_search",
    entity_id       : "ac_export",
    title           : "Search for Outbound Exchanges",
    short_title     : "Outbound Exchanges"
});

module.exports.sections.addAll([
    { id: "main", type: "Search", entity: "ac_export", show_row_control: false }
]);