text:
from __future__ import unicode_literals
import json

import boto
import boto.cloudformation
import boto.ec2
import boto.ec2.autoscale
import boto.ec2.elb
from boto.exception import BotoServerError
import boto.iam
import boto.redshift
import boto.sns
import boto.sqs
import boto.vpc
import sure  # noqa

from moto import (
    mock_autoscaling,
    mock_cloudformation,
    mock_ec2,
    mock_elb,
    mock_iam,
    mock_rds,
    mock_redshift,
    mock_route53,
    mock_sns,
    mock_sqs,
)

from .fixtures import (
    ec2_classic_eip,
    fn_join,
    rds_mysql_with_read_replica,
    redshift,
    route53_ec2_instance_with_public_ip,
    route53_health_check,
    route53_roundrobin,
    single_instance_with_ebs_volume,
    vpc_eip,
    vpc_single_instance_in_subnet,
)

@mock_cloudformation()
def test_stack_sqs_integration():
    sqs_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "QueueGroup": {

                "Type": "AWS::SQS::Queue",
                "Properties": {
                    "QueueName": "my-queue",
                    "VisibilityTimeout": 60,
                }
            },
        },
    }
    sqs_template_json = json.dumps(sqs_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=sqs_template_json,
    )

    stack = conn.describe_stacks()[0]
    queue = stack.describe_resources()[0]
    queue.resource_type.should.equal('AWS::SQS::Queue')
    queue.logical_resource_id.should.equal("QueueGroup")
    queue.physical_resource_id.should.equal("my-queue")

@mock_cloudformation()
def test_stack_list_resources():
    sqs_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "QueueGroup": {

                "Type": "AWS::SQS::Queue",
                "Properties": {
                    "QueueName": "my-queue",
                    "VisibilityTimeout": 60,
                }
            },
        },
    }
    sqs_template_json = json.dumps(sqs_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=sqs_template_json,
    )

    resources = conn.list_stack_resources("test_stack")
    assert len(resources) == 1
    queue = resources[0]
    queue.resource_type.should.equal('AWS::SQS::Queue')
    queue.logical_resource_id.should.equal("QueueGroup")
    queue.physical_resource_id.should.equal("my-queue")

@mock_cloudformation()
@mock_sqs()
def test_update_stack():
    sqs_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "QueueGroup": {

                "Type": "AWS::SQS::Queue",
                "Properties": {
                    "QueueName": "my-queue",
                    "VisibilityTimeout": 60,
                }
            },
        },
    }
    sqs_template_json = json.dumps(sqs_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=sqs_template_json,
    )

    sqs_conn = boto.sqs.connect_to_region("us-west-1")
    queues = sqs_conn.get_all_queues()
    queues.should.have.length_of(1)
    queues[0].get_attributes('VisibilityTimeout')['VisibilityTimeout'].should.equal('60')

    sqs_template['Resources']['QueueGroup']['Properties']['VisibilityTimeout'] = 100
    sqs_template_json = json.dumps(sqs_template)
    conn.update_stack("test_stack", sqs_template_json)

    queues = sqs_conn.get_all_queues()
    queues.should.have.length_of(1)
    queues[0].get_attributes('VisibilityTimeout')['VisibilityTimeout'].should.equal('100')

@mock_cloudformation()
@mock_sqs()
def test_update_stack_and_remove_resource():
    sqs_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "QueueGroup": {

                "Type": "AWS::SQS::Queue",
                "Properties": {
                    "QueueName": "my-queue",
                    "VisibilityTimeout": 60,
                }
            },
        },
    }
    sqs_template_json = json.dumps(sqs_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=sqs_template_json,
    )

    sqs_conn = boto.sqs.connect_to_region("us-west-1")
    queues = sqs_conn.get_all_queues()
    queues.should.have.length_of(1)

    sqs_template['Resources'].pop('QueueGroup')
    sqs_template_json = json.dumps(sqs_template)
    conn.update_stack("test_stack", sqs_template_json)

    queues = sqs_conn.get_all_queues()
    queues.should.have.length_of(0)

@mock_cloudformation()
@mock_sqs()
def test_update_stack_and_add_resource():
    sqs_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {},
    }
    sqs_template_json = json.dumps(sqs_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=sqs_template_json,
    )

    sqs_conn = boto.sqs.connect_to_region("us-west-1")
    queues = sqs_conn.get_all_queues()
    queues.should.have.length_of(0)

    sqs_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "QueueGroup": {

                "Type": "AWS::SQS::Queue",
                "Properties": {
                    "QueueName": "my-queue",
                    "VisibilityTimeout": 60,
                }
            },
        },
    }
    sqs_template_json = json.dumps(sqs_template)
    conn.update_stack("test_stack", sqs_template_json)

    queues = sqs_conn.get_all_queues()
    queues.should.have.length_of(1)

@mock_ec2()
@mock_cloudformation()
def test_stack_ec2_integration():
    ec2_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "WebServerGroup": {
                "Type": "AWS::EC2::Instance",
                "Properties": {
                    "ImageId": "ami-1234abcd",
                    "UserData": "some user data",
                }
            },
        },
    }
    ec2_template_json = json.dumps(ec2_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "ec2_stack",
        template_body=ec2_template_json,
    )

    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]

    stack = conn.describe_stacks()[0]
    instance = stack.describe_resources()[0]
    instance.resource_type.should.equal('AWS::EC2::Instance')
    instance.logical_resource_id.should.contain("WebServerGroup")
    instance.physical_resource_id.should.equal(ec2_instance.id)

@mock_ec2()
@mock_elb()
@mock_cloudformation()
def test_stack_elb_integration_with_attached_ec2_instances():
    elb_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "MyELB": {
                "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
                "Instances": [{"Ref": "Ec2Instance1"}],
                "Properties": {
                    "LoadBalancerName": "test-elb",
                    "AvailabilityZones": ['us-east1'],
                }
            },
            "Ec2Instance1": {
                "Type": "AWS::EC2::Instance",
                "Properties": {
                    "ImageId": "ami-1234abcd",
                    "UserData": "some user data",
                }
            },
        },
    }
    elb_template_json = json.dumps(elb_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "elb_stack",
        template_body=elb_template_json,
    )

    elb_conn = boto.ec2.elb.connect_to_region("us-west-1")
    load_balancer = elb_conn.get_all_load_balancers()[0]

    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]
    instance_id = ec2_instance.id

    load_balancer.instances[0].id.should.equal(ec2_instance.id)
    list(load_balancer.availability_zones).should.equal(['us-east1'])

@mock_ec2()
@mock_redshift()
@mock_cloudformation()
def test_redshift_stack():
    redshift_template_json = json.dumps(redshift.template)

    vpc_conn = boto.vpc.connect_to_region("us-west-2")
    conn = boto.cloudformation.connect_to_region("us-west-2")
    conn.create_stack(
        "redshift_stack",
        template_body=redshift_template_json,
        parameters=[
            ("DatabaseName", "mydb"),
            ("ClusterType", "multi-node"),
            ("NumberOfNodes", 2),
            ("NodeType", "dw1.xlarge"),
            ("MasterUsername", "myuser"),
            ("MasterUserPassword", "mypass"),
            ("InboundTraffic", "10.0.0.1/16"),
            ("PortNumber", 5439),
        ]
    )

    redshift_conn = boto.redshift.connect_to_region("us-west-2")

    cluster_res = redshift_conn.describe_clusters()
    clusters = cluster_res['DescribeClustersResponse']['DescribeClustersResult']['Clusters']
    clusters.should.have.length_of(1)
    cluster = clusters[0]
    cluster['DBName'].should.equal("mydb")
    cluster['NumberOfNodes'].should.equal(2)
    cluster['NodeType'].should.equal("dw1.xlarge")
    cluster['MasterUsername'].should.equal("myuser")
    cluster['Port'].should.equal(5439)
    cluster['VpcSecurityGroups'].should.have.length_of(1)
    security_group_id = cluster['VpcSecurityGroups'][0]['VpcSecurityGroupId']

    groups = vpc_conn.get_all_security_groups(group_ids=[security_group_id])
    groups.should.have.length_of(1)
    group = groups[0]
    group.rules.should.have.length_of(1)
    group.rules[0].grants[0].cidr_ip.should.equal("10.0.0.1/16")

@mock_ec2()
@mock_cloudformation()
def test_stack_security_groups():
    security_group_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "my-security-group": {
                "Type": "AWS::EC2::SecurityGroup",
                "Properties": {
                    "GroupDescription": "My other group",
                },
            },
            "Ec2Instance2": {
                "Type": "AWS::EC2::Instance",
                "Properties": {
                    "SecurityGroups": [{"Ref": "InstanceSecurityGroup"}],
                    "ImageId": "ami-1234abcd",
                }
            },
            "InstanceSecurityGroup": {
                "Type": "AWS::EC2::SecurityGroup",
                "Properties": {
                    "GroupDescription": "My security group",
                    "SecurityGroupIngress": [{
                        "IpProtocol": "tcp",
                        "FromPort": "22",
                        "ToPort": "22",
                        "CidrIp": "123.123.123.123/32",
                    }, {
                        "IpProtocol": "tcp",
                        "FromPort": "80",
                        "ToPort": "8000",
                        "SourceSecurityGroupId": {"Ref": "my-security-group"},
                    }]
                }
            }
        },
    }
    security_group_template_json = json.dumps(security_group_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "security_group_stack",
        template_body=security_group_template_json,
    )

    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    instance_group = ec2_conn.get_all_security_groups(filters={'description': ['My security group']})[0]
    other_group = ec2_conn.get_all_security_groups(filters={'description': ['My other group']})[0]

    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]

    ec2_instance.groups[0].id.should.equal(instance_group.id)
    instance_group.description.should.equal("My security group")
    rule1, rule2 = instance_group.rules
    int(rule1.to_port).should.equal(22)
    int(rule1.from_port).should.equal(22)
    rule1.grants[0].cidr_ip.should.equal("123.123.123.123/32")
    rule1.ip_protocol.should.equal('tcp')

    int(rule2.to_port).should.equal(8000)
    int(rule2.from_port).should.equal(80)
    rule2.ip_protocol.should.equal('tcp')
    rule2.grants[0].group_id.should.equal(other_group.id)

