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

DOCUMENTATION = '''
---
module: aws_kms
short_description: Perform various KMS management tasks.
description:
     - Manage role/user access to a KMS key. Not designed for encrypting/decrypting.
version_added: "2.3"
options:
  alias:
    description: An alias for a key. For safety, even though KMS does not require keys
      to have an alias, this module expects all new keys to be given an alias
      to make them easier to manage. Existing keys without an alias may be
      referred to by I(key_id). Use M(aws_kms_info) to find key ids. Required
      if I(key_id) is not given. Note that passing a I(key_id) and I(alias)
      will only cause a new alias to be added, an alias will never be renamed.
      The 'alias/' prefix is optional.
    required: false
    aliases:
      - key_alias
  key_id:
    description:
    - Key ID or ARN of the key. One of C(alias) or C(key_id) are required.
    required: false
    aliases:
      - key_arn
  policy_mode:
    description:
    - (deprecated) Grant or deny access.
    - Used for modifying the Key Policy rather than modifying a grant and only
      works on the default policy created through the AWS Console.
    - This option has been deprecated, and will be removed in 2.13. Use I(policy) instead.
    default: grant
    choices: [ grant, deny ]
    aliases:
    - mode
  policy_role_name:
    description:
    - (deprecated) Role to allow/deny access. One of C(policy_role_name) or C(policy_role_arn) are required.
    - Used for modifying the Key Policy rather than modifying a grant and only
      works on the default policy created through the AWS Console.
    - This option has been deprecated, and will be removed in 2.13. Use I(policy) instead.
    required: false
    aliases:
    - role_name
  policy_role_arn:
    description:
    - (deprecated) ARN of role to allow/deny access. One of C(policy_role_name) or C(policy_role_arn) are required.
    - Used for modifying the Key Policy rather than modifying a grant and only
      works on the default policy created through the AWS Console.
    - This option has been deprecated, and will be removed in 2.13. Use I(policy) instead.
    required: false
    aliases:
    - role_arn
  policy_grant_types:
    description:
    - (deprecated) List of grants to give to user/role. Likely "role,role grant" or "role,role grant,admin". Required when C(policy_mode=grant).
    - Used for modifying the Key Policy rather than modifying a grant and only
      works on the default policy created through the AWS Console.
    - This option has been deprecated, and will be removed in 2.13. Use I(policy) instead.
    required: false
    aliases:
    - grant_types
  policy_clean_invalid_entries:
    description:
    - (deprecated) If adding/removing a role and invalid grantees are found, remove them. These entries will cause an update to fail in all known cases.
    - Only cleans if changes are being made.
    - Used for modifying the Key Policy rather than modifying a grant and only
      works on the default policy created through the AWS Console.
    - This option has been deprecated, and will be removed in 2.13. Use I(policy) instead.
    type: bool
    default: true
    aliases:
    - clean_invalid_entries
  state:
    description: Whether a key should be present or absent. Note that making an
      existing key absent only schedules a key for deletion.  Passing a key that
      is scheduled for deletion with state present will cancel key deletion.
    required: False
    choices:
      - present
      - absent
    default: present
    version_added: 2.8
  enabled:
    description: Whether or not a key is enabled
    default: True
    version_added: 2.8
    type: bool
  description:
    description:
      A description of the CMK. Use a description that helps you decide
      whether the CMK is appropriate for a task.
    version_added: 2.8
  tags:
    description: A dictionary of tags to apply to a key.
    version_added: 2.8
  purge_tags:
    description: Whether the I(tags) argument should cause tags not in the list to
      be removed
    version_added: 2.8
    default: False
    type: bool
  purge_grants:
    description: Whether the I(grants) argument should cause grants not in the list to
      be removed
    default: False
    version_added: 2.8
    type: bool
  grants:
    description:
      - A list of grants to apply to the key. Each item must contain I(grantee_principal).
        Each item can optionally contain I(retiring_principal), I(operations), I(constraints),
        I(name).
      - Valid operations are C(Decrypt), C(Encrypt), C(GenerateDataKey), C(GenerateDataKeyWithoutPlaintext),
        C(ReEncryptFrom), C(ReEncryptTo), C(CreateGrant), C(RetireGrant), C(DescribeKey), C(Verify) and
        C(Sign)
      - Constraints is a dict containing C(encryption_context_subset) or C(encryption_context_equals),
        either or both being a dict specifying an encryption context match.
        See U(https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantConstraints.html)
      - I(grantee_principal) and I(retiring_principal) must be ARNs
    version_added: 2.8
  policy:
    description:
      - policy to apply to the KMS key
      - See U(https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)
    version_added: 2.8
author:
  - Ted Timmons (@tedder)
  - Will Thames (@willthames)
  - Mark Chappell (@tremble)
extends_documentation_fragment:
- aws
- ec2
'''

EXAMPLES = '''
# Managing the KMS IAM Policy via policy_mode and policy_grant_types is fragile
# and has been deprecated in favour of the policy option.
- name: grant user-style access to production secrets
  aws_kms:
  args:
    alias: "alias/my_production_secrets"
    policy_mode: grant
    policy_role_name: "prod-appServerRole-1R5AQG2BSEL6L"
    policy_grant_types: "role,role grant"
- name: remove access to production secrets from role
  aws_kms:
  args:
    alias: "alias/my_production_secrets"
    policy_mode: deny
    policy_role_name: "prod-appServerRole-1R5AQG2BSEL6L"

# Create a new KMS key
- aws_kms:
    alias: mykey
    tags:
      Name: myKey
      Purpose: protect_stuff

# Update previous key with more tags
- aws_kms:
    alias: mykey
    tags:
      Name: myKey
      Purpose: protect_stuff
      Owner: security_team

# Update a known key with grants allowing an instance with the billing-prod IAM profile
# to decrypt data encrypted with the environment: production, application: billing
# encryption context
- aws_kms:
    key_id: abcd1234-abcd-1234-5678-ef1234567890
    grants:
      - name: billing_prod
        grantee_principal: arn:aws:iam::1234567890123:role/billing_prod
        constraints:
          encryption_context_equals:
            environment: production
            application: billing
        operations:
          - Decrypt
          - RetireGrant
'''

RETURN = '''
key_id:
  description: ID of key
  type: str
  returned: always
  sample: abcd1234-abcd-1234-5678-ef1234567890
key_arn:
  description: ARN of key
  type: str
  returned: always
  sample: arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890
key_state:
  description: The state of the key
  type: str
  returned: always
  sample: PendingDeletion
key_usage:
  description: The cryptographic operations for which you can use the key.
  type: str
  returned: always
  sample: ENCRYPT_DECRYPT
origin:
  description: The source of the key's key material. When this value is C(AWS_KMS),
    AWS KMS created the key material. When this value is C(EXTERNAL), the
    key material was imported or the CMK lacks key material.
  type: str
  returned: always
  sample: AWS_KMS
aws_account_id:
  description: The AWS Account ID that the key belongs to
  type: str
  returned: always
  sample: 1234567890123
creation_date:
  description: Date of creation of the key
  type: str
  returned: always
  sample: "2017-04-18T15:12:08.551000+10:00"
description:
  description: Description of the key
  type: str
  returned: always
  sample: "My Key for Protecting important stuff"
enabled:
  description: Whether the key is enabled. True if C(KeyState) is true.
  type: str
  returned: always
  sample: false
aliases:
  description: list of aliases associated with the key
  type: list
  returned: always
  sample:
    - aws/acm
    - aws/ebs
policies:
  description: list of policy documents for the keys. Empty when access is denied even if there are policies.
  type: list
  returned: always
  sample:
    Version: "2012-10-17"
    Id: "auto-ebs-2"
    Statement:
    - Sid: "Allow access through EBS for all principals in the account that are authorized to use EBS"
      Effect: "Allow"
      Principal:
        AWS: "*"
      Action:
      - "kms:Encrypt"
      - "kms:Decrypt"
      - "kms:ReEncrypt*"
      - "kms:GenerateDataKey*"
      - "kms:CreateGrant"
      - "kms:DescribeKey"
      Resource: "*"
      Condition:
        StringEquals:
          kms:CallerAccount: "111111111111"
          kms:ViaService: "ec2.ap-southeast-2.amazonaws.com"
    - Sid: "Allow direct access to key metadata to the account"
      Effect: "Allow"
      Principal:
        AWS: "arn:aws:iam::111111111111:root"
      Action:
      - "kms:Describe*"
      - "kms:Get*"
      - "kms:List*"
      - "kms:RevokeGrant"
      Resource: "*"
tags:
  description: dictionary of tags applied to the key
  type: dict
  returned: always
  sample:
    Name: myKey
    Purpose: protecting_stuff
grants:
  description: list of grants associated with a key
  type: complex
  returned: always
  contains:
    constraints:
      description: Constraints on the encryption context that the grant allows.
        See U(https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantConstraints.html) for further details
      type: dict
      returned: always
      sample:
        encryption_context_equals:
           "aws:lambda:_function_arn": "arn:aws:lambda:ap-southeast-2:012345678912:function:xyz"
    creation_date:
      description: Date of creation of the grant
      type: str
      returned: always
      sample: 2017-04-18T15:12:08+10:00
    grant_id:
      description: The unique ID for the grant
      type: str
      returned: always
      sample: abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234
    grantee_principal:
      description: The principal that receives the grant's permissions
      type: str
      returned: always
      sample: arn:aws:sts::0123456789012:assumed-role/lambda_xyz/xyz
    issuing_account:
      description: The AWS account under which the grant was issued
      type: str
      returned: always
      sample: arn:aws:iam::01234567890:root
    key_id:
      description: The key ARN to which the grant applies.
      type: str
      returned: always
      sample: arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890
    name:
      description: The friendly name that identifies the grant
      type: str
      returned: always
      sample: xyz
    operations:
      description: The list of operations permitted by the grant
      type: list
      returned: always
      sample:
        - Decrypt
        - RetireGrant
    retiring_principal:
      description: The principal that can retire the grant
      type: str
      returned: always
      sample: arn:aws:sts::0123456789012:assumed-role/lambda_xyz/xyz
changes_needed:
  description: grant types that would be changed/were changed.
  type: dict
  returned: always
  sample: { "role": "add", "role grant": "add" }
had_invalid_entries:
  description: there are invalid (non-ARN) entries in the KMS entry. These don't count as a change, but will be removed if any changes are being made.
  type: bool
  returned: always
'''

# these mappings are used to go from simple labels to the actual 'Sid' values returned
# by get_policy. They seem to be magic values.
statement_label = {
    'role': 'Allow use of the key',
    'role grant': 'Allow attachment of persistent resources',
    'admin': 'Allow access for Key Administrators'
}

from ansible.module_utils.aws.core import AnsibleAWSModule, is_boto3_error_code
from ansible.module_utils.ec2 import ec2_argument_spec
from ansible.module_utils.ec2 import AWSRetry, camel_dict_to_snake_dict
from ansible.module_utils.ec2 import boto3_tag_list_to_ansible_dict, ansible_dict_to_boto3_tag_list
from ansible.module_utils.ec2 import compare_aws_tags, compare_policies
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native

import traceback
import json

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

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def get_iam_roles_with_backoff(connection):
    paginator = connection.get_paginator('list_roles')
    return paginator.paginate().build_full_result()

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def get_kms_keys_with_backoff(connection):
    paginator = connection.get_paginator('list_keys')
    return paginator.paginate().build_full_result()

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def get_kms_aliases_with_backoff(connection):
    paginator = connection.get_paginator('list_aliases')
    return paginator.paginate().build_full_result()

