uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a626900a846e9f9a3e04292 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_tag():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.add_tag("tag1", "value1")
instance1.add_tag("tag2", "value2")
instance2.add_ta... | @mock_ec2_deprecated
def test_get_instances_filtering_by_tag():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.add_tag("tag1", "value1")
instance1.add_tag("tag2", "value2")
instance2.add_tag("tag1", "value1")
instance2.add_tag("tag2", "wrong value")... | 0/25")
resp = client.create_vpc(CidrBlock=str(vpc_cidr),)
vpc_id = resp["Vpc"]["VpcId"]
resp = client.create_subnet(CidrBlock=str(subnet_cidr), VpcId=vpc_id)
subnet_id = resp["Subnet"]["SubnetId"]
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MaxCount=1, MinCount=1, SubnetId=subnet_id,
... | 158 | 158 | 527 | 16 | 142 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_tag | test_get_instances_filtering_by_tag | 657 | 701 | 657 | 658 | 1266dbe3dd3194955331e7d0db4e415995f3e090 | bigcode/the-stack | train |
fe325b60753092cfd1b70d95 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_architecture():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=1)
instance = reservation.instances
reservations = conn.get_all_reservations(filters={"architecture": "x86_64"})
# get_all_reservations shoul... | @mock_ec2_deprecated
def test_get_instances_filtering_by_architecture():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=1)
instance = reservation.instances
reservations = conn.get_all_reservations(filters={"architecture": "x86_64"})
# get_all_reservations should return the instance
reservations[0].instances.should.have.length_of... | id.should.equal(instance2.id)
reservations2[0].instances[0].vpc_id.should.equal(vpc2.id)
reservations2[0].instances[0].subnet_id.should.equal(subnet2.id)
@mock_ec2_deprecated
def test_get_instances_filtering_by_architecture():
| 64 | 64 | 92 | 17 | 47 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_architecture | test_get_instances_filtering_by_architecture | 540 | 548 | 540 | 541 | 4bb9e3423f8d71a7a25fdbbe583dcd341ef94b6b | bigcode/the-stack | train |
1cfd087d8556910f2c528bd3 | train | function | @mock_ec2
def test_run_instance_with_block_device_mappings_missing_size():
ec2_client = boto3.client("ec2", region_name="us-east-1")
kwargs = {
"MinCount": 1,
"MaxCount": 1,
"ImageId": EXAMPLE_AMI_ID,
"KeyName": "the_key",
"InstanceType": "t1.micro",
"BlockDevice... | @mock_ec2
def test_run_instance_with_block_device_mappings_missing_size():
| ec2_client = boto3.client("ec2", region_name="us-east-1")
kwargs = {
"MinCount": 1,
"MaxCount": 1,
"ImageId": EXAMPLE_AMI_ID,
"KeyName": "the_key",
"InstanceType": "t1.micro",
"BlockDeviceMappings": [
{"DeviceName": "/dev/sda2", "Ebs": {"VolumeType": ... | .equal("MissingParameter")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
ex.value.response["Error"]["Message"].should.equal(
"The request must contain the parameter ebs"
)
@mock_ec2
def test_run_instance_with_block_device_mappings_missing_size():
| 64 | 64 | 199 | 17 | 47 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_block_device_mappings_missing_size | test_run_instance_with_block_device_mappings_missing_size | 1,361 | 1,382 | 1,361 | 1,362 | 60f9ff06eb9c6b54075ce5e92dbf336d76069eab | bigcode/the-stack | train |
e1e7f005ba8af5399c8dd6d4 | train | function | @mock_ec2
def test_instance_terminate_keep_volumes_implicit():
ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[{"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": 50}}],
... | @mock_ec2
def test_instance_terminate_keep_volumes_implicit():
| ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[{"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": 50}}],
)
instance = result[0]
instance_volume_ids = []
... | _ids = []
for volume in instance.volumes.all():
instance_volume_ids.append(volume.volume_id)
instance.terminate()
instance.wait_until_terminated()
assert len(list(ec2_resource.volumes.all())) == 1
@mock_ec2
def test_instance_terminate_keep_volumes_implicit():
| 64 | 64 | 168 | 16 | 47 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_terminate_keep_volumes_implicit | test_instance_terminate_keep_volumes_implicit | 157 | 178 | 157 | 158 | 15cad207bc1ce9ac980e9d4f628cb44708de6813 | bigcode/the-stack | train |
bc896b4efb73baefd0388d84 | train | function | @mock_ec2
def test_create_with_tags():
ec2 = boto3.client("ec2", region_name="us-west-2")
instances = ec2.run_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
InstanceType="t2.micro",
TagSpecifications=[
{
"ResourceType": "instance",
... | @mock_ec2
def test_create_with_tags():
| ec2 = boto3.client("ec2", region_name="us-west-2")
instances = ec2.run_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
InstanceType="t2.micro",
TagSpecifications=[
{
"ResourceType": "instance",
"Tags": [
... | Token"]
next_token.should_not.be.none
resp2 = client.describe_instances(NextToken=next_token)
reservations.extend(resp2["Reservations"])
reservations.should.have.length_of(100)
assert "NextToken" not in resp2.keys()
@mock_ec2
def test_create_with_tags():
| 64 | 64 | 190 | 11 | 53 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_create_with_tags | test_create_with_tags | 311 | 334 | 311 | 312 | f0ab71ad738afb0fdeed0505243032ac904d8341 | bigcode/the-stack | train |
a4a9485cb7b2c92753a224ff | train | function | @mock_ec2_deprecated
def test_run_instance_with_nic_preexisting():
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
security_group1 = conn.create_security_group(
"test security group #1", "this is a test secu... | @mock_ec2_deprecated
def test_run_instance_with_nic_preexisting():
| conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
security_group1 = conn.create_security_group(
"test security group #1", "this is a test security group"
)
security_group2 = conn.create_security_group(... | .groups.should.have.length_of(2)
set([group.id for group in instance.groups]).should.equal(
set([security_group1.id, security_group2.id])
)
eni.subnet_id.should.equal(subnet.id)
eni.groups.should.have.length_of(2)
set([group.id for group in eni.groups]).should.equal(
set([security_g... | 132 | 132 | 441 | 17 | 115 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_nic_preexisting | test_run_instance_with_nic_preexisting | 1,158 | 1,209 | 1,158 | 1,159 | c0d4de10f1eb995c7d4ab0082887c7bbd7fcd6b2 | bigcode/the-stack | train |
4a7c6d8a95842a7fd3d43f64 | train | function | @mock_ec2_deprecated
def test_run_instance_with_nic_autocreated():
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
security_group1 = conn.create_security_group(
"test security group #1", "this is a test secu... | @mock_ec2_deprecated
def test_run_instance_with_nic_autocreated():
| conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
security_group1 = conn.create_security_group(
"test security group #1", "this is a test security group"
)
security_group2 = conn.create_security_group(... | resp = client.run_instances(
ImageId=EXAMPLE_AMI_ID, MaxCount=1, MinCount=1, SubnetId=subnet_id
)
instance = resp["Instances"][0]
instance.should.contain("PublicDnsName")
instance.should.contain("PublicIpAddress")
len(instance["PublicDnsName"]).should.be.greater_than(0)
len(instance["Pu... | 114 | 114 | 383 | 18 | 96 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_nic_autocreated | test_run_instance_with_nic_autocreated | 1,114 | 1,155 | 1,114 | 1,115 | e86b95d65fd8b3bc7ebb34b1b93b8f2eea8d90cb | bigcode/the-stack | train |
9b7850a29d491a3afdf56803 | train | function | @mock_ec2_deprecated
def test_run_instance_with_placement():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, placement="us-east-1b")
instance = reservation.instances[0]
instance.placement.should.equal("us-east-1b")
| @mock_ec2_deprecated
def test_run_instance_with_placement():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, placement="us-east-1b")
instance = reservation.instances[0]
instance.placement.should.equal("us-east-1b")
| ():
conn = boto.ec2.connect_to_region("us-east-1")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
instance.placement.should.equal("us-east-1a")
@mock_ec2_deprecated
def test_run_instance_with_placement():
| 64 | 64 | 71 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_placement | test_run_instance_with_placement | 1,009 | 1,015 | 1,009 | 1,010 | c4339274d572b31b888cef435f97b10d3fcbed13 | bigcode/the-stack | train |
86d4dbd1ccf4660e71ffc709 | train | function | @mock_ec2_deprecated
def test_add_servers():
add_servers(EXAMPLE_AMI_ID, 2)
conn = boto.connect_ec2()
reservations = conn.get_all_reservations()
assert len(reservations) == 2
instance1 = reservations[0].instances[0]
assert instance1.image_id == EXAMPLE_AMI_ID
| @mock_ec2_deprecated
def test_add_servers():
| add_servers(EXAMPLE_AMI_ID, 2)
conn = boto.connect_ec2()
reservations = conn.get_all_reservations()
assert len(reservations) == 2
instance1 = reservations[0].instances[0]
assert instance1.image_id == EXAMPLE_AMI_ID
| _boto_gte
decode_method = base64.decodebytes
################ Test Readme ###############
def add_servers(ami_id, count):
conn = boto.connect_ec2()
for index in range(count):
conn.run_instances(ami_id)
@mock_ec2_deprecated
def test_add_servers():
| 64 | 64 | 78 | 12 | 52 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_add_servers | test_add_servers | 32 | 40 | 32 | 33 | a9212641a2ba7bd2f52eed1b55774efc5e381be5 | bigcode/the-stack | train |
7c0035020055e9949441ee8b | train | function | @mock_ec2_deprecated
def test_describe_instance_status_no_instances():
conn = boto.connect_ec2("the_key", "the_secret")
all_status = conn.get_all_instance_status()
len(all_status).should.equal(0)
| @mock_ec2_deprecated
def test_describe_instance_status_no_instances():
| conn = boto.connect_ec2("the_key", "the_secret")
all_status = conn.get_all_instance_status()
len(all_status).should.equal(0)
| volumes = ec2_client.describe_volumes(VolumeIds=[volume["VolumeId"]])
volumes["Volumes"][0]["Size"].should.equal(30)
volumes["Volumes"][0]["SnapshotId"].should.equal(snapshot.snapshot_id)
@mock_ec2_deprecated
def test_describe_instance_status_no_instances():
| 64 | 64 | 51 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_describe_instance_status_no_instances | test_describe_instance_status_no_instances | 1,420 | 1,424 | 1,420 | 1,421 | 09e9c8c5661c595350f0ebd261d1d22c1b3110fd | bigcode/the-stack | train |
6727557fa831bf9846295dbd | train | function | @mock_ec2_deprecated
def test_run_instance_with_keypair():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
instance = reservation.instances[0]
instance.key_name.should.equal("keypair_name")
| @mock_ec2_deprecated
def test_run_instance_with_keypair():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
instance = reservation.instances[0]
instance.key_name.should.equal("keypair_name")
| _not.equal(None)
instance.public_dns_name.should.contain(instance.ip_address.replace(".", "-"))
instance.private_ip_address.should_not.equal(None)
instance.private_dns_name.should.contain(
instance.private_ip_address.replace(".", "-")
)
@mock_ec2_deprecated
def test_run_instance_with_keypair():
| 64 | 64 | 68 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_keypair | test_run_instance_with_keypair | 1,306 | 1,312 | 1,306 | 1,307 | 9367784a6f2f0f9904aba6b3089e289878f45bf7 | bigcode/the-stack | train |
b08817e4eec305b334b5008f | train | function | @mock_ec2
def test_instance_terminate_discard_volumes():
ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[
{
"DeviceName": "/dev/sda1",
... | @mock_ec2
def test_instance_terminate_discard_volumes():
| ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[
{
"DeviceName": "/dev/sda1",
"Ebs": {"VolumeSize": 50, "DeleteOnTermination... | succeeded, but DryRun flag is set"
)
conn.terminate_instances([instance.id])
reservations = conn.get_all_reservations()
instance = reservations[0].instances[0]
instance.state.should.equal("terminated")
@mock_ec2
def test_instance_terminate_discard_volumes():
| 64 | 64 | 161 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_terminate_discard_volumes | test_instance_terminate_discard_volumes | 101 | 126 | 101 | 103 | a71522aa7c9adf83ee15e678660b44e3f10d340b | bigcode/the-stack | train |
08416969d5b4db071da28aea | train | function | @mock_ec2
def test_run_instance_with_subnet_boto3():
client = boto3.client("ec2", region_name="eu-central-1")
ip_networks = [
(ipaddress.ip_network("10.0.0.0/16"), ipaddress.ip_network("10.0.99.0/24")),
(
ipaddress.ip_network("192.168.42.0/24"),
ipaddress.ip_network("192... | @mock_ec2
def test_run_instance_with_subnet_boto3():
| client = boto3.client("ec2", region_name="eu-central-1")
ip_networks = [
(ipaddress.ip_network("10.0.0.0/16"), ipaddress.ip_network("10.0.99.0/24")),
(
ipaddress.ip_network("192.168.42.0/24"),
ipaddress.ip_network("192.168.42.0/25"),
),
]
# Tests instanc... | -east-1a")
@mock_ec2_deprecated
def test_run_instance_with_placement():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, placement="us-east-1b")
instance = reservation.instances[0]
instance.placement.should.equal("us-east-1b")
@mock_ec2
def test_run_in... | 92 | 92 | 309 | 16 | 76 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_subnet_boto3 | test_run_instance_with_subnet_boto3 | 1,018 | 1,050 | 1,018 | 1,019 | 5c54b9208d4e5449d9662bae0bf13e8157601688 | bigcode/the-stack | train |
1703d74e237b0fceea0bdf28 | train | function | @mock_ec2
def test_get_instances_filtering_by_subnet_id():
client = boto3.client("ec2", region_name="us-east-1")
vpc_cidr = ipaddress.ip_network("192.168.42.0/24")
subnet_cidr = ipaddress.ip_network("192.168.42.0/25")
resp = client.create_vpc(CidrBlock=str(vpc_cidr),)
vpc_id = resp["Vpc"]["VpcId"]... | @mock_ec2
def test_get_instances_filtering_by_subnet_id():
| client = boto3.client("ec2", region_name="us-east-1")
vpc_cidr = ipaddress.ip_network("192.168.42.0/24")
subnet_cidr = ipaddress.ip_network("192.168.42.0/25")
resp = client.create_vpc(CidrBlock=str(vpc_cidr),)
vpc_id = resp["Vpc"]["VpcId"]
resp = client.create_subnet(CidrBlock=str(subnet_cidr... | "]
)
reservations = client.describe_instances(
Filters=[{"Name": "instance.group-id", "Values": [group_id]}]
)["Reservations"]
reservations[0]["Instances"].should.have.length_of(1)
@mock_ec2
def test_get_instances_filtering_by_subnet_id():
| 64 | 64 | 213 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_subnet_id | test_get_instances_filtering_by_subnet_id | 634 | 654 | 634 | 635 | ecb0e5422c0eda4c94cdd0f33388bd1c28e57364 | bigcode/the-stack | train |
5af104dbbbb7267636c88ac8 | train | function | @mock_ec2
def test_modify_delete_on_termination():
ec2_client = boto3.resource("ec2", region_name="us-west-1")
result = ec2_client.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
instance = result[0]
instance.load()
instance.block_device_mappings[0]["Ebs"]["DeleteOnTermination"].sho... | @mock_ec2
def test_modify_delete_on_termination():
| ec2_client = boto3.resource("ec2", region_name="us-west-1")
result = ec2_client.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
instance = result[0]
instance.load()
instance.block_device_mappings[0]["Ebs"]["DeleteOnTermination"].should.be(True)
instance.modify_attribute(
... | conn.modify_instance_attribute(instance.id, "groupSet", [security_group.id])
security_group_instances = security_group.instances()
assert len(security_group_instances) == 1
assert security_group_instances[0].id == instance.id
@mock_ec2
def test_modify_delete_on_termination():
| 64 | 64 | 151 | 13 | 50 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_modify_delete_on_termination | test_modify_delete_on_termination | 1,599 | 1,612 | 1,599 | 1,600 | c82a53f31fdd8525a2a6549b609299de48443dcc | bigcode/the-stack | train |
e30eec39ad6b408f6a885d9e | train | function | @requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_instance_with_nic_attach_detach():
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
security_group1 = conn.create_security_group(
"test security gro... | @requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_instance_with_nic_attach_detach():
| conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
security_group1 = conn.create_security_group(
"test security group #1", "this is a test security group"
)
security_group2 = conn.create_security_group... | Boto objects
reservation = conn.run_instances(
EXAMPLE_AMI_ID,
network_interfaces=interfaces,
security_group_ids=[security_group2.id],
)
instance = reservation.instances[0]
instance.subnet_id.should.equal(subnet.id)
all_enis = conn.get_all_network_interfaces()
all_eni... | 226 | 226 | 754 | 30 | 196 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_with_nic_attach_detach | test_instance_with_nic_attach_detach | 1,212 | 1,290 | 1,212 | 1,214 | de96b5f384924527dc73a28d2da0e23543fe7a4e | bigcode/the-stack | train |
585afb80770aff9153e928b3 | train | function | @mock_ec2_deprecated
def test_instance_attribute_instance_type():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
with pytest.raises(EC2ResponseError) as ex:
instance.modify_attribute("instanceType", "m1.small... | @mock_ec2_deprecated
def test_instance_attribute_instance_type():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
with pytest.raises(EC2ResponseError) as ex:
instance.modify_attribute("instanceType", "m1.small", dry_run=True)
ex.value.error_code.should.equal("DryRunOpera... | .value.message.should.equal(
"An error occurred (DryRunOperation) when calling the RebootInstance operation: Request would have succeeded, but DryRun flag is set"
)
instance.reboot()
instance.state.should.equal("pending")
@mock_ec2_deprecated
def test_instance_attribute_instance_type():
| 64 | 64 | 188 | 14 | 50 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_attribute_instance_type | test_instance_attribute_instance_type | 830 | 848 | 830 | 831 | 807e3e2345fbd3cb5b8ae1881a38f45dc2681b5c | bigcode/the-stack | train |
c2146f8b24ee98c453731baf | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_tag_name():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.add_tag("tag1")
instance1.add_tag("tag2")
instance2.add_tag("tag1")
i... | @mock_ec2_deprecated
def test_get_instances_filtering_by_tag_name():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.add_tag("tag1")
instance1.add_tag("tag2")
instance2.add_tag("tag1")
instance2.add_tag("tag2X")
instance3.add_tag("tag3")
reservat... | ["value2", "bogus"]})
# get_all_reservations should return both instances with one of the
# acceptable tag values
reservations.should.have.length_of(1)
reservations[0].instances.should.have.length_of(2)
reservations[0].instances[0].id.should.equal(instance1.id)
reservations[0].instances[1].id.s... | 102 | 102 | 343 | 17 | 85 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_tag_name | test_get_instances_filtering_by_tag_name | 746 | 775 | 746 | 747 | 545a7f90176714200bd8f30163849f4fe2751fb4 | bigcode/the-stack | train |
3b5ea98efa964db726ac367b | train | function | @mock_ec2_deprecated
def test_terminate_empty_instances():
conn = boto.connect_ec2("the_key", "the_secret")
conn.terminate_instances.when.called_with([]).should.throw(EC2ResponseError)
| @mock_ec2_deprecated
def test_terminate_empty_instances():
| conn = boto.connect_ec2("the_key", "the_secret")
conn.terminate_instances.when.called_with([]).should.throw(EC2ResponseError)
| .value.response["Error"]["Message"].should.equal(
"The volume {0} is not attached to instance {1} as device {2}".format(
volume.volume_id, instance.instance_id, "/dev/sdf"
)
)
@mock_ec2_deprecated
def test_terminate_empty_instances():
| 64 | 64 | 47 | 14 | 50 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_terminate_empty_instances | test_terminate_empty_instances | 227 | 230 | 227 | 228 | 8c61804f4cdb783978b1cdd512694fc825639b6b | bigcode/the-stack | train |
9049d27d21e07b92a334e498 | train | function | @mock_ec2
def test_run_multiple_instances_in_same_command():
instance_count = 4
client = boto3.client("ec2", region_name="us-east-1")
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=instance_count, MaxCount=instance_count
)
reservations = client.describe_instances()["Reservations"]
... | @mock_ec2
def test_run_multiple_instances_in_same_command():
| instance_count = 4
client = boto3.client("ec2", region_name="us-east-1")
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=instance_count, MaxCount=instance_count
)
reservations = client.describe_instances()["Reservations"]
reservations[0]["Instances"].should.have.length_of(instanc... | .be(False)
instance = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID, MaxCount=1, MinCount=1,
)[0]
instance.load()
instance.ebs_optimized.should.be(False)
@mock_ec2
def test_run_multiple_instances_in_same_command():
| 64 | 64 | 124 | 14 | 50 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_multiple_instances_in_same_command | test_run_multiple_instances_in_same_command | 1,636 | 1,649 | 1,636 | 1,637 | 18918f8892263da9cbb783ec44c0bb0d86449cf7 | bigcode/the-stack | train |
a2d3d7db23147321ef60528c | train | function | @mock_ec2_deprecated
def test_describe_instance_status_with_instances():
conn = boto.connect_ec2("the_key", "the_secret")
conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
all_status = conn.get_all_instance_status()
len(all_status).should.equal(1)
all_status[0].instance_status.status.shou... | @mock_ec2_deprecated
def test_describe_instance_status_with_instances():
| conn = boto.connect_ec2("the_key", "the_secret")
conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
all_status = conn.get_all_instance_status()
len(all_status).should.equal(1)
all_status[0].instance_status.status.should.equal("ok")
all_status[0].system_status.status.should.equal("ok")
| 2_deprecated
def test_describe_instance_status_no_instances():
conn = boto.connect_ec2("the_key", "the_secret")
all_status = conn.get_all_instance_status()
len(all_status).should.equal(0)
@mock_ec2_deprecated
def test_describe_instance_status_with_instances():
| 64 | 64 | 96 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_describe_instance_status_with_instances | test_describe_instance_status_with_instances | 1,427 | 1,435 | 1,427 | 1,428 | 5a69a80ca2def5a68a671c25093ded8866a0bd07 | bigcode/the-stack | train |
7821d4ef70c04bce1593d727 | train | function | @mock_ec2_deprecated
def test_run_instance_with_instance_type():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, instance_type="t1.micro")
instance = reservation.instances[0]
instance.instance_type.should.equal("t1.micro")
| @mock_ec2_deprecated
def test_run_instance_with_instance_type():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, instance_type="t1.micro")
instance = reservation.instances[0]
instance.instance_type.should.equal("t1.micro")
| conn.run_instances(EXAMPLE_AMI_ID, security_group_ids=[group.id])
instance = reservation.instances[0]
instance.groups[0].id.should.equal(group.id)
instance.groups[0].name.should.equal("group1")
@mock_ec2_deprecated
def test_run_instance_with_instance_type():
| 64 | 64 | 68 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_instance_type | test_run_instance_with_instance_type | 991 | 997 | 991 | 992 | bcebb1f66ec1b9cd89bce2d62830326ee1544f84 | bigcode/the-stack | train |
ecb5c6f518ae17c3348c6bff | train | function | @mock_ec2
def test_get_instances_filtering_by_account_id():
client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
conn.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
reservations = client.describe_instances(
Filters=[{"Name": "owner-id... | @mock_ec2
def test_get_instances_filtering_by_account_id():
| client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
conn.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
reservations = client.describe_instances(
Filters=[{"Name": "owner-id", "Values": ["123456789012"]}]
)["Reservations"]
r... | 1)
reservations = client.describe_instances(
Filters=[{"Name": "image-id", "Values": [EXAMPLE_AMI_ID]}]
)["Reservations"]
reservations[0]["Instances"].should.have.length_of(1)
@mock_ec2
def test_get_instances_filtering_by_account_id():
| 64 | 64 | 118 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_account_id | test_get_instances_filtering_by_account_id | 563 | 573 | 563 | 564 | 817a8ed3028969bfbe9a6ee0801ce82d54468ca8 | bigcode/the-stack | train |
6516db051cca03d14e409e33 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_reason_code():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.stop()
instance2.terminate()
reservations = conn.get_all_reservations... | @mock_ec2_deprecated
def test_get_instances_filtering_by_reason_code():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.stop()
instance2.terminate()
reservations = conn.get_all_reservations(
filters={"state-reason-code": "Client.UserInitiatedShutdown"}
... | 1.id, instance2.id, instance3.id]))
reservations = conn.get_all_reservations(filters={"instance-type": "bogus"})
# bogus instance-type should return none
reservations.should.have.length_of(0)
@mock_ec2_deprecated
def test_get_instances_filtering_by_reason_code():
| 64 | 64 | 211 | 17 | 47 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_reason_code | test_get_instances_filtering_by_reason_code | 466 | 486 | 466 | 467 | b66d464f3e003082c010d0f60cc443ce2b1e0853 | bigcode/the-stack | train |
17d1c74d7804a8561566b93e | train | function | @mock_ec2
def test_warn_on_invalid_ami():
if settings.TEST_SERVER_MODE:
raise SkipTest("Can't capture warnings in server mode.")
ec2 = boto3.resource("ec2", "us-east-1")
with pytest.warns(
PendingDeprecationWarning,
match=r"Could not find AMI with image-id:invalid-ami.+",
):
... | @mock_ec2
def test_warn_on_invalid_ami():
| if settings.TEST_SERVER_MODE:
raise SkipTest("Can't capture warnings in server mode.")
ec2 = boto3.resource("ec2", "us-east-1")
with pytest.warns(
PendingDeprecationWarning,
match=r"Could not find AMI with image-id:invalid-ami.+",
):
ec2.create_instances(ImageId="invalid-... | "].should.equal(400)
message = "Value ({invalid_instance_attribute}) for parameter attribute is invalid. Unknown attribute.".format(
invalid_instance_attribute=invalid_instance_attribute
)
ex.value.response["Error"]["Message"].should.equal(message)
@mock_ec2
def test_warn_on_invalid_... | 64 | 64 | 104 | 13 | 51 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_warn_on_invalid_ami | test_warn_on_invalid_ami | 1,717 | 1,726 | 1,717 | 1,718 | 0bc5b619197ad91227c60499b1ba7a296e063196 | bigcode/the-stack | train |
08413373e70f05ae022e20d5 | train | function | @requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_describe_instance_status_with_non_running_instances():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.stop()
in... | @requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_describe_instance_status_with_non_running_instances():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.stop()
instance2.terminate()
all_running_status = conn.get_all_instance_status()
all_running_status.should.have.le... | Filters=state_code_filter["stopped"]
)["InstanceStatuses"]
found_instance_ids = [status["InstanceId"] for status in found_statuses]
sorted(found_instance_ids).should.equal(stopped_instance_ids)
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_describe_instance_status_with_non_running_instances():... | 77 | 77 | 258 | 31 | 46 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_describe_instance_status_with_non_running_instances | test_describe_instance_status_with_non_running_instances | 1,545 | 1,569 | 1,545 | 1,547 | 47e548f502fbba73f60870e0250624ce74abd153 | bigcode/the-stack | train |
50c105f47d79a191eb9d8607 | train | function | @mock_ec2
def test_run_instance_with_block_device_mappings():
ec2_client = boto3.client("ec2", region_name="us-east-1")
kwargs = {
"MinCount": 1,
"MaxCount": 1,
"ImageId": EXAMPLE_AMI_ID,
"KeyName": "the_key",
"InstanceType": "t1.micro",
"BlockDeviceMappings": [{... | @mock_ec2
def test_run_instance_with_block_device_mappings():
| ec2_client = boto3.client("ec2", region_name="us-east-1")
kwargs = {
"MinCount": 1,
"MaxCount": 1,
"ImageId": EXAMPLE_AMI_ID,
"KeyName": "the_key",
"InstanceType": "t1.micro",
"BlockDeviceMappings": [{"DeviceName": "/dev/sda2", "Ebs": {"VolumeSize": 50}}],
}
... | .connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
instance = reservation.instances[0]
instance.key_name.should.equal("keypair_name")
@mock_ec2
def test_run_instance_with_block_device_mappings():
| 64 | 64 | 192 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_block_device_mappings | test_run_instance_with_block_device_mappings | 1,315 | 1,336 | 1,315 | 1,316 | ce37550210e0e4535f8c0b6d31b391802d0a3fac | bigcode/the-stack | train |
610eecc9bdd617d3f594b92b | train | function | @mock_ec2_deprecated
def test_modify_instance_attribute_security_groups():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
sg_id = conn.create_security_group(
"test security group", "this is a test security gr... | @mock_ec2_deprecated
def test_modify_instance_attribute_security_groups():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
sg_id = conn.create_security_group(
"test security group", "this is a test security group"
).id
sg_id2 = conn.create_security_group(
"test securi... | calling the ModifyInstanceType operation: Request would have succeeded, but DryRun flag is set"
)
instance.modify_attribute("instanceType", "m1.small")
instance_attribute = instance.get_attribute("instanceType")
instance_attribute.should.be.a(InstanceAttribute)
instance_attribute.get("instanceTyp... | 85 | 85 | 286 | 15 | 70 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_modify_instance_attribute_security_groups | test_modify_instance_attribute_security_groups | 851 | 878 | 851 | 852 | ac94628bef409f0c7a73c86fffb195bf689debb9 | bigcode/the-stack | train |
73120f1c0ee952f211b2753f | train | function | @mock_ec2
def test_get_instances_filtering_by_image_id():
client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
conn.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
reservations = client.describe_instances(
Filters=[{"Name": "image-id",... | @mock_ec2
def test_get_instances_filtering_by_image_id():
| client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
conn.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
reservations = client.describe_instances(
Filters=[{"Name": "image-id", "Values": [EXAMPLE_AMI_ID]}]
)["Reservations"]
re... | instance = reservation.instances
reservations = conn.get_all_reservations(filters={"architecture": "x86_64"})
# get_all_reservations should return the instance
reservations[0].instances.should.have.length_of(1)
@mock_ec2
def test_get_instances_filtering_by_image_id():
| 64 | 64 | 119 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_image_id | test_get_instances_filtering_by_image_id | 551 | 560 | 551 | 552 | c7bdcf81659fbf7818c85648033428d3b20077e8 | bigcode/the-stack | train |
3a7544650bf9d2763f2fec82 | train | function | @mock_ec2_deprecated
def test_run_instance_with_default_placement():
conn = boto.ec2.connect_to_region("us-east-1")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
instance.placement.should.equal("us-east-1a")
| @mock_ec2_deprecated
def test_run_instance_with_default_placement():
| conn = boto.ec2.connect_to_region("us-east-1")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
instance.placement.should.equal("us-east-1a")
| _ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, instance_type="t1.micro")
instance = reservation.instances[0]
instance.instance_type.should.equal("t1.micro")
@mock_ec2_deprecated
def test_run_instance_with_default_placement():
| 64 | 64 | 64 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_default_placement | test_run_instance_with_default_placement | 1,000 | 1,006 | 1,000 | 1,001 | f02b303fa95563d3bfe058eaa99886728868e864 | bigcode/the-stack | train |
764df17cb52b845dfa3503fe | train | function | @mock_ec2
def test_create_instance_ebs_optimized():
ec2_resource = boto3.resource("ec2", region_name="eu-west-1")
instance = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID, MaxCount=1, MinCount=1, EbsOptimized=True
)[0]
instance.load()
instance.ebs_optimized.should.be(True)
inst... | @mock_ec2
def test_create_instance_ebs_optimized():
| ec2_resource = boto3.resource("ec2", region_name="eu-west-1")
instance = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID, MaxCount=1, MinCount=1, EbsOptimized=True
)[0]
instance.load()
instance.ebs_optimized.should.be(True)
instance.modify_attribute(EbsOptimized={"Value": False})... | {"DeviceName": "/dev/sda1", "Ebs": {"DeleteOnTermination": False}}
]
)
instance.load()
instance.block_device_mappings[0]["Ebs"]["DeleteOnTermination"].should.be(False)
@mock_ec2
def test_create_instance_ebs_optimized():
| 64 | 64 | 162 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_create_instance_ebs_optimized | test_create_instance_ebs_optimized | 1,615 | 1,633 | 1,615 | 1,616 | 70c0be91cd592ae4949c7e1606b6d635751ba1a9 | bigcode/the-stack | train |
058efb8775f3d67092fef7d5 | train | function | @mock_ec2_deprecated
def test_get_instance_by_security_group():
conn = boto.connect_ec2("the_key", "the_secret")
conn.run_instances(EXAMPLE_AMI_ID)
instance = conn.get_only_instances()[0]
security_group = conn.create_security_group("test", "test")
with pytest.raises(EC2ResponseError) as ex:
... | @mock_ec2_deprecated
def test_get_instance_by_security_group():
| conn = boto.connect_ec2("the_key", "the_secret")
conn.run_instances(EXAMPLE_AMI_ID)
instance = conn.get_only_instances()[0]
security_group = conn.create_security_group("test", "test")
with pytest.raises(EC2ResponseError) as ex:
conn.modify_instance_attribute(
instance.id, "gro... | == instance2.id), None)
status2.state_name.should.equal("terminated")
status3 = next((s for s in all_status if s.id == instance3.id), None)
status3.state_name.should.equal("running")
@mock_ec2_deprecated
def test_get_instance_by_security_group():
| 64 | 64 | 214 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instance_by_security_group | test_get_instance_by_security_group | 1,572 | 1,596 | 1,572 | 1,573 | 551ee24593975ed3b3dc1d9b670af338ea563b47 | bigcode/the-stack | train |
1a5cf019d73fdbad8d8e94bd | train | function | @mock_ec2
def test_instance_detach_volume_wrong_path():
ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[{"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": 50}},],
)
... | @mock_ec2
def test_instance_detach_volume_wrong_path():
| ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[{"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": 50}},],
)
instance = result[0]
for volume in instance.volum... | response = instance.detach_volume(VolumeId=volume.volume_id)
response["State"].should.equal("detaching")
instance.terminate()
instance.wait_until_terminated()
assert len(list(ec2_resource.volumes.all())) == 2
@mock_ec2
def test_instance_detach_volume_wrong_path():
| 66 | 66 | 222 | 14 | 51 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_detach_volume_wrong_path | test_instance_detach_volume_wrong_path | 204 | 224 | 204 | 205 | 07430b185d7d39512fb168656a35032c00be384a | bigcode/the-stack | train |
f481339fae444dd97c51757a | train | function | @mock_ec2_deprecated
def test_instance_reboot():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
with pytest.raises(EC2ResponseError) as ex:
instance.reboot(dry_run=True)
ex.value.error_code.should.equal("... | @mock_ec2_deprecated
def test_instance_reboot():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
with pytest.raises(EC2ResponseError) as ex:
instance.reboot(dry_run=True)
ex.value.error_code.should.equal("DryRunOperation")
ex.value.status.should.equa... | DryRunOperation) when calling the StartInstance operation: Request would have succeeded, but DryRun flag is set"
)
started_instances = conn.start_instances([instances[0].id])
started_instances[0].state.should.equal("pending")
@mock_ec2_deprecated
def test_instance_reboot():
| 64 | 64 | 143 | 13 | 51 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_reboot | test_instance_reboot | 812 | 827 | 812 | 813 | 3f520bf16baf587f2a6689158064b718a63f509c | bigcode/the-stack | train |
ac91e997394aac16088ac6b2 | train | function | @mock_ec2
def test_instance_terminate_detach_volumes():
ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[
{"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": 50... | @mock_ec2
def test_instance_terminate_detach_volumes():
| ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[
{"DeviceName": "/dev/sda1", "Ebs": {"VolumeSize": 50}},
{"DeviceName": "/dev/sda2", "Ebs": {"Vol... | .append(volume.volume_id)
instance.terminate()
instance.wait_until_terminated()
assert len(instance_volume_ids) == 1
volume = ec2_resource.Volume(instance_volume_ids[0])
volume.state.should.equal("available")
@mock_ec2
def test_instance_terminate_detach_volumes():
| 64 | 64 | 185 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_terminate_detach_volumes | test_instance_terminate_detach_volumes | 181 | 201 | 181 | 182 | 2a66b099135263d04729fb8ca730fa83583ddcb0 | bigcode/the-stack | train |
6d22c9216d8fd0d9358eab06 | train | function | @mock_ec2
def test_get_paginated_instances():
client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
for i in range(100):
conn.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
resp = client.describe_instances(MaxResults=50)
reservation... | @mock_ec2
def test_get_paginated_instances():
| client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
for i in range(100):
conn.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
resp = client.describe_instances(MaxResults=50)
reservations = resp["Reservations"]
reservations.shou... | conn.get_all_reservations(instance_ids=[instance1.id, "i-1234abcd"])
cm.value.code.should.equal("InvalidInstanceID.NotFound")
cm.value.status.should.equal(400)
cm.value.request_id.should_not.be.none
@mock_ec2
def test_get_paginated_instances():
| 64 | 64 | 164 | 12 | 51 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_paginated_instances | test_get_paginated_instances | 294 | 308 | 294 | 295 | 8daa775624f92413a9f6946a2153a7415d52e172 | bigcode/the-stack | train |
fb566b2766a3feb4cb784c4f | train | function | @mock_ec2_deprecated
def test_instance_attribute_user_data():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
with pytest.raises(EC2ResponseError) as ex:
instance.modify_attribute("userData", "this is my user ... | @mock_ec2_deprecated
def test_instance_attribute_user_data():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
with pytest.raises(EC2ResponseError) as ex:
instance.modify_attribute("userData", "this is my user data", dry_run=True)
ex.value.error_code.should.equal("Dry... | (InstanceAttribute)
group_list = instance_attribute.get("groupSet")
any(g.id == sg_id for g in group_list).should.be.ok
any(g.id == sg_id2 for g in group_list).should.be.ok
@mock_ec2_deprecated
def test_instance_attribute_user_data():
| 64 | 64 | 194 | 14 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_attribute_user_data | test_instance_attribute_user_data | 881 | 899 | 881 | 882 | 3d062c7bb9d7410a9be684a3f286b74e79845b81 | bigcode/the-stack | train |
86622be369dac25c66b66726 | train | function | @mock_ec2
def test_instance_terminate_keep_volumes_explicit():
ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[
{
"DeviceName": "/dev/sda1"... | @mock_ec2
def test_instance_terminate_keep_volumes_explicit():
| ec2_resource = boto3.resource("ec2", "us-west-1")
result = ec2_resource.create_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[
{
"DeviceName": "/dev/sda1",
"Ebs": {"VolumeSize": 50, "DeleteOnTermination... | ]
instance_volume_ids = []
for volume in instance.volumes.all():
instance_volume_ids.append(volume.volume_id)
instance.terminate()
instance.wait_until_terminated()
assert not list(ec2_resource.volumes.all())
@mock_ec2
def test_instance_terminate_keep_volumes_explicit():
| 64 | 64 | 166 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_terminate_keep_volumes_explicit | test_instance_terminate_keep_volumes_explicit | 129 | 154 | 129 | 131 | 93025051d7170dbe7e06539d03b3129a9cde6ca7 | bigcode/the-stack | train |
77090819b497a99f0bff0cd0 | train | function | @mock_ec2
def test_get_instances_filtering_by_instance_group_id():
client = boto3.client("ec2", region_name="us-east-1")
create_sg = client.create_security_group(Description="test", GroupName="test_sg")
group_id = create_sg["GroupId"]
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, Max... | @mock_ec2
def test_get_instances_filtering_by_instance_group_id():
| client = boto3.client("ec2", region_name="us-east-1")
create_sg = client.create_security_group(Description="test", GroupName="test_sg")
group_id = create_sg["GroupId"]
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, SecurityGroups=["test_sg"]
)
reservations = client... | )
reservations = client.describe_instances(
Filters=[{"Name": "instance.group-name", "Values": ["test_sg"]}]
)["Reservations"]
reservations[0]["Instances"].should.have.length_of(1)
@mock_ec2
def test_get_instances_filtering_by_instance_group_id():
| 64 | 64 | 145 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_instance_group_id | test_get_instances_filtering_by_instance_group_id | 620 | 631 | 620 | 621 | 60e069b8a60b925ba73e6bf6d8163a8599dfb724 | bigcode/the-stack | train |
3072b45808de08eb6764d5d7 | train | function | @mock_ec2_deprecated
def test_describe_instance_status_with_instance_filter_deprecated():
conn = boto.connect_ec2("the_key", "the_secret")
# We want to filter based on this one
reservation = conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
instance = reservation.instances[0]
# This is j... | @mock_ec2_deprecated
def test_describe_instance_status_with_instance_filter_deprecated():
| conn = boto.connect_ec2("the_key", "the_secret")
# We want to filter based on this one
reservation = conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
instance = reservation.instances[0]
# This is just to setup the test
conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
... | = conn.get_all_instance_status()
len(all_status).should.equal(1)
all_status[0].instance_status.status.should.equal("ok")
all_status[0].system_status.status.should.equal("ok")
@mock_ec2_deprecated
def test_describe_instance_status_with_instance_filter_deprecated():
| 64 | 64 | 216 | 19 | 45 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_describe_instance_status_with_instance_filter_deprecated | test_describe_instance_status_with_instance_filter_deprecated | 1,438 | 1,458 | 1,438 | 1,439 | f7d4875f2df2f2d4c3631865166d48c87f65f472 | bigcode/the-stack | train |
d6b50d8ace606908ad9da456 | train | function | @mock_ec2
def test_run_instance_with_block_device_mappings_from_snapshot():
ec2_client = boto3.client("ec2", region_name="us-east-1")
ec2_resource = boto3.resource("ec2", region_name="us-east-1")
volume_details = {
"AvailabilityZone": "1a",
"Size": 30,
}
volume = ec2_resource.create... | @mock_ec2
def test_run_instance_with_block_device_mappings_from_snapshot():
| ec2_client = boto3.client("ec2", region_name="us-east-1")
ec2_resource = boto3.resource("ec2", region_name="us-east-1")
volume_details = {
"AvailabilityZone": "1a",
"Size": 30,
}
volume = ec2_resource.create_volume(**volume_details)
snapshot = volume.create_snapshot()
kwargs... | 2_client.run_instances(**kwargs)
ex.value.response["Error"]["Code"].should.equal("MissingParameter")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
ex.value.response["Error"]["Message"].should.equal(
"The request must contain the parameter size or snapshotId"
)
@mock_... | 83 | 83 | 277 | 17 | 66 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_block_device_mappings_from_snapshot | test_run_instance_with_block_device_mappings_from_snapshot | 1,385 | 1,417 | 1,385 | 1,386 | c2f7508dba4a52907495d3b6f99c0720ec55f5a9 | bigcode/the-stack | train |
5e70fd8b95b6d7e7c2ea34dd | train | function | @mock_ec2
def test_run_instance_with_specified_private_ipv4():
client = boto3.client("ec2", region_name="eu-central-1")
vpc_cidr = ipaddress.ip_network("192.168.42.0/24")
subnet_cidr = ipaddress.ip_network("192.168.42.0/25")
resp = client.create_vpc(
CidrBlock=str(vpc_cidr),
AmazonProv... | @mock_ec2
def test_run_instance_with_specified_private_ipv4():
| client = boto3.client("ec2", region_name="eu-central-1")
vpc_cidr = ipaddress.ip_network("192.168.42.0/24")
subnet_cidr = ipaddress.ip_network("192.168.42.0/25")
resp = client.create_vpc(
CidrBlock=str(vpc_cidr),
AmazonProvidedIpv6CidrBlock=False,
DryRun=False,
Instance... | =1, SubnetId=subnet_id
)
instance = resp["Instances"][0]
instance["SubnetId"].should.equal(subnet_id)
priv_ipv4 = ipaddress.ip_address(str(instance["PrivateIpAddress"]))
subnet_cidr.should.contain(priv_ipv4)
@mock_ec2
def test_run_instance_with_specified_private_ipv4():
| 76 | 76 | 254 | 16 | 60 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_specified_private_ipv4 | test_run_instance_with_specified_private_ipv4 | 1,053 | 1,080 | 1,053 | 1,054 | a6d3853e62acf83c4e5c2cee5942f76ab45afca7 | bigcode/the-stack | train |
6de37debac299eaff49603d5 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_tag_value():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.add_tag("tag1", "value1")
instance1.add_tag("tag2", "value2")
instance2.... | @mock_ec2_deprecated
def test_get_instances_filtering_by_tag_value():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
instance1.add_tag("tag1", "value1")
instance1.add_tag("tag2", "value2")
instance2.add_tag("tag1", "value1")
instance2.add_tag("tag2", "wrong value")... | .length_of(1)
reservations[0].instances[0].id.should.equal(instance1.id)
reservations = conn.get_all_reservations(filters={"tag:tag2": ["value2", "bogus"]})
# get_all_reservations should return both instances with one of the
# acceptable tag values
reservations.should.have.length_of(1)
reservat... | 139 | 139 | 464 | 17 | 122 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_tag_value | test_get_instances_filtering_by_tag_value | 704 | 743 | 704 | 705 | 6ed1bd3e77427fb2e14f73eeec37925354b8dc9a | bigcode/the-stack | train |
c3ddbc5e0361b66ac6e65946 | train | function | @mock_ec2_deprecated
def test_ec2_classic_has_public_ip_address():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
instance = reservation.instances[0]
instance.ip_address.should_not.equal(None)
instance.public_dns_name.should... | @mock_ec2_deprecated
def test_ec2_classic_has_public_ip_address():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, key_name="keypair_name")
instance = reservation.instances[0]
instance.ip_address.should_not.equal(None)
instance.public_dns_name.should.contain(instance.ip_address.replace(".", "-"))
instance.privat... | conn.detach_network_interface("eni-attach-1234abcd")
cm.value.code.should.equal("InvalidAttachmentID.NotFound")
cm.value.status.should.equal(400)
cm.value.request_id.should_not.be.none
@mock_ec2_deprecated
def test_ec2_classic_has_public_ip_address():
| 64 | 64 | 114 | 18 | 45 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_ec2_classic_has_public_ip_address | test_ec2_classic_has_public_ip_address | 1,293 | 1,303 | 1,293 | 1,294 | 4e017013e7c384f17e6cfd353ccc9c6a06facc66 | bigcode/the-stack | train |
dc2774d2b765943a3c13084c | train | function | @mock_ec2
def test_get_instances_filtering_by_private_dns():
client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
conn.create_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, PrivateIpAddress="10.0.0.1"
)
reservations = client.describe_ins... | @mock_ec2
def test_get_instances_filtering_by_private_dns():
| client = boto3.client("ec2", region_name="us-east-1")
conn = boto3.resource("ec2", "us-east-1")
conn.create_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, PrivateIpAddress="10.0.0.1"
)
reservations = client.describe_instances(
Filters=[{"Name": "private-dns-name", "Values... | =1)
reservations = client.describe_instances(
Filters=[{"Name": "owner-id", "Values": ["123456789012"]}]
)["Reservations"]
reservations[0]["Instances"].should.have.length_of(1)
@mock_ec2
def test_get_instances_filtering_by_private_dns():
| 64 | 64 | 144 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_private_dns | test_get_instances_filtering_by_private_dns | 576 | 586 | 576 | 577 | f16d0d6c9a8fccacf716552a53794aa7aa1097dc | bigcode/the-stack | train |
bbf015f30988ab49ebf32afc | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_state():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
conn.terminate_instances([instance1.id])
reservations = conn.get_all_reservations(filter... | @mock_ec2_deprecated
def test_get_instances_filtering_by_state():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
conn.terminate_instances([instance1.id])
reservations = conn.get_all_reservations(filters={"instance-state-name": "running"})
reservations.should.have... | Instances")
)
for instance in instances:
instance_volume = instance["BlockDeviceMappings"][0]["Ebs"]
volumes = ec2.describe_volumes(VolumeIds=[instance_volume["VolumeId"]]).get(
"Volumes"
)
for volume in volumes:
sorted(volume["Tags"], key=lambda i: i["Key... | 93 | 93 | 311 | 16 | 77 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_state | test_get_instances_filtering_by_state | 366 | 399 | 366 | 367 | 9de967404f68eabf7ef3d34db220de0246a271c6 | bigcode/the-stack | train |
765362e4274cde3651e8ead8 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_instance_type():
conn = boto.connect_ec2()
reservation1 = conn.run_instances(EXAMPLE_AMI_ID, instance_type="m1.small")
instance1 = reservation1.instances[0]
reservation2 = conn.run_instances(EXAMPLE_AMI_ID, instance_type="m1.small")
instance2 ... | @mock_ec2_deprecated
def test_get_instances_filtering_by_instance_type():
| conn = boto.connect_ec2()
reservation1 = conn.run_instances(EXAMPLE_AMI_ID, instance_type="m1.small")
instance1 = reservation1.instances[0]
reservation2 = conn.run_instances(EXAMPLE_AMI_ID, instance_type="m1.small")
instance2 = reservation2.instances[0]
reservation3 = conn.run_instances(EXAMPLE_... | .id})
# get_all_reservations should return just instance1
reservations[0].instances.should.have.length_of(1)
reservations[0].instances[0].id.should.equal(instance1.id)
reservations = conn.get_all_reservations(
filters={"instance-id": [instance1.id, instance2.id]}
)
# get_all_reservation... | 140 | 140 | 467 | 17 | 123 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_instance_type | test_get_instances_filtering_by_instance_type | 423 | 463 | 423 | 424 | 8996728d46e527fae52272191ae8469192700b2e | bigcode/the-stack | train |
5b1d5832f5ff1e6460ca446a | train | function | @mock_ec2
def test_get_instances_filtering_by_ni_private_dns():
client = boto3.client("ec2", region_name="us-west-2")
conn = boto3.resource("ec2", "us-west-2")
conn.create_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, PrivateIpAddress="10.0.0.1"
)
reservations = client.describe_... | @mock_ec2
def test_get_instances_filtering_by_ni_private_dns():
| client = boto3.client("ec2", region_name="us-west-2")
conn = boto3.resource("ec2", "us-west-2")
conn.create_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, PrivateIpAddress="10.0.0.1"
)
reservations = client.describe_instances(
Filters=[
{
"Name... | =[{"Name": "private-dns-name", "Values": ["ip-10-0-0-1.ec2.internal"]}]
)["Reservations"]
reservations[0]["Instances"].should.have.length_of(1)
@mock_ec2
def test_get_instances_filtering_by_ni_private_dns():
| 64 | 64 | 158 | 17 | 47 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_ni_private_dns | test_get_instances_filtering_by_ni_private_dns | 589 | 604 | 589 | 590 | 58a62e13bc817bbfed27f85568486ebe51720e74 | bigcode/the-stack | train |
577159ef96b691e0db2608c1 | train | function | @freeze_time("2014-01-01 05:00:00")
@mock_ec2_deprecated
def test_instance_attach_volume():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
vol1 = conn.create_volume(size=36, zone=conn.region.name)
vol1.attach(ins... | @freeze_time("2014-01-01 05:00:00")
@mock_ec2_deprecated
def test_instance_attach_volume():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
vol1 = conn.create_volume(size=36, zone=conn.region.name)
vol1.attach(instance.id, "/dev/sda1")
vol1.update()
vol2 = conn.create_volume(size=65, zone=conn.re... | , instance.instance_id, "/dev/sdf"
)
)
@mock_ec2_deprecated
def test_terminate_empty_instances():
conn = boto.connect_ec2("the_key", "the_secret")
conn.terminate_instances.when.called_with([]).should.throw(EC2ResponseError)
@freeze_time("2014-01-01 05:00:00")
@mock_ec2_deprecated
def test_... | 91 | 91 | 305 | 30 | 61 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_attach_volume | test_instance_attach_volume | 233 | 264 | 233 | 235 | b33282afbba8d624b0ae9978f32f68c46af4f676 | bigcode/the-stack | train |
90d869427d085a95102009f5 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_source_dest_check():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=2)
instance1, instance2 = reservation.instances
conn.modify_instance_attribute(
instance1.id, attribute="sourceDestCheck", value=Fals... | @mock_ec2_deprecated
def test_get_instances_filtering_by_source_dest_check():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=2)
instance1, instance2 = reservation.instances
conn.modify_instance_attribute(
instance1.id, attribute="sourceDestCheck", value=False
)
source_dest_check_false = conn.get_all_reservations(
filt... | -code": ""})
# get_all_reservations should return instance 3
reservations[0].instances.should.have.length_of(1)
reservations[0].instances[0].id.should.equal(instance3.id)
@mock_ec2_deprecated
def test_get_instances_filtering_by_source_dest_check():
| 64 | 64 | 197 | 18 | 46 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_source_dest_check | test_get_instances_filtering_by_source_dest_check | 489 | 509 | 489 | 490 | 00f6550d37ca067854b42db9330619d44c8d8e26 | bigcode/the-stack | train |
156f46692395649b76cc3e0f | train | function | @mock_ec2
def test_create_with_volume_tags():
ec2 = boto3.client("ec2", region_name="us-west-2")
volume_tags = [
{"Key": "MY_TAG1", "Value": "MY_VALUE1"},
{"Key": "MY_TAG2", "Value": "MY_VALUE2"},
]
instances = ec2.run_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=2,
... | @mock_ec2
def test_create_with_volume_tags():
| ec2 = boto3.client("ec2", region_name="us-west-2")
volume_tags = [
{"Key": "MY_TAG1", "Value": "MY_VALUE1"},
{"Key": "MY_TAG2", "Value": "MY_VALUE2"},
]
instances = ec2.run_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=2,
MaxCount=2,
InstanceType="t2.micro",... | "ResourceType": "instance",
"Tags": [{"Key": "MY_TAG3", "Value": "MY_VALUE3"}],
},
],
)
assert "Tags" in instances["Instances"][0]
len(instances["Instances"][0]["Tags"]).should.equal(3)
@mock_ec2
def test_create_with_volume_tags():
| 75 | 75 | 253 | 12 | 63 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_create_with_volume_tags | test_create_with_volume_tags | 337 | 363 | 337 | 338 | 150c24537666260527c86cd5d7ddb4ee2a1948dd | bigcode/the-stack | train |
0351cd20c1e4b8ef7f72a464 | train | function | @mock_ec2
def test_filter_wildcard_in_specified_tag_only():
ec2_client = boto3.client("ec2", region_name="us-west-1")
tags_name = [{"Key": "Name", "Value": "alice in wonderland"}]
ec2_client.run_instances(
ImageId=EXAMPLE_AMI_ID,
MaxCount=1,
MinCount=1,
TagSpecifications=[{"... | @mock_ec2
def test_filter_wildcard_in_specified_tag_only():
| ec2_client = boto3.client("ec2", region_name="us-west-1")
tags_name = [{"Key": "Name", "Value": "alice in wonderland"}]
ec2_client.run_instances(
ImageId=EXAMPLE_AMI_ID,
MaxCount=1,
MinCount=1,
TagSpecifications=[{"ResourceType": "instance", "Tags": tags_name}],
)
t... | "us-east-1")
with pytest.warns(
PendingDeprecationWarning,
match=r"Could not find AMI with image-id:invalid-ami.+",
):
ec2.create_instances(ImageId="invalid-ami", MinCount=1, MaxCount=1)
@mock_ec2
def test_filter_wildcard_in_specified_tag_only():
| 78 | 78 | 262 | 17 | 61 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_filter_wildcard_in_specified_tag_only | test_filter_wildcard_in_specified_tag_only | 1,729 | 1,755 | 1,729 | 1,730 | a8abba22b15c63a101176d13718debeb7c5a5ed9 | bigcode/the-stack | train |
273c781f5c79d47b5bfe1ece | train | function | @mock_ec2
def test_describe_instance_credit_specifications():
conn = boto3.client("ec2", region_name="us-west-1")
# We want to filter based on this one
reservation = conn.run_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
result = conn.describe_instance_credit_specifications(
Instanc... | @mock_ec2
def test_describe_instance_credit_specifications():
| conn = boto3.client("ec2", region_name="us-west-1")
# We want to filter based on this one
reservation = conn.run_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
result = conn.describe_instance_credit_specifications(
InstanceIds=[reservation["Instances"][0]["InstanceId"]]
)
ass... | conn.get_all_instance_status(instance_ids=[instance.id, "i-1234abcd"])
cm.value.code.should.equal("InvalidInstanceID.NotFound")
cm.value.status.should.equal(400)
cm.value.request_id.should_not.be.none
@mock_ec2
def test_describe_instance_credit_specifications():
| 64 | 64 | 122 | 14 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_describe_instance_credit_specifications | test_describe_instance_credit_specifications | 1,461 | 1,473 | 1,461 | 1,462 | 4898315b47348ea2a1f81259e7903756e83a5c7d | bigcode/the-stack | train |
ddff14294a4611c0df380acf | train | function | @mock_ec2
def test_describe_instance_attribute():
client = boto3.client("ec2", region_name="us-east-1")
security_group_id = client.create_security_group(
GroupName="test security group", Description="this is a test security group"
)["GroupId"]
client.run_instances(
ImageId=EXAMPLE_AMI_ID... | @mock_ec2
def test_describe_instance_attribute():
| client = boto3.client("ec2", region_name="us-east-1")
security_group_id = client.create_security_group(
GroupName="test security group", Description="this is a test security group"
)["GroupId"]
client.run_instances(
ImageId=EXAMPLE_AMI_ID,
MinCount=1,
MaxCount=1,
... | optimized.should.be(False)
@mock_ec2
def test_run_multiple_instances_in_same_command():
instance_count = 4
client = boto3.client("ec2", region_name="us-east-1")
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=instance_count, MaxCount=instance_count
)
reservations = client.describe_i... | 141 | 141 | 473 | 12 | 129 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_describe_instance_attribute | test_describe_instance_attribute | 1,652 | 1,714 | 1,652 | 1,653 | 12548a04487a33b41807136a4bcc23a55a4ab890 | bigcode/the-stack | train |
19a0b81da53f364e98a0389e | train | function | @mock_ec2
def test_get_instances_filtering_by_instance_group_name():
client = boto3.client("ec2", region_name="us-east-1")
client.create_security_group(Description="test", GroupName="test_sg")
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, SecurityGroups=["test_sg"]
)
... | @mock_ec2
def test_get_instances_filtering_by_instance_group_name():
| client = boto3.client("ec2", region_name="us-east-1")
client.create_security_group(Description="test", GroupName="test_sg")
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, SecurityGroups=["test_sg"]
)
reservations = client.describe_instances(
Filters=[{"Name": "... | -dns-name",
"Values": ["ip-10-0-0-1.us-west-2.compute.internal"],
}
]
)["Reservations"]
reservations[0]["Instances"].should.have.length_of(1)
@mock_ec2
def test_get_instances_filtering_by_instance_group_name():
| 64 | 64 | 131 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_instance_group_name | test_get_instances_filtering_by_instance_group_name | 607 | 617 | 607 | 608 | d4d15487b43db0713924344f056632b853c5e7c7 | bigcode/the-stack | train |
32086fc94e815d16af9f85f1 | train | function | @mock_ec2_deprecated
def test_instance_start_and_stop():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=2)
instances = reservation.instances
instances.should.have.length_of(2)
instance_ids = [instance.id for instance in instances]
wi... | @mock_ec2_deprecated
def test_instance_start_and_stop():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=2)
instances = reservation.instances
instances.should.have.length_of(2)
instance_ids = [instance.id for instance in instances]
with pytest.raises(EC2ResponseError) as ex:
stopped... | # acceptable tag values
reservations.should.have.length_of(1)
reservations[0].instances.should.have.length_of(3)
reservations[0].instances[0].id.should.equal(instance1.id)
reservations[0].instances[1].id.should.equal(instance2.id)
reservations[0].instances[2].id.should.equal(instance3.id)
@mock_... | 90 | 90 | 301 | 14 | 76 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_start_and_stop | test_instance_start_and_stop | 778 | 809 | 778 | 779 | 892869e0c449a6152b26ce9ea8be21902739105c | bigcode/the-stack | train |
57ce4e3284dfbfdf22e8c497 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_instance_id():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
reservations = conn.get_all_reservations(filters={"instance-id": instance1.id})
# g... | @mock_ec2_deprecated
def test_get_instances_filtering_by_instance_id():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=3)
instance1, instance2, instance3 = reservation.instances
reservations = conn.get_all_reservations(filters={"instance-id": instance1.id})
# get_all_reservations should return just instance1
reservations[0].ins... | _reservations()
reservations[0].instances.should.have.length_of(3)
conn.get_all_reservations.when.called_with(
filters={"not-implemented-filter": "foobar"}
).should.throw(NotImplementedError)
@mock_ec2_deprecated
def test_get_instances_filtering_by_instance_id():
| 64 | 64 | 194 | 17 | 47 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_instance_id | test_get_instances_filtering_by_instance_id | 402 | 420 | 402 | 403 | f5c0f0fc117628ab2ce16b08d2b469266fe3a5a1 | bigcode/the-stack | train |
88f5e22f7fd352d3bb389b37 | train | function | @mock_ec2_deprecated
def test_run_instance_with_security_group_id():
conn = boto.connect_ec2("the_key", "the_secret")
group = conn.create_security_group("group1", "some description")
reservation = conn.run_instances(EXAMPLE_AMI_ID, security_group_ids=[group.id])
instance = reservation.instances[0]
... | @mock_ec2_deprecated
def test_run_instance_with_security_group_id():
| conn = boto.connect_ec2("the_key", "the_secret")
group = conn.create_security_group("group1", "some description")
reservation = conn.run_instances(EXAMPLE_AMI_ID, security_group_ids=[group.id])
instance = reservation.instances[0]
instance.groups[0].id.should.equal(group.id)
instance.groups[0].n... | conn.run_instances(EXAMPLE_AMI_ID, security_groups=["group1"])
instance = reservation.instances[0]
instance.groups[0].id.should.equal(group.id)
instance.groups[0].name.should.equal("group1")
@mock_ec2_deprecated
def test_run_instance_with_security_group_id():
| 64 | 64 | 98 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_security_group_id | test_run_instance_with_security_group_id | 980 | 988 | 980 | 981 | 7f8b2af8e1e1b3d0da38cd540ab7e3ca34f188c9 | bigcode/the-stack | train |
bc9e484996b172bab4dfb108 | train | class | class DisableEnterpriseProjectResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
... | class DisableEnterpriseProjectResponse(SdkResponse):
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class DisableEnterpriseProjectResponse(SdkResponse):
| 39 | 128 | 427 | 10 | 28 | wuchen-huawei/huaweicloud-sdk-python-v3 | huaweicloud-sdk-eps/huaweicloudsdkeps/v1/model/disable_enterprise_project_response.py | Python | DisableEnterpriseProjectResponse | DisableEnterpriseProjectResponse | 12 | 81 | 12 | 14 | e34efff33c5c71f317759e39b100a2616271b588 | bigcode/the-stack | train |
86f0e286eb0bef26e900cf13 | train | function | def ensure_audio_doesnt_clip(list_of_arrays):
"""
Takes a list of arrays and scales them by the same factor such that
none clip.
Parameters
----------
list_of_arrays : list
A list of array_like objects
Returns
-------
new_list_of_arrays : list
A list of scaled ar... | def ensure_audio_doesnt_clip(list_of_arrays):
| """
Takes a list of arrays and scales them by the same factor such that
none clip.
Parameters
----------
list_of_arrays : list
A list of array_like objects
Returns
-------
new_list_of_arrays : list
A list of scaled array_like objects.
"""
max_peak = 1
... | An ISTFT processor.
"""
stft = transforms.STFT(window, num_points, num_points // 2)
istft = transforms.ISTFT(window, num_points, num_points // 2)
return stft, istft
def ensure_audio_doesnt_clip(list_of_arrays):
| 64 | 64 | 197 | 11 | 52 | IoSR-Surrey/source-separation-anchors | ssanchors/utilities.py | Python | ensure_audio_doesnt_clip | ensure_audio_doesnt_clip | 86 | 123 | 86 | 86 | 519f914f4f304e93996eefe7e0cb38f321f859cc | bigcode/the-stack | train |
0b16ce68f4b9858b80f1758a | train | function | def stft_istft(num_points=2048, window='hann'):
"""
Returns an STFT and an ISTFT Processor object, both configured with the
same window and transform length. These objects are to be used as follows:
>>> stft, istft = stft_istft()
>>> x = untwist.data.audio.Wave.tone() # Or some Wave
... | def stft_istft(num_points=2048, window='hann'):
| """
Returns an STFT and an ISTFT Processor object, both configured with the
same window and transform length. These objects are to be used as follows:
>>> stft, istft = stft_istft()
>>> x = untwist.data.audio.Wave.tone() # Or some Wave
>>> y = stft.process(x)
>>> x = istft.... | data.audio.Wave):
others = data.audio.Wave(others, sample_rate)
accompaniment = others
if not isinstance(target, data.audio.Wave):
target = data.audio.Wave(target, sample_rate)
return target, accompaniment
def stft_istft(num_points=2048, window='hann'):
| 68 | 68 | 229 | 16 | 51 | IoSR-Surrey/source-separation-anchors | ssanchors/utilities.py | Python | stft_istft | stft_istft | 53 | 83 | 53 | 53 | 791816976bfa2d90d3feb35a696d5a66273395fa | bigcode/the-stack | train |
4d4cf9498d45763b96eb70d6 | train | function | def target_accompaniment(target, others, sample_rate=None):
"""
Given a target source and list of 'other' sources, this function returns
the target and accompaniment as untwist.data.audio.Wave objects. The
accompaniment is defined as the sum of the other sources.
Parameters
----------
tar... | def target_accompaniment(target, others, sample_rate=None):
| """
Given a target source and list of 'other' sources, this function returns
the target and accompaniment as untwist.data.audio.Wave objects. The
accompaniment is defined as the sum of the other sources.
Parameters
----------
target : np.ndarray or Wave, shape=(num_samples, num_channels)
... | from __future__ import division
import numpy as np
from untwist import data
from untwist import transforms
def target_accompaniment(target, others, sample_rate=None):
| 37 | 87 | 292 | 13 | 23 | IoSR-Surrey/source-separation-anchors | ssanchors/utilities.py | Python | target_accompaniment | target_accompaniment | 7 | 50 | 7 | 7 | c7968ff60e16fec6aac02acc6462f80a3cb59f7a | bigcode/the-stack | train |
32bba441b284d1591b503c8d | train | class | class FakeClass(python_utils.OBJECT):
"""This is a fake docstring for valid syntax purposes"""
def __init__(self, fake_arg):
self.fake_arg = fake_arg
def fake_method(self, name):
"""This doesn't do anything.
Args:
name: str. Means nothing.
Yields:
... | class FakeClass(python_utils.OBJECT):
| """This is a fake docstring for valid syntax purposes"""
def __init__(self, fake_arg):
self.fake_arg = fake_arg
def fake_method(self, name):
"""This doesn't do anything.
Args:
name: str. Means nothing.
Yields:
tuple(str, str). The argument passed i... | .
"""Python file with invalid syntax, used by scripts/linters/
python_linter_test.py. This file does not have period at the end of docstring.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import python_utils
class FakeClass(python_utils.OBJECT):
| 64 | 64 | 95 | 9 | 54 | ReshuKumari/oppia | scripts/linters/test_files/invalid_docstring.py | Python | FakeClass | FakeClass | 27 | 42 | 27 | 27 | ee8218e38e5f969d2ca6e98b54150847d834423a | bigcode/the-stack | train |
6484bb978e5bc5617d169687 | train | class | class HydroShare:
"""
A HydroShare object for querying HydroShare's REST API. Provide a username and password at initialization or call
the sign_in() method to prompt for the username and password.
If using OAuth2 is desired, provide the client_id and token to use. If on CUAHSI JupyterHub or another ... | class HydroShare:
| """
A HydroShare object for querying HydroShare's REST API. Provide a username and password at initialization or call
the sign_in() method to prompt for the username and password.
If using OAuth2 is desired, provide the client_id and token to use. If on CUAHSI JupyterHub or another JupyterHub
env... | message {}".format(url, response.status_code, response.content)
)
return response
def put(self, path, status_code, data=None, **kwargs):
url = encode_resource_url(self._build_url(path))
response = self._session.put(url, data=data, **kwargs)
if response.status_code != st... | 256 | 256 | 1,947 | 4 | 251 | sblack-usu/hs_rdf | hsclient/hydroshare.py | Python | HydroShare | HydroShare | 808 | 1,007 | 808 | 808 | 91025018f8da437462f3569f2823cedf1d18fa8a | bigcode/the-stack | train |
51d8fa06f6325843e455aaff | train | class | class Aggregation:
"""Represents an Aggregation in HydroShare"""
def __init__(self, map_path, hs_session, checksums=None):
self._map_path = map_path
self._hs_session = hs_session
self._retrieved_map = None
self._retrieved_metadata = None
self._parsed_files = None
... | class Aggregation:
| """Represents an Aggregation in HydroShare"""
def __init__(self, map_path, hs_session, checksums=None):
self._map_path = map_path
self._hs_session = hs_session
self._retrieved_map = None
self._retrieved_metadata = None
self._parsed_files = None
self._parsed_aggre... | is in"""
return dirname(self)
@property
def checksum(self):
"""The md5 checksum of the file"""
return self._checksum
@property
def url(self):
"""The url to the file on HydroShare"""
return self._file_url
def refresh(f):
"""
Decorator for refreshing me... | 256 | 256 | 2,247 | 4 | 251 | sblack-usu/hs_rdf | hsclient/hydroshare.py | Python | Aggregation | Aggregation | 97 | 338 | 97 | 97 | 0ec2559e9456e0d0d540cc03daa4251a832953a0 | bigcode/the-stack | train |
21d5855fac693baef384a8a6 | train | function | def refresh(f):
"""
Decorator for refreshing metadata from HydroShare after the decorated method is called.
The docstring of a decorated method is updated to include
:param refresh: Defaults True, False to not refresh metadata from HydroShare
"""
@wraps(f)
def wrapper(*args, **kwargs):
... | def refresh(f):
| """
Decorator for refreshing metadata from HydroShare after the decorated method is called.
The docstring of a decorated method is updated to include
:param refresh: Defaults True, False to not refresh metadata from HydroShare
"""
@wraps(f)
def wrapper(*args, **kwargs):
self = args[... | is in"""
return dirname(self)
@property
def checksum(self):
"""The md5 checksum of the file"""
return self._checksum
@property
def url(self):
"""The url to the file on HydroShare"""
return self._file_url
def refresh(f):
| 64 | 64 | 192 | 4 | 59 | sblack-usu/hs_rdf | hsclient/hydroshare.py | Python | refresh | refresh | 72 | 94 | 72 | 72 | 18be1096fa7e4888977181259e523afe882e189f | bigcode/the-stack | train |
f99c425d584bf8782f1f05c4 | train | class | class File(str):
"""
A File path string representing the path to a file within a resource.
:param value: the string path value
:param file_url: the fully qualified url to the file on hydroshare.org
:param checksum: the md5 checksum of the file
"""
def __new__(cls, value, file_url, checksum)... | class File(str):
| """
A File path string representing the path to a file within a resource.
:param value: the string path value
:param file_url: the fully qualified url to the file on hydroshare.org
:param checksum: the md5 checksum of the file
"""
def __new__(cls, value, file_url, checksum):
return ... | df, rdf_string
from hsmodels.schemas.base_models import BaseMetadata
from hsmodels.schemas.enums import AggregationType
from hsmodels.schemas.fields import BoxCoverage, PointCoverage
from requests_oauthlib import OAuth2Session
from hsclient.json_models import ResourcePreview, User
from hsclient.utils import attribute_... | 82 | 82 | 274 | 4 | 77 | sblack-usu/hs_rdf | hsclient/hydroshare.py | Python | File | File | 26 | 69 | 26 | 26 | 9603b8f12e5d3d5ce2a5d968901edf64e312f5f9 | bigcode/the-stack | train |
a5d17eae43541abfc63e227f | train | class | class HydroShareSession:
def __init__(self, username, password, host, protocol, port, client_id=None, token=None):
self._host = host
self._protocol = protocol
self._port = port
self._client_id = client_id
self._token = token
if client_id or token:
if not t... | class HydroShareSession:
| def __init__(self, username, password, host, protocol, port, client_id=None, token=None):
self._host = host
self._protocol = protocol
self._port = port
self._client_id = client_id
self._token = token
if client_id or token:
if not token or not client_id:
... | aggregation._hs_session.post(path, status_code=200)
aggregation.refresh()
@refresh
def aggregation_delete(self, aggregation: Aggregation) -> None:
"""
Deletes an aggregation from HydroShare. This deletes the files and metadata in the aggregation.
:param aggregation: The... | 256 | 256 | 989 | 5 | 251 | sblack-usu/hs_rdf | hsclient/hydroshare.py | Python | HydroShareSession | HydroShareSession | 692 | 805 | 692 | 692 | 07f1fdd9b428065a99a8babab20e3b3656d95a31 | bigcode/the-stack | train |
2e76a7b5745c72aacc973e3a | train | class | class Resource(Aggregation):
"""Represents a Resource in HydroShare"""
@property
def _hsapi_path(self):
path = urlparse(self.metadata.identifier).path
return '/hsapi' + path
def _upload(self, file, destination_path):
path = urljoin(self._hsapi_path, "files", destination_path.st... | class Resource(Aggregation):
| """Represents a Resource in HydroShare"""
@property
def _hsapi_path(self):
path = urlparse(self.metadata.identifier).path
return '/hsapi' + path
def _upload(self, file, destination_path):
path = urljoin(self._hsapi_path, "files", destination_path.strip("/"))
self._hs_se... | _series(self, series_id: str, agg_path: str = None) -> Dict[int, pandas.Series]:
"""
Creates a pandas Series object out of an aggregation of type TimeSeries.
:param series_id: The series_id of the timeseries result to be converted to a Series object.
:param agg_path: Not required. Inclu... | 256 | 256 | 3,188 | 6 | 250 | sblack-usu/hs_rdf | hsclient/hydroshare.py | Python | Resource | Resource | 341 | 689 | 341 | 341 | 0240ecaf29784554858ede18072b81790a858f14 | bigcode/the-stack | train |
32d3459e2a570699b23fc34f | train | function | def tag_uninteresting_windows_codebase_resources(project):
"""
Tags known uninteresting files as uninteresting
"""
uninteresting_files = (
"DefaultUser_Delta",
"Sam_Delta",
"Security_Delta",
"Software_Delta",
"System_Delta",
"NTUSER.DAT",
"desktop.... | def tag_uninteresting_windows_codebase_resources(project):
| """
Tags known uninteresting files as uninteresting
"""
uninteresting_files = (
"DefaultUser_Delta",
"Sam_Delta",
"Security_Delta",
"Software_Delta",
"System_Delta",
"NTUSER.DAT",
"desktop.ini",
"BBI",
"BCD-Template",
"DEFAU... | /scancode.io for support and download.
import re
from django.db.models import Q
from packagedcode import win_reg
from scanpipe import pipes
def package_getter(root_dir, **kwargs):
"""
Returns installed package objects.
"""
packages = win_reg.get_installed_packages(root_dir)
for package in pack... | 87 | 87 | 292 | 10 | 76 | sa-y-an/scancode.io | scanpipe/pipes/windows.py | Python | tag_uninteresting_windows_codebase_resources | tag_uninteresting_windows_codebase_resources | 41 | 93 | 41 | 41 | 539d8b776154dc88849119cc2410c966b1a5c803 | bigcode/the-stack | train |
6f5cc0fd069c9695de64076e | train | function | def tag_installed_package_files(project, root_dir_pattern, package, q_objects=None):
"""
For all CodebaseResources from `project` whose `rootfs_path` starts with
`root_dir_pattern`, add `package` to the discovered_packages of each
CodebaseResource and set the status.
"""
qs = project.codebaseres... | def tag_installed_package_files(project, root_dir_pattern, package, q_objects=None):
| """
For all CodebaseResources from `project` whose `rootfs_path` starts with
`root_dir_pattern`, add `package` to the discovered_packages of each
CodebaseResource and set the status.
"""
qs = project.codebaseresources.no_status()
lookup = Q(rootfs_path__startswith=root_dir_pattern)
# If... | |= Q(rootfs_path__iendswith=file_name)
for file_extension in uninteresting_file_extensions:
lookups |= Q(extension__icontains=file_extension)
qs = project.codebaseresources.no_status()
qs.filter(lookups).update(status="ignored-not-interesting")
def tag_installed_package_files(project, root_dir_pat... | 78 | 78 | 263 | 18 | 60 | sa-y-an/scancode.io | scanpipe/pipes/windows.py | Python | tag_installed_package_files | tag_installed_package_files | 96 | 120 | 96 | 96 | 8af6e372675070cd61aa8846201a05f8fb6ba722 | bigcode/the-stack | train |
8dea8142cb31de87475a07f7 | train | function | def tag_known_software(project):
"""
Finds Windows software in `project` by checking CodebaseResources
to see if their rootfs_path is under a known software root directory. If
there are CodebaseResources that are under a known software root directory,
a DiscoveredPackage is created for that software... | def tag_known_software(project):
| """
Finds Windows software in `project` by checking CodebaseResources
to see if their rootfs_path is under a known software root directory. If
there are CodebaseResources that are under a known software root directory,
a DiscoveredPackage is created for that software package and all files under
... | .0",
copyright="Copyright (c) Oracle and/or its affiliates",
homepage_url="http://openjdk.java.net/",
)
tag_installed_package_files(
project=project,
root_dir_pattern=openjdk_path,
package=openjdk_package,
)
def tag_known_software(proje... | 64 | 64 | 155 | 7 | 57 | sa-y-an/scancode.io | scanpipe/pipes/windows.py | Python | tag_known_software | tag_known_software | 211 | 227 | 211 | 211 | 11fc4701b6c739c5595f2af1fe395670448a1fb7 | bigcode/the-stack | train |
b33c6e68043df841f207224c | train | function | def _tag_openjdk_software(project):
qs = project.codebaseresources.no_status()
openjdk_root_pattern = (
r"^(?P<root_path>/(Files/)?(open)?jdk(-(?P<version>(\d*)(\.\d+)*))*)/.*$"
)
openjdk_root_pattern_compiled = re.compile(openjdk_root_pattern)
openjdk_resources = qs.filter(
rootfs_p... | def _tag_openjdk_software(project):
| qs = project.codebaseresources.no_status()
openjdk_root_pattern = (
r"^(?P<root_path>/(Files/)?(open)?jdk(-(?P<version>(\d*)(\.\d+)*))*)/.*$"
)
openjdk_root_pattern_compiled = re.compile(openjdk_root_pattern)
openjdk_resources = qs.filter(
rootfs_path__regex=r"^(/(Files/)?(open)?jdk(... | ]
for python_path, python_version in python_versions_by_path.items():
python_package = win_reg.InstalledWindowsProgram(
name="Python",
version=python_version,
license_expression="python",
copyright="Copyright (c) Python Software Foundation",
homep... | 110 | 110 | 367 | 9 | 101 | sa-y-an/scancode.io | scanpipe/pipes/windows.py | Python | _tag_openjdk_software | _tag_openjdk_software | 168 | 208 | 168 | 168 | 92e5786f672c950de73474ec1a84d4906352e66d | bigcode/the-stack | train |
bfd26d5d017045bdeeeef6a3 | train | function | def package_getter(root_dir, **kwargs):
"""
Returns installed package objects.
"""
packages = win_reg.get_installed_packages(root_dir)
for package in packages:
yield package.purl, package
| def package_getter(root_dir, **kwargs):
| """
Returns installed package objects.
"""
packages = win_reg.get_installed_packages(root_dir)
for package in packages:
yield package.purl, package
| a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/nexB/scancode.io for support and download.
import re
from django.db.models import Q
from packagedcode import win_reg
from scanpipe import pipes
def package_getter(root_dir, **kwargs):
| 64 | 64 | 46 | 10 | 53 | sa-y-an/scancode.io | scanpipe/pipes/windows.py | Python | package_getter | package_getter | 32 | 38 | 32 | 32 | 0dde2e79081f4c989c3620072c66107ba941fb81 | bigcode/the-stack | train |
4de1b14471b0e56599d482e5 | train | function | def tag_program_files(project):
"""
Reports all subdirectories of Program Files and Program Files (x86) as Packages.
If a Package is detected in this manner, then we will attempt to determine
the version from the path. If a version cannot be determined, a version of
`nv` will be set for the Package... | def tag_program_files(project):
| """
Reports all subdirectories of Program Files and Program Files (x86) as Packages.
If a Package is detected in this manner, then we will attempt to determine
the version from the path. If a version cannot be determined, a version of
`nv` will be set for the Package.
"""
qs = project.codeb... | and all files under
that software package's root directory are considered installed files for
that package.
Currently, we are only checking for Python and openjdk in Windows Docker
image layers.
If a version number cannot be determined for an installed software Package,
then a version number ... | 112 | 112 | 376 | 6 | 106 | sa-y-an/scancode.io | scanpipe/pipes/windows.py | Python | tag_program_files | tag_program_files | 236 | 278 | 236 | 236 | 2cacadbf081a16105dc72f5a2351570923309ef7 | bigcode/the-stack | train |
95c348122de9609f3f00242e | train | function | def _tag_python_software(project):
qs = project.codebaseresources.no_status()
python_root_pattern = r"(?P<root_path>^/(Files/)?Python(?P<version>\d+)?)/.*$"
python_root_pattern_compiled = re.compile(python_root_pattern)
python_resources = qs.filter(rootfs_path__regex=r"(^/(Files/)?Python(\d+)?)/.*$")
... | def _tag_python_software(project):
| qs = project.codebaseresources.no_status()
python_root_pattern = r"(?P<root_path>^/(Files/)?Python(?P<version>\d+)?)/.*$"
python_root_pattern_compiled = re.compile(python_root_pattern)
python_resources = qs.filter(rootfs_path__regex=r"(^/(Files/)?Python(\d+)?)/.*$")
python_versions_by_path = {}
... | lookup)
# If we find files whose names start with `root_dir_pattern`, we consider
# these files to be part of the Package `package` and tag these files as such.
if installed_package_files:
created_package = pipes.update_or_create_package(project, package.to_dict())
for installed_package_file... | 111 | 111 | 372 | 8 | 103 | sa-y-an/scancode.io | scanpipe/pipes/windows.py | Python | _tag_python_software | _tag_python_software | 123 | 165 | 123 | 123 | 1113eb70e7147bc027167f139568ec08fac813e8 | bigcode/the-stack | train |
51bc4b1fd71cb61893bc04cb | train | function | @visit.register(alt.FilterTransform)
def visit_filter(transform: alt.FilterTransform, df: pd.DataFrame) -> pd.DataFrame:
mask = eval_predicate(transform.filter, df).astype(bool)
return df[mask].reset_index(drop=True)
| @visit.register(alt.FilterTransform)
def visit_filter(transform: alt.FilterTransform, df: pd.DataFrame) -> pd.DataFrame:
| mask = eval_predicate(transform.filter, df).astype(bool)
return df[mask].reset_index(drop=True)
| import Any
import altair as alt
import numpy as np
import pandas as pd
from .visitor import visit
from ..vegaexpr import eval_vegajs
@visit.register(alt.FilterTransform)
def visit_filter(transform: alt.FilterTransform, df: pd.DataFrame) -> pd.DataFrame:
| 64 | 64 | 53 | 28 | 35 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | visit_filter | visit_filter | 11 | 14 | 11 | 12 | d6f990625efa4ff5592bad96672f1b2ee0f90573 | bigcode/the-stack | train |
13b9c324510febc39dffa980 | train | function | @eval_predicate.register(alt.FieldLTPredicate)
def eval_field_lt(predicate: alt.FieldLTPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) < eval_value(predicate.lt)
| @eval_predicate.register(alt.FieldLTPredicate)
def eval_field_lt(predicate: alt.FieldLTPredicate, df: pd.DataFrame) -> pd.Series:
| return get_column(df, predicate) < eval_value(predicate.lt)
| -> pd.Series:
options = [eval_value(val) for val in predicate.oneOf]
return get_column(df, predicate).isin(options)
@eval_predicate.register(alt.FieldLTPredicate)
def eval_field_lt(predicate: alt.FieldLTPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 48 | 34 | 30 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_field_lt | eval_field_lt | 62 | 64 | 62 | 63 | e301fea0407b7f66fa527f632a94020ee482c0bc | bigcode/the-stack | train |
cf93ee3a3d48803b8bbed798 | train | function | @eval_predicate.register(alt.FieldEqualPredicate)
def eval_field_equal(predicate: alt.FieldEqualPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) == eval_value(predicate.equal)
| @eval_predicate.register(alt.FieldEqualPredicate)
def eval_field_equal(predicate: alt.FieldEqualPredicate, df: pd.DataFrame) -> pd.Series:
| return get_column(df, predicate) == eval_value(predicate.equal)
| : str, df: pd.DataFrame) -> pd.Series:
return df.apply(lambda datum: eval_vegajs(predicate, datum), axis=1)
@eval_predicate.register(alt.FieldEqualPredicate)
def eval_field_equal(predicate: alt.FieldEqualPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 46 | 32 | 32 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_field_equal | eval_field_equal | 40 | 42 | 40 | 41 | 728c236c95e4315d7c045c606e76c81e616139e6 | bigcode/the-stack | train |
18c03bd760c7b73ff0a86ac1 | train | function | @eval_predicate.register(alt.FieldGTEPredicate)
def eval_field_gte(predicate: alt.FieldGTEPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) >= eval_value(predicate.gte)
| @eval_predicate.register(alt.FieldGTEPredicate)
def eval_field_gte(predicate: alt.FieldGTEPredicate, df: pd.DataFrame) -> pd.Series:
| return get_column(df, predicate) >= eval_value(predicate.gte)
| .FieldGTPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) > eval_value(predicate.gt)
@eval_predicate.register(alt.FieldGTEPredicate)
def eval_field_gte(predicate: alt.FieldGTEPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 50 | 35 | 29 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_field_gte | eval_field_gte | 77 | 79 | 77 | 78 | 605667180471161dcc708ae435d9fabc0e67ccca | bigcode/the-stack | train |
a3e5d9bfa165bf6bb829c01e | train | function | @eval_predicate.register(alt.LogicalAndPredicate)
def eval_logical_and(predicate: alt.LogicalAndPredicate, df: pd.DataFrame) -> pd.Series:
return np.logical_and.reduce([eval_predicate(p, df) for p in predicate["and"]])
| @eval_predicate.register(alt.LogicalAndPredicate)
def eval_logical_and(predicate: alt.LogicalAndPredicate, df: pd.DataFrame) -> pd.Series:
| return np.logical_and.reduce([eval_predicate(p, df) for p in predicate["and"]])
| : alt.LogicalNotPredicate, df: pd.DataFrame) -> pd.Series:
return ~eval_predicate(predicate["not"], df)
@eval_predicate.register(alt.LogicalAndPredicate)
def eval_logical_and(predicate: alt.LogicalAndPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 57 | 35 | 29 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_logical_and | eval_logical_and | 87 | 89 | 87 | 88 | 9e20adaf6cc86cfd0a9a557e0dfa27fd91b6105d | bigcode/the-stack | train |
3660a70699ea5ba319ff680d | train | function | @eval_value.register(alt.DateTime)
def eval_datetime(value: alt.DateTime) -> pd.Series:
# TODO: implement datetime conversion & comparison
raise NotImplementedError("Evaluating alt.DateTime object")
| @eval_value.register(alt.DateTime)
def eval_datetime(value: alt.DateTime) -> pd.Series:
# TODO: implement datetime conversion & comparison
| raise NotImplementedError("Evaluating alt.DateTime object")
| (p, df) for p in predicate["or"]])
@singledispatch
def eval_value(value: Any) -> Any:
return value
@eval_value.register(alt.DateTime)
def eval_datetime(value: alt.DateTime) -> pd.Series:
# TODO: implement datetime conversion & comparison
| 64 | 64 | 45 | 32 | 31 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_datetime | eval_datetime | 102 | 105 | 102 | 104 | 355d9315d27073f82e10e6611e8ed13d7b783c95 | bigcode/the-stack | train |
5e07cecafd2d9337cefde1ce | train | function | @eval_predicate.register(str)
def eval_string(predicate: str, df: pd.DataFrame) -> pd.Series:
return df.apply(lambda datum: eval_vegajs(predicate, datum), axis=1)
| @eval_predicate.register(str)
def eval_string(predicate: str, df: pd.DataFrame) -> pd.Series:
| return df.apply(lambda datum: eval_vegajs(predicate, datum), axis=1)
|
def eval_dict(predicate: dict, df: pd.DataFrame) -> pd.Series:
transform = alt.FilterTrasform({"filter": predicate})
return eval_predicate(transform.filter, df)
@eval_predicate.register(str)
def eval_string(predicate: str, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 43 | 24 | 40 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_string | eval_string | 35 | 37 | 35 | 36 | 8c3d881cb620f9d12ae563088a7cc35fbe535f79 | bigcode/the-stack | train |
ff2ae1e3b8d1b057d075f00c | train | function | @singledispatch
def eval_predicate(predicate: Any, df: pd.DataFrame) -> pd.Series:
raise NotImplementedError(f"Evaluating predicate of type {type(predicate)}")
| @singledispatch
def eval_predicate(predicate: Any, df: pd.DataFrame) -> pd.Series:
| raise NotImplementedError(f"Evaluating predicate of type {type(predicate)}")
| the predicate."""
if predicate.timeUnit is not alt.Undefined:
raise NotImplementedError("timeUnit Transform in Predicates")
return df[eval_value(predicate["field"])]
@singledispatch
def eval_predicate(predicate: Any, df: pd.DataFrame) -> pd.Series:
| 63 | 64 | 41 | 24 | 39 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_predicate | eval_predicate | 24 | 26 | 24 | 25 | cffa5a7785275a9831cc8133a2d025cc1cc9ae10 | bigcode/the-stack | train |
f1527274adbfc6c33f960473 | train | function | @eval_predicate.register(alt.LogicalOrPredicate)
def eval_logical_or(predicate: alt.LogicalOrPredicate, df: pd.DataFrame) -> pd.Series:
return np.logical_or.reduce([eval_predicate(p, df) for p in predicate["or"]])
| @eval_predicate.register(alt.LogicalOrPredicate)
def eval_logical_or(predicate: alt.LogicalOrPredicate, df: pd.DataFrame) -> pd.Series:
| return np.logical_or.reduce([eval_predicate(p, df) for p in predicate["or"]])
| .DataFrame) -> pd.Series:
return np.logical_and.reduce([eval_predicate(p, df) for p in predicate["and"]])
@eval_predicate.register(alt.LogicalOrPredicate)
def eval_logical_or(predicate: alt.LogicalOrPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 57 | 35 | 29 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_logical_or | eval_logical_or | 92 | 94 | 92 | 93 | 1315728572d4176f30f6f17a7998885e95d78e11 | bigcode/the-stack | train |
6a0f93459b1e5adb43316751 | train | function | @eval_predicate.register(alt.FieldGTPredicate)
def eval_field_gt(predicate: alt.FieldGTPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) > eval_value(predicate.gt)
| @eval_predicate.register(alt.FieldGTPredicate)
def eval_field_gt(predicate: alt.FieldGTPredicate, df: pd.DataFrame) -> pd.Series:
| return get_column(df, predicate) > eval_value(predicate.gt)
| alt.FieldLTEPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) <= eval_value(predicate.lte)
@eval_predicate.register(alt.FieldGTPredicate)
def eval_field_gt(predicate: alt.FieldGTPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 48 | 34 | 30 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_field_gt | eval_field_gt | 72 | 74 | 72 | 73 | 72fd8b32baedaac7afe17a889819b328091cfd27 | bigcode/the-stack | train |
34622c46d5e08b60d3865285 | train | function | @eval_predicate.register(alt.FieldOneOfPredicate)
def eval_field_oneof(predicate: alt.FieldOneOfPredicate, df: pd.DataFrame) -> pd.Series:
options = [eval_value(val) for val in predicate.oneOf]
return get_column(df, predicate).isin(options)
| @eval_predicate.register(alt.FieldOneOfPredicate)
def eval_field_oneof(predicate: alt.FieldOneOfPredicate, df: pd.DataFrame) -> pd.Series:
| options = [eval_value(val) for val in predicate.oneOf]
return get_column(df, predicate).isin(options)
| column.min()
if max_ is None:
max_ = column.max()
return column.between(min_, max_, inclusive=True)
@eval_predicate.register(alt.FieldOneOfPredicate)
def eval_field_oneof(predicate: alt.FieldOneOfPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 61 | 35 | 29 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_field_oneof | eval_field_oneof | 56 | 59 | 56 | 57 | 20bd3361022552c647d3b1bf1f5335ae6fb09fdd | bigcode/the-stack | train |
30572c5c64dd15f30311454d | train | function | @singledispatch
def eval_value(value: Any) -> Any:
return value
| @singledispatch
def eval_value(value: Any) -> Any:
| return value
| OrPredicate)
def eval_logical_or(predicate: alt.LogicalOrPredicate, df: pd.DataFrame) -> pd.Series:
return np.logical_or.reduce([eval_predicate(p, df) for p in predicate["or"]])
@singledispatch
def eval_value(value: Any) -> Any:
| 64 | 64 | 20 | 16 | 48 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_value | eval_value | 97 | 99 | 97 | 98 | c02621abdf837615945474745d71cdacff7e4d47 | bigcode/the-stack | train |
6bddc14ab897b0b67d110037 | train | function | @eval_predicate.register(alt.FieldRangePredicate)
def eval_field_range(predicate: alt.FieldRangePredicate, df: pd.DataFrame) -> pd.Series:
min_, max_ = [eval_value(val) for val in predicate.range]
column = get_column(df, predicate)
if min_ is None:
min_ = column.min()
if max_ is None:
ma... | @eval_predicate.register(alt.FieldRangePredicate)
def eval_field_range(predicate: alt.FieldRangePredicate, df: pd.DataFrame) -> pd.Series:
| min_, max_ = [eval_value(val) for val in predicate.range]
column = get_column(df, predicate)
if min_ is None:
min_ = column.min()
if max_ is None:
max_ = column.max()
return column.between(min_, max_, inclusive=True)
| _equal(predicate: alt.FieldEqualPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) == eval_value(predicate.equal)
@eval_predicate.register(alt.FieldRangePredicate)
def eval_field_range(predicate: alt.FieldRangePredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 98 | 32 | 32 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_field_range | eval_field_range | 45 | 53 | 45 | 46 | 51f73263bc0d67f0e165db8eb27b4ff5c35ccfbe | bigcode/the-stack | train |
f71e26dcc4df97814a4e38d5 | train | function | @eval_predicate.register(alt.FieldLTEPredicate)
def eval_field_lte(predicate: alt.FieldLTEPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) <= eval_value(predicate.lte)
| @eval_predicate.register(alt.FieldLTEPredicate)
def eval_field_lte(predicate: alt.FieldLTEPredicate, df: pd.DataFrame) -> pd.Series:
| return get_column(df, predicate) <= eval_value(predicate.lte)
| : alt.FieldLTPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) < eval_value(predicate.lt)
@eval_predicate.register(alt.FieldLTEPredicate)
def eval_field_lte(predicate: alt.FieldLTEPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 48 | 33 | 31 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_field_lte | eval_field_lte | 67 | 69 | 67 | 68 | e926406ceb8f9a0523a9af588dd0f5b8af5923ba | bigcode/the-stack | train |
ed0b96302443834083d87f42 | train | function | @eval_predicate.register(alt.LogicalNotPredicate)
def eval_logical_not(predicate: alt.LogicalNotPredicate, df: pd.DataFrame) -> pd.Series:
return ~eval_predicate(predicate["not"], df)
| @eval_predicate.register(alt.LogicalNotPredicate)
def eval_logical_not(predicate: alt.LogicalNotPredicate, df: pd.DataFrame) -> pd.Series:
| return ~eval_predicate(predicate["not"], df)
| GTEPredicate, df: pd.DataFrame) -> pd.Series:
return get_column(df, predicate) >= eval_value(predicate.gte)
@eval_predicate.register(alt.LogicalNotPredicate)
def eval_logical_not(predicate: alt.LogicalNotPredicate, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 47 | 35 | 29 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_logical_not | eval_logical_not | 82 | 84 | 82 | 83 | 0d6b6c5c250f953ac97c181200c2debc669c5333 | bigcode/the-stack | train |
4182f9b4b3c75ed72b41897a | train | function | @eval_value.register(alt.SchemaBase)
def eval_schemabase(value: alt.SchemaBase) -> dict:
return value.to_dict()
| @eval_value.register(alt.SchemaBase)
def eval_schemabase(value: alt.SchemaBase) -> dict:
| return value.to_dict()
| (alt.DateTime)
def eval_datetime(value: alt.DateTime) -> pd.Series:
# TODO: implement datetime conversion & comparison
raise NotImplementedError("Evaluating alt.DateTime object")
@eval_value.register(alt.SchemaBase)
def eval_schemabase(value: alt.SchemaBase) -> dict:
| 64 | 64 | 29 | 23 | 41 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_schemabase | eval_schemabase | 108 | 110 | 108 | 109 | 94d7191b1755932a088d693e14eccea3120d349d | bigcode/the-stack | train |
ed8a7e547b41ed2e7499269d | train | function | def get_column(df: pd.DataFrame, predicate: Any) -> pd.Series:
"""Get the transformed column from the predicate."""
if predicate.timeUnit is not alt.Undefined:
raise NotImplementedError("timeUnit Transform in Predicates")
return df[eval_value(predicate["field"])]
| def get_column(df: pd.DataFrame, predicate: Any) -> pd.Series:
| """Get the transformed column from the predicate."""
if predicate.timeUnit is not alt.Undefined:
raise NotImplementedError("timeUnit Transform in Predicates")
return df[eval_value(predicate["field"])]
| Transform)
def visit_filter(transform: alt.FilterTransform, df: pd.DataFrame) -> pd.DataFrame:
mask = eval_predicate(transform.filter, df).astype(bool)
return df[mask].reset_index(drop=True)
def get_column(df: pd.DataFrame, predicate: Any) -> pd.Series:
| 64 | 64 | 63 | 17 | 47 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | get_column | get_column | 17 | 21 | 17 | 17 | 75ca7255992851d54c6225f668f3250b56dbf50e | bigcode/the-stack | train |
565b5c7290ee6430c103629b | train | function | @singledispatch
def eval_dict(predicate: dict, df: pd.DataFrame) -> pd.Series:
transform = alt.FilterTrasform({"filter": predicate})
return eval_predicate(transform.filter, df)
| @singledispatch
def eval_dict(predicate: dict, df: pd.DataFrame) -> pd.Series:
| transform = alt.FilterTrasform({"filter": predicate})
return eval_predicate(transform.filter, df)
| @singledispatch
def eval_predicate(predicate: Any, df: pd.DataFrame) -> pd.Series:
raise NotImplementedError(f"Evaluating predicate of type {type(predicate)}")
@singledispatch
def eval_dict(predicate: dict, df: pd.DataFrame) -> pd.Series:
| 64 | 64 | 45 | 23 | 41 | altair-viz/altair-transform | altair_transform/transform/filter.py | Python | eval_dict | eval_dict | 29 | 32 | 29 | 30 | 567e1f15455f2d6cdbd12574dc116db41987777e | bigcode/the-stack | train |
0692ea1cd3cf5d2db69538a9 | train | class | class ManualPriceOracle:
def can_query_history( # pylint: disable=no-self-use
self,
from_asset: Asset, # pylint: disable=unused-argument
to_asset: Asset, # pylint: disable=unused-argument
timestamp: Timestamp, # pylint: disable=unused-argument
seconds... | class ManualPriceOracle:
| def can_query_history( # pylint: disable=no-self-use
self,
from_asset: Asset, # pylint: disable=unused-argument
to_asset: Asset, # pylint: disable=unused-argument
timestamp: Timestamp, # pylint: disable=unused-argument
seconds: Optional[int] = None, #... | PriceForGivenTimestamp
from rotkehlchen.globaldb.handler import GlobalDBHandler
from rotkehlchen.history.types import HistoricalPriceOracle
from rotkehlchen.logging import RotkehlchenLogsAdapter
from rotkehlchen.types import Price, Timestamp
logger = logging.getLogger(__name__)
log = RotkehlchenLogsAdapter(logger)
cla... | 78 | 78 | 261 | 5 | 73 | rotkehlchenio/rotkehlchen | rotkehlchen/globaldb/manual_price_oracle.py | Python | ManualPriceOracle | ManualPriceOracle | 15 | 48 | 15 | 16 | 6e7c8656cc735fbe02391dd23d161e43833c4259 | bigcode/the-stack | train |
730e02a558013e3919c63b2b | train | class | class NLayerDiscriminator(nn.Module):
"""Defines a PatchGAN discriminator
This class is adopted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix
"""
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer="batch",
dimension="2d"):
"""Construct a PatchGAN discri... | class NLayerDiscriminator(nn.Module):
| """Defines a PatchGAN discriminator
This class is adopted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix
"""
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer="batch",
dimension="2d"):
"""Construct a PatchGAN discriminator
Parameters:
... | activ='lrelu'))
setattr(self, "conv{}".format(i), m)
input_chs.append(input_ch)
input_ch //= 2
m = ConvolutionBlock(
in_channels=base_ch, out_channels=output_ch, kernel_size=7,
stride=1, padding=3, conv=conv, pad=pad, norm='none', activ='tanh')
... | 184 | 184 | 615 | 8 | 175 | cpeng93/XraySyn | xraysyn/networks/common.py | Python | NLayerDiscriminator | NLayerDiscriminator | 73 | 125 | 73 | 73 | 0b96eb946fc092199c614ed778516a9840ecc954 | bigcode/the-stack | train |
018afa8cdefa308b40bb8e30 | train | function | def init_weights(net, init_type='normal', init_param=0.02):
def init_func(m):
classname = m.__class__.__name__
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
if init_type == 'normal':
nn.init.normal_(m.weight.data, 0.0, init_... | def init_weights(net, init_type='normal', init_param=0.02):
| def init_func(m):
classname = m.__class__.__name__
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
if init_type == 'normal':
nn.init.normal_(m.weight.data, 0.0, init_param)
elif init_type == 'xavier':
... | the data
gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps
return gradient_penalty, gradients
else:
return 0.0, None
def init_weights(net, init_type='normal', init_param=0.02):
| 80 | 80 | 267 | 17 | 62 | cpeng93/XraySyn | xraysyn/networks/common.py | Python | init_weights | init_weights | 232 | 252 | 232 | 232 | 60af5e8f077a0569b8c463660d211c0ad15c64a4 | bigcode/the-stack | train |
560d9601a9b88326442b3ffb | train | class | class GANLoss(nn.Module):
"""Define different GAN objectives.
The GANLoss class abstracts away the need to create the target label tensor
that has the same size as the input.
"""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
""" Initialize the GANLoss class.
... | class GANLoss(nn.Module):
| """Define different GAN objectives.
The GANLoss class abstracts away the need to create the target label tensor
that has the same size as the input.
"""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
""" Initialize the GANLoss class.
Parameters:
... | norm_layer else []) + [nn.LeakyReLU(0.2, True)]
nf_mult_prev = nf_mult
nf_mult = min(2 ** n_layers, 8)
sequence += [
conv(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw,
bias=use_bias)] + \
([no... | 180 | 180 | 601 | 6 | 174 | cpeng93/XraySyn | xraysyn/networks/common.py | Python | GANLoss | GANLoss | 128 | 191 | 128 | 128 | 0f438c5be11aec2d40935867de652e52dd77341b | bigcode/the-stack | train |
c802ac21aa06ff97a1c56546 | train | class | class ResEncoder(nn.Module):
def __init__(self, input_ch, base_ch, num_down, num_residual,
conv="con2d", pad='reflect2d', res_norm='instance2d', down_norm='instance2d'):
super(ResEncoder, self).__init__()
self.conv0 = ConvolutionBlock(
in_channels=input_ch, out_channels... | class ResEncoder(nn.Module):
| def __init__(self, input_ch, base_ch, num_down, num_residual,
conv="con2d", pad='reflect2d', res_norm='instance2d', down_norm='instance2d'):
super(ResEncoder, self).__init__()
self.conv0 = ConvolutionBlock(
in_channels=input_ch, out_channels=base_ch, kernel_size=7, stri... | import torch
import torch.nn as nn
from .blocks import ConvolutionBlock, ResidualBlock, FullyConnectedBlock
class ResEncoder(nn.Module):
| 31 | 96 | 322 | 6 | 24 | cpeng93/XraySyn | xraysyn/networks/common.py | Python | ResEncoder | ResEncoder | 6 | 33 | 6 | 6 | 238a10912036ebed77d9f39f5fdde1bacb25708d | bigcode/the-stack | train |
92d244b198dbdd4c6a7ae10b | train | function | def _calc_grad_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):
"""Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028
Arguments:
netD (network) -- discriminator network
real_data (tensor array) -- re... | def _calc_grad_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):
| """Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028
Arguments:
netD (network) -- discriminator network
real_data (tensor array) -- real images
fake_data (tensor array) -- generated images from the generator
device (str... | ) - - if the ground truth label is for real images or fake images
Returns:
the calculated loss.
"""
all_losses = []
for prediction in predictions:
if self.gan_mode in ['lsgan', 'vanilla']:
target_tensor = self.get_target_tensor(prediction, target_i... | 159 | 159 | 532 | 34 | 125 | cpeng93/XraySyn | xraysyn/networks/common.py | Python | _calc_grad_penalty | _calc_grad_penalty | 194 | 229 | 194 | 194 | c896c0e105000284549086115f8bb7067c56e4a6 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.