@mock_autoscaling()
@mock_elb()
@mock_cloudformation()
def test_autoscaling_group_with_elb():

    web_setup_template = {
        "AWSTemplateFormatVersion": "2010-09-09",

        "Resources": {
            "my-as-group": {
                "Type": "AWS::AutoScaling::AutoScalingGroup",
                "Properties": {
                    "AvailabilityZones": ['us-east1'],
                    "LaunchConfigurationName": {"Ref": "my-launch-config"},
                    "MinSize": "2",
                    "MaxSize": "2",
                    "LoadBalancerNames": [{"Ref": "my-elb"}]
                },
            },

            "my-launch-config": {
                "Type": "AWS::AutoScaling::LaunchConfiguration",
                "Properties": {
                    "ImageId": "ami-1234abcd",
                    "UserData": "some user data",
                }
            },

            "my-elb": {
                "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
                "Properties": {
                    "AvailabilityZones": ['us-east1'],
                    "Listeners": [{
                        "LoadBalancerPort": "80",
                        "InstancePort": "80",
                        "Protocol": "HTTP"
                    }],
                    "LoadBalancerName": "my-elb",
                    "HealthCheck": {
                        "Target": "80",
                        "HealthyThreshold": "3",
                        "UnhealthyThreshold": "5",
                        "Interval": "30",
                        "Timeout": "5",
                    },
                },
            },
        }
    }

    web_setup_template_json = json.dumps(web_setup_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "web_stack",
        template_body=web_setup_template_json,
    )

    autoscale_conn = boto.ec2.autoscale.connect_to_region("us-west-1")
    autoscale_group = autoscale_conn.get_all_groups()[0]
    autoscale_group.launch_config_name.should.contain("my-launch-config")
    autoscale_group.load_balancers[0].should.equal('my-elb')

    # Confirm the Launch config was actually created
    autoscale_conn.get_all_launch_configurations().should.have.length_of(1)

    # Confirm the ELB was actually created
    elb_conn = boto.ec2.elb.connect_to_region("us-west-1")
    elb_conn.get_all_load_balancers().should.have.length_of(1)

    stack = conn.describe_stacks()[0]
    resources = stack.describe_resources()
    as_group_resource = [resource for resource in resources if resource.resource_type == 'AWS::AutoScaling::AutoScalingGroup'][0]
    as_group_resource.physical_resource_id.should.contain("my-as-group")

    launch_config_resource = [resource for resource in resources if resource.resource_type == 'AWS::AutoScaling::LaunchConfiguration'][0]
    launch_config_resource.physical_resource_id.should.contain("my-launch-config")

    elb_resource = [resource for resource in resources if resource.resource_type == 'AWS::ElasticLoadBalancing::LoadBalancer'][0]
    elb_resource.physical_resource_id.should.contain("my-elb")

@mock_ec2()
@mock_cloudformation()
def test_vpc_single_instance_in_subnet():

    template_json = json.dumps(vpc_single_instance_in_subnet.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=template_json,
        parameters=[("KeyName", "my_key")],
    )

    vpc_conn = boto.vpc.connect_to_region("us-west-1")
    vpc = vpc_conn.get_all_vpcs()[0]
    vpc.cidr_block.should.equal("10.0.0.0/16")

    # Add this once we implement the endpoint
    # vpc_conn.get_all_internet_gateways().should.have.length_of(1)

    subnet = vpc_conn.get_all_subnets()[0]
    subnet.vpc_id.should.equal(vpc.id)

    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    reservation = ec2_conn.get_all_instances()[0]
    instance = reservation.instances[0]
    # Check that the EIP is attached the the EC2 instance
    eip = ec2_conn.get_all_addresses()[0]
    eip.domain.should.equal('vpc')
    eip.instance_id.should.equal(instance.id)

    security_group = ec2_conn.get_all_security_groups(filters={'vpc_id': [vpc.id]})[0]
    security_group.vpc_id.should.equal(vpc.id)

    stack = conn.describe_stacks()[0]
    resources = stack.describe_resources()
    vpc_resource = [resource for resource in resources if resource.resource_type == 'AWS::EC2::VPC'][0]
    vpc_resource.physical_resource_id.should.equal(vpc.id)

    subnet_resource = [resource for resource in resources if resource.resource_type == 'AWS::EC2::Subnet'][0]
    subnet_resource.physical_resource_id.should.equal(subnet.id)

    eip_resource = [resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
    eip_resource.physical_resource_id.should.equal(eip.allocation_id)

@mock_cloudformation()
@mock_ec2()
@mock_rds()
def test_rds_mysql_with_read_replica():
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    ec2_conn.create_security_group('application', 'Our Application Group')

    template_json = json.dumps(rds_mysql_with_read_replica.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=template_json,
        parameters=[
            ("DBInstanceIdentifier", "master_db"),
            ("DBName", "my_db"),
            ("DBUser", "my_user"),
            ("DBPassword", "my_password"),
            ("DBAllocatedStorage", "20"),
            ("DBInstanceClass", "db.m1.medium"),
            ("EC2SecurityGroup", "application"),
            ("MultiAZ", "true"),
        ],
    )

    rds_conn = boto.rds.connect_to_region("us-west-1")

    primary = rds_conn.get_all_dbinstances("master_db")[0]
    primary.master_username.should.equal("my_user")
    primary.allocated_storage.should.equal(20)
    primary.instance_class.should.equal("db.m1.medium")
    primary.multi_az.should.equal(True)
    list(primary.read_replica_dbinstance_identifiers).should.have.length_of(1)
    replica_id = primary.read_replica_dbinstance_identifiers[0]

    replica = rds_conn.get_all_dbinstances(replica_id)[0]
    replica.instance_class.should.equal("db.m1.medium")

    security_group_name = primary.security_groups[0].name
    security_group = rds_conn.get_all_dbsecurity_groups(security_group_name)[0]
    security_group.ec2_groups[0].name.should.equal("application")

@mock_cloudformation()
@mock_ec2()
@mock_rds()
def test_rds_mysql_with_read_replica_in_vpc():
    template_json = json.dumps(rds_mysql_with_read_replica.template)
    conn = boto.cloudformation.connect_to_region("eu-central-1")
    conn.create_stack(
        "test_stack",
        template_body=template_json,
        parameters=[
            ("DBInstanceIdentifier", "master_db"),
            ("DBName", "my_db"),
            ("DBUser", "my_user"),
            ("DBPassword", "my_password"),
            ("DBAllocatedStorage", "20"),
            ("DBInstanceClass", "db.m1.medium"),
            ("MultiAZ", "true"),
        ],
    )

    rds_conn = boto.rds.connect_to_region("eu-central-1")
    primary = rds_conn.get_all_dbinstances("master_db")[0]

    subnet_group_name = primary.subnet_group.name
    subnet_group = rds_conn.get_all_db_subnet_groups(subnet_group_name)[0]
    subnet_group.description.should.equal("my db subnet group")

@mock_autoscaling()
@mock_iam()
@mock_cloudformation()
def test_iam_roles():
    iam_template = {
        "AWSTemplateFormatVersion": "2010-09-09",

        "Resources": {

            "my-launch-config": {
                "Properties": {
                    "IamInstanceProfile": {"Ref": "my-instance-profile"},
                    "ImageId": "ami-1234abcd",
                },
                "Type": "AWS::AutoScaling::LaunchConfiguration"
            },
            "my-instance-profile": {
                "Properties": {
                    "Path": "my-path",
                    "Roles": [{"Ref": "my-role"}],
                },
                "Type": "AWS::IAM::InstanceProfile"
            },
            "my-role": {
                "Properties": {
                    "AssumeRolePolicyDocument": {
                        "Statement": [
                            {
                                "Action": [
                                    "sts:AssumeRole"
                                ],
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": [
                                        "ec2.amazonaws.com"
                                    ]
                                }
                            }
                        ]
                    },
                    "Path": "my-path",
                    "Policies": [
                        {
                            "PolicyDocument": {
                                "Statement": [
                                    {
                                        "Action": [
                                            "ec2:CreateTags",
                                            "ec2:DescribeInstances",
                                            "ec2:DescribeTags"
                                        ],
                                        "Effect": "Allow",
                                        "Resource": [
                                            "*"
                                        ]
                                    }
                                ],
                                "Version": "2012-10-17"
                            },
                            "PolicyName": "EC2_Tags"
                        },
                        {
                            "PolicyDocument": {
                                "Statement": [
                                    {
                                        "Action": [
                                            "sqs:*"
                                        ],
                                        "Effect": "Allow",
                                        "Resource": [
                                            "*"
                                        ]
                                    }
                                ],
                                "Version": "2012-10-17"
                            },
                            "PolicyName": "SQS"
                        },
                    ]
                },
                "Type": "AWS::IAM::Role"
            }
        }
    }

    iam_template_json = json.dumps(iam_template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=iam_template_json,
    )

    iam_conn = boto.iam.connect_to_region("us-west-1")

    role_result = iam_conn.list_roles()['list_roles_response']['list_roles_result']['roles'][0]
    role = iam_conn.get_role(role_result.role_name)
    role.role_name.should.contain("my-role")
    role.path.should.equal("my-path")

    instance_profile_response = iam_conn.list_instance_profiles()['list_instance_profiles_response']
    cfn_instance_profile = instance_profile_response['list_instance_profiles_result']['instance_profiles'][0]
    instance_profile = iam_conn.get_instance_profile(cfn_instance_profile.instance_profile_name)
    instance_profile.instance_profile_name.should.contain("my-instance-profile")
    instance_profile.path.should.equal("my-path")
    instance_profile.role_id.should.equal(role.role_id)

    autoscale_conn = boto.ec2.autoscale.connect_to_region("us-west-1")
    launch_config = autoscale_conn.get_all_launch_configurations()[0]
    launch_config.instance_profile_name.should.contain("my-instance-profile")

    stack = conn.describe_stacks()[0]
    resources = stack.describe_resources()
    instance_profile_resource = [resource for resource in resources if resource.resource_type == 'AWS::IAM::InstanceProfile'][0]
    instance_profile_resource.physical_resource_id.should.equal(instance_profile.instance_profile_name)

    role_resource = [resource for resource in resources if resource.resource_type == 'AWS::IAM::Role'][0]
    role_resource.physical_resource_id.should.equal(role.role_id)

