text:
import httplib

from datetime import datetime, timedelta
from mock import MagicMock, Mock, patch
from tests.unit import unittest
from tests.unit import AWSMockServiceTestCase

import boto.ec2

from boto.regioninfo import RegionInfo
from boto.ec2.connection import EC2Connection
from boto.ec2.snapshot import Snapshot

class TestEC2ConnectionBase(AWSMockServiceTestCase):
    connection_class = EC2Connection

    def setUp(self):
        super(TestEC2ConnectionBase, self).setUp()
        self.ec2 = self.service_connection

class TestReservedInstanceOfferings(TestEC2ConnectionBase):

    def default_body(self):
        return """
            <DescribeReservedInstancesOfferingsResponse>
                <requestId>d3253568-edcf-4897-9a3d-fb28e0b3fa38</requestId>
                    <reservedInstancesOfferingsSet>
                    <item>
                        <reservedInstancesOfferingId>2964d1bf71d8</reservedInstancesOfferingId>
                        <instanceType>c1.medium</instanceType>
                        <availabilityZone>us-east-1c</availabilityZone>
                        <duration>94608000</duration>
                        <fixedPrice>775.0</fixedPrice>
                        <usagePrice>0.0</usagePrice>
                        <productDescription>product description</productDescription>
                        <instanceTenancy>default</instanceTenancy>
                        <currencyCode>USD</currencyCode>
                        <offeringType>Heavy Utilization</offeringType>
                        <recurringCharges>
                            <item>
                                <frequency>Hourly</frequency>
                                <amount>0.095</amount>
                            </item>
                        </recurringCharges>
                        <marketplace>false</marketplace>
                        <pricingDetailsSet>
                            <item>
                                <price>0.045</price>
                                <count>1</count>
                            </item>
                        </pricingDetailsSet>
                    </item>
                    <item>
                        <reservedInstancesOfferingId>2dce26e46889</reservedInstancesOfferingId>
                        <instanceType>c1.medium</instanceType>
                        <availabilityZone>us-east-1c</availabilityZone>
                        <duration>94608000</duration>
                        <fixedPrice>775.0</fixedPrice>
                        <usagePrice>0.0</usagePrice>
                        <productDescription>Linux/UNIX</productDescription>
                        <instanceTenancy>default</instanceTenancy>
                        <currencyCode>USD</currencyCode>
                        <offeringType>Heavy Utilization</offeringType>
                        <recurringCharges>
                            <item>
                                <frequency>Hourly</frequency>
                                <amount>0.035</amount>
                            </item>
                        </recurringCharges>
                        <marketplace>false</marketplace>
                        <pricingDetailsSet/>
                    </item>
                </reservedInstancesOfferingsSet>
                <nextToken>next_token</nextToken>
            </DescribeReservedInstancesOfferingsResponse>
        """

    def test_get_reserved_instance_offerings(self):
        self.set_http_response(status_code=200)
        response = self.ec2.get_all_reserved_instances_offerings()
        self.assertEqual(len(response), 2)
        instance = response[0]
        self.assertEqual(instance.id, '2964d1bf71d8')
        self.assertEqual(instance.instance_type, 'c1.medium')
        self.assertEqual(instance.availability_zone, 'us-east-1c')
        self.assertEqual(instance.duration, 94608000)
        self.assertEqual(instance.fixed_price, '775.0')
        self.assertEqual(instance.usage_price, '0.0')
        self.assertEqual(instance.description, 'product description')
        self.assertEqual(instance.instance_tenancy, 'default')
        self.assertEqual(instance.currency_code, 'USD')
        self.assertEqual(instance.offering_type, 'Heavy Utilization')
        self.assertEqual(len(instance.recurring_charges), 1)
        self.assertEqual(instance.recurring_charges[0].frequency, 'Hourly')
        self.assertEqual(instance.recurring_charges[0].amount, '0.095')
        self.assertEqual(len(instance.pricing_details), 1)
        self.assertEqual(instance.pricing_details[0].price, '0.045')
        self.assertEqual(instance.pricing_details[0].count, '1')

    def test_get_reserved_instance_offerings_params(self):
        self.set_http_response(status_code=200)
        self.ec2.get_all_reserved_instances_offerings(
            reserved_instances_offering_ids=['id1','id2'],
            instance_type='t1.micro',
            availability_zone='us-east-1',
            product_description='description',
            instance_tenancy='dedicated',
            offering_type='offering_type',
            include_marketplace=False,
            min_duration=100,
            max_duration=1000,
            max_instance_count=1,
            next_token='next_token',
            max_results=10
        )
        self.assert_request_parameters({
            'Action': 'DescribeReservedInstancesOfferings',
            'ReservedInstancesOfferingId.1': 'id1',
            'ReservedInstancesOfferingId.2': 'id2',
            'InstanceType': 't1.micro',
            'AvailabilityZone': 'us-east-1',
            'ProductDescription': 'description',
            'InstanceTenancy': 'dedicated',
            'OfferingType': 'offering_type',
            'IncludeMarketplace': 'false',
            'MinDuration': '100',
            'MaxDuration': '1000',
            'MaxInstanceCount': '1',
            'NextToken': 'next_token',
            'MaxResults': '10',},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp', 'Version'])

class TestPurchaseReservedInstanceOffering(TestEC2ConnectionBase):
    def default_body(self):
        return """<PurchaseReservedInstancesOffering />"""

    def test_serialized_api_args(self):
        self.set_http_response(status_code=200)
        response = self.ec2.purchase_reserved_instance_offering(
                'offering_id', 1, (100.0, 'USD'))
        self.assert_request_parameters({
            'Action': 'PurchaseReservedInstancesOffering',
            'InstanceCount': 1,
            'ReservedInstancesOfferingId': 'offering_id',
            'LimitPrice.Amount': '100.0',
            'LimitPrice.CurrencyCode': 'USD',},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

class TestCancelReservedInstancesListing(TestEC2ConnectionBase):
    def default_body(self):
        return """
            <CancelReservedInstancesListingResponse>
                <requestId>request_id</requestId>
                <reservedInstancesListingsSet>
                    <item>
                        <reservedInstancesListingId>listing_id</reservedInstancesListingId>
                        <reservedInstancesId>instance_id</reservedInstancesId>
                        <createDate>2012-07-12T16:55:28.000Z</createDate>
                        <updateDate>2012-07-12T16:55:28.000Z</updateDate>
                        <status>cancelled</status>
                        <statusMessage>CANCELLED</statusMessage>
                        <instanceCounts>
                            <item>
                                <state>Available</state>
                                <instanceCount>0</instanceCount>
                            </item>
                            <item>
                                <state>Sold</state>
                                <instanceCount>0</instanceCount>
                            </item>
                            <item>
                                <state>Cancelled</state>
                                <instanceCount>1</instanceCount>
                            </item>
                            <item>
                                <state>Pending</state>
                                <instanceCount>0</instanceCount>
                            </item>
                        </instanceCounts>
                        <priceSchedules>
                            <item>
                                <term>5</term>
                                <price>166.64</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>4</term>
                                <price>133.32</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>3</term>
                                <price>99.99</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>2</term>
                                <price>66.66</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>1</term>
                                <price>33.33</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                        </priceSchedules>
                        <tagSet/>
                        <clientToken>XqJIt1342112125076</clientToken>
                    </item>
                </reservedInstancesListingsSet>
            </CancelReservedInstancesListingResponse>
        """

    def test_reserved_instances_listing(self):
        self.set_http_response(status_code=200)
        response = self.ec2.cancel_reserved_instances_listing()
        self.assertEqual(len(response), 1)
        cancellation = response[0]
        self.assertEqual(cancellation.status, 'cancelled')
        self.assertEqual(cancellation.status_message, 'CANCELLED')
        self.assertEqual(len(cancellation.instance_counts), 4)
        first = cancellation.instance_counts[0]
        self.assertEqual(first.state, 'Available')
        self.assertEqual(first.instance_count, 0)
        self.assertEqual(len(cancellation.price_schedules), 5)
        schedule = cancellation.price_schedules[0]
        self.assertEqual(schedule.term, 5)
        self.assertEqual(schedule.price, '166.64')
        self.assertEqual(schedule.currency_code, 'USD')
        self.assertEqual(schedule.active, False)

class TestCreateReservedInstancesListing(TestEC2ConnectionBase):
    def default_body(self):
        return """
            <CreateReservedInstancesListingResponse>
                <requestId>request_id</requestId>
                <reservedInstancesListingsSet>
                    <item>
                        <reservedInstancesListingId>listing_id</reservedInstancesListingId>
                        <reservedInstancesId>instance_id</reservedInstancesId>
                        <createDate>2012-07-17T17:11:09.449Z</createDate>
                        <updateDate>2012-07-17T17:11:09.468Z</updateDate>
                        <status>active</status>
                        <statusMessage>ACTIVE</statusMessage>
                        <instanceCounts>
                            <item>
                                <state>Available</state>
                                <instanceCount>1</instanceCount>
                            </item>
                            <item>
                                <state>Sold</state>
                                <instanceCount>0</instanceCount>
                            </item>
                            <item>
                                <state>Cancelled</state>
                                <instanceCount>0</instanceCount>
                            </item>
                            <item>
                                <state>Pending</state>
                                <instanceCount>0</instanceCount>
                            </item>
                        </instanceCounts>
                        <priceSchedules>
                            <item>
                                <term>11</term>
                                <price>2.5</price>
                                <currencyCode>USD</currencyCode>
                                <active>true</active>
                            </item>
                            <item>
                                <term>10</term>
                                <price>2.5</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>9</term>
                                <price>2.5</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>8</term>
                                <price>2.0</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>7</term>
                                <price>2.0</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>6</term>
                                <price>2.0</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>5</term>
                                <price>1.5</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>4</term>
                                <price>1.5</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>3</term>
                                <price>0.7</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>2</term>
                                <price>0.7</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                            <item>
                                <term>1</term>
                                <price>0.1</price>
                                <currencyCode>USD</currencyCode>
                                <active>false</active>
                            </item>
                        </priceSchedules>
                        <tagSet/>
                        <clientToken>myIdempToken1</clientToken>
                    </item>
                </reservedInstancesListingsSet>
            </CreateReservedInstancesListingResponse>
        """

    def test_create_reserved_instances_listing(self):
        self.set_http_response(status_code=200)
        response = self.ec2.create_reserved_instances_listing(
            'instance_id', 1, [('2.5', 11), ('2.0', 8)], 'client_token')
        self.assertEqual(len(response), 1)
        cancellation = response[0]
        self.assertEqual(cancellation.status, 'active')
        self.assertEqual(cancellation.status_message, 'ACTIVE')
        self.assertEqual(len(cancellation.instance_counts), 4)
        first = cancellation.instance_counts[0]
        self.assertEqual(first.state, 'Available')
        self.assertEqual(first.instance_count, 1)
        self.assertEqual(len(cancellation.price_schedules), 11)
        schedule = cancellation.price_schedules[0]
        self.assertEqual(schedule.term, 11)
        self.assertEqual(schedule.price, '2.5')
        self.assertEqual(schedule.currency_code, 'USD')
        self.assertEqual(schedule.active, True)

        self.assert_request_parameters({
            'Action': 'CreateReservedInstancesListing',
            'ReservedInstancesId': 'instance_id',
            'InstanceCount': '1',
            'ClientToken': 'client_token',
            'PriceSchedules.0.Price': '2.5',
            'PriceSchedules.0.Term': '11',
            'PriceSchedules.1.Price': '2.0',
            'PriceSchedules.1.Term': '8',},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

class TestDescribeSpotInstanceRequests(TestEC2ConnectionBase):
    def default_body(self):
        return """
        <DescribeSpotInstanceRequestsResponse>
            <requestId>requestid</requestId>
            <spotInstanceRequestSet>
                <item>
                    <spotInstanceRequestId>sir-id</spotInstanceRequestId>
                    <spotPrice>0.003000</spotPrice>
                    <type>one-time</type>
                    <state>active</state>
                    <status>
                        fulfilled
                        <updateTime>2012-10-19T18:09:26.000Z</updateTime>
                        <message>Your Spot request is fulfilled.</message>
                    </status>
                    <launchGroup>mylaunchgroup</launchGroup>
                    <launchSpecification>
                        <imageId>ami-id</imageId>
                        <keyName>mykeypair</keyName>
                        <groupSet>
                            <item>
                                <groupId>sg-id</groupId>
                                <groupName>groupname</groupName>
                            </item>
                        </groupSet>
                        <instanceType>t1.micro</instanceType>
                        <monitoring>
                            <enabled>false</enabled>
                        </monitoring>
                    </launchSpecification>
                    <instanceId>i-id</instanceId>
                    <createTime>2012-10-19T18:07:05.000Z</createTime>
                    <productDescription>Linux/UNIX</productDescription>
                    <launchedAvailabilityZone>us-east-1d</launchedAvailabilityZone>
                </item>
            </spotInstanceRequestSet>
        </DescribeSpotInstanceRequestsResponse>
        """

    def test_describe_spot_instance_requets(self):
        self.set_http_response(status_code=200)
        response = self.ec2.get_all_spot_instance_requests()
        self.assertEqual(len(response), 1)
        spotrequest = response[0]
        self.assertEqual(spotrequest.id, 'sir-id')
        self.assertEqual(spotrequest.price, 0.003)
        self.assertEqual(spotrequest.type, 'one-time')
        self.assertEqual(spotrequest.state, 'active')
        self.assertEqual(spotrequest.fault, None)
        self.assertEqual(spotrequest.valid_from, None)
        self.assertEqual(spotrequest.valid_until, None)
        self.assertEqual(spotrequest.launch_group, 'mylaunchgroup')
        self.assertEqual(spotrequest.launched_availability_zone, 'us-east-1d')
        self.assertEqual(spotrequest.product_description, 'Linux/UNIX')
        self.assertEqual(spotrequest.availability_zone_group, None)
        self.assertEqual(spotrequest.create_time,
                         '2012-10-19T18:07:05.000Z')
        self.assertEqual(spotrequest.instance_id, 'i-id')
        launch_spec = spotrequest.launch_specification
        self.assertEqual(launch_spec.key_name, 'mykeypair')
        self.assertEqual(launch_spec.instance_type, 't1.micro')
        self.assertEqual(launch_spec.image_id, 'ami-id')
        self.assertEqual(launch_spec.placement, None)
        self.assertEqual(launch_spec.kernel, None)
        self.assertEqual(launch_spec.ramdisk, None)
        self.assertEqual(launch_spec.monitored, False)
        self.assertEqual(launch_spec.subnet_id, None)
        self.assertEqual(launch_spec.block_device_mapping, None)
        self.assertEqual(launch_spec.instance_profile, None)
        self.assertEqual(launch_spec.ebs_optimized, False)
        status = spotrequest.status
        self.assertEqual(status.code, 'fulfilled')
        self.assertEqual(status.update_time, '2012-10-19T18:09:26.000Z')
        self.assertEqual(status.message, 'Your Spot request is fulfilled.')

class TestCopySnapshot(TestEC2ConnectionBase):
    def default_body(self):
        return """
        <CopySnapshotResponse xmlns="http://ec2.amazonaws.com/doc/2012-12-01/">
            <requestId>request_id</requestId>
            <snapshotId>snap-copied-id</snapshotId>
        </CopySnapshotResponse>
        """

    def test_copy_snapshot(self):
        self.set_http_response(status_code=200)
        snapshot_id = self.ec2.copy_snapshot('us-west-2', 'snap-id',
                                             'description')
        self.assertEqual(snapshot_id, 'snap-copied-id')

        self.assert_request_parameters({
            'Action': 'CopySnapshot',
            'Description': 'description',
            'SourceRegion': 'us-west-2',
            'SourceSnapshotId': 'snap-id'},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

class TestAccountAttributes(TestEC2ConnectionBase):
    def default_body(self):
        return """
        <DescribeAccountAttributesResponse xmlns="http://ec2.amazonaws.com/doc/2012-12-01/">
            <requestId>6d042e8a-4bc3-43e8-8265-3cbc54753f14</requestId>
            <accountAttributeSet>
                <item>
                    <attributeName>vpc-max-security-groups-per-interface</attributeName>
                    <attributeValueSet>
                        <item>
                            <attributeValue>5</attributeValue>
                        </item>
                    </attributeValueSet>
                </item>
                <item>
                    <attributeName>max-instances</attributeName>
                    <attributeValueSet>
                        <item>
                            <attributeValue>50</attributeValue>
                        </item>
                    </attributeValueSet>
                </item>
                <item>
                    <attributeName>supported-platforms</attributeName>
                    <attributeValueSet>
                        <item>
                            <attributeValue>EC2</attributeValue>
                        </item>
                        <item>
                            <attributeValue>VPC</attributeValue>
                        </item>
                    </attributeValueSet>
                </item>
                <item>
                    <attributeName>default-vpc</attributeName>
                    <attributeValueSet>
                        <item>
                            <attributeValue>none</attributeValue>
                        </item>
                    </attributeValueSet>
                </item>
            </accountAttributeSet>
        </DescribeAccountAttributesResponse>
        """

    def test_describe_account_attributes(self):
        self.set_http_response(status_code=200)
        parsed = self.ec2.describe_account_attributes()
        self.assertEqual(len(parsed), 4)
        self.assertEqual(parsed[0].attribute_name,
                         'vpc-max-security-groups-per-interface')
        self.assertEqual(parsed[0].attribute_values,
                         ['5'])
        self.assertEqual(parsed[-1].attribute_name,
                         'default-vpc')
        self.assertEqual(parsed[-1].attribute_values,
                         ['none'])

class TestDescribeVPCAttribute(TestEC2ConnectionBase):
    def default_body(self):
        return """
        <DescribeVpcAttributeResponse xmlns="http://ec2.amazonaws.com/doc/2013-02-01/">
            <requestId>request_id</requestId>
            <vpcId>vpc-id</vpcId>
            <enableDnsHostnames>
                <value>false</value>
            </enableDnsHostnames>
        </DescribeVpcAttributeResponse>
        """

    def test_describe_vpc_attribute(self):
        self.set_http_response(status_code=200)
        parsed = self.ec2.describe_vpc_attribute('vpc-id',
                                                 'enableDnsHostnames')
        self.assertEqual(parsed.vpc_id, 'vpc-id')
        self.assertFalse(parsed.enable_dns_hostnames)
        self.assert_request_parameters({
            'Action': 'DescribeVpcAttribute',
            'VpcId': 'vpc-id',
            'Attribute': 'enableDnsHostnames',},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

class TestGetAllNetworkInterfaces(TestEC2ConnectionBase):
    def default_body(self):
        return """
<DescribeNetworkInterfacesResponse xmlns="http://ec2.amazonaws.com/\
    doc/2013-06-15/">
    <requestId>fc45294c-006b-457b-bab9-012f5b3b0e40</requestId>
     <networkInterfaceSet>
       <item>
         <networkInterfaceId>eni-0f62d866</networkInterfaceId>
         <subnetId>subnet-c53c87ac</subnetId>
         <vpcId>vpc-cc3c87a5</vpcId>
         <availabilityZone>ap-southeast-1b</availabilityZone>
         <description/>
         <ownerId>053230519467</ownerId>
         <requesterManaged>false</requesterManaged>
         <status>in-use</status>
         <macAddress>02:81:60:cb:27:37</macAddress>
         <privateIpAddress>10.0.0.146</privateIpAddress>
         <sourceDestCheck>true</sourceDestCheck>
         <groupSet>
           <item>
             <groupId>sg-3f4b5653</groupId>
             <groupName>default</groupName>
           </item>
         </groupSet>
         <attachment>
           <attachmentId>eni-attach-6537fc0c</attachmentId>
           <instanceId>i-22197876</instanceId>
           <instanceOwnerId>053230519467</instanceOwnerId>
           <deviceIndex>5</deviceIndex>
           <status>attached</status>
           <attachTime>2012-07-01T21:45:27.000Z</attachTime>
           <deleteOnTermination>true</deleteOnTermination>
         </attachment>
         <tagSet/>
         <privateIpAddressesSet>
           <item>
             <privateIpAddress>10.0.0.146</privateIpAddress>
             <primary>true</primary>
           </item>
           <item>
             <privateIpAddress>10.0.0.148</privateIpAddress>
             <primary>false</primary>
           </item>
           <item>
             <privateIpAddress>10.0.0.150</privateIpAddress>
             <primary>false</primary>
           </item>
         </privateIpAddressesSet>
       </item>
    </networkInterfaceSet>
</DescribeNetworkInterfacesResponse>"""

    def test_attachment_has_device_index(self):
        self.set_http_response(status_code=200)
        parsed = self.ec2.get_all_network_interfaces()

        self.assertEqual(5, parsed[0].attachment.device_index)

class TestModifyInterfaceAttribute(TestEC2ConnectionBase):
    def default_body(self):
        return """
<ModifyNetworkInterfaceAttributeResponse \
    xmlns="http://ec2.amazonaws.com/doc/2013-06-15/">
    <requestId>657a4623-5620-4232-b03b-427e852d71cf</requestId>
    <return>true</return>
</ModifyNetworkInterfaceAttributeResponse>
"""

    def test_modify_description(self):
        self.set_http_response(status_code=200)
        self.ec2.modify_network_interface_attribute('id', 'description', 'foo')

        self.assert_request_parameters({
            'Action': 'ModifyNetworkInterfaceAttribute',
            'NetworkInterfaceId': 'id',
            'Description.Value': 'foo'},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

    def test_modify_source_dest_check_bool(self):
        self.set_http_response(status_code=200)
        self.ec2.modify_network_interface_attribute('id', 'sourceDestCheck',
                                                    True)

        self.assert_request_parameters({
            'Action': 'ModifyNetworkInterfaceAttribute',
            'NetworkInterfaceId': 'id',
            'SourceDestCheck.Value': 'true'},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

    def test_modify_source_dest_check_str(self):
        self.set_http_response(status_code=200)
        self.ec2.modify_network_interface_attribute('id', 'sourceDestCheck',
                                                    'true')

        self.assert_request_parameters({
            'Action': 'ModifyNetworkInterfaceAttribute',
            'NetworkInterfaceId': 'id',
            'SourceDestCheck.Value': 'true'},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

    def test_modify_source_dest_check_invalid(self):
        self.set_http_response(status_code=200)

        with self.assertRaises(ValueError):
            self.ec2.modify_network_interface_attribute('id',
                                                        'sourceDestCheck',
                                                        123)

    def test_modify_delete_on_termination_str(self):
        self.set_http_response(status_code=200)
        self.ec2.modify_network_interface_attribute('id',
                                                    'deleteOnTermination',
                                                    True, attachment_id='bar')

        self.assert_request_parameters({
            'Action': 'ModifyNetworkInterfaceAttribute',
            'NetworkInterfaceId': 'id',
            'Attachment.AttachmentId': 'bar',
            'Attachment.DeleteOnTermination': 'true'},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

    def test_modify_delete_on_termination_bool(self):
        self.set_http_response(status_code=200)
        self.ec2.modify_network_interface_attribute('id',
                                                    'deleteOnTermination',
                                                    'false',
                                                    attachment_id='bar')

        self.assert_request_parameters({
            'Action': 'ModifyNetworkInterfaceAttribute',
            'NetworkInterfaceId': 'id',
            'Attachment.AttachmentId': 'bar',
            'Attachment.DeleteOnTermination': 'false'},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

    def test_modify_delete_on_termination_invalid(self):
        self.set_http_response(status_code=200)

        with self.assertRaises(ValueError):
            self.ec2.modify_network_interface_attribute('id',
                                                        'deleteOnTermination',
                                                        123,
                                                        attachment_id='bar')

    def test_modify_group_set_list(self):
        self.set_http_response(status_code=200)
        self.ec2.modify_network_interface_attribute('id', 'groupSet',
                                                    ['sg-1', 'sg-2'])

        self.assert_request_parameters({
            'Action': 'ModifyNetworkInterfaceAttribute',
            'NetworkInterfaceId': 'id',
            'SecurityGroupId.1': 'sg-1',
            'SecurityGroupId.2': 'sg-2'},
             ignore_params_values=['AWSAccessKeyId', 'SignatureMethod',
                                   'SignatureVersion', 'Timestamp',
                                   'Version'])

    def test_modify_group_set_invalid(self):
        self.set_http_response(status_code=200)

        with self.assertRaisesRegexp(TypeError, 'iterable'):
            self.ec2.modify_network_interface_attribute('id', 'groupSet',
                                                        False)

    def test_modify_attr_invalid(self):
        self.set_http_response(status_code=200)

        with self.assertRaisesRegexp(ValueError, 'Unknown attribute'):
            self.ec2.modify_network_interface_attribute('id', 'invalid', 0)

class TestConnectToRegion(unittest.TestCase):
    def setUp(self):
        self.https_connection = Mock(spec=httplib.HTTPSConnection)
        self.https_connection_factory = (
            Mock(return_value=self.https_connection), ())

    def test_aws_region(self):
        region = boto.ec2.RegionData.keys()[0]
        self.ec2 = boto.ec2.connect_to_region(region,
            https_connection_factory=self.https_connection_factory,
            aws_access_key_id='aws_access_key_id',
            aws_secret_access_key='aws_secret_access_key'
        )
        self.assertEqual(boto.ec2.RegionData[region], self.ec2.host)

    def test_non_aws_region(self):
        self.ec2 = boto.ec2.connect_to_region('foo',
            https_connection_factory=self.https_connection_factory,
            aws_access_key_id='aws_access_key_id',
            aws_secret_access_key='aws_secret_access_key',
            region = RegionInfo(name='foo', endpoint='https://foo.com/bar')
        )
        self.assertEqual('https://foo.com/bar', self.ec2.host)

    def test_missing_region(self):
        self.ec2 = boto.ec2.connect_to_region('foo',
            https_connection_factory=self.https_connection_factory,
            aws_access_key_id='aws_access_key_id',
            aws_secret_access_key='aws_secret_access_key'
        )
        self.assertEqual(None, self.ec2)

class TestTrimSnapshots(TestEC2ConnectionBase):
    """
    Test snapshot trimming functionality by ensuring that expected calls
    are made when given a known set of volume snapshots.
    """
    def _get_snapshots(self):
        """
        Generate a list of fake snapshots with names and dates.
        """
        snaps = []

        # Generate some dates offset by days, weeks, months
        now = datetime.now()
        dates = [
            now,
            now - timedelta(days=1),
            now - timedelta(days=2),
            now - timedelta(days=7),
            now - timedelta(days=14),
            datetime(now.year, now.month, 1) - timedelta(days=30),
            datetime(now.year, now.month, 1) - timedelta(days=60),
            datetime(now.year, now.month, 1) - timedelta(days=90)
        ]

        for date in dates:
            # Create a fake snapshot for each date
            snap = Snapshot(self.ec2)
            snap.tags['Name'] = 'foo'
            # Times are expected to be ISO8601 strings
            snap.start_time = date.strftime('%Y-%m-%dT%H:%M:%S.000Z')
            snaps.append(snap)

        return snaps

    def test_trim_defaults(self):
        """
        Test trimming snapshots with the default arguments, which should
        keep all monthly backups forever. The result of this test should
        be that nothing is deleted.
        """
        # Setup mocks
        orig = {
            'get_all_snapshots': self.ec2.get_all_snapshots,
            'delete_snapshot': self.ec2.delete_snapshot
        }

        snaps = self._get_snapshots()

        self.ec2.get_all_snapshots = MagicMock(return_value=snaps)
        self.ec2.delete_snapshot = MagicMock()

        # Call the tested method
        self.ec2.trim_snapshots()

        # Assertions
        self.assertEqual(True, self.ec2.get_all_snapshots.called)
        self.assertEqual(False, self.ec2.delete_snapshot.called)

        # Restore
        self.ec2.get_all_snapshots = orig['get_all_snapshots']
        self.ec2.delete_snapshot = orig['delete_snapshot']

    def test_trim_months(self):
        """
        Test trimming monthly snapshots and ensure that older months
        get deleted properly. The result of this test should be that
        the two oldest snapshots get deleted.
        """
        # Setup mocks
        orig = {
            'get_all_snapshots': self.ec2.get_all_snapshots,
            'delete_snapshot': self.ec2.delete_snapshot
        }

        snaps = self._get_snapshots()

        self.ec2.get_all_snapshots = MagicMock(return_value=snaps)
        self.ec2.delete_snapshot = MagicMock()

        # Call the tested method
        self.ec2.trim_snapshots(monthly_backups=1)

        # Assertions
        self.assertEqual(True, self.ec2.get_all_snapshots.called)
        self.assertEqual(2, self.ec2.delete_snapshot.call_count)

        # Restore
        self.ec2.get_all_snapshots = orig['get_all_snapshots']
        self.ec2.delete_snapshot = orig['delete_snapshot']

if __name__ == '__main__':
    unittest.main()


text:
package drat.proteus.services.general;

public class DratServiceStatus extends ServiceStatus {
  public enum State {
    INDEX, CRAWL, MAP, REDUCE, IDLE, INTERRUPTED
  }

  private State currentState;
  private int progress;

  public DratServiceStatus() {
    super(false); // since the status is a static variable, DRAT hasn't started
                  // yet
    this.currentState = State.IDLE;
  }

  public State getCurrentState() {
    return currentState;
  }

  public void setCurrentState(State status) {
    this.currentState = status;
    super.isRunning(currentState != State.IDLE
        && currentState != State.INTERRUPTED);
  }

  public int getProgress() {
    return progress;
  }

  public void setProgress(int progress) {
    this.progress = progress;
  }

  @Override
  public boolean isRunning() {
    return super.isRunning();
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.jme3.gde.core.filters.impl.plsf;

import javax.swing.JPanel;
import javax.swing.JTextField;

@SuppressWarnings({"unchecked", "rawtypes"})
public final class PLSFVisualPanel1 extends JPanel {

    /**
     * Creates new form BloomVisualPanel1
     */
    public PLSFVisualPanel1() {
        initComponents();
    }

    @Override
    public String getName() {
        return "PointLightShadowFilter settings";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */

    public JTextField getjShadowMapField() {
        return jShadowMapField;
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jShadowMapField = new javax.swing.JTextField();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(PLSFVisualPanel1.class, "shadowMapSize")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(PLSFVisualPanel1.class, "lblDescription")); // NOI18N

        jShadowMapField.setText(org.openide.util.NbBundle.getMessage(PLSFVisualPanel1.class, "PLSFVisualPanel1.jShadowMapField.text")); // NOI18N
        jShadowMapField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jShadowMapFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jShadowMapField, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3))
                .addContainerGap(249, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jShadowMapField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(193, Short.MAX_VALUE))
        );

        jLabel2.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(PLSFVisualPanel1.class, "shadowMapSize")); // NOI18N
        jLabel3.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(PLSFVisualPanel1.class, "lblDescription")); // NOI18N
    }// </editor-fold>//GEN-END:initComponents

    private void jShadowMapFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jShadowMapFieldActionPerformed

    }//GEN-LAST:event_jShadowMapFieldActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jShadowMapField;
    // End of variables declaration//GEN-END:variables
}


text:
package oneand

import org.scalacheck.{Arbitrary, Gen}
import org.specs2.{Specification, ScalaCheck}

class NonEmptyMapSpec extends Specification with ScalaCheck {
  import NonEmptyMapSpec.arbitraryNonEmptyMap

  def is = s2"""
    removing the only element leaves nothing ${ prop((k: Int, v: Int) => (NonEmptyMap(k -> v) - k).isEmpty) }
    removing 2nd elements leaves something ${
      prop((k1: Int, v1: Int, k2: Int, v2: Int) =>
        (NonEmptyMap(k1 -> v1, k2 -> v2) - k1).isEmpty === (k1 == k2))
    }
    removing non-member element leaves something ${
      prop((k1: Int, v1: Int, k2: Int) =>
        (NonEmptyMap(k1 -> v1) - k2).isEmpty === (k1 == k2))
    }
    ++(NonEmptyMap) ${ prop((a: NonEmptyMap[Int,String], b: NonEmptyMap[Int,String]) => (a ++ b).toMap === (a.toMap ++ b.toMap)) }
    ++(Map) ${ prop((a: NonEmptyMap[Int,String], b: Map[Int,String]) => (a ++ b).toMap === (a.toMap ++ b)) }
    .mapValues.toMap consistent with .toMap.mapValues ${
      prop((a: NonEmptyMap[Int,Int]) => a.mapValues(_+1).toMap === a.toMap.mapValues(_+1))
    }
    .contains ${ prop((m: NonEmptyMap[Int,String], a: Int) => m.contains(a) === m.toMap.contains(a)) }
    .get ${ prop((m: NonEmptyMap[Int,String], a: Int) => m.get(a) === m.toMap.get(a)) }
    .size ${ prop((m: NonEmptyMap[Int,String]) => m.size === m.toMap.size) }
    .head ${ prop((kv: (Int, String)) => NonEmptyMap(kv).head === kv)
  }
  """
}

object NonEmptyMapSpec {
  implicit def arbitraryNonEmptyMap[K: Arbitrary, V: Arbitrary]: Arbitrary[NonEmptyMap[K, V]] = Arbitrary {
    val pair: Gen[(K, V)] = Arbitrary.arbitrary[(K, V)]
    for {
      first <- pair
      rest <- Gen.listOf(pair)
    } yield rest.foldLeft(NonEmptyMap(first))((l, kv) => l + kv)
  }
}


text:
package http2

import (
	"fmt"
	"math"
	"reflect"
	"testing"
)

func makeWriteNonStreamRequest() FrameWriteRequest {
	return FrameWriteRequest{writeSettingsAck{}, nil, nil}
}

func makeWriteHeadersRequest(streamID uint32) FrameWriteRequest {
	st := &stream{id: streamID}
	return FrameWriteRequest{&writeResHeaders{streamID: streamID, httpResCode: 200}, st, nil}
}

func checkConsume(wr FrameWriteRequest, nbytes int32, want []FrameWriteRequest) error {
	consumed, rest, n := wr.Consume(nbytes)
	var wantConsumed, wantRest FrameWriteRequest
	switch len(want) {
	case 0:
	case 1:
		wantConsumed = want[0]
	case 2:
		wantConsumed = want[0]
		wantRest = want[1]
	}
	if !reflect.DeepEqual(consumed, wantConsumed) || !reflect.DeepEqual(rest, wantRest) || n != len(want) {
		return fmt.Errorf("got %v, %v, %v\nwant %v, %v, %v", consumed, rest, n, wantConsumed, wantRest, len(want))
	}
	return nil
}

func TestFrameWriteRequestNonData(t *testing.T) {
	wr := makeWriteNonStreamRequest()
	if got, want := wr.DataSize(), 0; got != want {
		t.Errorf("DataSize: got %v, want %v", got, want)
	}

	// Non-DATA frames are always consumed whole.
	if err := checkConsume(wr, 0, []FrameWriteRequest{wr}); err != nil {
		t.Errorf("Consume:\n%v", err)
	}
}

func TestFrameWriteRequestData(t *testing.T) {
	st := &stream{
		id: 1,
		sc: &serverConn{maxFrameSize: 16},
	}
	const size = 32
	wr := FrameWriteRequest{&writeData{st.id, make([]byte, size), true}, st, make(chan error)}
	if got, want := wr.DataSize(), size; got != want {
		t.Errorf("DataSize: got %v, want %v", got, want)
	}

	// No flow-control bytes available: cannot consume anything.
	if err := checkConsume(wr, math.MaxInt32, []FrameWriteRequest{}); err != nil {
		t.Errorf("Consume(limited by flow control):\n%v", err)
	}

	// Add enough flow-control bytes to consume the entire frame,
	// but we're now restricted by st.sc.maxFrameSize.
	st.flow.add(size)
	want := []FrameWriteRequest{
		{
			write:  &writeData{st.id, make([]byte, st.sc.maxFrameSize), false},
			stream: st,
			done:   nil,
		},
		{
			write:  &writeData{st.id, make([]byte, size-st.sc.maxFrameSize), true},
			stream: st,
			done:   wr.done,
		},
	}
	if err := checkConsume(wr, math.MaxInt32, want); err != nil {
		t.Errorf("Consume(limited by maxFrameSize):\n%v", err)
	}
	rest := want[1]

	// Consume 8 bytes from the remaining frame.
	want = []FrameWriteRequest{
		{
			write:  &writeData{st.id, make([]byte, 8), false},
			stream: st,
			done:   nil,
		},
		{
			write:  &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true},
			stream: st,
			done:   wr.done,
		},
	}
	if err := checkConsume(rest, 8, want); err != nil {
		t.Errorf("Consume(8):\n%v", err)
	}
	rest = want[1]

	// Consume all remaining bytes.
	want = []FrameWriteRequest{
		{
			write:  &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true},
			stream: st,
			done:   wr.done,
		},
	}
	if err := checkConsume(rest, math.MaxInt32, want); err != nil {
		t.Errorf("Consume(remainder):\n%v", err)
	}
}

func TestFrameWriteRequest_StreamID(t *testing.T) {
	const streamID = 123
	wr := FrameWriteRequest{write: streamError(streamID, ErrCodeNo)}
	if got := wr.StreamID(); got != streamID {
		t.Errorf("FrameWriteRequest(StreamError) = %v; want %v", got, streamID)
	}
}


text:
from sys import argv

script , input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)

print "First let:\n"

print_all(current_file)

print "Now"

rewind(current_file)

print "Let"

current_line = 1
print_a_line(current_line, current_file)
rewind(current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <title>Basselope</title>
    <link rel="shortcut icon" type="image/png" href="assets/favicon.ico"/>
    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/master/devicon.min.css">
    <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet">


text:
import plugins.InterpreterPlugin

class Plugin(plugins.InterpreterPlugin.InterpreterPlugin, object):

    name = None
    author = None
    description = None
    connection = None

    def __init__(self, **kwargs):
        self.name = "perl"
        self.author = "Mischa-Alff"
        self.description = "A Perl evaluation plugin."

        self.interpreter_command = ["/usr/bin/perl"]

        super(Plugin, self).__init__(**kwargs)

        self.commands.append(
            plugins.BasePlugin.Command(
                self.snippet, ["%%prefix%%"], ["pl"],
                {
                    "lang_extension": "pl"
                }
            )
        )
        self.commands.append(
            plugins.BasePlugin.Command(
                self.snippet, ["%%prefix%%"], ["perl"],
                {
                    "lang_extension": "pl"
                }
            )
        )


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memmove_74b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml
Template File: sources-sink-74b.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using new[] and set data pointer to a small buffer
 * GoodSource: Allocate using new[] and set data pointer to a large buffer
 * Sinks: memmove
 *    BadSink : Copy string to data using memmove
 * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <map>

#include <wchar.h>

using namespace std;

namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memmove_74
{

#ifndef OMITBAD

void badSink(map<int, char *> dataMap)
{
    /* copy data out of dataMap */
    char * data = dataMap[2];
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
        memmove(data, source, 100*sizeof(char));
        data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */
        printLine(data);
        delete [] data;
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, char *> dataMap)
{
    char * data = dataMap[2];
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
        memmove(data, source, 100*sizeof(char));
        data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */
        printLine(data);
        delete [] data;
    }
}

#endif /* OMITGOOD */

} /* close namespace */


text:
* Added Data.RTree.Strict

* Added Data.Binary interface for GHC 7.6

## 0.0.5.0

* changed the Functor instance of Data.RTree.Strict to be strict

* Data.RTree.Strict.RTree is now a newtype of Data.RTree.RTree

## 0.6.0

* Add `lookupContainsRange` and `lookupContainsRangeWithKey`.
* Add `intersectWithKey` and `intersect`.
* Now supports GHC 8.4, 8.5 and 8.6.
* Removed `test-strict` flag.
* Minimal Bounding Box is now also an instance of `Ord`


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/ask_question_textview"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:hint="Type your question here"
        />

    <Button
        android:id="@+id/submit_question_button"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:onClick="submitQuestion"
        android:text="Submit"
        />

</LinearLayout>


text:
using System;

namespace _09.ReturnMaximalElement
{
    class ReturnMaximalElement
    {
        //Write a method that return the maximal element in a portion of array of integers starting at given index. Using it write another method that sorts an array in ascending / descending order.

        static void Main(string[] args)
        {
            Console.WriteLine("Enter lenght of the array:");
            int lenght = int.Parse(Console.ReadLine());
            int[] numberArray = new int[lenght];
            Console.WriteLine("Enter members of the integer array:");
            for (int i = 0; i < numberArray.Length; i++)
            {
                numberArray[i] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Descending sorted array:");
            SortArrayDescending(numberArray);
            PrintArray(numberArray);
            Console.WriteLine("Ascending sorted array:");
            SortArrayAcsending(numberArray);
            PrintArray(numberArray);
        }

        private static int ReturnMax(int[] array, int startIndex, out int index)
        {
            int maxElement = array[startIndex];
            index = startIndex;
            for (int i = startIndex + 1; i < array.Length; i++)
            {
                if (array[i] > maxElement)
                {
                    index = i;
                    maxElement = array[i];
                }
            }
            return maxElement;
        }

        private static void SortArrayDescending(int[] array)
        {
            for (int i = 0; i < array.Length; i++)
            {
                int index;
                int max = ReturnMax(array, i, out index);
                //swap
                int swapNum = array[i];
                array[i] = max;
                array[index] = swapNum;
            }
        }

        private static void SortArrayAcsending(int[] array)
        {
            SortArrayDescending(array);
            Array.Reverse(array);
        }

        private static void PrintArray(int[] array)
        {
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(array[i] + " ");
            }
            Console.WriteLine();
        }
    }
}


text:
static inline const size_t _get_size(struct Obj** prop_objs) {
    size_t size = 0;
    struct Obj* obj = NULL;
    css_iter (obj, prop_objs)
        size++;  // counter
    return size;
}

struct ShiftDrawPair** _build_many_objs(struct SeriesObj* series, struct Helper* helper) {
    struct Rule* rule = helper->rule;
    enum FillDirection fill_direction = series->fill_direction;
    struct Obj** prop_objs = css_find_objs(rule, "body");
    if (!prop_objs) {
        return NULL;
    }

    const size_t size = _get_size(prop_objs);
    struct BasicObj basic_temp = builder_build_empty_basic();
    struct ShiftDrawPair** pairs = malloc(sizeof(struct ShiftDrawPair*) * (size + 1));
    int shift = 0;

    size_t index = 0;
    struct Obj* obj = NULL;
    css_iter (obj, prop_objs) {
        struct RuleSelector* selector = css_eval_rule(obj);
        struct DrawObj* child = series_make_draw_obj(helper, selector);
        if (!child) continue;

        pairs[index++] = series_make_pair(shift, child);

        int child_width = series_get_basic_metric_by_fill_direction(&child->basic, fill_direction);
        int padding = builder_get_padding(rule);
        series_add_max_basic_by_fill_direction(&basic_temp, &child->basic, fill_direction);
        if (index < size) {
            series_add_basic_metric_by_fill_direction(&basic_temp, fill_direction, padding);
            shift += child_width + padding;
        }
    }

    // resize array
    pairs = realloc(pairs, sizeof(struct ShiftDrawPair*) * (index + 1));
    pairs[index] = NULL;

    series_max_basic(&helper->parent->basic, &basic_temp);  // resize parent

    int end_width =
        series_get_basic_metric_by_fill_direction(&helper->parent->basic, fill_direction);
    series_align_objs(helper, pairs, fill_direction, size, end_width);

    return pairs;
}

struct DrawObj* builder_build_series(struct Helper* helper, enum FillDirection fill_direction) {
    struct Rule* rule = helper->rule;

    struct SeriesObj* obj = malloc(sizeof(struct SeriesObj));
    obj->fill_direction = fill_direction;

    struct BasicObj basic = builder_build_basic(rule, helper->parent);
    struct DrawObj* draw_obj = builder_make_draw_obj(helper, basic, DRAW_OBJ_SERIES, obj);
    struct Helper inner_helper = {
        .program = helper->program,
        .rule = helper->rule,
        .parent = draw_obj,
    };
    obj->pairs = _build_many_objs(obj, &inner_helper);

    return draw_obj;
}


text:
<?php

namespace Booker\BookBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="Booker\BookBundle\Entity\Repository\UserRepository")
 * @ORM\Table(name="users")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="Booking", mappedBy="user")
     */
    protected $booking;

    public function __construct()
    {
        parent::__construct();
        // your own logic
        $this->booking = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add booking
     *
     * @param \Booker\BookBundle\Entity\Booking $booking
     * @return User
     */
    public function addBooking(\Booker\BookBundle\Entity\Booking $booking)
    {
        $this->booking[] = $booking;

        return $this;
    }

    /**
     * Remove booking
     *
     * @param \Booker\BookBundle\Entity\Booking $booking
     */
    public function removeBooking(\Booker\BookBundle\Entity\Booking $booking)
    {
        $this->booking->removeElement($booking);
    }

    /**
     * Get booking
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getBooking()
    {
        return $this->booking;
    }
}


text:
import { Catalog16 } from "../../";

export = Catalog16;


text:
<Alloy>
	<Window class="container">
		<ActivityIndicator id="loading"></ActivityIndicator>

	</Window>
</Alloy>


text:
using namespace v8;

class FileOutputStream: public OutputStream {
	public:
		FileOutputStream(FILE* stream): stream_(stream) { }
		virtual int GetChunkSize() {
			return 65536;
		}
		virtual void EndOfStream() { }
		virtual WriteResult WriteAsciiChunk(char* data, int size) {
			const size_t len = static_cast<size_t>(size);
			size_t off = 0;
			while (off < len && !feof(stream_) && !ferror(stream_))
				off += fwrite(data + off, 1, len - off, stream_);
			return off == len ? kContinue : kAbort;
		}

	private:
		FILE* stream_;
};

static void OnFatalError(const char* location, const char* message) {
	if (location) {
		fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
	} else {
		fprintf(stderr, "FATAL ERROR: %s\n", message);
	}
	fprintf(stderr, "Generating HeapDump\n");
	timeval tv;
	if (gettimeofday(&tv, NULL)) abort();

	char filename[256];
	snprintf(filename,
			sizeof(filename),
			"heapdump-%u.%u.heapsnapshot",
			static_cast<unsigned int>(tv.tv_sec),
			static_cast<unsigned int>(tv.tv_usec));
	FILE* fp = fopen(filename, "w");
	if (fp == NULL) abort();

	const HeapSnapshot* snap = HeapProfiler::TakeSnapshot(String::Empty());
	FileOutputStream stream(fp);
	snap->Serialize(&stream, HeapSnapshot::kJSON);
	fclose(fp);
	exit(1);
}

Handle<Value> Method(const Arguments& args) {
	HandleScope scope;
	V8::SetFatalErrorHandler(OnFatalError);
	return scope.Close(String::New("done"));
}

void Init(Handle<Object> target) {
	V8::SetFatalErrorHandler(OnFatalError);
	target->Set(String::NewSymbol("call"),
			FunctionTemplate::New(Method)->GetFunction());
}

NODE_MODULE(ofe, Init)


text:
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;

namespace NetOffice.WordApi
{
	/// <summary>
	/// DispatchInterface ListLevel
	/// SupportByVersion Word, 9,10,11,12,14,15,16
	/// </summary>
	/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel"/> </remarks>
	[SupportByVersion("Word", 9,10,11,12,14,15,16)]
	[EntityType(EntityType.IsDispatchInterface)]
 	public class ListLevel : COMObject
	{
		#pragma warning disable

		#region Type Information

		/// <summary>
		/// Instance Type
		/// </summary>
		[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
		public override Type InstanceType
		{
			get
			{
				return LateBindingApiWrapperType;
			}
		}

        private static Type _type;

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public static Type LateBindingApiWrapperType
        {
            get
            {
                if (null == _type)
                    _type = typeof(ListLevel);
                return _type;
            }
        }

        #endregion

		#region Ctor

		/// <param name="factory">current used factory core</param>
		/// <param name="parentObject">object there has created the proxy</param>
		/// <param name="proxyShare">proxy share instead if com proxy</param>
		public ListLevel(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
		public ListLevel(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
		{

		}

        ///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ListLevel(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ListLevel(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
		{

		}

		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ListLevel(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
		{
		}

		///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ListLevel(ICOMObject replacedObject) : base(replacedObject)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ListLevel() : base()
		{
		}

		/// <param name="progId">registered progID</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public ListLevel(string progId) : base(progId)
		{
		}

		#endregion

		#region Properties

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.Index"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public Int32 Index
		{
			get
			{
				return Factory.ExecuteInt32PropertyGet(this, "Index");
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.NumberFormat"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public string NumberFormat
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "NumberFormat");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "NumberFormat", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.TrailingCharacter"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public NetOffice.WordApi.Enums.WdTrailingCharacter TrailingCharacter
		{
			get
			{
				return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdTrailingCharacter>(this, "TrailingCharacter");
			}
			set
			{
				Factory.ExecuteEnumPropertySet(this, "TrailingCharacter", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.NumberStyle"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public NetOffice.WordApi.Enums.WdListNumberStyle NumberStyle
		{
			get
			{
				return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdListNumberStyle>(this, "NumberStyle");
			}
			set
			{
				Factory.ExecuteEnumPropertySet(this, "NumberStyle", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.NumberPosition"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public Single NumberPosition
		{
			get
			{
				return Factory.ExecuteSinglePropertyGet(this, "NumberPosition");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "NumberPosition", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.Alignment"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public NetOffice.WordApi.Enums.WdListLevelAlignment Alignment
		{
			get
			{
				return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdListLevelAlignment>(this, "Alignment");
			}
			set
			{
				Factory.ExecuteEnumPropertySet(this, "Alignment", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.TextPosition"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public Single TextPosition
		{
			get
			{
				return Factory.ExecuteSinglePropertyGet(this, "TextPosition");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "TextPosition", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.TabPosition"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public Single TabPosition
		{
			get
			{
				return Factory.ExecuteSinglePropertyGet(this, "TabPosition");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "TabPosition", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public bool ResetOnHigherOld
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "ResetOnHigherOld");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "ResetOnHigherOld", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.StartAt"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public Int32 StartAt
		{
			get
			{
				return Factory.ExecuteInt32PropertyGet(this, "StartAt");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "StartAt", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.LinkedStyle"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public string LinkedStyle
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "LinkedStyle");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "LinkedStyle", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.Font"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public NetOffice.WordApi.Font Font
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Font>(this, "Font", NetOffice.WordApi.Font.LateBindingApiWrapperType);
			}
			set
			{
				Factory.ExecuteReferencePropertySet(this, "Font", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.Application"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public NetOffice.WordApi.Application Application
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Application>(this, "Application", NetOffice.WordApi.Application.LateBindingApiWrapperType);
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.Creator"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public Int32 Creator
		{
			get
			{
				return Factory.ExecuteInt32PropertyGet(this, "Creator");
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get
		/// Unknown COM Proxy
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.Parent"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16), ProxyResult]
		public object Parent
		{
			get
			{
				return Factory.ExecuteReferencePropertyGet(this, "Parent");
			}
		}

		/// <summary>
		/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.ResetOnHigher"/> </remarks>
		[SupportByVersion("Word", 9,10,11,12,14,15,16)]
		public Int32 ResetOnHigher
		{
			get
			{
				return Factory.ExecuteInt32PropertyGet(this, "ResetOnHigher");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "ResetOnHigher", value);
			}
		}

		/// <summary>
		/// SupportByVersion Word 10, 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.PictureBullet"/> </remarks>
		[SupportByVersion("Word", 10,11,12,14,15,16)]
		public NetOffice.WordApi.InlineShape PictureBullet
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.InlineShape>(this, "PictureBullet", NetOffice.WordApi.InlineShape.LateBindingApiWrapperType);
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// SupportByVersion Word 10, 11, 12, 14, 15, 16
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.ListLevel.ApplyPictureBullet"/> </remarks>
		/// <param name="fileName">string fileName</param>
		[SupportByVersion("Word", 10,11,12,14,15,16)]
		public NetOffice.WordApi.InlineShape ApplyPictureBullet(string fileName)
		{
			return Factory.ExecuteKnownReferenceMethodGet<NetOffice.WordApi.InlineShape>(this, "ApplyPictureBullet", NetOffice.WordApi.InlineShape.LateBindingApiWrapperType, fileName);
		}

		#endregion

		#pragma warning restore
	}
}


text:
Full-featured example of publishing platform built with
[React](http://facebook.github.io/react/),
[Redux](http://rackt.github.io/redux/),
[React Router](http://rackt.github.io/react-router/),
[Babel](https://babeljs.io/) and
[Webpack](http://webpack.github.io/).

Some features:
- Server-side rendering
- Token-based authorization with [JWT](https://www.npmjs.com/package/jsonwebtoken)
- Markdown editor of posts with [marked](https://www.npmjs.com/package/marked)
- Modular CSS with [React CSS Modules](https://github.com/gajus/react-css-modules)
- API mock with [JSON server](https://www.npmjs.com/package/json-server)

## Running
```bash
npm install
```

### Production
```bash
npm run build # build assets and server
npm start # start the server
```

Open [http://localhost:3000/](http://localhost:3000/) in the browser.

### Development
```bash
npm run dev # start development server with hot reloading
```

It will automatically open your default browser with project loaded.

**Note**: You will notice some latency between the moment it open the browser and really load the page. It's okay.

## You can

### while unauthorized

- View list of published posts
- View single post
- Log in with hardcoded credentials
- Be redirected from protected routes

### while authorized

- view `/dashboard` with unpublished posts
- edit and unpublish any `post`
- edit your `firstname` and `lastname` in `/profile`

## How it works

All data stored in API implemented with `jsonServer`. There're pre-populated `users` and `posts` entities. This implementation is example-only and you can easily drop-in your own backend solution. We aim just to show the direction.

## TODO

- [ ] comments
- [ ] pagination
- [ ] tests


text:
(function() {
     function RoomCtrl(Room, Message, $uibModal) {
       var home = this;
       home.rooms = Room.all;
       home.currentRoom = null;

       home.addRoom = function() {
         $uibModal.open({
           templateUrl: '/templates/modal.html',
           size: 'sm',
           controller: 'ModalCtrl as modal'
           });
       }

     home.setCurrentRoom = function (room) {
       home.currentRoom = room;
       home.messages = Message.getByRoomId(home.currentRoom.$id);
       console.log(home.messages)
     }
   }

     angular
         .module('blocChat')
         .controller('RoomCtrl', ['Room', 'Message', '$uibModal', RoomCtrl]);
 })();


text:
using SharpShell.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerRegistrationManager.OutputService
{
    /// <summary>
    /// Implements the <see cref="IOutputService"/> contract and writes
    /// output to the Console.
    /// </summary>
    public class ConsoleOutputService : IOutputService
    {
        /// <summary>
        /// Writes a message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="log">if set to <c>true</c> the message is also logged.</param>
        public void WriteMessage(string message, bool log = false)
        {
            //  Set the colour.
            Console.ForegroundColor = ConsoleColor.Gray;

            //  Write the message.
            Console.WriteLine(message);

            //  If required, write to the SharpShell log.
            if (log)
                Logging.Log(message);
        }

        /// <summary>
        /// Writes the success.
        /// </summary>
        /// <param name="messabe">The message.</param>
        /// <param name="log">if set to <c>true</c> [log].</param>
        public void WriteSuccess(string message, bool log = false)
        {
            //  Set the colour.
            Console.ForegroundColor = ConsoleColor.Green;

            //  Write the message.
            Console.WriteLine(message);
            Console.ForegroundColor = ConsoleColor.Gray;

            //  If required, write to the SharpShell log.
            if (log)
                Logging.Log(message);
        }

        /// <summary>
        /// Writes an error.
        /// </summary>
        /// <param name="error">The error.</param>
        /// <param name="log">if set to <c>true</c> the message is also logged.</param>
        public void WriteError(string error, bool log = false)
        {
            //  Set the colour.
            Console.ForegroundColor = ConsoleColor.Red;

            //  Write the message.
            Console.WriteLine(error);
            Console.ForegroundColor = ConsoleColor.Gray;

            //  If required, write to the SharpShell log.
            if (log)
                Logging.Error(error);
        }
    }
}


text:
/**
 * Created by ZhaokangYuan on 2016/1/14.
 */

var CreateCities = function (url) {
    this.url = url;

    this.create = function (scene, radius) {
        /*$.getJSON(url, function (cities) {
            var material = new THREE.ParticleBasicMaterial({size: 2, vertexColors: true, color: 0xffffff});
            var geom = new THREE.Geometry();

            for (var i = 0; i < cities.length; i++) {
                var lngLat = {lng: cities[i].long, lat: cities[i].lat};

                var l = radius * Math.cos(lngLat.lat / 180 * Math.PI);
                var x = l * Math.sin(lngLat.lng / 180 * Math.PI);
                var y = radius * Math.sin(lngLat.lat / 180 * Math.PI);
                var z = l * Math.cos(lngLat.lng / 180 * Math.PI);

                var particle = new THREE.Vector3(x, y, z);
                geom.vertices.push(particle);

                geom.colors.push(new THREE.Color(0x2EFFFF));
            }

            var system = new THREE.ParticleSystem(geom, material);
            scene.add(system);
        });*/

        d3.csv(url, function (error,data) {
            if(error)
                console.log(error);
            else{
                var material = new THREE.ParticleBasicMaterial({size: 0.5, vertexColors: true, color: 0xffffff});
                var geom = new THREE.Geometry();

                for (var i = 0; i < data.length; i++) {
                    var id=data[i]['id'];
                    var short_name=data[i]['short_name'];
                    var long_name=data[i]['long_name'];
                    var state=data[i]['state'];
                    var city=data[i]['city'];
                    var ip_count=data[i]['ip_count'];
                    var lat=data[i]['lat'];
                    var lng=data[i]['lng'];

                    var lngLat = {lng: lng, lat: lat};

                    var l = radius * Math.cos(lngLat.lat / 180 * Math.PI);
                    var x = l * Math.sin(lngLat.lng / 180 * Math.PI);
                    var y = radius * Math.sin(lngLat.lat / 180 * Math.PI);
                    var z = l * Math.cos(lngLat.lng / 180 * Math.PI);

                    var particle = new THREE.Vector3(x, y, z);
                    geom.vertices.push(particle);

                    geom.colors.push(new THREE.Color(0x2EFFFF));
                }

                var system = new THREE.ParticleSystem(geom, material);
                scene.add(system);
            }
        })
    }
}


text:
package be.rubus.web.testing.widget.extension.primefaces.internal;

import be.rubus.web.testing.widget.extension.primefaces.AbstractPrimeFacesWidget;
import be.rubus.web.testing.widget.extension.primefaces.PFDataTable;
import org.openqa.selenium.WebElement;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 *
 */
public class Paginator extends AbstractPrimeFacesWidget {
    private WebElement firstButton;
    private WebElement previousButton;
    private WebElement nextButton;
    private WebElement lastButton;
    private WebElement pages;

    @PostConstruct
    public void retrieveButtons() {
        List<WebElement> elements = getAllChildren(root);
        for (WebElement element : elements) {
            if (containsClassName(element, "ui-paginator-first")) {
                firstButton = element;
            }
            if (containsClassName(element, "ui-paginator-prev")) {
                previousButton = element;
            }
            if (containsClassName(element, "ui-paginator-pages")) {
                pages = element;
            }
            if (containsClassName(element, "ui-paginator-next")) {
                nextButton = element;
            }
            if (containsClassName(element, "ui-paginator-last")) {
                lastButton = element;
            }
        }
    }

    public boolean isButtonActive(PFDataTable.PaginatorButton paginatorButton) {
        boolean result;
        switch (paginatorButton) {

            case FIRST:
                result = !containsClassName(firstButton, UI_DISABLED);
                break;
            case PREVIOUS:
                result = !containsClassName(previousButton, UI_DISABLED);
                break;
            case NEXT:
                result = !containsClassName(nextButton, UI_DISABLED);
                break;
            case LAST:
                result = !containsClassName(lastButton, UI_DISABLED);
                break;
            default:
                throw new IllegalArgumentException(paginatorButton + " not recognized");
        }
        return result;
    }

    public void clickButton(PFDataTable.PaginatorButton paginatorButton) {
        switch (paginatorButton) {

            case FIRST:
                firstButton.click();
                break;
            case PREVIOUS:
                previousButton.click();
                break;
            case NEXT:
                nextButton.click();
                break;
            case LAST:
                lastButton.click();
                break;
        }
        waitForAjax();
    }

    public String getPageNumber() {
        String result = "";
        List<WebElement> elements = getAllChildren(pages);
        for (WebElement element : elements) {
            if (containsClassName(element, UI_ACTIVE)) {
                result = element.getText();
            }
        }
        return result;
    }
}


text:
using System.Collections.ObjectModel;
using System.Runtime;

namespace System.IdentityModel.Tokens
{
    public abstract class SecurityToken
    {
        public abstract string Id { get; }
        public abstract ReadOnlyCollection<SecurityKey> SecurityKeys { get; }
        public abstract DateTime ValidFrom { get; }
        public abstract DateTime ValidTo { get; }
    }
}


text:
<?php

declare(strict_types=1);

namespace Railt\Config;

use Railt\Observer\NotifiableInterface;
use Railt\Observer\NotifiableObserverTrait;

/**
 * Class MutableRepository
 */
class MutableRepository extends Repository implements
    MutableRepositoryInterface,
    NotifiableInterface
{
    use NotifiableObserverTrait;

    /**
     * {@inheritDoc}
     */
    public function set(string $key, $value = null): void
    {
        $before = $this->items;
        $result = &$this->items;

        $chunks = $this->chunks($key);

        while (\count($chunks) > 1) {
            $current = \array_shift($chunks);

            if (! isset($result[$current]) || ! \is_array($result[$current])) {
                $result[$current] = [];
            }

            $result = &$result[$current];
        }

        $result[\array_shift($chunks)] = $value;

        $this->notifyWith($this->items, $before);
    }

    /**
     * {@inheritDoc}
     */
    public function merge(iterable $items): void
    {
        $this->items = \array_merge_recursive(
            $before = $this->items,
            $this->iterableToArray($items)
        );

        $this->notifyWith($this->items, $before);
    }

    /**
     * @return void
     */
    public function notify(): void
    {
        $this->notifyWith($this->items);
    }

    /**
     * @param iterable $items
     * @return array
     */
    private function iterableToArray(iterable $items): array
    {
        switch (true) {
            case $items instanceof RepositoryInterface:
                $items = $items->all();
                break;

            case $items instanceof \Traversable:
                $items = \iterator_to_array($items);
                break;
        }

        return $items;
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name clientApp.controller:AddcommoditymodalCtrl
 * @description
 * # AddcommoditymodalCtrl
 * Controller of the clientApp
 */
angular.module('clientApp')
    .controller('AddCommodityModalCtrl', ['Commodities', 'gameDataService', '$modalInstance', '$scope', function(Commodities, gameDataService, $modalInstance, $scope) {
        var self = this;

        self.commodityCategories = gameDataService.commodityCategories();

        // Alert messages.
        self.alerts = [];
        self.closeAlert = function(index) {
            self.alerts.splice(index, 1);
        };

        self.reset = function(form) {
            if (form) {
                form.$setPristine();
                form.$setUntouched();
            }
            self.newCommodity = {};
        };

        self.cancel = function() {
            $modalInstance.dismiss('User canceled.');
        };

        self.saveCommodity = function(newCommodity) {
            var commodity = new Commodities(newCommodity);
            commodity.$save().then(function(response) {
                $modalInstance.close(response);
            }, function(errResponse) {
                self.alerts.push({
                    type: 'danger',
                    message: errResponse.data
                });
            });
        };

        self.reset();

        self.newCommodity.name = $scope.params.name;
        if ($scope.params.galacticAverage) {
            self.newCommodity.galacticAverage = $scope.params.galacticAverage;
        }
    }]);


text:
import type { ValidationContext } from '../index';
import { GraphQLError } from '../../error';
import type { ASTVisitor } from '../../language/visitor';

export function duplicateArgMessage(argName: string): string {
  return `There can be only one argument named "${argName}".`;
}

/**
 * Unique argument names
 *
 * A GraphQL field or directive is only valid if all supplied arguments are
 * uniquely named.
 */
export function UniqueArgumentNames(context: ValidationContext): ASTVisitor {
  let knownArgNames = Object.create(null);
  return {
    Field() {
      knownArgNames = Object.create(null);
    },
    Directive() {
      knownArgNames = Object.create(null);
    },
    Argument(node) {
      const argName = node.name.value;
      if (knownArgNames[argName]) {
        context.reportError(
          new GraphQLError(duplicateArgMessage(argName), [
            knownArgNames[argName],
            node.name,
          ]),
        );
      } else {
        knownArgNames[argName] = node.name;
      }
      return false;
    },
  };
}


text:
<object-stream>
  <com.fatwire.realtime.ResourceDataImpl>
    <id class="string">OpenMarket/Xcelerate/AssetType/Template/ContentDetailsHelper</id>
    <resourceType>ELEMENTCATALOG</resourceType>
    <deps class="empty-set"/>
    <data class="com.openmarket.xcelerate.common.ElementCatalogEntry" serialization="custom">
      <com.openmarket.xcelerate.common.ElementCatalogEntry>
        <int>1</int>
        <string>OpenMarket/Xcelerate/AssetType/Template/ContentDetailsHelper</string>
        <string>Helper JSP for ContentDetails</string>
        <string></string>
        <string></string>
        <string>OpenMarket\Xcelerate\AssetType\Template\ContentDetailsHelper.jsp</string>
        <string></string>
        <string></string>
      </com.openmarket.xcelerate.common.ElementCatalogEntry>
    </data>
  </com.fatwire.realtime.ResourceDataImpl>
</object-stream>
<!--==================___ METADATA ___================
<dependencies>
  <list/>
</dependencies>
==================______________________==================
#
#Mon Dec 16 23:39:32 UTC 2013
storable0=/ELEMENTS/JSP/OpenMarket/Xcelerate/AssetType/Template/ContentDetailsHelper.jsp|null|_storable_type\=%2FELEMENTS%2FJSP%2FOpenMarket%2FXcelerate%2FAssetType%2FTemplate%2FContentDetailsHelper.jsp
@hashval=2059836241
key=@ELEMENTCATALOG-OpenMarket/Xcelerate/AssetType/Template/ContentDetailsHelper
type=ELEMENTCATALOG

==================___ END METADATA ___==================-->


text:
create database if not exists ${DB};
use ${DB};

drop table if exists household_demographics;

create external table household_demographics
(
    hd_demo_sk                int,
    hd_income_band_sk         int,
    hd_buy_potential          string,
    hd_dep_count              int,
    hd_vehicle_count          int
)
row format delimited fields terminated by '|'
location '${LOCATION}';


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
   <item android:state_selected="true" android:drawable="@drawable/discard_dialog_pressed" />
   <item android:state_pressed="true" android:state_selected="false" android:drawable="@drawable/discard_dialog_pressed" />
   <item android:state_selected="false" android:drawable="@drawable/discard_dialog" />
</selector>


text:
%CAPTION
fprintf('\n');
disp('Figure 9.9')
disp('Window 1: Signal synthesized with a sum of chirps, truncated sinusoids,')
disp(' short time transients and Diracs.')
disp('Window 2: Heisenberg boxes of a best wavelet packet basis')
disp('calculated with Daubechies 8 filters.')
disp('The darkness is proportional to the coefficient amplitude.')
%disp('Window 3: Heisenberg boxes of wavelet packets selected by a')
%disp('matching pursuit.')
disp('Window 4: Heisenberg boxes of wavelet packets selected by an')
disp('orthogonal matching pursuit.')
%disp('Window 5: Heisenberg boxes of wavelet packets selected by a')
%disp('basis pursuit.')
fprintf('\n');
disp('The matching pursuit figure in a Gabor dictionary is not yet')
disp('implemented in Wavelab. It can be reproduced with the')
disp('LastWave software, which is available on the Internet at')
disp('http://www.cmap.polytechnique.fr/users/www.bacry')
fprintf('\n');

close all;
global WLVERBOSE;
WLVERBOSE='No';
% axes handles
	N = 512;
	delta = 1/15;
	unit = (1-3*delta)/3;
	h2 = [delta delta 1-2*delta 2*unit];
	h1 = [delta 2*(unit+delta) 1-2*delta unit];
x = ReadSignal('Transients');
[n,J] = dyadlength(x);
figure(1);clf
 set(gcf, 'NumberTitle','off', 'Name','Window 1')
plot(x);
axis([0 N min(x)*1.1 max(x)*1.1]);

figure(2);clf
set(gcf, 'NumberTitle','off', 'Name','Window 2')
%[cp, btree] = AutoCPTour(x,J-4,'',0,0,0,0,0);
 %ImagePhasePlane('CP',btree,cp,'')

D = J-1;
qmf = MakeONFilter('Daubechies',16);

[wp, btreewp] = AutoWPTour(x,D,qmf,'',0,0,0,0,0);
ImagePhasePlane('WP',btreewp,wp,'',256,qmf)

%figure(4);clf
% set(gcf, 'NumberTitle','off', 'Name','Window 4')
%D = J-1;
%c = BP_Interior(x,'WP',D,qmf,0);
%[TFPlane, TFScaleOut] = PhasePlane(c,'WP',n,qmf);
%colormap(1-gray(256));

natom = 128;

figure(3);clf
 set(gcf, 'NumberTitle','off', 'Name','Window 4')
[atomic,resid] = WPMPursuitTour(x,D,qmf,natom,'');
size(atomic);

ImageAtomicPhase('WP',atomic,n,'',256,qmf)
colormap(1-gray(256));

%figure(6);clf
% set(gcf, 'NumberTitle','off', 'Name','Window 5')
%D = J-1;
%atomic=OMP(x,'WP',D,qmf,0,natom);
%PhasePlane(atomic,'WP',n,qmf);

%colormap(1-gray(256));

WLVERBOSE='Yes';
% Written by Maureen Clerc and Jerome Kalifa, 1997
% clerc@cmapx.polytechnique.fr, kalifa@cmapx.polytechnique.fr

%
%  Part of Wavelab Version 850
%  Built Tue Jan  3 13:20:39 EST 2006
%  This is Copyrighted Material
%  For Copying permissions see COPYING.m
%  Comments? e-mail wavelab@stat.stanford.edu


text:
import unittest
import os
import stat
from test.support import TESTFN, run_unittest

def get_mode(fname=TESTFN):
    return stat.filemode(os.lstat(fname).st_mode)

class TestFilemode(unittest.TestCase):

    def setUp(self):
        try:
            os.remove(TESTFN)
        except OSError:
            try:
                os.rmdir(TESTFN)
            except OSError:
                pass
    tearDown = setUp

    def test_mode(self):
        with open(TESTFN, 'w'):
            pass
        if os.name == 'posix':
            os.chmod(TESTFN, 0o700)
            self.assertEqual(get_mode(), '-rwx------')
            os.chmod(TESTFN, 0o070)
            self.assertEqual(get_mode(), '----rwx---')
            os.chmod(TESTFN, 0o007)
            self.assertEqual(get_mode(), '-------rwx')
            os.chmod(TESTFN, 0o444)
            self.assertEqual(get_mode(), '-r--r--r--')
        else:
            os.chmod(TESTFN, 0o700)
            self.assertEqual(get_mode()[:3], '-rw')

    def test_directory(self):
        os.mkdir(TESTFN)
        os.chmod(TESTFN, 0o700)
        if os.name == 'posix':
            self.assertEqual(get_mode(), 'drwx------')
        else:
            self.assertEqual(get_mode()[0], 'd')

    @unittest.skipUnless(hasattr(os, 'symlink'), 'os.symlink not available')
    def test_link(self):
        try:
            os.symlink(os.getcwd(), TESTFN)
        except (OSError, NotImplementedError) as err:
            raise unittest.SkipTest(str(err))
        else:
            self.assertEqual(get_mode()[0], 'l')

    @unittest.skipUnless(hasattr(os, 'mkfifo'), 'os.mkfifo not available')
    def test_fifo(self):
        os.mkfifo(TESTFN, 0o700)
        self.assertEqual(get_mode(), 'prwx------')

def test_main():
    run_unittest(TestFilemode)

if __name__ == '__main__':
    test_main()


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/widget29"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TCP Server demo"
>
</TextView>
<LinearLayout
android:id="@+id/widget41"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/TVhostname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hostname: localhost, always localhost"
>
</TextView>
</LinearLayout>
<LinearLayout
android:id="@+id/widget42"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/TVport"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="port: "
>
</TextView>
<EditText
android:id="@+id/ETport"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="3012"
android:textSize="18sp"
>
</EditText>
</LinearLayout>
<Button
android:id="@+id/makeconn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10px"
android:text="  Accept Connection  "
android:layout_gravity="center_horizontal"
>
</Button>
<ScrollView
android:id="@+id/ScrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/output"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="output: "
></TextView>

</ScrollView>

</LinearLayout>


text:
void parallel_quicksort( T* first, T* last ) {
    if( last-first<=QUICKSORT_CUTOFF ) {
        std::sort(first,last);
    } else {
        // Divide
        if( T* middle = divide(first,last) ) {
            // Conquer subproblems in parallel
            cilk_spawn parallel_quicksort( first, middle );
            parallel_quicksort( middle+1, last );
            // no cilk_sync needed here because of implicit one later
        }
    }
    // Implicit cilk_sync when function returns
}


text:
package org.yeastrc.xlink.www.web_utils;

import java.util.List;
import org.yeastrc.xlink.dto.UnifiedRepPepDynamicModLookupDTO;

public class FormatDynamicModsToString {
	/**
	 * @param unifiedRpDynamicModListPeptide
	 * @return
	 */
	public static String formatDynamicModsToString( List<UnifiedRepPepDynamicModLookupDTO> unifiedRpDynamicModListPeptide ) {
		if ( unifiedRpDynamicModListPeptide == null || unifiedRpDynamicModListPeptide.isEmpty() ) {
			return "";
		}
		StringBuilder modsStringPeptideSB = new StringBuilder();
		for ( UnifiedRepPepDynamicModLookupDTO UnifiedRpDynamicModDTO : unifiedRpDynamicModListPeptide ) {
			if ( modsStringPeptideSB.length() > 0 )  {
				modsStringPeptideSB.append( ", " );
			}
			if ( UnifiedRpDynamicModDTO.isIs_N_Terminal() ) {
				modsStringPeptideSB.append( "n" );
			} else if ( UnifiedRpDynamicModDTO.isIs_C_Terminal() ) {
				modsStringPeptideSB.append( "c" );
			} else {
				modsStringPeptideSB.append( UnifiedRpDynamicModDTO.getPosition() );
			}
			modsStringPeptideSB.append( "(" );
			modsStringPeptideSB.append( UnifiedRpDynamicModDTO.getMassRoundedString() );
			modsStringPeptideSB.append( ")" );
		}
		String modsStringPeptide = modsStringPeptideSB.toString();
		return modsStringPeptide;
	}
}