def get_kms_aliases_lookup(connection):
    _aliases = dict()
    for alias in get_kms_aliases_with_backoff(connection)['Aliases']:
        # Not all aliases are actually associated with a key
        if 'TargetKeyId' in alias:
            # strip off leading 'alias/' and add it to key's aliases
            if alias['TargetKeyId'] in _aliases:
                _aliases[alias['TargetKeyId']].append(alias['AliasName'][6:])
            else:
                _aliases[alias['TargetKeyId']] = [alias['AliasName'][6:]]
    return _aliases

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def get_kms_tags_with_backoff(connection, key_id, **kwargs):
    return connection.list_resource_tags(KeyId=key_id, **kwargs)

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def get_kms_grants_with_backoff(connection, key_id):
    params = dict(KeyId=key_id)
    paginator = connection.get_paginator('list_grants')
    return paginator.paginate(**params).build_full_result()

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def get_kms_metadata_with_backoff(connection, key_id):
    return connection.describe_key(KeyId=key_id)

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def list_key_policies_with_backoff(connection, key_id):
    paginator = connection.get_paginator('list_key_policies')
    return paginator.paginate(KeyId=key_id).build_full_result()

@AWSRetry.backoff(tries=5, delay=5, backoff=2.0)
def get_key_policy_with_backoff(connection, key_id, policy_name):
    return connection.get_key_policy(KeyId=key_id, PolicyName=policy_name)

def get_kms_tags(connection, module, key_id):
    # Handle pagination here as list_resource_tags does not have
    # a paginator
    kwargs = {}
    tags = []
    more = True
    while more:
        try:
            tag_response = get_kms_tags_with_backoff(connection, key_id, **kwargs)
            tags.extend(tag_response['Tags'])
        except is_boto3_error_code('AccessDeniedException'):
            tag_response = {}
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:  # pylint: disable=duplicate-except
            module.fail_json_aws(e, msg="Failed to obtain key tags")
        if tag_response.get('NextMarker'):
            kwargs['Marker'] = tag_response['NextMarker']
        else:
            more = False
    return tags

def get_kms_policies(connection, module, key_id):
    try:
        policies = list_key_policies_with_backoff(connection, key_id)['PolicyNames']
        return [get_key_policy_with_backoff(connection, key_id, policy)['Policy'] for
                policy in policies]
    except is_boto3_error_code('AccessDeniedException'):
        return []
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:  # pylint: disable=duplicate-except
        module.fail_json_aws(e, msg="Failed to obtain key policies")

def key_matches_filter(key, filtr):
    if filtr[0] == 'key-id':
        return filtr[1] == key['key_id']
    if filtr[0] == 'tag-key':
        return filtr[1] in key['tags']
    if filtr[0] == 'tag-value':
        return filtr[1] in key['tags'].values()
    if filtr[0] == 'alias':
        return filtr[1] in key['aliases']
    if filtr[0].startswith('tag:'):
        return key['Tags'][filtr[0][4:]] == filtr[1]

def key_matches_filters(key, filters):
    if not filters:
        return True
    else:
        return all([key_matches_filter(key, filtr) for filtr in filters.items()])

def camel_to_snake_grant(grant):
    ''' camel_to_snake_grant snakifies everything except the encryption context '''
    constraints = grant.get('Constraints', {})
    result = camel_dict_to_snake_dict(grant)
    if 'EncryptionContextEquals' in constraints:
        result['constraints']['encryption_context_equals'] = constraints['EncryptionContextEquals']
    if 'EncryptionContextSubset' in constraints:
        result['constraints']['encryption_context_subset'] = constraints['EncryptionContextSubset']
    return result

def get_key_details(connection, module, key_id):
    try:
        result = get_kms_metadata_with_backoff(connection, key_id)['KeyMetadata']
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to obtain key metadata")
    result['KeyArn'] = result.pop('Arn')

    try:
        aliases = get_kms_aliases_lookup(connection)
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to obtain aliases")

    result['aliases'] = aliases.get(result['KeyId'], [])

    result = camel_dict_to_snake_dict(result)

    # grants and tags get snakified differently
    try:
        result['grants'] = [camel_to_snake_grant(grant) for grant in
                            get_kms_grants_with_backoff(connection, key_id)['Grants']]
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to obtain key grants")
    tags = get_kms_tags(connection, module, key_id)
    result['tags'] = boto3_tag_list_to_ansible_dict(tags, 'TagKey', 'TagValue')
    result['policies'] = get_kms_policies(connection, module, key_id)
    return result

def get_kms_facts(connection, module):
    try:
        keys = get_kms_keys_with_backoff(connection)['Keys']
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to obtain keys")

    return [get_key_details(connection, module, key['KeyId']) for key in keys]

def convert_grant_params(grant, key):
    grant_params = dict(KeyId=key['key_arn'],
                        GranteePrincipal=grant['grantee_principal'])
    if grant.get('operations'):
        grant_params['Operations'] = grant['operations']
    if grant.get('retiring_principal'):
        grant_params['RetiringPrincipal'] = grant['retiring_principal']
    if grant.get('name'):
        grant_params['Name'] = grant['name']
    if grant.get('constraints'):
        grant_params['Constraints'] = dict()
        if grant['constraints'].get('encryption_context_subset'):
            grant_params['Constraints']['EncryptionContextSubset'] = grant['constraints']['encryption_context_subset']
        if grant['constraints'].get('encryption_context_equals'):
            grant_params['Constraints']['EncryptionContextEquals'] = grant['constraints']['encryption_context_equals']
    return grant_params

def different_grant(existing_grant, desired_grant):
    if existing_grant.get('grantee_principal') != desired_grant.get('grantee_principal'):
        return True
    if existing_grant.get('retiring_principal') != desired_grant.get('retiring_principal'):
        return True
    if set(existing_grant.get('operations', [])) != set(desired_grant.get('operations')):
        return True
    if existing_grant.get('constraints') != desired_grant.get('constraints'):
        return True
    return False

def compare_grants(existing_grants, desired_grants, purge_grants=False):
    existing_dict = dict((eg['name'], eg) for eg in existing_grants)
    desired_dict = dict((dg['name'], dg) for dg in desired_grants)
    to_add_keys = set(desired_dict.keys()) - set(existing_dict.keys())
    if purge_grants:
        to_remove_keys = set(existing_dict.keys()) - set(desired_dict.keys())
    else:
        to_remove_keys = set()
    to_change_candidates = set(existing_dict.keys()) & set(desired_dict.keys())
    for candidate in to_change_candidates:
        if different_grant(existing_dict[candidate], desired_dict[candidate]):
            to_add_keys.add(candidate)
            to_remove_keys.add(candidate)

    to_add = []
    to_remove = []
    for key in to_add_keys:
        grant = desired_dict[key]
        to_add.append(grant)
    for key in to_remove_keys:
        grant = existing_dict[key]
        to_remove.append(grant)
    return to_add, to_remove

def ensure_enabled_disabled(connection, module, key):
    changed = False
    if key['key_state'] == 'Disabled' and module.params['enabled']:
        try:
            connection.enable_key(KeyId=key['key_arn'])
            changed = True
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Failed to enable key")

    if key['key_state'] == 'Enabled' and not module.params['enabled']:
        try:
            connection.disable_key(KeyId=key['key_arn'])
            changed = True
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Failed to disable key")
    return changed

def update_alias(connection, module, key_id, alias):
    if not alias.startswith('alias/'):
        alias = 'alias/' + alias
    aliases = get_kms_aliases_with_backoff(connection)['Aliases']
    if key_id:
        # We will only add new aliases, not rename existing ones
        if alias not in [_alias['AliasName'] for _alias in aliases]:
            try:
                connection.create_alias(KeyId=key_id, AliasName=alias)
                return True
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, msg="Failed create key alias")
    return False

def update_key(connection, module, key):
    changed = False
    alias = module.params.get('alias')
    key_id = key['key_arn']

    if alias:
        changed = update_alias(connection, module, key_id, alias) or changed

    if key['key_state'] == 'PendingDeletion':
        try:
            connection.cancel_key_deletion(KeyId=key_id)
            # key is disabled after deletion cancellation
            # set this so that ensure_enabled_disabled works correctly
            key['key_state'] = 'Disabled'
            changed = True
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Failed to cancel key deletion")

    changed = ensure_enabled_disabled(connection, module, key) or changed

    description = module.params.get('description')
    # don't update description if description is not set
    # (means you can't remove a description completely)
    if description and key['description'] != description:
        try:
            connection.update_key_description(KeyId=key_id, Description=description)
            changed = True
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Failed to update key description")

    desired_tags = module.params.get('tags')
    to_add, to_remove = compare_aws_tags(key['tags'], desired_tags,
                                         module.params.get('purge_tags'))
    if to_remove:
        try:
            connection.untag_resource(KeyId=key_id, TagKeys=to_remove)
            changed = True
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Unable to remove or update tag")
    if to_add:
        try:
            connection.tag_resource(KeyId=key_id,
                                    Tags=[{'TagKey': tag_key, 'TagValue': desired_tags[tag_key]}
                                          for tag_key in to_add])
            changed = True
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Unable to add tag to key")

    # Update existing policy before trying to tweak grants
    if module.params.get('policy'):
        policy = module.params.get('policy')
        try:
            keyret = connection.get_key_policy(KeyId=key_id, PolicyName='default')
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            # If we can't fetch the current policy assume we're making a change
            # Could occur if we have PutKeyPolicy without GetKeyPolicy
            original_policy = {}
        original_policy = json.loads(keyret['Policy'])
        try:
            new_policy = json.loads(policy)
        except ValueError as e:
            module.fail_json_aws(e, msg="Unable to parse new policy as JSON")
        if compare_policies(original_policy, new_policy):
            changed = True
            if not module.check_mode:
                try:
                    connection.put_key_policy(KeyId=key_id, PolicyName='default', Policy=policy)
                except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                    module.fail_json_aws(e, msg="Unable to update key policy")

    desired_grants = module.params.get('grants')
    existing_grants = key['grants']

    to_add, to_remove = compare_grants(existing_grants, desired_grants,
                                       module.params.get('purge_grants'))
    if to_remove:
        for grant in to_remove:
            try:
                connection.retire_grant(KeyId=key_id, GrantId=grant['grant_id'])
                changed = True
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, msg="Unable to retire grant")

    if to_add:
        for grant in to_add:
            grant_params = convert_grant_params(grant, key)
            try:
                connection.create_grant(**grant_params)
                changed = True
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, msg="Unable to create grant")

    # make results consistent with kms_facts before returning
    result = get_key_details(connection, module, key_id)
    module.exit_json(changed=changed, **result)