@mock_ec2()
@mock_cloudformation()
def test_single_instance_with_ebs_volume():

    template_json = json.dumps(single_instance_with_ebs_volume.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=template_json,
        parameters=[("KeyName", "key_name")]
    )

    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]

    volume = ec2_conn.get_all_volumes()[0]
    volume.volume_state().should.equal('in-use')
    volume.attach_data.instance_id.should.equal(ec2_instance.id)

    stack = conn.describe_stacks()[0]
    resources = stack.describe_resources()
    ebs_volume = [resource for resource in resources if resource.resource_type == 'AWS::EC2::Volume'][0]
    ebs_volume.physical_resource_id.should.equal(volume.id)

@mock_cloudformation()
def test_create_template_without_required_param():
    template_json = json.dumps(single_instance_with_ebs_volume.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack.when.called_with(
        "test_stack",
        template_body=template_json,
    ).should.throw(BotoServerError)

@mock_ec2()
@mock_cloudformation()
def test_classic_eip():

    template_json = json.dumps(ec2_classic_eip.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack("test_stack", template_body=template_json)
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    eip = ec2_conn.get_all_addresses()[0]

    stack = conn.describe_stacks()[0]
    resources = stack.describe_resources()
    cfn_eip = [resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
    cfn_eip.physical_resource_id.should.equal(eip.public_ip)

@mock_ec2()
@mock_cloudformation()
def test_vpc_eip():

    template_json = json.dumps(vpc_eip.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack("test_stack", template_body=template_json)
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    eip = ec2_conn.get_all_addresses()[0]

    stack = conn.describe_stacks()[0]
    resources = stack.describe_resources()
    cfn_eip = [resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
    cfn_eip.physical_resource_id.should.equal(eip.allocation_id)

@mock_ec2()
@mock_cloudformation()
def test_fn_join():

    template_json = json.dumps(fn_join.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack("test_stack", template_body=template_json)
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    eip = ec2_conn.get_all_addresses()[0]

    stack = conn.describe_stacks()[0]
    fn_join_output = stack.outputs[0]
    fn_join_output.value.should.equal('test eip:{0}'.format(eip.public_ip))

@mock_cloudformation()
@mock_sqs()
def test_conditional_resources():
    sqs_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Parameters": {
            "EnvType": {
                "Description": "Environment type.",
                "Type": "String",
            }
        },
        "Conditions": {
            "CreateQueue": {"Fn::Equals": [{"Ref": "EnvType"}, "prod"]}
        },
        "Resources": {
            "QueueGroup": {
                "Condition": "CreateQueue",
                "Type": "AWS::SQS::Queue",
                "Properties": {
                    "QueueName": "my-queue",
                    "VisibilityTimeout": 60,
                }
            },
        },
    }
    sqs_template_json = json.dumps(sqs_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack_without_queue",
        template_body=sqs_template_json,
        parameters=[("EnvType", "staging")],
    )
    sqs_conn = boto.sqs.connect_to_region("us-west-1")
    list(sqs_conn.get_all_queues()).should.have.length_of(0)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack_with_queue",
        template_body=sqs_template_json,
        parameters=[("EnvType", "prod")],
    )
    sqs_conn = boto.sqs.connect_to_region("us-west-1")
    list(sqs_conn.get_all_queues()).should.have.length_of(1)

@mock_cloudformation()
@mock_ec2()
def test_conditional_if_handling():
    dummy_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Conditions": {
            "EnvEqualsPrd": {
                "Fn::Equals": [
                    {
                        "Ref": "ENV"
                    },
                    "prd"
                ]
            }
        },
        "Parameters": {
            "ENV": {
                "Default": "dev",
                "Description": "Deployment environment for the stack (dev/prd)",
                "Type": "String"
            },
        },
        "Description": "Stack 1",
        "Resources": {
            "App1": {
                "Properties": {
                    "ImageId": {
                        "Fn::If": [
                            "EnvEqualsPrd",
                            "ami-00000000",
                            "ami-ffffffff"
                        ]
                    },
                },
                "Type": "AWS::EC2::Instance"
            },
        }
    }
    dummy_template_json = json.dumps(dummy_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack('test_stack1', template_body=dummy_template_json)
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]
    ec2_instance.image_id.should.equal("ami-ffffffff")
    ec2_instance.terminate()

    conn = boto.cloudformation.connect_to_region("us-west-2")
    conn.create_stack('test_stack1', template_body=dummy_template_json, parameters=[("ENV", "prd")])
    ec2_conn = boto.ec2.connect_to_region("us-west-2")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]
    ec2_instance.image_id.should.equal("ami-00000000")

@mock_cloudformation()
@mock_ec2()
def test_cloudformation_mapping():
    dummy_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Mappings": {
            "RegionMap": {
                "us-east-1": {"32": "ami-6411e20d", "64": "ami-7a11e213"},
                "us-west-1": {"32": "ami-c9c7978c", "64": "ami-cfc7978a"},
                "eu-west-1": {"32": "ami-37c2f643", "64": "ami-31c2f645"},
                "ap-southeast-1": {"32": "ami-66f28c34", "64": "ami-60f28c32"},
                "ap-northeast-1": {"32": "ami-9c03a89d", "64": "ami-a003a8a1"}
            }
        },
        "Resources": {
            "WebServer": {
                "Type": "AWS::EC2::Instance",
                "Properties": {
                    "ImageId": {
                        "Fn::FindInMap": ["RegionMap", {"Ref": "AWS::Region"}, "32"]
                    },
                    "InstanceType": "m1.small"
                },
                "Type": "AWS::EC2::Instance",
            },
        },
    }

    dummy_template_json = json.dumps(dummy_template)

    conn = boto.cloudformation.connect_to_region("us-east-1")
    conn.create_stack('test_stack1', template_body=dummy_template_json)
    ec2_conn = boto.ec2.connect_to_region("us-east-1")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]
    ec2_instance.image_id.should.equal("ami-6411e20d")

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack('test_stack1', template_body=dummy_template_json)
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]
    ec2_instance.image_id.should.equal("ami-c9c7978c")

@mock_cloudformation()
@mock_route53()
def test_route53_roundrobin():
    route53_conn = boto.connect_route53()

    template_json = json.dumps(route53_roundrobin.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    stack = conn.create_stack(
        "test_stack",
        template_body=template_json,
    )

    zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
    list(zones).should.have.length_of(1)
    zone_id = zones[0]['Id']

    rrsets = route53_conn.get_all_rrsets(zone_id)
    rrsets.hosted_zone_id.should.equal(zone_id)
    rrsets.should.have.length_of(2)
    record_set1 = rrsets[0]
    record_set1.name.should.equal('test_stack.us-west-1.my_zone.')
    record_set1.identifier.should.equal("test_stack AWS")
    record_set1.type.should.equal('CNAME')
    record_set1.ttl.should.equal('900')
    record_set1.weight.should.equal('3')
    record_set1.resource_records[0].should.equal("aws.amazon.com")

    record_set2 = rrsets[1]
    record_set2.name.should.equal('test_stack.us-west-1.my_zone.')
    record_set2.identifier.should.equal("test_stack Amazon")
    record_set2.type.should.equal('CNAME')
    record_set2.ttl.should.equal('900')
    record_set2.weight.should.equal('1')
    record_set2.resource_records[0].should.equal("www.amazon.com")

    stack = conn.describe_stacks()[0]
    output = stack.outputs[0]
    output.key.should.equal('DomainName')
    output.value.should.equal('arn:aws:route53:::hostedzone/{0}'.format(zone_id))

@mock_cloudformation()
@mock_ec2()
@mock_route53()
def test_route53_ec2_instance_with_public_ip():
    route53_conn = boto.connect_route53()
    ec2_conn = boto.ec2.connect_to_region("us-west-1")

    template_json = json.dumps(route53_ec2_instance_with_public_ip.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=template_json,
    )

    instance_id = ec2_conn.get_all_reservations()[0].instances[0].id

    zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
    list(zones).should.have.length_of(1)
    zone_id = zones[0]['Id']

    rrsets = route53_conn.get_all_rrsets(zone_id)
    rrsets.should.have.length_of(1)

    record_set1 = rrsets[0]
    record_set1.name.should.equal('{0}.us-west-1.my_zone.'.format(instance_id))
    record_set1.identifier.should.equal(None)
    record_set1.type.should.equal('A')
    record_set1.ttl.should.equal('900')
    record_set1.weight.should.equal(None)
    record_set1.resource_records[0].should.equal("10.0.0.25")

@mock_cloudformation()
@mock_route53()
def test_route53_associate_health_check():
    route53_conn = boto.connect_route53()

    template_json = json.dumps(route53_health_check.template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack(
        "test_stack",
        template_body=template_json,
    )

    checks = route53_conn.get_list_health_checks()['ListHealthChecksResponse']['HealthChecks']
    list(checks).should.have.length_of(1)
    check = checks[0]
    health_check_id = check['Id']
    config = check['HealthCheckConfig']
    config["FailureThreshold"].should.equal("3")
    config["IPAddress"].should.equal("10.0.0.4")
    config["Port"].should.equal("80")
    config["RequestInterval"].should.equal("10")
    config["ResourcePath"].should.equal("/")
    config["Type"].should.equal("HTTP")

    zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
    list(zones).should.have.length_of(1)
    zone_id = zones[0]['Id']

    rrsets = route53_conn.get_all_rrsets(zone_id)
    rrsets.should.have.length_of(1)

    record_set = rrsets[0]
    record_set.health_check.should.equal(health_check_id)

@mock_cloudformation()
@mock_sns()
def test_sns_topic():
    dummy_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "MySNSTopic": {
                "Type": "AWS::SNS::Topic",
                "Properties": {
                    "Subscription": [
                        {"Endpoint": "https://example.com", "Protocol": "https"},
                    ],
                    "TopicName": "my_topics",
                }
            }
        },
        "Outputs": {
            "topic_name": {
                "Value": {"Fn::GetAtt": ["MySNSTopic", "TopicName"]}
            },
            "topic_arn": {
                "Value": {"Ref": "MySNSTopic"}
            },
        }
    }
    template_json = json.dumps(dummy_template)
    conn = boto.cloudformation.connect_to_region("us-west-1")
    stack = conn.create_stack(
        "test_stack",
        template_body=template_json,
    )

    sns_conn = boto.sns.connect_to_region("us-west-1")
    topics = sns_conn.get_all_topics()["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
    topics.should.have.length_of(1)
    topic_arn = topics[0]['TopicArn']
    topic_arn.should.contain("my_topics")

    subscriptions = sns_conn.get_all_subscriptions()["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["Subscriptions"]
    subscriptions.should.have.length_of(1)
    subscription = subscriptions[0]
    subscription["TopicArn"].should.equal(topic_arn)
    subscription["Protocol"].should.equal("https")
    subscription["SubscriptionArn"].should.contain(topic_arn)
    subscription["Endpoint"].should.equal("https://example.com")

    stack = conn.describe_stacks()[0]
    topic_name_output = [x for x in stack.outputs if x.key == 'topic_name'][0]
    topic_name_output.value.should.equal("my_topics")
    topic_arn_output = [x for x in stack.outputs if x.key == 'topic_arn'][0]
    topic_arn_output.value.should.equal(topic_arn)

@mock_cloudformation
@mock_ec2
def test_vpc_gateway_attachment_creation_should_attach_itself_to_vpc():
    template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "internetgateway": {
                "Type": "AWS::EC2::InternetGateway"
            },
            "testvpc": {
                "Type": "AWS::EC2::VPC",
                "Properties": {
                    "CidrBlock": "10.0.0.0/16",
                    "EnableDnsHostnames": "true",
                    "EnableDnsSupport": "true",
                    "InstanceTenancy": "default"
                },
            },
            "vpcgatewayattachment": {
                "Type": "AWS::EC2::VPCGatewayAttachment",
                "Properties": {
                    "InternetGatewayId": {
                        "Ref": "internetgateway"
                    },
                    "VpcId": {
                        "Ref": "testvpc"
                    }
                },
            },
        }
    }

    template_json = json.dumps(template)
    cf_conn = boto.cloudformation.connect_to_region("us-west-1")
    cf_conn.create_stack(
        "test_stack",
        template_body=template_json,
    )

    vpc_conn = boto.vpc.connect_to_region("us-west-1")
    vpc = vpc_conn.get_all_vpcs()[0]
    igws = vpc_conn.get_all_internet_gateways(
        filters={'attachment.vpc-id': vpc.id}
    )

    igws.should.have.length_of(1)

@mock_cloudformation
@mock_ec2
def test_vpc_peering_creation():
    vpc_conn = boto.vpc.connect_to_region("us-west-1")
    vpc_source = vpc_conn.create_vpc("10.0.0.0/16")
    peer_vpc = vpc_conn.create_vpc("10.1.0.0/16")
    template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "vpcpeeringconnection": {
                "Type": "AWS::EC2::VPCPeeringConnection",
                "Properties": {
                    "PeerVpcId": peer_vpc.id,
                    "VpcId": vpc_source.id,
                }
            },
        }
    }

    template_json = json.dumps(template)
    cf_conn = boto.cloudformation.connect_to_region("us-west-1")
    cf_conn.create_stack(
        "test_stack",
        template_body=template_json,
    )

    peering_connections = vpc_conn.get_all_vpc_peering_connections()
    peering_connections.should.have.length_of(1)

@mock_cloudformation
@mock_ec2
def test_multiple_security_group_ingress_separate_from_security_group_by_id():
    template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "test-security-group1": {
                "Type": "AWS::EC2::SecurityGroup",
                "Properties": {
                    "GroupDescription": "test security group",
                    "Tags": [
                        {
                            "Key": "sg-name",
                            "Value": "sg1"
                        }
                    ]
                },
            },
            "test-security-group2": {
                "Type": "AWS::EC2::SecurityGroup",
                "Properties": {
                    "GroupDescription": "test security group",
                    "Tags": [
                        {
                            "Key": "sg-name",
                            "Value": "sg2"
                        }
                    ]
                },
            },
            "test-sg-ingress": {
                "Type": "AWS::EC2::SecurityGroupIngress",
                "Properties": {
                    "GroupId": {"Ref": "test-security-group1"},
                    "IpProtocol": "tcp",
                    "FromPort": "80",
                    "ToPort": "8080",
                    "SourceSecurityGroupId": {"Ref": "test-security-group2"},
                }
            }
        }
    }

    template_json = json.dumps(template)
    cf_conn = boto.cloudformation.connect_to_region("us-west-1")
    cf_conn.create_stack(
        "test_stack",
        template_body=template_json,
    )
    ec2_conn = boto.ec2.connect_to_region("us-west-1")

    security_group1 = ec2_conn.get_all_security_groups(filters={"tag:sg-name": "sg1"})[0]
    security_group2 = ec2_conn.get_all_security_groups(filters={"tag:sg-name": "sg2"})[0]

    security_group1.rules.should.have.length_of(1)
    security_group1.rules[0].grants.should.have.length_of(1)
    security_group1.rules[0].grants[0].group_id.should.equal(security_group2.id)
    security_group1.rules[0].ip_protocol.should.equal('tcp')
    security_group1.rules[0].from_port.should.equal('80')
    security_group1.rules[0].to_port.should.equal('8080')

@mock_cloudformation
@mock_ec2
def test_security_group_ingress_separate_from_security_group_by_id():
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    ec2_conn.create_security_group("test-security-group1", "test security group")

    template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "test-security-group2": {
                "Type": "AWS::EC2::SecurityGroup",
                "Properties": {
                    "GroupDescription": "test security group",
                    "Tags": [
                        {
                            "Key": "sg-name",
                            "Value": "sg2"
                        }
                    ]
                },
            },
            "test-sg-ingress": {
                "Type": "AWS::EC2::SecurityGroupIngress",
                "Properties": {
                    "GroupName": "test-security-group1",
                    "IpProtocol": "tcp",
                    "FromPort": "80",
                    "ToPort": "8080",
                    "SourceSecurityGroupId": {"Ref": "test-security-group2"},
                }
            }
        }
    }

    template_json = json.dumps(template)
    cf_conn = boto.cloudformation.connect_to_region("us-west-1")
    cf_conn.create_stack(
        "test_stack",
        template_body=template_json,
    )
    security_group1 = ec2_conn.get_all_security_groups(groupnames=["test-security-group1"])[0]
    security_group2 = ec2_conn.get_all_security_groups(filters={"tag:sg-name": "sg2"})[0]

    security_group1.rules.should.have.length_of(1)
    security_group1.rules[0].grants.should.have.length_of(1)
    security_group1.rules[0].grants[0].group_id.should.equal(security_group2.id)
    security_group1.rules[0].ip_protocol.should.equal('tcp')
    security_group1.rules[0].from_port.should.equal('80')
    security_group1.rules[0].to_port.should.equal('8080')

@mock_cloudformation
@mock_ec2
def test_security_group_ingress_separate_from_security_group_by_id_using_vpc():
    vpc_conn = boto.vpc.connect_to_region("us-west-1")
    vpc = vpc_conn.create_vpc("10.0.0.0/16")

    template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "test-security-group1": {
                "Type": "AWS::EC2::SecurityGroup",
                "Properties": {
                    "GroupDescription": "test security group",
                    "VpcId": vpc.id,
                    "Tags": [
                        {
                            "Key": "sg-name",
                            "Value": "sg1"
                        }
                    ]
                },
            },
            "test-security-group2": {
                "Type": "AWS::EC2::SecurityGroup",
                "Properties": {
                    "GroupDescription": "test security group",
                    "VpcId": vpc.id,
                    "Tags": [
                        {
                            "Key": "sg-name",
                            "Value": "sg2"
                        }
                    ]
                },
            },
            "test-sg-ingress": {
                "Type": "AWS::EC2::SecurityGroupIngress",
                "Properties": {
                    "GroupId": {"Ref": "test-security-group1"},
                    "VpcId": vpc.id,
                    "IpProtocol": "tcp",
                    "FromPort": "80",
                    "ToPort": "8080",
                    "SourceSecurityGroupId": {"Ref": "test-security-group2"},
                }
            }
        }
    }

    template_json = json.dumps(template)
    cf_conn = boto.cloudformation.connect_to_region("us-west-1")
    cf_conn.create_stack(
        "test_stack",
        template_body=template_json,
    )
    security_group1 = vpc_conn.get_all_security_groups(filters={"tag:sg-name": "sg1"})[0]
    security_group2 = vpc_conn.get_all_security_groups(filters={"tag:sg-name": "sg2"})[0]

    security_group1.rules.should.have.length_of(1)
    security_group1.rules[0].grants.should.have.length_of(1)
    security_group1.rules[0].grants[0].group_id.should.equal(security_group2.id)
    security_group1.rules[0].ip_protocol.should.equal('tcp')
    security_group1.rules[0].from_port.should.equal('80')
    security_group1.rules[0].to_port.should.equal('8080')