def create_key(connection, module):
    params = dict(BypassPolicyLockoutSafetyCheck=False,
                  Tags=ansible_dict_to_boto3_tag_list(module.params['tags'], tag_name_key_name='TagKey', tag_value_key_name='TagValue'),
                  KeyUsage='ENCRYPT_DECRYPT',
                  Origin='AWS_KMS')
    if module.params.get('description'):
        params['Description'] = module.params['description']
    if module.params.get('policy'):
        params['Policy'] = module.params['policy']

    try:
        result = connection.create_key(**params)['KeyMetadata']
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to create initial key")
    key = get_key_details(connection, module, result['KeyId'])

    alias = module.params['alias']
    if not alias.startswith('alias/'):
        alias = 'alias/' + alias
    try:
        connection.create_alias(AliasName=alias, TargetKeyId=key['key_id'])
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to create alias")

    ensure_enabled_disabled(connection, module, key)
    for grant in module.params.get('grants'):
        grant_params = convert_grant_params(grant, key)
        try:
            connection.create_grant(**grant_params)
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Failed to add grant to key")

    # make results consistent with kms_facts
    result = get_key_details(connection, module, key['key_id'])
    module.exit_json(changed=True, **result)

def delete_key(connection, module, key_metadata, key_id):
    changed = False

    if key_metadata['KeyState'] != 'PendingDeletion':
        try:
            connection.schedule_key_deletion(KeyId=key_id)
            changed = True
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            module.fail_json_aws(e, msg="Failed to schedule key for deletion")

    result = get_key_details(connection, module, key_id)
    module.exit_json(changed=changed, **result)

def get_arn_from_kms_alias(kms, aliasname):
    ret = kms.list_aliases()
    key_id = None
    for a in ret['Aliases']:
        if a['AliasName'] == aliasname:
            key_id = a['TargetKeyId']
            break
    if not key_id:
        raise Exception('could not find alias {0}'.format(aliasname))

    # now that we have the ID for the key, we need to get the key's ARN. The alias
    # has an ARN but we need the key itself.
    ret = kms.list_keys()
    for k in ret['Keys']:
        if k['KeyId'] == key_id:
            return k['KeyArn']
    raise Exception('could not find key from id: {0}'.format(key_id))

def get_arn_from_role_name(iam, rolename):
    ret = iam.get_role(RoleName=rolename)
    if ret.get('Role') and ret['Role'].get('Arn'):
        return ret['Role']['Arn']
    raise Exception('could not find arn for name {0}.'.format(rolename))

def do_policy_grant(module, kms, keyarn, role_arn, granttypes, mode='grant', dry_run=True, clean_invalid_entries=True):
    ret = {}
    keyret = get_key_policy_with_backoff(kms, keyarn, 'default')
    policy = json.loads(keyret['Policy'])

    changes_needed = {}
    assert_policy_shape(policy)
    had_invalid_entries = False
    for statement in policy['Statement']:
        for granttype in ['role', 'role grant', 'admin']:
            # do we want this grant type? Are we on its statement?
            # and does the role have this grant type?

            # create Principal and 'AWS' so we can safely use them later.
            if not isinstance(statement.get('Principal'), dict):
                statement['Principal'] = dict()

            if 'AWS' in statement['Principal'] and isinstance(statement['Principal']['AWS'], string_types):
                # convert to list
                statement['Principal']['AWS'] = [statement['Principal']['AWS']]
            if not isinstance(statement['Principal'].get('AWS'), list):
                statement['Principal']['AWS'] = list()

            if mode == 'grant' and statement['Sid'] == statement_label[granttype]:
                # we're granting and we recognize this statement ID.

                if granttype in granttypes:
                    invalid_entries = [item for item in statement['Principal']['AWS'] if not item.startswith('arn:aws:iam::')]
                    if clean_invalid_entries and invalid_entries:
                        # we have bad/invalid entries. These are roles that were deleted.
                        # prune the list.
                        valid_entries = [item for item in statement['Principal']['AWS'] if item.startswith('arn:aws:iam::')]
                        statement['Principal']['AWS'] = valid_entries
                        had_invalid_entries = True

                    if role_arn not in statement['Principal']['AWS']:  # needs to be added.
                        changes_needed[granttype] = 'add'
                        if not dry_run:
                            statement['Principal']['AWS'].append(role_arn)
                elif role_arn in statement['Principal']['AWS']:  # not one the places the role should be
                    changes_needed[granttype] = 'remove'
                    if not dry_run:
                        statement['Principal']['AWS'].remove(role_arn)

            elif mode == 'deny' and statement['Sid'] == statement_label[granttype] and role_arn in statement['Principal']['AWS']:
                # we don't selectively deny. that's a grant with a
                # smaller list. so deny=remove all of this arn.
                changes_needed[granttype] = 'remove'
                if not dry_run:
                    statement['Principal']['AWS'].remove(role_arn)

    try:
        if len(changes_needed) and not dry_run:
            policy_json_string = json.dumps(policy)
            kms.put_key_policy(KeyId=keyarn, PolicyName='default', Policy=policy_json_string)
            # returns nothing, so we have to just assume it didn't throw
            ret['changed'] = True
    except Exception as e:
        module.fail_json(msg='Could not update key_policy', new_policy=policy_json_string, details=to_native(e), exception=traceback.format_exc())
        raise

    ret['changes_needed'] = changes_needed
    ret['had_invalid_entries'] = had_invalid_entries
    ret['new_policy'] = policy
    if dry_run:
        # true if changes > 0
        ret['changed'] = len(changes_needed) > 0

    return ret

def assert_policy_shape(policy):
    '''Since the policy seems a little, uh, fragile, make sure we know approximately what we're looking at.'''
    errors = []
    if policy['Version'] != "2012-10-17":
        errors.append('Unknown version/date ({0}) of policy. Things are probably different than we assumed they were.'.format(policy['Version']))

    found_statement_type = {}
    for statement in policy['Statement']:
        for label, sidlabel in statement_label.items():
            if statement['Sid'] == sidlabel:
                found_statement_type[label] = True

    for statementtype in statement_label.keys():
        if not found_statement_type.get(statementtype):
            errors.append('Policy is missing {0}.'.format(statementtype))

    if len(errors):
        raise Exception('Problems asserting policy shape. Cowardly refusing to modify it: {0}'.format(' '.join(errors)) + "\n" + str(policy))
    return None

def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            alias=dict(aliases=['key_alias']),
            policy_mode=dict(aliases=['mode'], choices=['grant', 'deny'], default='grant'),
            policy_role_name=dict(aliases=['role_name']),
            policy_role_arn=dict(aliases=['role_arn']),
            policy_grant_types=dict(aliases=['grant_types'], type='list'),
            policy_clean_invalid_entries=dict(aliases=['clean_invalid_entries'], type='bool', default=True),
            key_id=dict(aliases=['key_arn']),
            description=dict(),
            enabled=dict(type='bool', default=True),
            tags=dict(type='dict', default={}),
            purge_tags=dict(type='bool', default=False),
            grants=dict(type='list', default=[]),
            policy=dict(),
            purge_grants=dict(type='bool', default=False),
            state=dict(default='present', choices=['present', 'absent']),
        )
    )

    module = AnsibleAWSModule(
        supports_check_mode=True,
        argument_spec=argument_spec,
        required_one_of=[['alias', 'key_id']],
    )

    result = {}
    mode = module.params['policy_mode']

    kms = module.client('kms')
    iam = module.client('iam')

    key_id = module.params.get('key_id')
    alias = module.params.get('alias')
    if alias and alias.startswith('alias/'):
        alias = alias[6:]

    # Fetch/Canonicalize key_id where possible
    if key_id:
        try:
            # Don't use get_key_details it triggers module.fail when the key
            # doesn't exist
            key_metadata = get_kms_metadata_with_backoff(kms, key_id)['KeyMetadata']
            key_id = key_metadata['Arn']
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            # We can't create keys with a specific ID, if we can't access the
            # key we'll have to fail
            if module.params.get('state') == 'present':
                module.fail_json(msg="Could not find key with id %s to update")
            key_metadata = None
    elif alias:
        try:
            key_metadata = get_kms_metadata_with_backoff(kms, 'alias/%s' % alias)['KeyMetadata']
            key_id = key_metadata['Arn']
        except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
            key_metadata = None

    if module.params.get('policy_grant_types') or mode == 'deny':
        module.deprecate('Managing the KMS IAM Policy via policy_mode and policy_grant_types is fragile'
                         ' and has been deprecated in favour of the policy option.', version='2.13')
        if module.params.get('policy_role_name') and not module.params.get('policy_role_arn'):
            module.params['policy_role_arn'] = get_arn_from_role_name(iam, module.params['policy_role_name'])
        if not module.params.get('policy_role_arn'):
            module.fail_json(msg='policy_role_arn or policy_role_name is required to {0}'.format(module.params['policy_mode']))

        # check the grant types for 'grant' only.
        if mode == 'grant':
            for g in module.params['policy_grant_types']:
                if g not in statement_label:
                    module.fail_json(msg='{0} is an unknown grant type.'.format(g))

        ret = do_policy_grant(module, kms,
                              key_id,
                              module.params['policy_role_arn'],
                              module.params['policy_grant_types'],
                              mode=mode,
                              dry_run=module.check_mode,
                              clean_invalid_entries=module.params['policy_clean_invalid_entries'])
        result.update(ret)

        module.exit_json(**result)

    else:
        if module.params.get('state') == 'present':
            if key_metadata:
                key_details = get_key_details(kms, module, key_id)
                update_key(kms, module, key_details)
            else:
                if key_id:
                    module.fail_json(msg="Could not find key with id %s to update" % key_id)
                else:
                    create_key(kms, module)
        else:
            if key_metadata:
                delete_key(kms, module, key_metadata, key_id)
            else:
                module.exit_json(changed=False)

if __name__ == '__main__':
    main()


text:
package com.gemstone.gemfire.cache.query.functional;

import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.query.CacheUtils;
import com.gemstone.gemfire.cache.query.Index;
import com.gemstone.gemfire.cache.query.IndexType;
import com.gemstone.gemfire.cache.query.Query;
import com.gemstone.gemfire.cache.query.QueryService;
import com.gemstone.gemfire.cache.query.SelectResults;
import com.gemstone.gemfire.cache.query.Struct;
import com.gemstone.gemfire.cache.query.Utils;
import com.gemstone.gemfire.cache.query.data.Portfolio;
import com.gemstone.gemfire.cache.query.data.Position;
import com.gemstone.gemfire.cache.query.internal.QueryObserverAdapter;
import com.gemstone.gemfire.cache.query.internal.QueryObserverHolder;
import com.gemstone.gemfire.cache.query.types.StructType;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;

/**
 * IUM6Bug32345ReJUnitTest.java
 *
 * Created on May 5, 2005, 10:32 AM
 */
@Category(IntegrationTest.class)
public class IUM6Bug32345ReJUnitTest{
  StructType resType1=null;
  StructType resType2= null;

  String[] strg1 = null;
  String[] strg2= null;

  int resSize1=0;
  int resSize2=0;

  Object valPf1=null;
  Object valPos1=null;

  Object valPf2=null;
  Object valPos2=null;

  Iterator itert1=null;
  Iterator itert2=null;

  Set set1=null;
  Set set2=null;

  boolean isActive1=false;
  boolean isActive2=false;

  @Before
  public void setUp() throws java.lang.Exception {
    CacheUtils.startCache();
  }

  @After
  public void tearDown() throws java.lang.Exception {
    CacheUtils.closeCache();
  }