@mock_cloudformation
@mock_ec2
def test_subnets_should_be_created_with_availability_zone():
    vpc_conn = boto.vpc.connect_to_region('us-west-1')
    vpc = vpc_conn.create_vpc("10.0.0.0/16")

    subnet_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "testSubnet": {
                "Type": "AWS::EC2::Subnet",
                "Properties": {
                    "VpcId": vpc.id,
                    "CidrBlock": "10.0.0.0/24",
                    "AvailabilityZone": "us-west-1b",
                }
            }
        }
    }
    cf_conn = boto.cloudformation.connect_to_region("us-west-1")
    template_json = json.dumps(subnet_template)
    cf_conn.create_stack(
        "test_stack",
        template_body=template_json,
    )
    subnet = vpc_conn.get_all_subnets(filters={'cidrBlock': '10.0.0.0/24'})[0]
    subnet.availability_zone.should.equal('us-west-1b')


text:
@class CAAnimation, NSArray, NSString;

@protocol SCNMaterialPropertyJSExport <JSExport>
+ (id)materialPropertyWithContents:(id)arg1;
@property(nonatomic) double maxAnisotropy;
@property(nonatomic) long long mappingChannel;
@property(retain, nonatomic) id borderColor;
@property(nonatomic) long long wrapT;
@property(nonatomic) long long wrapS;
@property(nonatomic) struct CATransform3D contentsTransform;
@property(nonatomic) long long mipFilter;
@property(nonatomic) long long magnificationFilter;
@property(nonatomic) long long minificationFilter;
@property(nonatomic) double intensity;
@property(retain, nonatomic) id contents;
- (void)resumeAnimationForKey:(NSString *)arg1;
- (void)pauseAnimationForKey:(NSString *)arg1;
- (CAAnimation *)animationForKey:(NSString *)arg1;
- (NSArray *)animationKeys;
- (void)removeAnimationForKey:(NSString *)arg1;
- (void)removeAllAnimations;
- (void)addAnimation:(CAAnimation *)arg1 forKey:(NSString *)arg2;
@end

redpajama_set_name: RedPajamaGithub


text:
/***********************************************************************************************************************************
Build Common
***********************************************************************************************************************************/
#include "build.auto.h"

#include <ctype.h>

#include "build/common/render.h"
#include "common/type/stringId.h"

/**********************************************************************************************************************************/
String *
bldStrId(const char *const buffer)
{
    StringId result = strIdFromZ(buffer);

    return strNewFmt("STRID%u(\"%s\", 0x%" PRIx64 ")", (unsigned int)(result & STRING_ID_BIT_MASK) + 5, buffer, result);
}

/**********************************************************************************************************************************/
String *
bldEnum(const char *const prefix, const String *const value)
{
    String *const result = strNew();
    const char *const valuePtr = strZ(value);
    bool upper = false;

    // Add prefix and set first non-prefix letter to upper
    if (prefix != NULL)
    {
        strCatZ(result, prefix);
        upper = true;
    }

    // Add remaining letters removing dashes and upper-casing the letter after the dash
    for (unsigned int valueIdx = 0; valueIdx < strSize(value); valueIdx++)
    {
        strCatChr(result, upper ? (char)toupper(valuePtr[valueIdx]) : valuePtr[valueIdx]);
        upper = false;

        if (valuePtr[valueIdx + 1] == '-')
        {
            upper = true;
            valueIdx++;
        }
    }

    return result;
}