  @Test
  public void testComparisonBetnWithAndWithoutIndexCreation() throws Exception {

    Region region = CacheUtils.createRegion("pos", Portfolio.class);
    for(int i=0;i<4;i++){
      region.put(""+i, new Portfolio(i));
    }
    QueryService qs;
    qs = CacheUtils.getQueryService();
    String queries[] = {
        "SELECT DISTINCT * FROM /pos pf,  positions.values pos where pf.status='active' and pos.secId= 'IBM' and ID = 0"
    };
    SelectResults sr[][] = new SelectResults[queries.length][2];
    for (int i = 0; i < queries.length; i++) {
      Query q = null;
      try {
        q = CacheUtils.getQueryService().newQuery(queries[i]);
        QueryObserverImpl observer = new QueryObserverImpl();
        QueryObserverHolder.setInstance(observer);
        sr[i][0] =(SelectResults) q.execute();
        if(!observer.isIndexesUsed){
          CacheUtils.log("NO INDEX USED");
        }
        CacheUtils.log(Utils.printResult(sr[i][0]));
        resType1 =(StructType)(sr[i][0]).getCollectionType().getElementType();
        resSize1 =((sr[i][0]).size());

        strg1=resType1.getFieldNames();

        set1=((sr[i][0]).asSet());
        Iterator iter=set1.iterator();
        while (iter.hasNext()){
          Struct stc1=(Struct)iter.next();
          valPf1=stc1.get(strg1[0]);
          valPos1=stc1.get(strg1[1]);
          isActive1=((Portfolio)stc1.get(strg1[0])).isActive();

        }
      }
      catch (Exception e) {
        e.printStackTrace();
        fail(q.getQueryString());
      }
    }

    //  Create an Index on status and execute the same query again.

    qs = CacheUtils.getQueryService();
    qs.createIndex("statusIndex", IndexType.FUNCTIONAL,"pf.status","/pos pf, pf.positions.values pos");
    //Retesting BUG # 32345
    //Index index2 = (Index)qs.createIndex("secIdIndex", IndexType.FUNCTIONAL,"pos.secId","/pos pf, pf.positions.values pos");
    qs.createIndex("IDIndex", IndexType.FUNCTIONAL,"pf.ID","/pos pf, pf.positions.values pos");
    String queries2[] = {
        "SELECT DISTINCT * FROM /pos pf,  positions.values pos where pf.status='active' and pos.secId= 'IBM' and ID = 0"
    };
    for (int i = 0; i < queries.length; i++) {
      Query q = null;
      try {
        q = CacheUtils.getQueryService().newQuery(queries[i]);
        QueryObserverImpl observer2 = new QueryObserverImpl();
        QueryObserverHolder.setInstance(observer2);
        sr[i][1] = (SelectResults)q.execute();
        if(observer2.isIndexesUsed){
          CacheUtils.log("YES INDEX IS USED!");
        }
        else {
          fail("Index NOT Used");
        }
        CacheUtils.log(Utils.printResult(sr[i][1]));
        resType2 =(StructType)(sr[i][1]).getCollectionType().getElementType();
        resSize2 =((sr[i][1]).size());
        //         CacheUtils.log(resType2);
        strg2=resType2.getFieldNames();
        //         CacheUtils.log(strg2[0]);
        //         CacheUtils.log(strg2[1]);

        set2=((sr[i][1]).asSet());
        Iterator iter=set2.iterator();
        while (iter.hasNext()){
          Struct stc2=(Struct)iter.next();
          valPf2=stc2.get(strg2[0]);
          valPos2=stc2.get(strg2[1]);
          isActive2=((Portfolio)stc2.get(strg2[0])).isActive();
          //        CacheUtils.log(valPf2);
          //        CacheUtils.log(valPos2);
        }
      }
      catch (Exception e) {
        e.printStackTrace();
        fail(q.getQueryString());
      }
    }

    if ((resType1).equals(resType2)){
      CacheUtils.log("Both Search Results are of the same Type i.e.--> "+resType1);
    }else {
      fail("FAILED:Search result Type is different in both the cases");
    }
    if (resSize1==resSize2 || resSize1 != 0){
      CacheUtils.log("Both Search Results are Non-zero and are of Same Size i.e.  Size= "+resSize1);
    }else {
      fail("FAILED:Search result Type is different in both the cases");
    }
    itert2 = set2.iterator();
    itert1 = set1.iterator();
    while (itert1.hasNext()){
      Struct stc2=(Struct)itert2.next();
      Struct stc1 = (Struct)itert1.next();
      if( stc2.get(strg2[0]) != stc1.get(strg1[0])  )
        fail("FAILED: In both the Cases the first member of StructSet i.e. Portfolio are different. ");
      if(stc2.get(strg2[1]) != stc1.get(strg1[1]))
        fail("FAILED: In both the cases Positions are different");
      if(((Position)stc2.get(strg2[1])).secId != ((Position)stc1.get(strg1[1])).secId)
        fail("FAILED: In both the cases Positions secIds are different");
      if (((Portfolio)stc2.get(strg2[0])).isActive() != ((Portfolio)stc1.get(strg1[0])).isActive() )
        fail("FAILED: Status of the Portfolios found are different");
      if (((Portfolio)stc2.get(strg2[0])).getID() != ((Portfolio)stc1.get(strg1[0])).getID() )
        fail("FAILED: IDs of the Portfolios found are different");
    }
    CacheUtils.compareResultsOfWithAndWithoutIndex(sr, this);
  }

  class QueryObserverImpl extends QueryObserverAdapter{
    boolean isIndexesUsed = false;
    ArrayList indexesUsed = new ArrayList();

    public void beforeIndexLookup(Index index, int oper, Object key) {
      indexesUsed.add(index.getName());
    }