text:
Java client for Twingly Search API (previously known as Twingly Analytics API). Twingly is a blog search service that provides a searchable API known as [Twingly Search API](https://developer.twingly.com/resources/search/).

## Installation

Get the latest release from [Maven Central](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22twingly-search%22).

## Usage

```Java
import com.twingly.search.*;
public class Test{
    public static void main(String[] args){
        String apiKey = "API_KEY";
        // create Client object using your API key
        Client client = new UrlConnectionClient(apiKey);
        String q = "spotify";
        Result result = client.makeRequest(q);
        // Get the total number of matches returned
        int numberOfMatchesReturned = result.getNumberOfMatchesReturned();
        // Get the total number of matches to the search query
        int numberOfMatchesTotal = result.getNumberOfMatchesTotal();
        // Get number of seconds it took to execute query
        double secondsElapsed = result.getSecondsElapsed();
        for (Post p : result.getPosts()){
            System.out.println(p.getUrl());             // print url for each post
            System.out.println(p.getTitle());           // print title for each post
        }
    }
}
```

To learn more about the features of this client, check out the example code that can be found in [example](example).

To learn more about the capabilities of the API, please read the [Twingly Search API documentation].

[Twingly Search API documentation]: https://developer.twingly.com/resources/search/

### API key from Java system properties

Additionally, you can create Client object with API key from Java system properties (property name is `TWINGLY_SEARCH_KEY`):

```Java
import com.twingly.search.client.*;
public class Test{
    public static void main(String[] args){
        Client client = new UrlConnectionClient(); // create client object with API key from java system property
    }
}
```

To do so, you will need to run Java with property. For example, run your own `jar` file with twingly search key property:

```
java -jar myJar.jar -DTWINGLY_SEARCH_KEY=some_key_value
```

### Exception handling

Given exception hierarchy is now available:
* TwinglySearchException - super class for any TwinglySearch-related exception
    * TwinglySearchErrorException - super class exceptions, that have some Error details from Twingly Search API response
        * TwinglySearchServerException - exceptions that happened on the API side
        * TwinglySearchClientException - exceptions that happened due to Client misconfiguration or incorrect query
          * TwinglySearchAuthenticationException - exception that happened due to Client Authentication problems
          * TwinglySEarchQueryException - exception that happened due to problems with Query

Check documentation [Error paragraph][error] for additional information.

[error]: https://developer.twingly.com/resources/search/#error

## Requirements

* API key, [sign up](https://www.twingly.com/try-for-free) via [twingly.com](https://www.twingly.com/) to get one
* Java:
    * v 1.7
    * v 1.8

## Development

### Tests

Make sure you have all the dependencies

```
gradlew assemble
```

Run the tests

```
gradlew check
```

Generate coverage report, using [JaCoCo]. Note that you need to run the tests first.

```
gradlew jacocoTestReport

open build/jacocoHtml/index.html
```

[JaCoCo]: https://docs.gradle.org/current/userguide/jacoco_plugin.html

#### Betamax

To be able to run the Betamax-based tests you need to add Betamax's certificate into Java's trust store, `cacerts`:

```
sudo keytool -importcert -keystore $JAVA_HOME/jre/lib/security/cacerts -file betamax.pem -alias betamax -storepass changeit -noprompt
```

It is adviced to remove the certificate after testing is done:

```
sudo keytool -delete -keystore $JAVA_HOME/jre/lib/security/cacerts -alias betamax -storepass changeit -noprompt
```

Note that the temporary files generated by Betamax:

* api.twingly.com.jks
* api.twingly.com.cert
* api.twingly.com.csr
* betamax-local.jks

need to be removed if generated __before__ Betamax's certificate was added to the trust store, tests will fail otherwise.

For more information, check out [Betamax's SSL configuration documentation](https://github.com/betamaxteam/betamax/tree/b65a972d239d1acadd2f9911c3697d263aa20729#ssl-configuration).

### JavaDoc generation

To generate java docs just run gradle task `javadoc`:

```
gradlew javadoc
```

This will save javadocs in `docs` folder under build-folder.

### One-jar generation

To generate one fat jar library with all compile dependencies just run gradle task `generateOneJar`:

```
gradlew generateOneJar
```

This will save JAR file with all needed dependencies in `build/libs/` with `-all` suffix. (like `twingly-search-api-java-all-0.0.1.jar`)

### Release

#### Before you start

* Ensure that you have a properly setup
    * `~/.gradle/gradle.properties` ([see the example](http://central.sonatype.org/pages/gradle.html#credentials))
    * [GPG](https://www.gnupg.org/) keyring
        * `brew install gpg`
        * get the secret key from our secret stash
        * `gpg --import <path to key>`
            * Note: if you use gpg2 you may need to [export the key](https://stackoverflow.com/a/33129703) to the older format

#### Make the release

1. Ensure you are using Java 7
1. Bump the version in [`version.properties`](./src/main/resources/version.properties)
1. Commit the changes
1. Tag the current commit with the same version number and push it
1. Run `gradlew uploadArchives -Prelease` to release to the staging repository
1. Log into [Nexus Repository Manager](https://oss.sonatype.org/) and [find the archive](http://central.sonatype.org/pages/releasing-the-deployment.html#locate-and-examine-your-staging-repository)
1. Read [Releasing the Deployment](http://central.sonatype.org/pages/releasing-the-deployment.html)
1. Release to Central Repository using [Nexus Repository Manager](https://oss.sonatype.org/)

#### Update the changelog

* Install [GitHub Changelog Generator](https://github.com/skywinder/github-changelog-generator/) if you don't have it
    * `gem install github_changelog_generator`
* Set `CHANGELOG_GITHUB_TOKEN` to a personal access token to increase your GitHub API rate limit
* Generate the changelog
    * `github_changelog_generator`

## License

The MIT License (MIT)

Copyright (c) 2012-2016 Twingly AB

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class AutoInvoke extends StdCommand
{
	public AutoInvoke(){}

	private final String[] access=_i(new String[]{"AUTOINVOKE"});
	@Override public String[] getAccessWords(){return access;}

	@Override
	public boolean execute(final MOB mob, Vector commands, int metaFlags)
		throws java.io.IOException
	{
		final Vector<String> abilities=new Vector<String>();
		for(int a=0;a<mob.numAbilities();a++)
		{
			final Ability A=mob.fetchAbility(a);
			if((A!=null)
			&&(A.isAutoInvoked())
			&&((A.classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE)
			&&((A.classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_PROPERTY))
				abilities.addElement(A.ID());
		}

		final Vector<String> effects=new Vector<String>();
		for(int a=0;a<mob.numEffects();a++)
		{
			final Ability A=mob.fetchEffect(a);
			if((A!=null)
			&&(abilities.contains(A.ID()))
			&&(!A.isSavable()))
				effects.addElement(A.ID());
		}

		final StringBuffer str=new StringBuffer(_("^xAuto-invoking abilities:^?^.\n\r^N"));
		int col=0;
		for(int a=0;a<abilities.size();a++)
		{
			final Ability A=mob.fetchAbility(abilities.elementAt(a));
			if(A!=null)
			{
				if(effects.contains(A.ID()))
					str.append(_("@x1.^xACTIVE^?^.^N ",CMStrings.padRightWith(A.Name(),'.',30)));
				else
					str.append(_("@x1^xINACTIVE^?^.^N",CMStrings.padRightWith(A.Name(),'.',30)));
				if(++col==2)
				{
					col=0;
					str.append("\n\r");
				}
				else
					str.append("  ");
			}
		}
		if(col==1)
			str.append("\n\r");

		mob.tell(str.toString());
		final Session session=mob.session();
		if(session!=null)
		{
			session.prompt(new InputCallback(InputCallback.Type.PROMPT,"",0)
			{
				@Override public void showPrompt() { session.promptPrint(_("Enter one to toggle or RETURN: "));}
				@Override public void timedOut() { }
				@Override public void callBack()
				{
					final String s=this.input;
					Ability foundA=null;
					if(s.length()>0)
					{
						for(int a=0;a<abilities.size();a++)
						{
							final Ability A=mob.fetchAbility(abilities.elementAt(a));
							if((A!=null)&&(A.name().equalsIgnoreCase(s)))
							{ foundA=A; break;}
						}
						if(foundA==null)
						for(int a=0;a<abilities.size();a++)
						{
							final Ability A=mob.fetchAbility(abilities.elementAt(a));
							if((A!=null)&&(CMLib.english().containsString(A.name(),s)))
							{ foundA=A; break;}
						}
						if(foundA==null)
							mob.tell(_("'@x1' is invalid.",s));
						else
						if(effects.contains(foundA.ID()))
						{
							foundA=mob.fetchEffect(foundA.ID());
							if(foundA!=null)
							{
								mob.delEffect(foundA);
								if(mob.fetchEffect(foundA.ID())!=null)
									mob.tell(_("@x1 failed to successfully deactivate.",foundA.name()));
								else
									mob.tell(_("@x1 successfully deactivated.",foundA.name()));
							}
						}
						else
						{
							foundA.autoInvocation(mob);
							if(mob.fetchEffect(foundA.ID())!=null)
								mob.tell(_("@x1 successfully invoked.",foundA.name()));
							else
								mob.tell(_("@x1 failed to successfully invoke.",foundA.name()));
						}
					}
				}
			});
		}
		return false;
	}

	@Override public boolean canBeOrdered(){return true;}

}


text:
//
//  lock.h
//  Firedrake
//
//  Created by Sidney Just
//  Copyright (c) 2012 by Sidney Just
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//  documentation files (the "Software"), to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
//  and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
//  PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
//  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
//  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#ifndef _LOCK_H_
#define _LOCK_H_

#include <types.h>

typedef uint8_t spinlock_t;

#define SPINLOCK_INIT 0
#define SPINLOCK_INIT_LOCKED 1

void spinlock_lock(spinlock_t *lock);
bool spinlock_tryLock(spinlock_t *lock);
void spinlock_unlock(spinlock_t *lock);

#endif /* _LOCK_H_ */


text:
@import UIKit;
#import <ResearchKit/ORKRecorder.h>
#import <Availability.h>

NS_ASSUME_NONNULL_BEGIN

/**
 The `ORKHealthClinicalTypeRecorder` class represents a recorder for collecting health records data from HealthKit during
 an active task.
 */
#if defined(__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_12_0
ORK_CLASS_AVAILABLE
API_AVAILABLE(ios(12.0))
@interface ORKHealthClinicalTypeRecorder : ORKRecorder

@property (nonatomic, copy, readonly) HKClinicalType *healthClinicalType;

@property (nonatomic, copy, readonly) HKFHIRResourceType healthFHIRResourceType;

/**
 Returns an initialized health clinical type recorder using the specified HKClinicalType and HKFHIRResourceType.

 @param identifier              The unique identifier of the recorder (assigned by the recorder configuration).
 @param healthClinicalType      The HKClinicalType data that should be collected during the active task.
 @param healthFHIRResourceType  The HKFHIRResourceType for the predicate used to query the HKClinicalType.
 @param step                    The step that requested this recorder.
 @param outputDirectory         The directory in which the health records data queried from HealthKit should be stored.

 @return An initialized health quantity type recorder.
 */
- (instancetype)initWithIdentifier:(NSString *)identifier
                healthClinicalType:(HKClinicalType *)healthClinicalType
            healthFHIRResourceType:(nullable HKFHIRResourceType)healthFHIRResourceType
                              step:(nullable ORKStep *)step
                   outputDirectory:(nullable NSURL *)outputDirectory NS_DESIGNATED_INITIALIZER API_AVAILABLE(ios(12.0));

@end
#endif

NS_ASSUME_NONNULL_END


text:
//-----------------------------------------------------------------------
// <copyright file="TestActor.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using Akka.Actor;

namespace Akka.TestKit
{
    /// <summary>
    /// TBD
    /// </summary>
    public static class TestActor
    {
        /// <summary>
        /// A delegate that returns <c>true</c> if the <paramref name="message"/> should be ignored.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>TBD</returns>
        public delegate bool Ignore(object message);

        /// <summary>
        /// TBD
        /// </summary>
        public static AutoPilot NoAutoPilot { get { return TestKit.NoAutoPilot.Instance; } }
        /// <summary>
        /// TBD
        /// </summary>
        public static AutoPilot KeepRunning { get { return TestKit.KeepRunning.Instance; } }
        /// <summary>
        /// TBD
        /// </summary>
        public static NullMessageEnvelope NullMessage { get { return NullMessageEnvelope.Instance; } }

        /// <summary>
        /// Message that is supposed to be sent to a <see cref="TestActor"/> to make it ignore
        /// received messages. If the delegate specified on the constructor returns
        /// <c>true</c> the message will be ignored by <see cref="TestActor"/>
        /// </summary>
        public class SetIgnore : INoSerializationVerificationNeeded
        {
            private readonly Ignore _ignore;

            /// <summary>
            /// TBD
            /// </summary>
            /// <param name="ignore">TBD</param>
            public SetIgnore(Ignore ignore) { _ignore = ignore; }

            /// <summary>
            /// TBD
            /// </summary>
            public Ignore Ignore { get { return _ignore; } }
        }

        /// <summary>
        /// Message that is supposed to be sent to a <see cref="TestActor"/> to make it watch
        /// the specified actor and receive death notifications,
        /// i.e. <see cref="Terminated"/> messages.
        /// </summary>
        public class Watch : INoSerializationVerificationNeeded
        {
            private readonly IActorRef _actorToWatch;

            /// <summary>
            /// TBD
            /// </summary>
            /// <param name="actorToWatch">TBD</param>
            public Watch(IActorRef actorToWatch) { _actorToWatch = actorToWatch; }

            /// <summary>
            /// TBD
            /// </summary>
            public IActorRef Actor { get { return _actorToWatch; } }
        }

        /// <summary>
        /// Message that is supposed to be sent to a <see cref="TestActor"/> to make it unwatch
        /// a previously watched actor.
        /// </summary>
        public class Unwatch : INoSerializationVerificationNeeded
        {
            private readonly IActorRef _actorToUnwatch;

            /// <summary>
            /// TBD
            /// </summary>
            /// <param name="actorToUnwatch">TBD</param>
            public Unwatch(IActorRef actorToUnwatch) { _actorToUnwatch = actorToUnwatch; }

            /// <summary>
            /// TBD
            /// </summary>
            public IActorRef Actor { get { return _actorToUnwatch; } }
        }

        /// <summary>
        /// Message that is supposed to be sent to a <see cref="TestActor"/>
        /// to install an AutoPilot to drive the <see cref="TestActor"/>: the AutoPilot
        /// will be run for each received message and can be used to send or forward
        /// messages, etc. Each invocation must return the AutoPilot for the next round.
        /// </summary>
        public class SetAutoPilot : INoSerializationVerificationNeeded
        {
            private readonly AutoPilot _autoPilot;

            /// <summary>
            /// TBD
            /// </summary>
            /// <param name="autoPilot">TBD</param>
            public SetAutoPilot(AutoPilot autoPilot) { _autoPilot = autoPilot; }

            /// <summary>
            /// TBD
            /// </summary>
            public AutoPilot AutoPilot { get { return _autoPilot; } }
        }
    }
}


text:
namespace remoting {

bool LoadResources(const std::string& pref_locale) {
  // Do nothing since .pak files are not used on Windows.
  return false;
}

void UnloadResources() {
}

}  // namespace remoting


text:
package nl.kaninefatendreef.si.server.model.mongo;

public class SimplerInvoiceDocumentContent implements nl.kaninefatendreef.si.server.model.SimplerInvoiceDocumentContent{

	byte [] document = null;

	public byte[] getDocument() {
		return document;
	}
	public void setDocument(byte[] document) {
		this.document = document;
	}

}


text:
namespace agge
{
	long interlocked_compare_exchange(volatile long *destination, long new_value, long comparand);
	long interlocked_exchange(volatile long *destination, long new_value);
	void pause();
}


text:
<?php

class MercadoPago_Core_Model_Core
    extends Mage_Payment_Model_Method_Abstract
{
    protected $_code = 'mercadopago';

    protected $_isGateway = true;
    protected $_canOrder = true;
    protected $_canAuthorize = true;
    protected $_canCapture = true;
    protected $_canCapturePartial = true;
    protected $_canRefund = true;
    protected $_canRefundInvoicePartial = true;
    protected $_canVoid = true;
    protected $_canUseInternal = true;
    protected $_canUseCheckout = true;
    protected $_canUseForMultishipping = true;
    protected $_canFetchTransactionInfo = true;
    protected $_canCreateBillingAgreement = true;
    protected $_canReviewPayment = true;

    const XML_PATH_ACCESS_TOKEN = 'payment/mercadopago_custom_checkout/access_token';
    const LOG_FILE = 'mercadopago-custom.log';

    /**
     * @return Mage_Checkout_Model_Session
     */
    protected function _getCheckout()
    {
        return Mage::getSingleton('checkout/session');
    }

    /**
     * Get admin checkout session namespace
     *
     * @return Mage_Adminhtml_Model_Session_Quote
     */
    protected function _getAdminCheckout()
    {
        return Mage::getSingleton('adminhtml/session_quote');
    }

    /**
     * Retrieves Quote
     *
     * @param integer $quoteId
     *
     * @return Mage_Sales_Model_Quote
     */
    protected function _getQuote($quoteId = null)
    {
        if (!empty($quoteId)) {
            return Mage::getModel('sales/quote')->load($quoteId);
        } else {
            if (Mage::app()->getStore()->isAdmin()) {
                return $this->_getAdminCheckout()->getQuote();
            } else {
                return $this->_getCheckout()->getQuote();
            }
        }
    }

    /**
     * Retrieves Order
     *
     * @param integer $incrementId
     *
     * @return Mage_Sales_Model_Order
     */
    protected function _getOrder($incrementId)
    {
        return Mage::getModel('sales/order')->loadByIncrementId($incrementId);
    }

    public function getInfoPaymentByOrder($order_id)
    {
        $order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
        $payment = $order->getPayment();
        $info_payments = array();
        $fields = array(
            array("field" => "cardholderName", "title" => "Card Holder Name: %s"),
            array("field" => "trunc_card", "title" => "Card Number: %s"),
            array("field" => "payment_method", "title" => "Payment Method: %s"),
            array("field" => "expiration_date", "title" => "Expiration Date: %s"),
            array("field" => "installments", "title" => "Installments: %s"),
            array("field" => "statement_descriptor", "title" => "Statement Descriptor: %s"),
            array("field" => "payment_id", "title" => "Payment id (MercadoPago): %s"),
            array("field" => "status", "title" => "Payment Status: %s"),
            array("field" => "status_detail", "title" => "Payment Detail: %s"),
            array("field" => "activation_uri", "title" => "Generate Ticket")
        );

        foreach ($fields as $field):
            if ($payment->getAdditionalInformation($field['field']) != ""):
                $text = Mage::helper('mercadopago')->__($field['title'], $payment->getAdditionalInformation($field['field']));
                $info_payments[$field['field']] = array(
                    "text"  => $text,
                    "value" => $payment->getAdditionalInformation($field['field'])
                );
            endif;
        endforeach;

        return $info_payments;
    }

    protected function validStatusTwoPayments($status)
    {
        $array_status = explode(" | ", $status);
        $status_verif = true;
        $status_final = "";
        foreach ($array_status as $status):

            if ($status_final == "") {
                $status_final = $status;
            } else {
                if ($status_final != $status) {
                    $status_verif = false;
                }
            }
        endforeach;

        if ($status_verif === false) {
            $status_final = "other";
        }

        return $status_final;
    }

    public function getMessageByStatus($status, $status_detail, $payment_method, $installment, $amount)
    {
        $status = $this->validStatusTwoPayments($status);
        $status_detail = $this->validStatusTwoPayments($status_detail);

        $message = array(
            "title"   => "",
            "message" => ""
        );

        $rawMessage = Mage::helper('mercadopago/statusMessage')->getMessage($status);
        $message['title'] = Mage::helper('mercadopago')->__($rawMessage['title']);

        if ($status == 'rejected') {
            if ($status_detail == 'cc_rejected_invalid_installments') {
                $message['message'] = Mage::helper('mercadopago')
                    ->__(Mage::helper('mercadopago/statusDetailMessage')->getMessage($status_detail), strtoupper($payment_method), $installment);
            } elseif ($status_detail == 'cc_rejected_call_for_authorize') {
                $message['message'] = Mage::helper('mercadopago')
                    ->__(Mage::helper('mercadopago/statusDetailMessage')->getMessage($status_detail), strtoupper($payment_method), $amount);
            } else {
                $message['message'] = Mage::helper('mercadopago')
                    ->__(Mage::helper('mercadopago/statusDetailMessage')->getMessage($status_detail), strtoupper($payment_method));
            }
        } else {
            $message['message'] = Mage::helper('mercadopago')->__($rawMessage['message']);
        }

        return $message;
    }

    protected function getCustomerInfo($customer, $order)
    {
        $email = htmlentities($customer->getEmail());
        if ($email == "") {
            $email = $order['customer_email'];
        }

        $first_name = htmlentities($customer->getFirstname());
        if ($first_name == "") {
            $first_name = $order->getBillingAddress()->getFirstname();
        }

        $last_name = htmlentities($customer->getLastname());
        if ($last_name == "") {
            $last_name = $order->getBillingAddress()->getLastname();
        }

        return array('email' => $email, 'first_name' => $first_name, 'last_name' => $last_name);
    }

    protected function getItemsInfo($order)
    {
        $dataItems = array();
        foreach ($order->getAllVisibleItems() as $item) {
            $product = $item->getProduct();
            $image = (string)Mage::helper('catalog/image')->init($product, 'image');

            $dataItems[] = array(
                "id"          => $item->getSku(),
                "title"       => $product->getName(),
                "description" => $product->getName(),
                "picture_url" => $image,
                "category_id" => Mage::getStoreConfig('payment/mercadopago/category_id'),
                "quantity"    => (int)number_format($item->getQtyOrdered(), 0, '.', ''),
                "unit_price"  => (float)number_format($product->getPrice(), 2, '.', '')
            );
        }

        /* verify discount and add it like an item */
        $discount = $this->getDiscount();
        if ($discount != 0) {
            $dataItems[] = array(
                "title"       => "Discount by the Store",
                "description" => "Discount by the Store",
                "quantity"    => 1,
                "unit_price"  => (float)number_format($discount, 2, '.', '')
            );
        }

        return $dataItems;

    }

    protected function getCouponInfo($coupon, $coupon_code)
    {
        $infoCoupon = array();
        $infoCoupon['coupon_amount'] = (float)$coupon['response']['coupon_amount'];
        $infoCoupon['coupon_code'] = $coupon_code;
        $infoCoupon['campaign_id'] = $coupon['response']['id'];
        if ($coupon['status'] == 200) {
            Mage::helper('mercadopago')->log("Coupon applied. API response 200.", self::LOG_FILE);
        } else {
            Mage::helper('mercadopago')->log("Coupon invalid, not applied.", self::LOG_FILE);
        }

        return $infoCoupon;
    }

    public function makeDefaultPreferencePaymentV1($payment_info = array())
    {
        $quote = $this->_getQuote();
        $order_id = $quote->getReservedOrderId();
        $order = $this->_getOrder($order_id);
        $customer = Mage::getSingleton('customer/session')->getCustomer();

        $billing_address = $quote->getBillingAddress()->getData();
        $customerInfo = $this->getCustomerInfo($customer, $order);

        /* INIT PREFERENCE */
        $preference = array();

        $preference['notification_url'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . "mercadopago/notifications/custom";

        $preference['transaction_amount'] = (float)$this->getAmount();

        $preference['external_reference'] = $order_id;
        $preference['payer']['email'] = $customerInfo['email'];

        if (!empty($payment_info['identification_type'])) {
            $preference['payer']['identification']['type'] = $payment_info['identification_type'];
            $preference['payer']['identification']['number'] = $payment_info['identification_number'];
        }
        $preference['additional_info']['items'] = $this->getItemsInfo($order);

        $preference['additional_info']['payer']['first_name'] = $customerInfo['first_name'];
        $preference['additional_info']['payer']['last_name'] = $customerInfo['last_name'];

        $preference['additional_info']['payer']['address'] = array(
            "zip_code"      => $billing_address['postcode'],
            "street_name"   => $billing_address['street'] . " - " . $billing_address['city'] . " - " . $billing_address['country_id'],
            "street_number" => ''
        );

        $preference['additional_info']['payer']['registration_date'] = date('Y-m-d', $customer->getCreatedAtTimestamp()) . "T" . date('H:i:s', $customer->getCreatedAtTimestamp());

        $shipping = $order->getShippingAddress()->getData();

        $preference['additional_info']['shipments']['receiver_address'] = array(
            "zip_code"      => $shipping['postcode'],
            "street_name"   => $shipping['street'] . " - " . $shipping['city'] . " - " . $shipping['country_id'],
            "street_number" => '',
            "floor"         => "-",
            "apartment"     => "-",

        );

        $preference['additional_info']['payer']['phone'] = array(
            "area_code" => "0",
            "number"    => $shipping['telephone']
        );

        if (!empty($payment_info['coupon_code'])) {
            $coupon_code = $payment_info['coupon_code'];
            Mage::helper('mercadopago')->log("Validating coupon_code: " . $coupon_code, self::LOG_FILE);

            $coupon = $this->validCoupon($coupon_code);
            Mage::helper('mercadopago')->log("Response API Coupon: ", self::LOG_FILE, $coupon);

            $couponInfo = $this->getCouponInfo($coupon, $coupon_code);
            $preference['coupon_amount'] = $couponInfo['coupon_amount'];
            $preference['coupon_code'] = $couponInfo['coupon_code'];
            $preference['campaign_id'] = $couponInfo['campaign_id'];

        }

        $sponsor_id = Mage::getStoreConfig('payment/mercadopago/sponsor_id');
        Mage::helper('mercadopago')->log("Sponsor_id", 'mercadopago-standard.log', $sponsor_id);
        if (!empty($sponsor_id)) {
            Mage::helper('mercadopago')->log("Sponsor_id identificado", self::LOG_FILE, $sponsor_id);
            $preference['sponsor_id'] = (int)$sponsor_id;
        }

        return $preference;
    }

    public function postPaymentV1($preference)
    {

        //obtem access_token
        $access_token = Mage::getStoreConfig(self::XML_PATH_ACCESS_TOKEN);
        Mage::helper('mercadopago')->log("Access Token for Post", self::LOG_FILE, $access_token);

        //seta sdk php mercadopago
        $mp = Mage::helper('mercadopago')->getApiInstance($access_token);
        $response = $mp->post("/v1/payments", $preference);
        Mage::helper('mercadopago')->log("POST /v1/payments", self::LOG_FILE, $response);

        if ($response['status'] == 200 || $response['status'] == 201) {
            return $response;
        } else {
            $e = "";
            $exception = new MercadoPago_Core_Model_Api_V1_Exception();
            if (count($response['response']['cause']) > 0) {
                foreach ($response['response']['cause'] as $error) {
                    $e .= $exception->getUserMessage($error) . " ";
                }
            } else {
                $e = $exception->getUserMessage();
            }

            Mage::helper('mercadopago')->log("error post pago: " . $e, self::LOG_FILE);
            Mage::helper('mercadopago')->log("response post pago: ", self::LOG_FILE, $response);

            $exception->setMessage($e);
            throw $exception;
        }
    }

    public function getPayment($payment_id)
    {
        $clienId = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_ID);
        $clientSecret = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_SECRET);
        $mp = Mage::helper('mercadopago')->getApiInstance($clienId, $clientSecret);

        return $mp->get_payment($payment_id);
    }

    public function getPaymentV1($payment_id)
    {
        $this->access_token = Mage::getStoreConfig(self::XML_PATH_ACCESS_TOKEN);
        $mp = Mage::helper('mercadopago')->getApiInstance($this->access_token);

        return $mp->get("/v1/payments/" . $payment_id);
    }

    public function getMerchantOrder($merchant_order_id)
    {
        $clientId = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_ID);
        $clientSecret = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_SECRET);
        $mp = Mage::helper('mercadopago')->getApiInstance($clientId, $clientSecret);

        return $mp->get("/merchant_orders/" . $merchant_order_id);
    }

    public function getPaymentMethods()
    {
        $this->access_token = Mage::getStoreConfig(self::XML_PATH_ACCESS_TOKEN);

        $mp = Mage::helper('mercadopago')->getApiInstance($this->access_token);

        $payment_methods = $mp->get("/v1/payment_methods");

        return $payment_methods;
    }

    public function getEmailCustomer()
    {
        $customer = Mage::getSingleton('customer/session')->getCustomer();
        $email = $customer->getEmail();

        if (empty($email)) {
            $quote = $this->_getQuote();
            $email = $quote->getBillingAddress()->getEmail();
        }

        return $email;
    }

    public function getAmount()
    {
        $quote = $this->_getQuote();
        $total = $quote->getBaseSubtotalWithDiscount() + $quote->getShippingAddress()->getShippingAmount() + $quote->getShippingAddress()->getBaseTaxAmount();

        return (float)$total;

    }

    public function validCoupon($id)
    {
        $this->access_token = Mage::getStoreConfig(self::XML_PATH_ACCESS_TOKEN);

        $mp = Mage::helper('mercadopago')->getApiInstance($this->access_token);

        $params = array(
            "transaction_amount" => $this->getAmount(),
            "payer_email"        => $this->getEmailCustomer(),
            "coupon_code"        => $id
        );

        $details_discount = $mp->get("/discount_campaigns", $params);

        //add value on return api discount
        $details_discount['response']['transaction_amount'] = $params['transaction_amount'];
        $details_discount['response']['params'] = $params;

        return $details_discount;
    }

    public function setStatusOrder($payment, $stateObject = null)
    {
        $helper = Mage::helper('mercadopago');
        $order = Mage::getModel('sales/order')->loadByIncrementId($payment["external_reference"]);
        $status = $payment['status'];

        if (isset($payment['status_final'])) {
            $status = $payment['status_final'];
        }
        $message = $helper->getMessage($status, $payment);

        try {
            if ($status == 'approved') {
                Mage::helper('mercadopago')->setOrderSubtotals($payment, $order);

                if (!$order->hasInvoices()) {
                    $invoice = $order->prepareInvoice();
                    $invoice->register()->pay();
                    Mage::getModel('core/resource_transaction')
                        ->addObject($invoice)
                        ->addObject($invoice->getOrder())
                        ->save();

                    $invoice->sendEmail(true, $message);
                }
                //Associate card to customer
                $additionalInfo = $order->getPayment()->getAdditionalInformation();
                if (isset($additionalInfo['token'])) {
                    Mage::getModel('mercadopago/custom_payment')->customerAndCards($additionalInfo['token'], $payment);
                }

            } elseif ($status == 'refunded' || $status == 'cancelled') {
                $order->cancel();
            }

            $statusOrder = $helper->getStatusOrder($status);
            if ($stateObject) {
                $stateObject->setStatus($statusOrder);
                $stateObject->setState($helper->_getAssignedState($statusOrder));
                $stateObject->setIsNotified(true);
            }

            $order->setState($helper->_getAssignedState($statusOrder));
            $order->addStatusToHistory($statusOrder, $message, true);
            $order->sendOrderUpdateEmail(true, $message);

            $status_save = $order->save();
            $helper->log("Update order", 'mercadopago.log', $status_save->getData());
            $helper->log($message, 'mercadopago.log');

            return ['text' => $message, 'code' => MercadoPago_Core_Helper_Response::HTTP_OK];
        } catch (Exception $e) {
            $helper->log("error in set order status: " . $e, 'mercadopago.log');

            return ['text' => $e, 'code' => MercadoPago_Core_Helper_Response::HTTP_BAD_REQUEST];
        }
    }

    public function updateOrder($data)
    {
        Mage::helper('mercadopago')->log("Update Order", 'mercadopago-notification.log');

        try {
            $order = Mage::getModel('sales/order')->loadByIncrementId($data["external_reference"]);

            $payment_order = $order->getPayment();

            $additionalFields = array(
                'status',
                'status_detail',
                'payment_id',
                'transaction_amount',
                'cardholderName',
                'installments',
                'statement_descriptor',
                'trunc_card'

            );

            foreach ($additionalFields as $field) {
                if (isset($data[$field])) {
                    $payment_order->setAdditionalInformation($field, $data[$field]);
                }
            }

            if (isset($data['payment_method_id'])) {
                $payment_order->setAdditionalInformation('payment_method', $data['payment_method_id']);
            }

            $payment_status = $payment_order->save();
            Mage::helper('mercadopago')->log("Update Payment", 'mercadopago.log', $payment_status->getData());

            if ($data['payer_first_name']) {
                $order->setCustomerFirstname($data['payer_first_name']);
            }

            if ($data['payer_last_name']) {
                $order->setCustomerLastname($data['payer_last_name']);
            }

            if ($data['payer_email']) {
                $order->setCustomerEmail($data['payer_email']);
            }

            $status_save = $order->save();
            Mage::helper('mercadopago')->log("Update order", 'mercadopago.log', $status_save->getData());
        } catch (Exception $e) {
            Mage::helper('mercadopago')->log("error in update order status: " . $e, 'mercadopago.log');
            $this->getResponse()->setBody($e);

            $this->getResponse()->setHttpResponseCode(MercadoPago_Core_Helper_Response::HTTP_BAD_REQUEST);
        }
    }

}


text:
import React, { useState, useRef, useCallback } from 'react';
import { Input, Divider } from 'src/common/components';
import { CronPicker, CronError, CronProps } from '.';

export default {
  title: 'CronPicker',
  component: CronPicker,
};

export const InteractiveCronPicker = (props: CronProps) => {
  // @ts-ignore
  const inputRef = useRef<Input>(null);
  const [value, setValue] = useState(props.value);
  const customSetValue = useCallback(
    (newValue: string) => {
      setValue(newValue);
      inputRef.current?.setValue(newValue);
    },
    [inputRef],
  );
  const [error, onError] = useState<CronError>();

  return (

      <Input
        ref={inputRef}
        onBlur={event => {
          setValue(event.target.value);
        }}
        onChange={e => setValue(e.target.value || '')}
      />
      <Divider />
      <CronPicker
        {...props}
        value={value}
        setValue={customSetValue}
        onError={onError}
      />
      {error &&
Error: {error.description}
}

  );
};

InteractiveCronPicker.args = {
  clearButton: false,
  disabled: false,
  readOnly: false,
};

InteractiveCronPicker.argTypes = {
  value: {
    defaultValue: '30 5 * * *',
    table: {
      disable: true,
    },
  },
  theme: {
    table: {
      disable: true,
    },
  },
};

InteractiveCronPicker.story = {
  parameters: {
    knobs: {
      disable: true,
    },
  },
};