    public void afterIndexLookup(Collection results) {
      if(results != null){
        isIndexesUsed = true;
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.deltaspike.test.jsf.impl.config.view.navigation.parameter.uc003;

import javax.enterprise.inject.Model;

import org.apache.deltaspike.core.api.config.view.ViewConfig;
import org.apache.deltaspike.core.api.config.view.navigation.NavigationParameter;

@Model
public class PageBean003
{
    private int nextValue = 0;

    @NavigationParameter(key = "param1", value = "#{pageBean003.nextValue}")
    public Class<? extends ViewConfig> actionMethod()
    {
        this.nextValue++;
        return SimplePageConfig.class;
    }

    public int getNextValue()
    {
        return nextValue;
    }
}


text:
package leap.web.security.csrf;

public class MissingCsrfTokenException extends CsrfException {

	private static final long serialVersionUID = -1668214193248419206L;

	public MissingCsrfTokenException() {

	}

	public MissingCsrfTokenException(String s) {
		super(s);
	}

	public MissingCsrfTokenException(Throwable cause) {
		super(cause);
	}

	public MissingCsrfTokenException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
**This directory is not required, you can delete it if you don't want to use it.**

This directory contains your static files.
Each file inside this directory is mapped to `/`.
Thus you'd want to delete this README.md before deploying to production.

Example: `/static/robots.txt` is mapped as `/robots.txt`.

More information about the usage of this directory in [the documentation](https://nuxtjs.org/guide/assets#static).


text:
* Ruby version

* System dependencies

* Configuration --> config/application.yml

* Database creation

* Database initialization

* How to run the test suite

* Services (job queues, cache servers, search engines, etc.)

* Deployment instructions

1. pull github repository
2. run bundle install
3. create config/application.yml ad add the following settings:

	# SMTP SERVER SETTINGS
	EMAIL_USERNAME:
	EMAIL_PASSWORD:
	EMAIL_SERVER_ADRESS:

	# Database settings
	UBERSPACE_MYSQL_USER:
	UBERSPACE_MYSQL_PASSWORD:
	UBERSPACE_MYSQL_DATABASE:

	#MAILAGENT_DEBUG_MODE: # if wanted
	MAILAGENT_DEBUG_MAIL_ADDRESS:
	MAILAGENT_ADMIN_MAIL_ADDRESS:

	MAILAGENT_ADDRESS:
	DEFAULT_FROM_MAIL_ADDRESS:
	MAILAGENT_BASE_URL:

	SECRET_TOKEN:

4. create database that has been set up
5. adapt mailagent/script/mail_receiver.rb to target domain
6. mailserver incoming mail forward to mailagent/script/mail_receiver.rb
7. copy mailagent/script/mailagent into fcgi path and adapt it
8. run rake db:migrate RAILS_ENV='production'
9. run rake assets:precompile and copy asset folder if necessary to public html folder
10. run application

Changelog

- mail: reply field verteiler address
- recipients as bcc
- attachements work well
- ensure that incomingmessage is only available from same host
- if empty send no lists error
- user import
- list#show: remove user,
- add no of users to lists overview
- Gemfile add versions and divide by environments!!
- list recognition only from [] and case insensitive separated by , | \s
- remove old lists mailer
- redirect to dashboard
- xls export für liste improve: filename
- removed mail content completely
- favicon
- bug melden funktion
- exclude message param from log
- set mail status pending and then OK when received a second time!!
- dashboard
- migrate to bootstrap 3.0
- new menu bar
- confirmation for subscription delete added
- show active page in menu as active
- clean subscriptions pages
- bug when creating new user with list solved
- downcase all email inputs
- removed all unused routes for ressources
- add no of recipients to email
- clean, explain and improve import functionality
- VERIFIED: test capital letters in emails
- VERIFIED: render message for curl and save this to curl log
- users in alphabetical order
- lists and subscriptions in alphabetical order
- bug with sorting and included models fixed
- reply_to field removed
- strip emails before save
- CSV import corrected

# VERIFY THAT IT WORKS

- all translations are there

# TODO:

- warn when admin created that email and password is send out
- implement authentication with gem device to implement auto end session and stuff
- add more roles for selective lists

## To make it nicer
- tooltips
- dashboard highcharts

License
-------

Mailagent is licensed under the MIT license. See [LICENSE](LICENSE) for details.


text:
package com.bansal.mobile.base;

import android.content.Intent;

import android.os.Bundle;

import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import android.support.v7.app.AppCompatActivity;

import butterknife.ButterKnife;

abstract class BaseActivity extends AppCompatActivity implements FragmentController {

    @LayoutRes
    protected abstract Integer getLayoutId();

    @IdRes
    protected abstract Integer getContainerId();

    protected abstract Fragment getContentFragment();

    protected void initFromBundle(@NonNull final Intent bundle) { }

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getLayoutId() == null) {
            throw new NullPointerException("Please Provide a valid layout resource!");
        }

        // FragmentArgs.inject(this); // read @Arg fields

        // Activity must extract all fields from bundle in order to delegate to Root Fragment
        if (getIntent() != null) {
            initFromBundle(getIntent());
        }

        setContentView(getLayoutId());

        // It's important to inject view after setting content layout
        ButterKnife.bind(this);

        if (savedInstanceState == null) {
            setContentFragment(getContentFragment(), false);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    @Override
    public void addFragmentToRootContainer(@NonNull final Fragment fragment) {
        setContentFragment(fragment, true);
    }

    @Override
    public void replaceRootContainerFragment(@NonNull final Fragment fragment) {
        setContentFragment(fragment, false);
    }

    protected void setContentFragment(@NonNull final Fragment fragment, final boolean isStack) {

        if (fragment == null) {
            throw new IllegalArgumentException("Fragment instance cannot be null");
        }

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        final String fragmentTag = fragment.getClass().getSimpleName();
        fragmentTransaction.replace(getContainerId(), fragment, fragmentTag);

        if (isStack) {
            fragmentTransaction.addToBackStack(fragmentTag);
        }

        fragmentTransaction.commit();
    }
}


text:
package org.locationtech.geomesa.convert.json

import com.google.gson.JsonElement
import com.typesafe.config.{Config, ConfigValueFactory}
import com.typesafe.scalalogging.LazyLogging
import org.locationtech.geomesa.convert2.AbstractConverter.BasicOptions
import org.locationtech.geomesa.convert2.transforms.Predicate
import org.locationtech.geomesa.convert2.{AbstractConverterFactory, ParsingConverter, SimpleFeatureConverter, SimpleFeatureConverterFactory}
import org.opengis.feature.simple.SimpleFeatureType
import pureconfig.ConfigConvert

import scala.util.control.NonFatal

class JsonCompositeConverterFactory extends SimpleFeatureConverterFactory with LazyLogging {

  import JsonCompositeConverterFactory.TypeToProcess

  import scala.collection.JavaConverters._

  override def apply(sft: SimpleFeatureType, conf: Config): Option[SimpleFeatureConverter] = {
    if (!conf.hasPath("type") || conf.getString("type") != TypeToProcess) { None } else {
      val defaults = AbstractConverterFactory.standardDefaults(conf, logger)
      try {
        implicit val convert: ConfigConvert[BasicOptions] = AbstractConverterFactory.BasicOptionsConvert
        val options = pureconfig.loadConfigOrThrow[BasicOptions](defaults)
        val typeToProcess = ConfigValueFactory.fromAnyRef(JsonConverterFactory.TypeToProcess)
        val delegates = defaults.getConfigList("converters").asScala.map { base =>
          val conf = base.withFallback(defaults).withValue("type", typeToProcess)
          val converter = SimpleFeatureConverter(sft, conf) match {
            case c: ParsingConverter[JsonElement] => c
            case c => throw new IllegalArgumentException(s"Expected JsonConverter but got: $c")
          }
          val predicate = Predicate(conf.getString("predicate"))
          (predicate, converter)
        }
        Some(new JsonCompositeConverter(sft, options.encoding, options.errorMode, delegates.toSeq))
      } catch {
        case NonFatal(e) => throw new IllegalArgumentException(s"Invalid configuration: ${e.getMessage}")
      }
    }
  }
}

object JsonCompositeConverterFactory {
  val TypeToProcess = "composite-json"
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.ClientStack;
using OpenSim.Region.ClientStack.LindenUDP;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;

namespace OpenSim.Client.Linden
{
    public class LLClientStackModule : IRegionModule
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        #region IRegionModule Members

        protected Scene m_scene;
        protected bool m_createClientStack = false;
        protected IClientNetworkServer m_clientServer;
        protected ClientStackManager m_clientStackManager;
        protected IConfigSource m_source;

        protected string m_clientStackDll = "OpenSim.Region.ClientStack.LindenUDP.dll";

        public void Initialise(Scene scene, IConfigSource source)
        {
            if (m_scene == null)
            {
                m_scene = scene;
                m_source = source;

                IConfig startupConfig = m_source.Configs["Startup"];
                if (startupConfig != null)
                {
                    m_clientStackDll = startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
                }
            }
        }

        public void PostInitialise()
        {
            if ((m_scene != null) && (m_createClientStack))
            {
                m_log.Info("[LLClientStackModule] Starting up LLClientStack.");
                IPEndPoint endPoint = m_scene.RegionInfo.InternalEndPoint;

                uint port = (uint)endPoint.Port;
                m_clientStackManager = new ClientStackManager(m_clientStackDll);

                m_clientServer
                   = m_clientStackManager.CreateServer(endPoint.Address,
                     ref port, m_scene.RegionInfo.ProxyOffset, m_scene.RegionInfo.m_allow_alternate_ports, m_source,
                       m_scene.CommsManager.AssetCache);

                m_clientServer.AddScene(m_scene);

                m_clientServer.Start();
            }
        }

        public void Close()
        {

        }

        public string Name
        {
            get { return "LLClientStackModule"; }
        }

        public bool IsSharedModule
        {
            get { return false; }
        }

        #endregion
    }
}


text:
title: Talks that Last
description: |
  This is a list for your talks, workshops, or other events with a time, date, and place.
author: "The R Markdown Team @RStudio"
show_post_thumbnail: true
show_author_byline: true
show_post_date: true
show_post_time: true
show_button_links: true
# for listing page layout
layout: list # list, list-sidebar

# for list-sidebar layout
sidebar:
  title: Talks that Last
  description: |
    This is a list for your talks, workshops, or
    other events with a time, date, and place.
    Even this sidebar offers a ton of customizations.

    Check out the _index.md file in the /talk folder
    to edit this content.
  author: "The R Markdown Team @RStudio"
  text_link_label: Subscribe via RSS
  text_link_url: /talk/index.xml
  show_sidebar_adunit: false # show ad container

# set up common front matter for all pages inside blog/
cascade:
  author: "The R Markdown Team @RStudio"
  show_author_byline: true
  show_post_date: true
  show_post_time: true
  show_comments: false # see site config to choose Disqus or Utterances
  # for single-sidebar layout
  sidebar:
    text_link_label: View recent talks
    text_link_url: /talk/
    show_sidebar_adunit: false # show ad container
---

** No content below YAML for the talk _index. This file provides front matter for the listing page layout and sidebar content. It is also a branch bundle, and all settings under `cascade` provide front matter for all pages inside talk/. You may still override any of these by changing them in a page's front matter.**


text:
use core::mem;

use paging::{ActivePageTable, VirtualAddress};

pub mod exception;
pub mod ipi;
pub mod irq;
pub mod syscall;

/// Clear interrupts
#[inline(always)]
pub unsafe fn disable() {
    asm!("cli" : : : : "intel", "volatile");
}

/// Set interrupts
#[inline(always)]
pub unsafe fn enable() {
    asm!("sti" : : : : "intel", "volatile");
}

/// Set interrupts and halt
/// This will atomically wait for the next interrupt
/// Performing enable followed by halt is not guaranteed to be atomic, use this instead!
#[inline(always)]
pub unsafe fn enable_and_halt() {
    asm!("sti
        hlt"
        : : : : "intel", "volatile");
}

/// Set interrupts and nop
/// This will enable interrupts and allow the IF flag to be processed
/// Simply enabling interrupts does not gurantee that they will trigger, use this instead!
#[inline(always)]
pub unsafe fn enable_and_nop() {
    asm!("sti
        nop"
        : : : : "intel", "volatile");
}

/// Halt instruction
#[inline(always)]
pub unsafe fn halt() {
    asm!("hlt" : : : : "intel", "volatile");
}

/// Pause instruction
/// Safe because it is similar to a NOP, and has no memory effects
#[inline(always)]
pub fn pause() {
    unsafe { asm!("pause" : : : : "intel", "volatile"); }
}

/// Get a stack trace
//TODO: Check for stack being mapped before dereferencing
#[inline(never)]
pub unsafe fn stack_trace() {
    let mut rbp: usize;
    asm!("" : "={rbp}"(rbp) : : : "intel", "volatile");

    println!("TRACE: {:>016X}", rbp);
    //Maximum 64 frames
    let active_table = ActivePageTable::new();
    for _frame in 0..64 {
        if let Some(rip_rbp) = rbp.checked_add(mem::size_of::<usize>()) {
            if active_table.translate(VirtualAddress::new(rbp)).is_some() && active_table.translate(VirtualAddress::new(rip_rbp)).is_some() {
                let rip = *(rip_rbp as *const usize);
                if rip == 0 {
                    println!(" {:>016X}: EMPTY RETURN", rbp);
                    break;
                }
                println!("  {:>016X}: {:>016X}", rbp, rip);
                rbp = *(rbp as *const usize);
            } else {
                println!("  {:>016X}: GUARD PAGE", rbp);
                break;
            }
        } else {
            println!("  {:>016X}: RBP OVERFLOW", rbp);
        }
    }
}


text:
(function() {
	'use strict';
	angular.module('auth.controllers')
	.controller('LoginCtrl', ['$scope', 'Auth', function($scope, Auth) {
		var vm = this;
		vm.login = login;
		function login() {
			Auth.login(vm.email, vm.password);
		}

	}]);

})();


text:
  <?= form_open('Sistemactrl/actualizarAlm','',array('id' =>$almacen[0]['id'] ))?>

Nuevo Almacen

    <input type="text" name="nombre" id="nombre" value="<?=$almacen[0]['nombre']?>" required>
    Nombre:

    <textarea name="ubicacion" id="ubicacion" class="materialize-textarea" rows="4" cols="40" ><?=str_replace('
','',$almacen[0]['ubicacion'])?></textarea>

    Ubicacion:

    <?= form_submit('submitGua','Guardar','class="col s6 btn waves-effect green darken-3"')?>
    <button type="button" name="button" class="col s6 btn waves-effect red lighten-1" onclick="cerrarVentana()">Cancelar</button>

  <?= form_close()?>


text:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

"""
# default
engine = create_engine('mysql://scott:tiger@localhost/foo')

# mysql-python
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')

# MySQL-connector-python
engine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo')

# OurSQL
engine = create_engine('mysql+oursql://scott:tiger@localhost/foo')

For more details, please visit:
    http://docs.sqlalchemy.org/en/latest/core/engines.html?highlight=create_engine

"""

engine = create_engine('mysql+pymysql://username:password@localhost:3306/database')

Session = sessionmaker(bind=engine, autocommit=True)

db = Session()
Base = declarative_base()

class CRUDMixin(object):
    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)

    def update(self):
        """Saves the object to the database."""
        db.commit()
        return self

    def save(self):
        """Saves the object to the database."""
        db.add(self)
        db.commit()
        return self

    def delete(self):
        """Delete the object from the database."""
        db.delete(self)
        db.commit()
        return self

    @classmethod
    def clear(cls):
        """Delete all datas form database"""
        db.query(cls).delete()
        db.commit()

class Transaction(object):
    """get a connection and do something in transaction"""
    global db

    def __enter__(self):
        db.autocommit = False
        return db

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            db.rollback()
            print(u"事务执行失败,回滚")
        else:
            db.commit()
            print(u"事务执行成功,提交")


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingLeft="25dip"
        android:paddingTop="5dip">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/rowkey"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/entityPropertyRowKeyValue"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/entityPropertiesListRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            android:paddingTop="5dip"
            android:scrollbars="vertical"
            tools:context=".MainActivity" />

    </LinearLayout>
</ScrollView>


text:
namespace gp::utility {
    //describes error type of the TypeInfo
    struct error{};
    //describes any type of TypeInfo (this is used in the PrognNode because PrognNode takes any types of chlid)
    struct any{};

    template <typename T>
    class TypeInfoImpl;

    class TypeInfo {
    private:
        friend class StringToType;
        virtual void setName(const std::string&) = 0;
    public:
        virtual std::string name()const = 0;
    public://expect singleton
        bool operator==(const TypeInfo& other) const {return this == &other;}
        bool operator!=(const TypeInfo& other) const {return !(*this == other);}
        virtual bool isAnyType()const noexcept {return false;}
        virtual bool isErrorType()const noexcept {return false;}
        virtual bool isReferenceType()const noexcept {return false;}
        virtual bool isLeftHandValueType()const noexcept {return false;}
        virtual const TypeInfo& removeReferenceType()const noexcept {return *this;}
        virtual const TypeInfo& removeLeftHandValueType()const noexcept {return *this;}
    private:
        template <typename T> friend class TypeInfoImpl;
        TypeInfo() = default;
    };

    template <typename T>
    class TypeInfoImpl: public TypeInfo {
    private:
        static std::string name_;
    private:
        void setName(const std::string& str)override {name_ = str;}
    public:
        std::string name()const override {return name_;}
        bool isAnyType()const noexcept override {return std::is_same_v<T, any>;}
        bool isErrorType()const noexcept override {return std::is_same_v<T, error>;}
    public:
        TypeInfoImpl(const TypeInfoImpl&) = delete;
        TypeInfoImpl(TypeInfoImpl&&) = delete;
        TypeInfoImpl& operator=(const TypeInfoImpl&) = delete;
        TypeInfoImpl& operator=(TypeInfoImpl&&) = delete;
    private:// singleton
        TypeInfoImpl() = default;
        ~TypeInfoImpl() = default;
    public:
        static TypeInfo& get(){
            static TypeInfoImpl type;
            return type;
        }
    };

    template <typename T>
    std::string TypeInfoImpl<T>::name_ = typeid(T).name();

    template <typename T>
    class TypeInfoImpl<Reference<T>>: public TypeInfo {
    private:
        static std::string name_;
    private:
        void setName(const std::string& str)override {name_ = str;}
    public:
        std::string name()const override {return name_;}
    public:
        TypeInfoImpl(const TypeInfoImpl&) = delete;
        TypeInfoImpl(TypeInfoImpl&&) = delete;
        TypeInfoImpl& operator=(const TypeInfoImpl&) = delete;
        TypeInfoImpl& operator=(TypeInfoImpl&&) = delete;
    private:// singleton
        TypeInfoImpl() = default;
        ~TypeInfoImpl() = default;
    public:
        bool isReferenceType()const noexcept override {return true;}
        const TypeInfo& removeReferenceType()const noexcept override {return TypeInfoImpl<T>::get();}
        static TypeInfo& get(){
            static TypeInfoImpl type;
            return type;
        }
    };

    template <typename T>
    std::string TypeInfoImpl<Reference<T>>::name_ = typeid(Reference<T>).name();

    template <typename T>
    class TypeInfoImpl<LeftHandValue<T>>: public TypeInfo {
    private:
        static std::string name_;
    private:
        void setName(const std::string& str)override {name_ = str;}
    public:
        std::string name()const override {return name_;}
    public:
        TypeInfoImpl(const TypeInfoImpl&) = delete;
        TypeInfoImpl(TypeInfoImpl&&) = delete;
        TypeInfoImpl& operator=(const TypeInfoImpl&) = delete;
        TypeInfoImpl& operator=(TypeInfoImpl&&) = delete;
    private:// singleton
        TypeInfoImpl() = default;
        ~TypeInfoImpl() = default;
    public:
        bool isLeftHandValueType()const noexcept override {return true;}
        const TypeInfo& removeLeftHandValueType()const noexcept override {return TypeInfoImpl<T>::get();}
        static TypeInfo& get(){
            static TypeInfoImpl type;
            return type;
        }
    };

    template <typename T>
    std::string TypeInfoImpl<LeftHandValue<T>>::name_ = typeid(Reference<T>).name();

    class TypeIndex {
    private:
        const TypeInfo& type;
    public:
        bool operator==(const TypeIndex& other)const {return type == other.type;}
        bool operator!=(const TypeIndex& other)const {return type != other.type;}
        TypeIndex(const TypeInfo& type_): type(type_){}
    public://hash function
        struct Hash {
            std::size_t operator()(const TypeIndex& key)const {return std::hash<const TypeInfo*>()(&key.type);}
        };
    };

    template <typename T>
    const TypeInfo& typeInfo(){
        return TypeInfoImpl<T>::get();
    }

    class StringToType {
    public:
        using Type = const TypeInfo&;
        using KeyType = std::string;
        using HoldingType = const TypeInfo*;
        using ContainerType = std::unordered_map<KeyType, HoldingType>;
    private:
        ContainerType container;
    public:
        template <typename String>
        Type operator()(String&& name)const {return *container.find(std::forward<String>(name))->second;}
        template <typename String>
        bool hasType(String&& name)const {return container.find(std::forward<String>(name)) != std::end(container);}
        template <typename T, typename String>
        void setTypeNamePair(String&& name) {
            auto& type = TypeInfoImpl<T>::get();
            for(auto itr = std::begin(container); itr != std::end(container); ++itr){
                if(*itr->second == type){
                    container.erase(itr);
                    break;
                }
            }
            type.setName(name);
            container[name] = &type;
        }
    };
}

#endif


text:
using System.IO;

namespace UnrealBuildTool.Rules
{
	using System.IO;

	public class LogiLed : ModuleRules
	{
		public LogiLed(ReadOnlyTargetRules Target) : base(Target)
		{
			PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

			PrivateDependencyModuleNames.AddRange(
				new string[] {
					"Core",
					"CoreUObject",
					"Engine",
				});

			PrivateIncludePaths.AddRange(
				new string[] {
					"LogiLed/Private",
					"LogiLed/Private/Assets",
				});

			if (Target.bBuildEditor)
			{
				PrivateDependencyModuleNames.Add("UnrealEd");
			}

			// add Logitech SDK libraries
			string LogiDir = Path.GetFullPath(Path.Combine(ModuleDirectory, "..", "..", "ThirdParty"));
			string LibDir = Path.Combine(LogiDir, "lib");

			PrivateIncludePaths.Add(Path.Combine(LogiDir, "include"));

			if (Target.Platform == UnrealTargetPlatform.Win32)
			{
				PublicLibraryPaths.Add(Path.Combine(LibDir, "x86"));
				PublicAdditionalLibraries.Add("LogitechLEDLib.lib");
			}
			else if (Target.Platform == UnrealTargetPlatform.Win64)
			{
				PublicLibraryPaths.Add(Path.Combine(LibDir, "x64"));
				PublicAdditionalLibraries.Add("LogitechLEDLib.lib");
			}
			else
			{
				System.Console.WriteLine("Logitech SDK does not support this platform");
			}
		}
	}
}


text:
<idea-plugin>
  <extensionPoints>
    <extensionPoint name="pushSupport"
                    interface="com.intellij.dvcs.push.PushSupport" area="IDEA_PROJECT"/>
    <extensionPoint name="cherryPicker"
                    interface="com.intellij.dvcs.cherrypick.VcsCherryPicker" area="IDEA_PROJECT"/>
    <extensionPoint name="vcsRepositoryCreator" interface="com.intellij.dvcs.repo.VcsRepositoryCreator" area="IDEA_PROJECT"/>

    <extensionPoint name="prePushHandler" interface="com.intellij.dvcs.push.PrePushHandler" area="IDEA_PROJECT"/>

  </extensionPoints>
  <actions>
    <action id="Vcs.CherryPick" class="com.intellij.dvcs.cherrypick.VcsCherryPickAction" icon="DvcsImplIcons.CherryPick"/>
    <action id="Vcs.Push" class="com.intellij.dvcs.push.VcsPushAction" icon="AllIcons.Vcs.Push" text="Push...">
      <keyboard-shortcut first-keystroke="control shift K" keymap="$default"/>
    </action>
    <group id="Dvcs.Log.ContextMenu">
      <separator/>
      <reference id="Vcs.CherryPick"/>
      <add-to-group group-id="Vcs.Log.ContextMenu"/>
    </group>

    <group id="Dvcs.Log.Toolbar">
      <reference id="Vcs.CherryPick"/>
      <add-to-group group-id="Vcs.Log.Toolbar"/>
    </group>

    <group>
      <reference ref="Vcs.CherryPick"/>
      <reference ref="Vcs.Push"/>
      <separator/>

      <add-to-group group-id="VcsGeneral.KeymapGroup"/>
    </group>
  </actions>
  <project-components>
    <component>
      <implementation-class>com.intellij.dvcs.repo.VcsRepositoryManager</implementation-class>
    </component>
  </project-components>

  <extensions defaultExtensionNs="com.intellij">
    <projectService serviceImplementation="com.intellij.dvcs.push.PushSettings"/>
    <projectService serviceImplementation="com.intellij.dvcs.cherrypick.VcsCherryPickManager"/>
  </extensions>
</idea-plugin>


text:
SURFnet OS X SSO Library
===================================================

Now you can easily integrate the [SURFnet](https://www.surf.nl) SSO process flow in your OS X application by using this library.

If you want to see it in action, check out the sample app in this repository.

HOW TO USE THE LIBRARY
-----

Before you can use the library you need to have your `consumerId` registered by SURFnet and have received your `consumer secret`.

### 1. Include library

If you are using CocoaPods, add the following line to your Podfile:

    pod 'SSOService-OSX'

alternatively, add the code from the SSOService folder into your project directly.

### 2. Register URL scheme

In the Info.plist of your app, add an entry in CFBundleURLTypes with the value for CFBundleURLSchemes set to the one registered with Surfnet.

### 3. Showing authorization screen

When you want to let the user login, create an authorization view controller and display it.

    - (IBAction)authorize:(id)sender {
        [SSOService authorizeForEndpoint:@"https://nonweb.demo.surfconext.nl/php-oauth-as/authorize.php" consumerId:@"your consumer id" state:@"demo" delegate:self];
    }

You should also implement a few delegate callback methods.

    #pragma mark - SSOAuthorizationDelegate

    - (void)authorizationDidSucceedWithToken:(NSString * _Nonnull)token {
        NSAlert *alert = [[NSAlert alloc] init];
        alert.messageText = NSLocalizedString(@"Authorization succeeded", @"");
        alert.informativeText = [NSString stringWithFormat:NSLocalizedString(@"Access token: %@", @""), token];
        [alert runModal];
    }

    - (void)authorizationDidFailWithError:(NSError * _Nonnull)error {
        NSAlert *alert = [NSAlert alertWithError:error];
        [alert runModal];
    }

### 4. Receiving access token

The access token will be delivered to your app via a callback URL. In your application delegate, implement these methods to handle the URL.

    - (void)applicationWillFinishLaunching:(NSNotification *)aNotification {
        [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(handleAppleEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
    }

    - (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
        NSString *urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
        if (urlString == nil) {
            return;
        }
        NSURL *url = [NSURL URLWithString:urlString];
        if (url == nil) {
            return;
        }
        BOOL urlHandled = [SSOService handleURL:url callbackScheme:@"sfoauth"];
        if (!urlHandled) {
            // Handle any other URLs
        }
    }

[CHANGELOG](https://github.com/SURFnet/nonweb-sso-osx/blob/master/CHANGELOG.md)
-----

Current version: 0.0.1

DEVELOPED BY
------------

* SURFnet - [https://www.surf.nl](https://www.surf.nl)
* Egeniq - [https://www.egeniq.com/](https://www.egeniq.com/)

LICENSE
-----

    Copyright 2015 SURFnet BV, The Netherlands

    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.


text:
FROM debian:jessie-backports

# explicitly set user/group IDs
RUN groupadd -r cassandra --gid=999 && useradd -r -g cassandra --uid=999 cassandra

# grab gosu for easy step-down from root
ENV GOSU_VERSION 1.7
RUN set -x \
	&& apt-get update && apt-get install -y --no-install-recommends ca-certificates wget && rm -rf /var/lib/apt/lists/* \
	&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$(dpkg --print-architecture)" \
	&& wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$(dpkg --print-architecture).asc" \
	&& export GNUPGHOME="$(mktemp -d)" \
	&& gpg --keyserver ha.pool.sks-keyservers.net --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 \
	&& gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \
	&& rm -r "$GNUPGHOME" /usr/local/bin/gosu.asc \
	&& chmod +x /usr/local/bin/gosu \
	&& gosu nobody true \
	&& apt-get purge -y --auto-remove ca-certificates wget

RUN apt-key adv --keyserver ha.pool.sks-keyservers.net --recv-keys 514A2AD631A57A16DD0047EC749D6EEC0353B12C

RUN echo 'deb http://www.apache.org/dist/cassandra/debian 21x main' >> /etc/apt/sources.list.d/cassandra.list

ENV CASSANDRA_VERSION 2.1.13

RUN apt-get update \
	&& apt-get install -y cassandra="$CASSANDRA_VERSION" \
	&& rm -rf /var/lib/apt/lists/*

ENV CASSANDRA_CONFIG /etc/cassandra

COPY docker-entrypoint.sh /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]

RUN mkdir -p /var/lib/cassandra "$CASSANDRA_CONFIG" \
	&& chown -R cassandra:cassandra /var/lib/cassandra "$CASSANDRA_CONFIG" \
	&& chmod 777 /var/lib/cassandra "$CASSANDRA_CONFIG"
VOLUME /var/lib/cassandra

# 7000: intra-node communication
# 7001: TLS intra-node communication
# 7199: JMX
# 9042: CQL
# 9160: thrift service
EXPOSE 7000 7001 7199 9042 9160
CMD ["cassandra", "-f"]


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
?>

	 <?php echo t('Versions')?>

				<input type="checkbox" />
				<button type="button" class="btn-link disabled" data-version-action="delete"><?php echo t('Delete')?></button>


text:
#ifndef _RDO_STUDIO_MODEL_VIEW_H_
#define _RDO_STUDIO_MODEL_VIEW_H_

// ----------------------------------------------------------------------- INCLUDES
#include "utils/src/common/warning_disable.h"
#include <QWidget>
#include "utils/src/common/warning_enable.h"
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio/src/model/model.h"
#include "app/rdo_studio/src/dialog/find_dialog.h"
// --------------------------------------------------------------------------------

namespace rdo { namespace gui { namespace model {

class TabCtrl;

class View: public QWidget
{
Q_OBJECT

public:
	View(QWidget* pParent);
	virtual ~View();

	void setModel(Model* pModel);

	TabCtrl& getTab();

private:
	typedef  QWidget  parent_type;

	FindDialog* m_pFindDialog;
	FindDialog::Settings m_findSettings;
	TabCtrl* m_pTabCtrl;
	Model* m_pModel;

	void closeEvent(QCloseEvent* event);

	void onFindDlgFind(const FindDialog::Settings& settings);
	void onFindDlgClose();

	void onSearchFindAll();

private slots:
	void onSearchFindInModel();
};

}}} // namespace rdo::gui::model

#endif // RDOSTUDIOMODELVIEW_H


text:
module CommentsHelper
  def comment_url(commentable)
    path = if commentable.is_a?(Answer)
      question_answer_comments_path(commentable.question, commentable)
    else
      question_comments_path(commentable)
    end
  end
end


text:
/**
 * TCustUpdateCfgDao.java	2010/03/24
 */

package com.ycsoft.business.dao.config;

import java.util.List;

import org.springframework.stereotype.Component;

import com.ycsoft.beans.config.TUpdateCfg;
import com.ycsoft.commons.constants.StatusConstants;
import com.ycsoft.daos.abstracts.BaseEntityDao;
import com.ycsoft.daos.core.JDBCException;

/**
 * TUpdateCfgDao -> T_UPDATE_CFG table's operator
 */
@Component
public class TUpdateCfgDao extends BaseEntityDao<TUpdateCfg> {

	/**
	 *
	 */
	private static final long serialVersionUID = -7157392671708686330L;

	/**
	 * default empty constructor
	 */
	public TUpdateCfgDao() {}
	/**
	 * 根据模板ID删除记录
	 * @param templateId
	 * @throws JDBCException
	 */
	public void deleteByTplId(String templateId) throws JDBCException{
		String sql = "delete from t_update_cfg t where t.template_id=?";
		executeUpdate(sql, templateId);
	}

	/**
	 * 查询信息修改字段名
	 * @return
	 * @throws JDBCException
	 */
	public List<TUpdateCfg> queryFields() throws JDBCException{
		String sql = "SELECT t.comments remark, t.field_name,t.table_name FROM t_tab_define t " +
				" WHERE t.field_name IS NOT NULL and t.status = ? ";
		return createQuery(TUpdateCfg.class, sql,StatusConstants.ACTIVE).list();
	}

	/**
	 * 查询信息修改模板数据
	 * @param templateId
	 * @return
	 * @throws JDBCException
	 */
	public List<TUpdateCfg> queryUpdCfgTpls(String templateId) throws JDBCException{
		String sql = "select t1.*,t2.busi_name,t3.remark from t_update_cfg t1,t_busi_code t2,"
			+ " (SELECT t.comments remark, t.field_name  FROM t_tab_define t "
			+ " WHERE t.field_name IS NOT NULL and t.status = ? ) t3 "
			+ " where t1.template_id=? and t1.busi_code=t2.busi_code and t1.field_name = t3.field_name";
		return createQuery(TUpdateCfg.class, sql, StatusConstants.ACTIVE,templateId).list();
	}

}


text:
package com.theagilemonkeys.meets.models;

import com.theagilemonkeys.meets.models.base.MeetsModel;

import java.util.List;
import java.util.Map;

public interface MeetsProduct extends MeetsModel<MeetsProduct> {
    String getType();
    String getSku();
    String getName();
    String getDescription();
    double getPrice();
    String getImageUrl();
    Map<String, String> getImageVersions();
    Map<String, String> getAdditionalAttributes();
    List<MeetsProduct> getAssociatedProducts();

    MeetsProduct fetchImageVersions();
    MeetsProduct fetchWithAdditionalAttributes(String... additionalAttributes);
    MeetsProduct fetchWithAdditionalAttributes(List<String> additionalAttributes);
    MeetsProduct fetchAssociatedProducts();

}


text:
#include "NxOgreStable.h"

#if NxOgreHasFluids == 1

#include "NxOgreFluid.h"
#include "NxOgreFluidDescription.h"
#include "NxOgreCompartment.h"
#include "NxOgreScene.h"
#include "NxOgreRenderable.h"

#include "NxPhysics.h"

namespace NxOgre
{

Fluid::Fluid(const FluidDescription& description, Renderable* renderable, Enums::Priority priority, Scene* scene)
: mName(description.mName),
  mScene(scene),
  mRenderable(renderable),
  mPriority(priority)
{
 mNameHash = Strings::hash(mName);

 mParticleData = GC::safe_new0<PhysXParticleData>(NXOGRE_GC_THIS);
 mParticleData->configure(description.mMaxParticles, 2);

 NxFluidDesc fd;
 fd.attractionForDynamicShapes = description.mAttractionForDynamicShapes;
 fd.attractionForStaticShapes  = description.mAttractionForStaticShapes;
 fd.collisionDistanceMultiplier = description.mCollisionDistanceMultiplier;
 fd.collisionGroup = description.mCollisionGroup;
 fd.collisionMethod = description.mCollisionMethod;
 fd.collisionResponseCoefficient = description.mCollisionResponseCoefficient;
 if (description.mCompartment)
  fd.compartment = description.mCompartment->getCompartment();
 fd.damping = description.mDamping;
 fd.dynamicFrictionForDynamicShapes = description.mDynamicFrictionForDynamicShapes;
 fd.dynamicFrictionForStaticShapes = description.mDynamicFrictionForStaticShapes;
 fd.externalAcceleration = description.mExternalAcceleration.as<NxVec3>();
 fd.fadeInTime = description.mFadeInTime;
 fd.flags = description.mFlags;
 // fd.fluidPacketData = ...
 fd.forceFieldMaterial = description.mForceFieldMaterial;
 fd.groupsMask.bits0 = description.mGroupsMask.w;
 fd.groupsMask.bits1 = description.mGroupsMask.x;
 fd.groupsMask.bits2 = description.mGroupsMask.y;
 fd.groupsMask.bits3 = description.mGroupsMask.z;
 // fd.initialParticleData = ...
 fd.kernelRadiusMultiplier = description.mKernelRadiusMultiplier;
 fd.maxParticles = description.mMaxParticles;
 fd.motionLimitMultiplier = description.mMotionLimitMultiplier;
 fd.name = mName.c_str();
 fd.numReserveParticles = description.mNbReserveParticles;
 fd.packetSizeMultiplier = description.mPacketSizeMultiplier;
 //fd.particleCreationIdWriteData = ...
 //fd.particleDeletionIdWriteData = ...
 mParticleData->getParticleData(fd.particlesWriteData);
 //fd.projectionPlane = ...
 fd.restDensity = description.mRestDensity;
 fd.restitutionForDynamicShapes = description.mRestitutionForDynamicShapes;
 fd.restitutionForStaticShapes = description.mRestitutionForStaticShapes;
 fd.restParticlesPerMeter = description.mRestParticlesPerMetre;
 fd.simulationMethod = description.mSimulationMethod;
 fd.staticFrictionForDynamicShapes = description.mStaticFrictionForDynamicShapes;
 fd.staticFrictionForStaticShapes = description.mStaticFrictionForStaticShapes;
 fd.stiffness = description.mStiffness;
 fd.surfaceTension = description.mSurfaceTension;
 fd.viscosity = description.mViscosity;

 mFluid = mScene->getScene()->createFluid(fd);
 if (mFluid == 0)
 {
  StringStream ss;
  ss << "Fluid was not created! \n";
//     << "Reason(s) are: \n" <<  Reason::whyAsStream(actor_description);
  NxOgre_ThrowException(IOException, ss.str(), Classes::_Fluid);
  return;
 }

 mScene->addRenderListener(this, mPriority);

}

Fluid::~Fluid()
{

 mScene->addRenderListener(this, mPriority);

 if (mFluid)
 {
  mFluidEmitters.remove_all();
  mScene->getScene()->releaseFluid(*mFluid);
  mFluid = 0;
 }

 GC::safe_delete(mParticleData, NXOGRE_GC_THIS);

}

Renderable* Fluid::getRenderable()
{
 return mRenderable;
}

NxFluid* Fluid::getFluid()
{
 return mFluid;
}

bool Fluid::advance(float, const Enums::Priority&, const Enums::SceneFunction&)
{
 if (mRenderable && mParticleData)
 {
  NxBounds3 bounds;
  mFluid->getWorldBounds(bounds);
  mRenderable->drawFluid(mParticleData, Bounds3::from(bounds));
 }
 return true;
}

FluidEmitter* Fluid::createEmitter(const FluidEmitterDescription& description)
{
 FluidEmitter* emitter = GC::safe_new2<FluidEmitter>(description, this, NXOGRE_GC_THIS);
 mFluidEmitters.insert(emitter->getNameHash(), emitter);
 return emitter;
}

//void Fluid::destroyEmitter(FluidEmitter*)
//{
//}

unsigned int Fluid::getNbParticles() const
{
 return mParticleData->getNbParticles();
}

unsigned int Fluid::getNbEmitters() const
{
 return mFluidEmitters.size();
}

Fluid::FluidEmitterIterator Fluid::getEmitters()
{
 return mFluidEmitters.elements();
}

unsigned int Fluid::addParticles(ParticleData&, bool)
{
 return 0; // Temp.
}

void Fluid::removeAllParticles()
{
 mFluid->removeAllParticles();
}

//ParticleData* Fluid::getParticleData()
//{
// return 0;
//}

unsigned int Fluid::getNbReserveParticles() const
{
 return mFluid->getNumReserveParticles();
}

void Fluid::setNbReserveParticles(unsigned int particles)
{
 mFluid->setNumReserveParticles(particles);
}

unsigned int Fluid::getCurrentParticleLimit() const
{
 return mFluid->getCurrentParticleLimit();
}

void Fluid::setCurrentParticleLimit(unsigned int limit)
{
 mFluid->setCurrentParticleLimit(limit);
}

buffer<FluidPacket*> Fluid::getFluidPacketData() const
{
 return buffer<FluidPacket*>(); // Temp.
}

unsigned int Fluid::getSimulationMethod() const
{
 return mFluid->getSimulationMethod();
}

void Fluid::setSimulationMethod(unsigned int simulationMethod)
{
 mFluid->setSimulationMethod(simulationMethod);
}

Real Fluid::getStiffness() const
{
 return mFluid->getStiffness();
}

void Fluid::setStiffness(Real stiffness)
{
 mFluid->setStiffness(stiffness);
}

Real Fluid::getViscosity() const
{
 return mFluid->getViscosity();
}

void Fluid::setViscosity(Real viscosity)
{
 mFluid->setViscosity(viscosity);
}

void Fluid::setSurfaceTension(Real surfaceTension)
{
 mFluid->setSurfaceTension(surfaceTension);
}

Real Fluid::getDamping() const
{
 return mFluid->getDamping();
}

void Fluid::setDamping(Real damping)
{
 mFluid->setDamping(damping);
}

Real Fluid::getFadeInTime() const
{
 return mFluid->getFadeInTime();
}

void Fluid::setFadeInTime(Real fadeIn)
{
 mFluid->setFadeInTime(fadeIn);
}

Vec3 Fluid::getExternalAcceleration() const
{
 return Vec3(mFluid->getExternalAcceleration());
}

void Fluid::setExternalAcceleration(const Vec3& acceleration)
{
 mFluid->setExternalAcceleration(acceleration.as<NxVec3>());
}

SimplePlane Fluid::getProjectionPlane() const
{
 SimplePlane plane;
 NxPlane  nx_plane;
 mFluid->setProjectionPlane(nx_plane);
 plane.mNormal = nx_plane.normal;
 plane.mDistance = nx_plane.d;
 return plane;
}

void Fluid::setProjectionPlane(const SimplePlane& plane)
{
 NxPlane nx_plane;
 nx_plane.d = plane.mDistance;
 nx_plane.normal = plane.mNormal.as<NxVec3>();
 mFluid->setProjectionPlane(nx_plane);
}

unsigned int Fluid::getCollisionMethod() const
{
 return mFluid->getCollisionMethod();
}

void Fluid::setCollisionMethod(unsigned int collisionMethod)
{
 mFluid->setCollisionMethod(collisionMethod);
}

Real Fluid::getRestitutionForStaticShapes() const
{
 return mFluid->getRestitutionForStaticShapes();
}

void Fluid::setRestitutionForStaticShapes(Real restitution)
{
 mFluid->setRestitutionForStaticShapes(restitution);
}

Real Fluid::getDynamicFrictionForStaticShapes() const
{
 return mFluid->getDynamicFrictionForStaticShapes();
}

void Fluid::setDynamicFrictionForStaticShapes(Real friction)
{
 mFluid->setDynamicFrictionForStaticShapes(friction);
}

Real Fluid::getStaticFrictionForStaticShapes() const
{
 return mFluid->getStaticFrictionForStaticShapes();
}

void Fluid::setStaticFrictionForStaticShapes(Real friction)
{
 mFluid->setStaticFrictionForStaticShapes(friction);
}

Real Fluid::getAttractionForStaticShapes() const
{
 return mFluid->getAttractionForStaticShapes();
}

void Fluid::setAttractionForStaticShapes(Real attraction)
{
 mFluid->setAttractionForStaticShapes(attraction);
}

Real Fluid::getRestitutionForDynamicShapes() const
{
 return mFluid->getRestitutionForDynamicShapes();
}

void Fluid::setRestitutionForDynamicShapes(Real restitution)
{
 mFluid->setRestitutionForDynamicShapes(restitution);
}

Real Fluid::getDynamicFrictionForDynamicShapes() const
{
 return mFluid->getDynamicFrictionForDynamicShapes();
}

void Fluid::setDynamicFrictionForDynamicShapes(Real friction)
{
 mFluid->setDynamicFrictionForDynamicShapes(friction);
}

Real Fluid::getStaticFrictionForDynamicShapes() const
{
 return mFluid->getStaticFrictionForDynamicShapes();
}

void Fluid::setStaticFrictionForDynamicShapes(Real friction)
{
 mFluid->setStaticFrictionForDynamicShapes(friction);
}

Real Fluid::getAttractionForDynamicShapes() const
{
 return mFluid->getAttractionForDynamicShapes();
}

void Fluid::setAttractionForDynamicShapes(Real attraction)
{
 mFluid->setAttractionForDynamicShapes(attraction);
}

void Fluid::setCollisionResponseCoefficient(Real coefficient)
{
 mFluid->setCollisionResponseCoefficient(coefficient);
}

Real Fluid::getCollisionResponseCoefficient() const
{
 return mFluid->getCollisionResponseCoefficient();
}

void Fluid::setFlag(Enums::FluidFlags flags, bool value)
{
 mFluid->setFlag(NxFluidFlag(unsigned int(flags)), value);
}

bool Fluid::getFlag(Enums::FluidFlags flags) const
{
 return mFluid->getFlag(NxFluidFlag(unsigned int(flags)));
}

Scene* Fluid::getScene()
{
 return mScene;
}

unsigned int Fluid::getMaxParticles() const
{
 return mFluid->getMaxParticles();
}

Real Fluid::getKernelRadiusMultiplier() const
{
 return mFluid->getKernelRadiusMultiplier();
}

Real Fluid::getMotionLimitMultiplier() const
{
 return mFluid->getMotionLimitMultiplier();
}

Real Fluid::getCollisionDistanceMultiplier() const
{
 return mFluid->getCollisionDistanceMultiplier();
}

unsigned int Fluid::getPacketSizeMultiplier() const
{
 return mFluid->getPacketSizeMultiplier();
}

Real Fluid::getRestParticlesPerMetre() const
{
 return mFluid->getRestParticlesPerMeter();
}

Real Fluid::getRestDensity() const
{
 return mFluid->getRestDensity();
}

Real Fluid::getRestParticleDistance() const
{
 return mFluid->getRestParticleDistance();
}

Real Fluid::getParticleMass() const
{
 return mFluid->getParticleMass();
}

void Fluid::setGroup(GroupIdentifier collisionGroup)
{
 mFluid->setGroup(collisionGroup);
}

GroupIdentifier Fluid::getGroup() const
{
 return mFluid->getGroup();
}

void Fluid::setGroupsMask(const int4& mask)
{
 NxGroupsMask groups_mask;
 groups_mask.bits0 = mask.w;
 groups_mask.bits1 = mask.x;
 groups_mask.bits2 = mask.y;
 groups_mask.bits3 = mask.z;
 mFluid->setGroupsMask(groups_mask);
}

int4 Fluid::getGroupsMask() const
{
 NxGroupsMask groups_mask = mFluid->getGroupsMask();
 int4 mask;
 mask.w = groups_mask.bits0;
 mask.x = groups_mask.bits1;
 mask.y = groups_mask.bits2;
 mask.z = groups_mask.bits3;
 return mask;
}

Bounds3 Fluid::getWorldBounds() const
{
 NxBounds3 nx_bounds;
 mFluid->getWorldBounds(nx_bounds);
 return Bounds3().from(nx_bounds);
}

unsigned int Fluid::getPPUTime() const
{
 return mFluid->getPPUTime();
}

void Fluid::setName(const String& name)
{
 mName = name;
 mFluid->setName(mName.c_str());
}

String Fluid::getName() const
{
 return mName;
}

StringHash Fluid::getNameHash() const
{
 return mNameHash;
}

Compartment* Fluid::getCompartment()
{
 return mCompartment;
}

MaterialIdentifier Fluid::getForceFieldMaterial() const
{
 return mFluid->getForceFieldMaterial();
}

void Fluid::setForceFieldMaterial(MaterialIdentifier identifier)
{
 mFluid->setForceFieldMaterial(identifier);
}

} // namespace NxOgre

#endif


text:
require 'test_helper'

class TagsControllerTest < ActionDispatch::IntegrationTest
  test "can create tag" do

    #$stderr.puts "#{ApplicationController::JSONAPI[:content_type]}"

    assert_difference 'Tag.count' do
      post(
        tags_path,
        headers: {
        # 'Accept':       ApplicationController::JSONAPI[:content_type],
        # 'Content-Type': ApplicationController::JSONAPI[:content_type]
        },
        xhr: true,
        params: {
          type: :tags,
          data: {
            attributes: {
              name: 'Travel'
            }
          }
        }
      )
    end
    assert_response :success
    json = JSON.parse response.body, symbolize_names: true
    #$stderr.puts "#{json}"
    assert          json,               "no json response"
    refute          json[:errors],      'response is error instead of record'
    assert          json[:data],        "response is not a record"

  end

  test "can update tag" do

    # create tag
    post(
      tags_path,
      xhr: true,
      params: {
        type: :tags,
        data: {
          attributes: {
            name: 'Fun'
          }
        }
      }
    )
    json = JSON.parse response.body, symbolize_names: true
    #$stderr.puts "#{json}"

    # update tag
    patch tag_path(json[:data][:id]), params: {
      data: {
        type: json[:data][:type],
        id: json[:data][:id],
        attributes: {name: 'Leisure'}
      }
    }
    json2 = JSON.parse response.body, symbolize_names: true
    #$stderr.puts "#{json2}"
    assert          json2,               "no json2 response"
    refute          json2[:errors],      'response is error'
    assert_kind_of  Hash, json2[:data],        "response is not hash"
    assert_equal json[:data][:id], json2[:data][:id], "update has changed the id"
    assert_equal 'Leisure', json2[:data][:attributes][:name], "attribute has not been updated"

  end

end


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

<title>Camera</title>
<meta name="date" content="2016-07-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

graphics.nim.volterra

Class Camera

java.lang.Object

graphics.nim.volterra.Camera

public class Camera
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

private Vector2f
position

private float
rotation

private Vector2f
zoom

Constructor Summary

Constructors

Constructor and Description

Camera()

Class constructor.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

Vector2f
getPosition()

float
getRotation()

Vector2f
getZoom()

void
setPosition(float x,
           float y)

void
setRotation(float angle)

void
setZoom(float zoomX,
       float zoomY)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

position

private Vector2f position

rotation

private float rotation

zoom

private Vector2f zoom

Constructor Detail

Camera

public Camera()

Class constructor.

Method Detail

getPosition

public Vector2f getPosition()

getRotation

public float getRotation()

getZoom

public Vector2f getZoom()

setPosition

public void setPosition(float x,
                        float y)

setRotation

public void setRotation(float angle)

setZoom

public void setZoom(float zoomX,
                    float zoomY)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method