content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
borg.algorithms
===============
This package is intended for hash and checksum functions.
"""
| """
borg.algorithms
===============
This package is intended for hash and checksum functions.
""" |
"""
Working with Binary Search Trees (BSTs).
The height of a binary search tree is the number of edges between the tree's
root and its furthest leaf. You are given a pointer, root, pointing to the
root of a binary search tree. Complete the getHeight function provided in your
editor so that it returns the height of the binary search tree.
Link: https://www.hackerrank.com/challenges/30-binary-search-trees/problem
Link: https://en.wikipedia.org/wiki/Binary_search_tree
"""
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def getHeight(self,root):
if root == None:
return -1
else:
return 1 + max( self.getHeight(root.left), self.getHeight(root.right) )
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(f'Height: {height}') | """
Working with Binary Search Trees (BSTs).
The height of a binary search tree is the number of edges between the tree's
root and its furthest leaf. You are given a pointer, root, pointing to the
root of a binary search tree. Complete the getHeight function provided in your
editor so that it returns the height of the binary search tree.
Link: https://www.hackerrank.com/challenges/30-binary-search-trees/problem
Link: https://en.wikipedia.org/wiki/Binary_search_tree
"""
class Node:
def __init__(self, data):
self.right = self.left = None
self.data = data
class Solution:
def insert(self, root, data):
if root == None:
return node(data)
elif data <= root.data:
cur = self.insert(root.left, data)
root.left = cur
else:
cur = self.insert(root.right, data)
root.right = cur
return root
def get_height(self, root):
if root == None:
return -1
else:
return 1 + max(self.getHeight(root.left), self.getHeight(root.right))
t = int(input())
my_tree = solution()
root = None
for i in range(T):
data = int(input())
root = myTree.insert(root, data)
height = myTree.getHeight(root)
print(f'Height: {height}') |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class ContentType:
O365_CONNECTOR_CARD = "application/vnd.microsoft.teams.card.o365connector"
FILE_CONSENT_CARD = "application/vnd.microsoft.teams.card.file.consent"
FILE_DOWNLOAD_INFO = "application/vnd.microsoft.teams.file.download.info"
FILE_INFO_CARD = "application/vnd.microsoft.teams.card.file.info"
class Type:
O365_CONNECTOR_CARD_VIEWACTION = "ViewAction"
O365_CONNECTOR_CARD_OPEN_URI = "OpenUri"
O365_CONNECTOR_CARD_HTTP_POST = "HttpPOST"
O365_CONNECTOR_CARD_ACTION_CARD = "ActionCard"
O365_CONNECTOR_CARD_TEXT_INPUT = "TextInput"
O365_CONNECTOR_CARD_DATE_INPUT = "DateInput"
O365_CONNECTOR_CARD_MULTICHOICE_INPUT = "MultichoiceInput"
| class Contenttype:
o365_connector_card = 'application/vnd.microsoft.teams.card.o365connector'
file_consent_card = 'application/vnd.microsoft.teams.card.file.consent'
file_download_info = 'application/vnd.microsoft.teams.file.download.info'
file_info_card = 'application/vnd.microsoft.teams.card.file.info'
class Type:
o365_connector_card_viewaction = 'ViewAction'
o365_connector_card_open_uri = 'OpenUri'
o365_connector_card_http_post = 'HttpPOST'
o365_connector_card_action_card = 'ActionCard'
o365_connector_card_text_input = 'TextInput'
o365_connector_card_date_input = 'DateInput'
o365_connector_card_multichoice_input = 'MultichoiceInput' |
class Log:
lines = []
def __init__(self):
self.lines = []
def add(self, line):
self.lines.append(line)
def flush(self):
for line in self.lines:
print(line)
self.lines = []
battle_log = Log()
general_log = Log() | class Log:
lines = []
def __init__(self):
self.lines = []
def add(self, line):
self.lines.append(line)
def flush(self):
for line in self.lines:
print(line)
self.lines = []
battle_log = log()
general_log = log() |
num1 = 111
num2 = 222
num3 = 333333
num3 = 333
num4 = 4444
| num1 = 111
num2 = 222
num3 = 333333
num3 = 333
num4 = 4444 |
"""This module contains a collection of functions related to
flood data.
"""
#ml2015
def stations_level_over_threshold(stations,tol):
"""For Task 2B - returns a list of tuples
The tuples contain a station and then a relative water level
the relative water level must be greater than tol
returned list should be in descending order"""
threshold_list=[]
for station in stations:
m=station.relative_water_level()
if m==None:
pass
elif m>tol:
threshold_list.append((station, m))
final_threshold_list = sorted(threshold_list, key=lambda x: x[1], reverse=True)
return final_threshold_list
def stations_highest_rel_level(stations, N):
"""For Task 2C - returns a list of N stations at which relative typical water level is highest
List is sorted in descending order"""
list_highest_level = []
for station in stations:
m=station.relative_water_level()
if m==None:
pass
else:
list_highest_level.append((station,m))
sorted_list_highest_level = sorted(list_highest_level, key=lambda x: x[1], reverse=True)
i=0
short_list=[]
while i<N:
short_list.append(sorted_list_highest_level[i][0])
i+=1
return short_list
| """This module contains a collection of functions related to
flood data.
"""
def stations_level_over_threshold(stations, tol):
"""For Task 2B - returns a list of tuples
The tuples contain a station and then a relative water level
the relative water level must be greater than tol
returned list should be in descending order"""
threshold_list = []
for station in stations:
m = station.relative_water_level()
if m == None:
pass
elif m > tol:
threshold_list.append((station, m))
final_threshold_list = sorted(threshold_list, key=lambda x: x[1], reverse=True)
return final_threshold_list
def stations_highest_rel_level(stations, N):
"""For Task 2C - returns a list of N stations at which relative typical water level is highest
List is sorted in descending order"""
list_highest_level = []
for station in stations:
m = station.relative_water_level()
if m == None:
pass
else:
list_highest_level.append((station, m))
sorted_list_highest_level = sorted(list_highest_level, key=lambda x: x[1], reverse=True)
i = 0
short_list = []
while i < N:
short_list.append(sorted_list_highest_level[i][0])
i += 1
return short_list |
class MaterialPropertyMap:
def __init__(self):
self._lowCutoffs = []
self._highCutoffs = []
self._properties = []
def error_check(self, cutoff, conductivity):
if not isinstance(cutoff, tuple) or len(cutoff) != 2:
raise Exception("Cutoff has to be a tuple(int,int) specifying the low and high cutoffs")
for i in range(len(self._lowCutoffs)):
if (self._highCutoffs[i] >= cutoff[0] >= self._lowCutoffs[i]) \
or (self._highCutoffs[i] >= cutoff[1] >= self._lowCutoffs[i]):
raise Exception("Invalid material range. The range overlaps an existing material range")
check = False
if isinstance(conductivity, tuple):
if any(i < 0 for i in conductivity):
check = True
else:
if conductivity < 0:
check = True
if check:
raise Exception("Invalid conductivity. Must be positive")
return conductivity
def _append_inputs(self, cutoff, conductivity):
self._lowCutoffs.append(cutoff[0])
self._highCutoffs.append(cutoff[1])
self._properties.append(conductivity)
def get_size(self):
return len(self._lowCutoffs)
def get_material(self, i):
if i >= len(self._lowCutoffs):
raise Exception("Invalid index. Maximum size: " + str(self.get_size()))
if i < 0:
raise Exception("Invalid index. Must be >= 0")
return self._lowCutoffs[i], self._highCutoffs[i], self._properties[i]
def show(self):
print("Material conductivity as [low-high cutoffs] = conductivity:")
for i in range(len(self._lowCutoffs)):
print('[{} - {}] = {}'.format(self._lowCutoffs[i], self._highCutoffs[i], self._properties[i]))
class IsotropicConductivityMap(MaterialPropertyMap):
def __init__(self):
super().__init__()
def add_material(self, cutoff, conductivity):
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
class AnisotropicConductivityMap(MaterialPropertyMap):
def __init__(self):
super().__init__()
def add_material(self, cutoff, kxx, kyy, kzz, kxy, kxz, kyz):
conductivity = (kxx, kyy, kzz, kxy, kxz, kyz)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
def add_isotropic_material(self, cutoff, k):
conductivity = (k, k, k, 0., 0., 0.)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
def add_orthotropic_material(self, cutoff, kxx, kyy, kzz):
conductivity = (kxx, kyy, kzz, 0., 0., 0.)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
def add_material_to_orient(self, cutoff, k_axial, k_radial):
conductivity = (k_axial, k_radial)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
class ElasticityMap(MaterialPropertyMap):
def __init__(self):
super().__init__()
def add_material(self, cutoff, C11, C12, C13, C14, C15, C16, C22, C23, C24, C25, C26,
C33, C34, C35, C36, C44, C45, C46, C55, C56, C66):
elasticity = (C11, C12, C13, C14, C15, C16,
C22, C23, C24, C25, C26,
C33, C34, C35, C36,
C44, C45, C46,
C55, C56,
C66)
elasticity = self.error_check(cutoff, elasticity)
if isinstance(elasticity, bool):
return
self._append_inputs(cutoff, elasticity)
def add_isotropic_material(self, cutoff, E_youngmod, nu_poissrat):
Lambda = (nu_poissrat * E_youngmod) / ((1 + nu_poissrat) * (1 - 2 * nu_poissrat))
mu = E_youngmod / (2 * (1 + nu_poissrat))
elasticity = (Lambda + 2 * mu, Lambda, Lambda, 0., 0., 0.,
Lambda + 2 * mu, Lambda, 0., 0., 0.,
Lambda + 2 * mu, 0., 0., 0.,
2 * mu, 0., 0.,
2 * mu, 0.,
2 * mu)
elasticity = self.error_check(cutoff, elasticity)
if isinstance(elasticity, bool):
return
self._append_inputs(cutoff, elasticity)
def add_material_to_orient(self, cutoff, E_axial, E_radial, nu_poissrat_12, nu_poissrat_23, G12):
elasticity = (E_axial, E_radial, nu_poissrat_12, nu_poissrat_23, G12)
elasticity = self.error_check(cutoff, elasticity)
if isinstance(elasticity, bool):
return
self._append_inputs(cutoff, elasticity)
def show(self):
print("Material elasticity as [low-high cutoffs] = elasticity:")
for i in range(len(self._lowCutoffs)):
print('[{} - {}] = '.format(self._lowCutoffs[i], self._highCutoffs[i], self._properties[i]))
if len(self._properties[i]) == 5:
print('{}'.format(self._properties[i]))
else:
first_elast, last_elast = (0, 6)
for i2 in range(6):
print('{}'.format(self._properties[i][first_elast:last_elast]))
first_elast = last_elast
last_elast += 5 - i2
| class Materialpropertymap:
def __init__(self):
self._lowCutoffs = []
self._highCutoffs = []
self._properties = []
def error_check(self, cutoff, conductivity):
if not isinstance(cutoff, tuple) or len(cutoff) != 2:
raise exception('Cutoff has to be a tuple(int,int) specifying the low and high cutoffs')
for i in range(len(self._lowCutoffs)):
if self._highCutoffs[i] >= cutoff[0] >= self._lowCutoffs[i] or self._highCutoffs[i] >= cutoff[1] >= self._lowCutoffs[i]:
raise exception('Invalid material range. The range overlaps an existing material range')
check = False
if isinstance(conductivity, tuple):
if any((i < 0 for i in conductivity)):
check = True
elif conductivity < 0:
check = True
if check:
raise exception('Invalid conductivity. Must be positive')
return conductivity
def _append_inputs(self, cutoff, conductivity):
self._lowCutoffs.append(cutoff[0])
self._highCutoffs.append(cutoff[1])
self._properties.append(conductivity)
def get_size(self):
return len(self._lowCutoffs)
def get_material(self, i):
if i >= len(self._lowCutoffs):
raise exception('Invalid index. Maximum size: ' + str(self.get_size()))
if i < 0:
raise exception('Invalid index. Must be >= 0')
return (self._lowCutoffs[i], self._highCutoffs[i], self._properties[i])
def show(self):
print('Material conductivity as [low-high cutoffs] = conductivity:')
for i in range(len(self._lowCutoffs)):
print('[{} - {}] = {}'.format(self._lowCutoffs[i], self._highCutoffs[i], self._properties[i]))
class Isotropicconductivitymap(MaterialPropertyMap):
def __init__(self):
super().__init__()
def add_material(self, cutoff, conductivity):
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
class Anisotropicconductivitymap(MaterialPropertyMap):
def __init__(self):
super().__init__()
def add_material(self, cutoff, kxx, kyy, kzz, kxy, kxz, kyz):
conductivity = (kxx, kyy, kzz, kxy, kxz, kyz)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
def add_isotropic_material(self, cutoff, k):
conductivity = (k, k, k, 0.0, 0.0, 0.0)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
def add_orthotropic_material(self, cutoff, kxx, kyy, kzz):
conductivity = (kxx, kyy, kzz, 0.0, 0.0, 0.0)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
def add_material_to_orient(self, cutoff, k_axial, k_radial):
conductivity = (k_axial, k_radial)
conductivity = self.error_check(cutoff, conductivity)
if isinstance(conductivity, bool):
return
self._append_inputs(cutoff, conductivity)
class Elasticitymap(MaterialPropertyMap):
def __init__(self):
super().__init__()
def add_material(self, cutoff, C11, C12, C13, C14, C15, C16, C22, C23, C24, C25, C26, C33, C34, C35, C36, C44, C45, C46, C55, C56, C66):
elasticity = (C11, C12, C13, C14, C15, C16, C22, C23, C24, C25, C26, C33, C34, C35, C36, C44, C45, C46, C55, C56, C66)
elasticity = self.error_check(cutoff, elasticity)
if isinstance(elasticity, bool):
return
self._append_inputs(cutoff, elasticity)
def add_isotropic_material(self, cutoff, E_youngmod, nu_poissrat):
lambda = nu_poissrat * E_youngmod / ((1 + nu_poissrat) * (1 - 2 * nu_poissrat))
mu = E_youngmod / (2 * (1 + nu_poissrat))
elasticity = (Lambda + 2 * mu, Lambda, Lambda, 0.0, 0.0, 0.0, Lambda + 2 * mu, Lambda, 0.0, 0.0, 0.0, Lambda + 2 * mu, 0.0, 0.0, 0.0, 2 * mu, 0.0, 0.0, 2 * mu, 0.0, 2 * mu)
elasticity = self.error_check(cutoff, elasticity)
if isinstance(elasticity, bool):
return
self._append_inputs(cutoff, elasticity)
def add_material_to_orient(self, cutoff, E_axial, E_radial, nu_poissrat_12, nu_poissrat_23, G12):
elasticity = (E_axial, E_radial, nu_poissrat_12, nu_poissrat_23, G12)
elasticity = self.error_check(cutoff, elasticity)
if isinstance(elasticity, bool):
return
self._append_inputs(cutoff, elasticity)
def show(self):
print('Material elasticity as [low-high cutoffs] = elasticity:')
for i in range(len(self._lowCutoffs)):
print('[{} - {}] = '.format(self._lowCutoffs[i], self._highCutoffs[i], self._properties[i]))
if len(self._properties[i]) == 5:
print('{}'.format(self._properties[i]))
else:
(first_elast, last_elast) = (0, 6)
for i2 in range(6):
print('{}'.format(self._properties[i][first_elast:last_elast]))
first_elast = last_elast
last_elast += 5 - i2 |
class EncodingApiCommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, path, command, arguments=None, queries=None,
additional_queries=()):
path = path.encode()
command = command.encode()
arguments = self.transform_dictionary(arguments or {})
queries = self.transform_dictionary(queries or {})
promise = self.inner.call(
path, command, arguments, queries, additional_queries)
return self.decorate_promise(promise)
def transform_dictionary(self, dictionary):
return dict(self.transform_item(item) for item in dictionary.items())
def transform_item(self, item):
key, value = item
return (key.encode(), value)
def decorate_promise(self, promise):
return EncodedPromiseDecorator(promise)
class EncodedPromiseDecorator(object):
def __init__(self, inner):
self.inner = inner
def get(self):
response = self.inner.get()
return response.map(self.transform_row)
def __iter__(self):
return map(self.transform_row, self.inner)
def transform_row(self, row):
return dict(self.transform_item(item) for item in row.items())
def transform_item(self, item):
key, value = item
return (key.decode(), value)
| class Encodingapicommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, path, command, arguments=None, queries=None, additional_queries=()):
path = path.encode()
command = command.encode()
arguments = self.transform_dictionary(arguments or {})
queries = self.transform_dictionary(queries or {})
promise = self.inner.call(path, command, arguments, queries, additional_queries)
return self.decorate_promise(promise)
def transform_dictionary(self, dictionary):
return dict((self.transform_item(item) for item in dictionary.items()))
def transform_item(self, item):
(key, value) = item
return (key.encode(), value)
def decorate_promise(self, promise):
return encoded_promise_decorator(promise)
class Encodedpromisedecorator(object):
def __init__(self, inner):
self.inner = inner
def get(self):
response = self.inner.get()
return response.map(self.transform_row)
def __iter__(self):
return map(self.transform_row, self.inner)
def transform_row(self, row):
return dict((self.transform_item(item) for item in row.items()))
def transform_item(self, item):
(key, value) = item
return (key.decode(), value) |
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.age = 0
def full_name(self):
return self.first_name + " " + self.last_name
def record_info(self):
return self.last_name + ", " + self.first_name
person = Person("Bob", "Smith")
person2 = Person("Sally", "Smith")
Person.record_info = record_info
myfn = Person.full_name
print(myfn(person2))
# print(Person)
# print(person)
# print(person.full_name())
# print(person.record_info())
# print(person.first_name)
# print(person.age)
# person.age = 34
# print(person.age)
# del person.first_name
# print(person.first_name)
| class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.age = 0
def full_name(self):
return self.first_name + ' ' + self.last_name
def record_info(self):
return self.last_name + ', ' + self.first_name
person = person('Bob', 'Smith')
person2 = person('Sally', 'Smith')
Person.record_info = record_info
myfn = Person.full_name
print(myfn(person2)) |
class Node:
def __init__(self, data) -> None:
self.data = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.head = None
self.numOfNodes = 0
def insert_new(self, data):
self.numOfNodes += 1
new_node = Node(data)
if not self.head:
self.head = new_node
else:
new_node.nextNode = self.head
self.head = new_node
def insert_to_end(self, data):
self.numOfNodes += 1
new_node = Node(data)
actual_node = self.head
while actual_node.nextNode is not None:
actual_node = actual_node.nextNode
actual_node.nextNode = new_node
def remove(self, data):
if self.head is None:
return
actual_node = self.head
previous = None
while actual_node is not None and actual_node.data != data:
previous = actual_node
actual_node = actual_node.nextNode
if actual_node is None:
return
if previous is None:
self.head = actual_node.nextNode
else:
previous.nextNode = actual_node.nextNode
@property
def get_size(self):
return self.numOfNodes
def traverse(self):
actual = self.head
while actual is not None:
print(actual.data)
actual = actual.nextNode
if __name__ == "__main__":
t = LinkedList()
t.insert_new(1)
t.insert_new(10)
print(t.get_size)
t.traverse()
| class Node:
def __init__(self, data) -> None:
self.data = data
self.nextNode = None
class Linkedlist:
def __init__(self):
self.head = None
self.numOfNodes = 0
def insert_new(self, data):
self.numOfNodes += 1
new_node = node(data)
if not self.head:
self.head = new_node
else:
new_node.nextNode = self.head
self.head = new_node
def insert_to_end(self, data):
self.numOfNodes += 1
new_node = node(data)
actual_node = self.head
while actual_node.nextNode is not None:
actual_node = actual_node.nextNode
actual_node.nextNode = new_node
def remove(self, data):
if self.head is None:
return
actual_node = self.head
previous = None
while actual_node is not None and actual_node.data != data:
previous = actual_node
actual_node = actual_node.nextNode
if actual_node is None:
return
if previous is None:
self.head = actual_node.nextNode
else:
previous.nextNode = actual_node.nextNode
@property
def get_size(self):
return self.numOfNodes
def traverse(self):
actual = self.head
while actual is not None:
print(actual.data)
actual = actual.nextNode
if __name__ == '__main__':
t = linked_list()
t.insert_new(1)
t.insert_new(10)
print(t.get_size)
t.traverse() |
adventures = [
{"id": 1, "name": "Test Location"},
{"id": 12, "name": "The Sewer"},
{"id": 15, "name": "The Spooky Forest"},
{"id": 16, "name": "The Haiku Dungeon"},
{"id": 17, "name": "The Hidden Temple"},
{"id": 18, "name": "Degrassi Knoll"},
{"id": 19, "name": "The Limerick Dungeon"},
{"id": 20, "name": 'The "Fun" House'},
{"id": 21, "name": "The Misspelled Cemetary (Pre-Cyrpt)"},
{"id": 22, "name": "Tower Ruins"},
{"id": 23, "name": "Drunken Stupor"},
{"id": 24, "name": "The Typical Tavern Rats"},
{"id": 25, "name": "The Typical Tavern Booze"},
{"id": 26, "name": "The Hippy Camp"},
{"id": 27, "name": "Orcish Frat House"},
{"id": 29, "name": "Orcish Frat House (In Disguise)"},
{"id": 30, "name": "The Bat Hole Entryway"},
{"id": 31, "name": "Guano Junction"},
{"id": 32, "name": "Batrat and Ratbat Burrow"},
{"id": 33, "name": "Beanbat Chamber"},
{"id": 34, "name": "The Boss Bat's Lair"},
{"id": 37, "name": "The Spectral Pickle Factory"},
{"id": 38, "name": "The Enormous Greater-Then Sign"},
{"id": 39, "name": "The Dungeons of Doom"},
{"id": 40, "name": "Cobb's Knob Kitchens"},
{"id": 41, "name": "Cobb's Knob Treasury"},
{"id": 42, "name": "Cobb's Knob Harem"},
{"id": 43, "name": "Outskirts of Camp Logging Camp"},
{"id": 44, "name": "Camp Logging Camp"},
{"id": 45, "name": "South of the Border"},
{"id": 46, "name": "Thugnderdome"},
{"id": 47, "name": "The Bugbear Pens (Pre-Quest)"},
{"id": 48, "name": "The Spooky Gravy Barrow"},
{"id": 49, "name": "The Bugbear Pens (Post-Quest)"},
{"id": 50, "name": "Knob Goblin Laboratory"},
{"id": 51, "name": "Cobb's Knob Menagerie, Level 1"},
{"id": 52, "name": "Cobb's Knob Menagerie, Level 2"},
{"id": 53, "name": "Cobb's Knob Menagerie, Level 3"},
{"id": 54, "name": "The Defiled Nook"},
{"id": 55, "name": "The Defiled Cranny"},
{"id": 56, "name": "The Defiled Alcove"},
{"id": 57, "name": "The Defiled Niche"},
{"id": 58, "name": "The Misspelled Cemetary (Post-Cyrpt)"},
{"id": 59, "name": "The Icy Peak in The Recent Past"},
{"id": 60, "name": "The Goatlet"},
{"id": 61, "name": "Itznotyerzitz Mine"},
{"id": 62, "name": "Lair of the Ninja Snowmen"},
{"id": 63, "name": "The eXtreme Slope"},
{"id": 65, "name": "The Hippy Camp"},
{"id": 66, "name": "The Obligatory Pirate's Cove"},
{"id": 67, "name": "The Obligatory Pirate's Cove (In Disguise)"},
{"id": 70, "name": "The Roulette Tables"},
{"id": 71, "name": "The Poker Room"},
{"id": 73, "name": "The Inexplicable Door"},
{"id": 75, "name": "The Dark Neck of the Woods"},
{"id": 76, "name": "The Dark Heart of the Woods"},
{"id": 77, "name": "The Dark Elbow of the Woods"},
{"id": 79, "name": "The Deep Fat Friar's Gate"},
{"id": 80, "name": "The Valley Beyond the Orc Chasm"},
{"id": 81, "name": "The Penultimate Fantasy Airship"},
{"id": 82, "name": "The Castle in the Clouds in the Sky"},
{"id": 83, "name": "The Hole in the Sky"},
{"id": 84, "name": "St. Sneaky Pete's Day Stupor"},
{"id": 85, "name": "A Battlefield (No Uniform)"},
{"id": 86, "name": "A BattleField (In Cloaca-Cola Uniform)"},
{"id": 87, "name": "A Battlefield (In Dyspepsi-Cola Uniform)"},
{"id": 88, "name": "Market Square, 28 Days Later"},
{"id": 89, "name": "The Mall of Loathing, 28 Days Later"},
{"id": 90, "name": "Wrong Side of the Tracks, 28 Days Later"},
{"id": 91, "name": "Noob Cave"},
{"id": 92, "name": "The Dire Warren"},
{"id": 93, "name": "Crimbo Town Toy Factory (2005)"},
{"id": 94, "name": "Crimbo Toy Town Factory (2005) (Protesting)"},
{"id": 96, "name": "An Incredibly Strange Place (Bad Trip)"},
{"id": 97, "name": "An Incredibly Strange Place (Great Trip)"},
{"id": 98, "name": "An Incredibly Strange Place (Mediocre Trip)"},
{"id": 99, "name": "The Road to White Citadel"},
{"id": 100, "name": "Whitey's Grove"},
{"id": 101, "name": "The Knob Shaft"},
{"id": 102, "name": "The Haunted Kitchen"},
{"id": 103, "name": "The Haunted Conservatory"},
{"id": 104, "name": "The Haunted Library"},
{"id": 105, "name": "The Haunted Billiards Room"},
{"id": 106, "name": "The Haunted Gallery"},
{"id": 107, "name": "The Haunted Bathroom"},
{"id": 108, "name": "The Haunted Bedroom"},
{"id": 109, "name": "The Haunted Ballroom"},
{"id": 110, "name": "The Icy Peak"},
{"id": 111, "name": "The Black Forest"},
{"id": 112, "name": "The Sleazy Back Alley"},
{"id": 113, "name": "The Haunted Pantry"},
{"id": 114, "name": "Outskirts of Cobb's Knob"},
{"id": 115, "name": "Simple Tool-Making Cave"},
{"id": 116, "name": "The Spooky Fright Factory"},
{"id": 117, "name": "The Crimborg Collective Factory"},
{"id": 118, "name": "The Hidden City"},
{"id": 119, "name": "The Palindome"},
{"id": 121, "name": "The Arid, Extra-Dry Desert (without Ultrahydrated)"},
{"id": 122, "name": "An Oasis"},
{"id": 123, "name": "The Arid, Extra-Dry Desert (with Ultrahydrated)"},
{"id": 124, "name": "The Upper Chamber"},
{"id": 125, "name": "The Middle Chamber"},
{"id": 126, "name": "The Themthar Hills"},
{"id": 127, "name": "The Hatching Chamber"},
{"id": 128, "name": "The Feeding Chamber"},
{"id": 129, "name": "The Guards' Chamber"},
{"id": 130, "name": "The Queen's Chamber"},
{"id": 131, "name": "Wartime Hippy Camp (In Frat Boy Ensemble)"},
{"id": 132, "name": "The Battlefield (In Frat Warrior Fatigues)"},
{"id": 133, "name": "Wartime Hippy Camp"},
{"id": 134, "name": "Wartime Frat House (In Filthy Hippy Disguise)"},
{"id": 135, "name": "Wartime Frat House"},
{"id": 136, "name": "Sonofa Beach"},
{"id": 137, "name": "McMillicancuddy's Barn"},
{"id": 139, "name": "The Junkyard"},
{"id": 140, "name": "The Battlefield (In War Hippy Fatigues)"},
{"id": 141, "name": "The Pond"},
{"id": 142, "name": "The Back 40"},
{"id": 143, "name": "The Other Back 40"},
{"id": 144, "name": "The Granary"},
{"id": 145, "name": "The Bog"},
{"id": 146, "name": "The Family Plot"},
{"id": 147, "name": "The Shady Thicket"},
{"id": 148, "name": "Heartbreaker's Hotel"},
{"id": 149, "name": "The Hippy Camp (Bombed Back to the Stone Age)"},
{"id": 150, "name": "The Orcish Frat House (Bombed Back to the Stone Age)"},
{"id": 151, "name": "The Stately Pleasure Dome"},
{"id": 152, "name": "The Mouldering Mansion"},
{"id": 153, "name": "The Rogue Windmill"},
{"id": 154, "name": "The Junkyard (Post-War)"},
{"id": 155, "name": "McMillicancuddy's Farm (Post-War)"},
{"id": 156, "name": "The Grim Grimacite Site"},
{"id": 157, "name": "Barrrney's Barrr"},
{"id": 158, "name": "The F'c'le"},
{"id": 159, "name": "The Poop Deck"},
{"id": 160, "name": "Belowdecks"},
{"id": 161, "name": "A Sinister Dodecahedron"},
{"id": 162, "name": "Crimbo Town Toy Factory (2007)"},
{"id": 163, "name": "A Yuletide Bonfire"},
{"id": 164, "name": "A Shimmering Portal"},
{"id": 166, "name": "A Maze of Sewer Tunnels"},
{"id": 167, "name": "Hobopolis Town Square"},
{"id": 168, "name": "Burnbarrel Blvd."},
{"id": 169, "name": "Exposure Esplanade"},
{"id": 170, "name": "The Heap"},
{"id": 171, "name": "The Ancient Hobo Burial Ground"},
{"id": 172, "name": "The Purple Light District"},
{"id": 173, "name": "Go for a Swim"},
{"id": 174, "name": "The Arrrboretum"},
{"id": 175, "name": "The Spectral Salad Factory"},
{"id": 177, "name": "Mt. Molehill"},
{"id": 178, "name": "Wine Racks (Northwest)"},
{"id": 179, "name": "Wine Racks (Northeast)"},
{"id": 180, "name": "Wine Racks (Southwest)"},
{"id": 181, "name": "Wine Racks (Southeast)"},
{"id": 182, "name": "Next to that Barrel with Something Burning in it"},
{"id": 183, "name": "Near an Abandoned Refrigerator"},
{"id": 184, "name": "Over Where the Old Tires Are"},
{"id": 185, "name": "Out By that Rusted-Out Car"},
]
| adventures = [{'id': 1, 'name': 'Test Location'}, {'id': 12, 'name': 'The Sewer'}, {'id': 15, 'name': 'The Spooky Forest'}, {'id': 16, 'name': 'The Haiku Dungeon'}, {'id': 17, 'name': 'The Hidden Temple'}, {'id': 18, 'name': 'Degrassi Knoll'}, {'id': 19, 'name': 'The Limerick Dungeon'}, {'id': 20, 'name': 'The "Fun" House'}, {'id': 21, 'name': 'The Misspelled Cemetary (Pre-Cyrpt)'}, {'id': 22, 'name': 'Tower Ruins'}, {'id': 23, 'name': 'Drunken Stupor'}, {'id': 24, 'name': 'The Typical Tavern Rats'}, {'id': 25, 'name': 'The Typical Tavern Booze'}, {'id': 26, 'name': 'The Hippy Camp'}, {'id': 27, 'name': 'Orcish Frat House'}, {'id': 29, 'name': 'Orcish Frat House (In Disguise)'}, {'id': 30, 'name': 'The Bat Hole Entryway'}, {'id': 31, 'name': 'Guano Junction'}, {'id': 32, 'name': 'Batrat and Ratbat Burrow'}, {'id': 33, 'name': 'Beanbat Chamber'}, {'id': 34, 'name': "The Boss Bat's Lair"}, {'id': 37, 'name': 'The Spectral Pickle Factory'}, {'id': 38, 'name': 'The Enormous Greater-Then Sign'}, {'id': 39, 'name': 'The Dungeons of Doom'}, {'id': 40, 'name': "Cobb's Knob Kitchens"}, {'id': 41, 'name': "Cobb's Knob Treasury"}, {'id': 42, 'name': "Cobb's Knob Harem"}, {'id': 43, 'name': 'Outskirts of Camp Logging Camp'}, {'id': 44, 'name': 'Camp Logging Camp'}, {'id': 45, 'name': 'South of the Border'}, {'id': 46, 'name': 'Thugnderdome'}, {'id': 47, 'name': 'The Bugbear Pens (Pre-Quest)'}, {'id': 48, 'name': 'The Spooky Gravy Barrow'}, {'id': 49, 'name': 'The Bugbear Pens (Post-Quest)'}, {'id': 50, 'name': 'Knob Goblin Laboratory'}, {'id': 51, 'name': "Cobb's Knob Menagerie, Level 1"}, {'id': 52, 'name': "Cobb's Knob Menagerie, Level 2"}, {'id': 53, 'name': "Cobb's Knob Menagerie, Level 3"}, {'id': 54, 'name': 'The Defiled Nook'}, {'id': 55, 'name': 'The Defiled Cranny'}, {'id': 56, 'name': 'The Defiled Alcove'}, {'id': 57, 'name': 'The Defiled Niche'}, {'id': 58, 'name': 'The Misspelled Cemetary (Post-Cyrpt)'}, {'id': 59, 'name': 'The Icy Peak in The Recent Past'}, {'id': 60, 'name': 'The Goatlet'}, {'id': 61, 'name': 'Itznotyerzitz Mine'}, {'id': 62, 'name': 'Lair of the Ninja Snowmen'}, {'id': 63, 'name': 'The eXtreme Slope'}, {'id': 65, 'name': 'The Hippy Camp'}, {'id': 66, 'name': "The Obligatory Pirate's Cove"}, {'id': 67, 'name': "The Obligatory Pirate's Cove (In Disguise)"}, {'id': 70, 'name': 'The Roulette Tables'}, {'id': 71, 'name': 'The Poker Room'}, {'id': 73, 'name': 'The Inexplicable Door'}, {'id': 75, 'name': 'The Dark Neck of the Woods'}, {'id': 76, 'name': 'The Dark Heart of the Woods'}, {'id': 77, 'name': 'The Dark Elbow of the Woods'}, {'id': 79, 'name': "The Deep Fat Friar's Gate"}, {'id': 80, 'name': 'The Valley Beyond the Orc Chasm'}, {'id': 81, 'name': 'The Penultimate Fantasy Airship'}, {'id': 82, 'name': 'The Castle in the Clouds in the Sky'}, {'id': 83, 'name': 'The Hole in the Sky'}, {'id': 84, 'name': "St. Sneaky Pete's Day Stupor"}, {'id': 85, 'name': 'A Battlefield (No Uniform)'}, {'id': 86, 'name': 'A BattleField (In Cloaca-Cola Uniform)'}, {'id': 87, 'name': 'A Battlefield (In Dyspepsi-Cola Uniform)'}, {'id': 88, 'name': 'Market Square, 28 Days Later'}, {'id': 89, 'name': 'The Mall of Loathing, 28 Days Later'}, {'id': 90, 'name': 'Wrong Side of the Tracks, 28 Days Later'}, {'id': 91, 'name': 'Noob Cave'}, {'id': 92, 'name': 'The Dire Warren'}, {'id': 93, 'name': 'Crimbo Town Toy Factory (2005)'}, {'id': 94, 'name': 'Crimbo Toy Town Factory (2005) (Protesting)'}, {'id': 96, 'name': 'An Incredibly Strange Place (Bad Trip)'}, {'id': 97, 'name': 'An Incredibly Strange Place (Great Trip)'}, {'id': 98, 'name': 'An Incredibly Strange Place (Mediocre Trip)'}, {'id': 99, 'name': 'The Road to White Citadel'}, {'id': 100, 'name': "Whitey's Grove"}, {'id': 101, 'name': 'The Knob Shaft'}, {'id': 102, 'name': 'The Haunted Kitchen'}, {'id': 103, 'name': 'The Haunted Conservatory'}, {'id': 104, 'name': 'The Haunted Library'}, {'id': 105, 'name': 'The Haunted Billiards Room'}, {'id': 106, 'name': 'The Haunted Gallery'}, {'id': 107, 'name': 'The Haunted Bathroom'}, {'id': 108, 'name': 'The Haunted Bedroom'}, {'id': 109, 'name': 'The Haunted Ballroom'}, {'id': 110, 'name': 'The Icy Peak'}, {'id': 111, 'name': 'The Black Forest'}, {'id': 112, 'name': 'The Sleazy Back Alley'}, {'id': 113, 'name': 'The Haunted Pantry'}, {'id': 114, 'name': "Outskirts of Cobb's Knob"}, {'id': 115, 'name': 'Simple Tool-Making Cave'}, {'id': 116, 'name': 'The Spooky Fright Factory'}, {'id': 117, 'name': 'The Crimborg Collective Factory'}, {'id': 118, 'name': 'The Hidden City'}, {'id': 119, 'name': 'The Palindome'}, {'id': 121, 'name': 'The Arid, Extra-Dry Desert (without Ultrahydrated)'}, {'id': 122, 'name': 'An Oasis'}, {'id': 123, 'name': 'The Arid, Extra-Dry Desert (with Ultrahydrated)'}, {'id': 124, 'name': 'The Upper Chamber'}, {'id': 125, 'name': 'The Middle Chamber'}, {'id': 126, 'name': 'The Themthar Hills'}, {'id': 127, 'name': 'The Hatching Chamber'}, {'id': 128, 'name': 'The Feeding Chamber'}, {'id': 129, 'name': "The Guards' Chamber"}, {'id': 130, 'name': "The Queen's Chamber"}, {'id': 131, 'name': 'Wartime Hippy Camp (In Frat Boy Ensemble)'}, {'id': 132, 'name': 'The Battlefield (In Frat Warrior Fatigues)'}, {'id': 133, 'name': 'Wartime Hippy Camp'}, {'id': 134, 'name': 'Wartime Frat House (In Filthy Hippy Disguise)'}, {'id': 135, 'name': 'Wartime Frat House'}, {'id': 136, 'name': 'Sonofa Beach'}, {'id': 137, 'name': "McMillicancuddy's Barn"}, {'id': 139, 'name': 'The Junkyard'}, {'id': 140, 'name': 'The Battlefield (In War Hippy Fatigues)'}, {'id': 141, 'name': 'The Pond'}, {'id': 142, 'name': 'The Back 40'}, {'id': 143, 'name': 'The Other Back 40'}, {'id': 144, 'name': 'The Granary'}, {'id': 145, 'name': 'The Bog'}, {'id': 146, 'name': 'The Family Plot'}, {'id': 147, 'name': 'The Shady Thicket'}, {'id': 148, 'name': "Heartbreaker's Hotel"}, {'id': 149, 'name': 'The Hippy Camp (Bombed Back to the Stone Age)'}, {'id': 150, 'name': 'The Orcish Frat House (Bombed Back to the Stone Age)'}, {'id': 151, 'name': 'The Stately Pleasure Dome'}, {'id': 152, 'name': 'The Mouldering Mansion'}, {'id': 153, 'name': 'The Rogue Windmill'}, {'id': 154, 'name': 'The Junkyard (Post-War)'}, {'id': 155, 'name': "McMillicancuddy's Farm (Post-War)"}, {'id': 156, 'name': 'The Grim Grimacite Site'}, {'id': 157, 'name': "Barrrney's Barrr"}, {'id': 158, 'name': "The F'c'le"}, {'id': 159, 'name': 'The Poop Deck'}, {'id': 160, 'name': 'Belowdecks'}, {'id': 161, 'name': 'A Sinister Dodecahedron'}, {'id': 162, 'name': 'Crimbo Town Toy Factory (2007)'}, {'id': 163, 'name': 'A Yuletide Bonfire'}, {'id': 164, 'name': 'A Shimmering Portal'}, {'id': 166, 'name': 'A Maze of Sewer Tunnels'}, {'id': 167, 'name': 'Hobopolis Town Square'}, {'id': 168, 'name': 'Burnbarrel Blvd.'}, {'id': 169, 'name': 'Exposure Esplanade'}, {'id': 170, 'name': 'The Heap'}, {'id': 171, 'name': 'The Ancient Hobo Burial Ground'}, {'id': 172, 'name': 'The Purple Light District'}, {'id': 173, 'name': 'Go for a Swim'}, {'id': 174, 'name': 'The Arrrboretum'}, {'id': 175, 'name': 'The Spectral Salad Factory'}, {'id': 177, 'name': 'Mt. Molehill'}, {'id': 178, 'name': 'Wine Racks (Northwest)'}, {'id': 179, 'name': 'Wine Racks (Northeast)'}, {'id': 180, 'name': 'Wine Racks (Southwest)'}, {'id': 181, 'name': 'Wine Racks (Southeast)'}, {'id': 182, 'name': 'Next to that Barrel with Something Burning in it'}, {'id': 183, 'name': 'Near an Abandoned Refrigerator'}, {'id': 184, 'name': 'Over Where the Old Tires Are'}, {'id': 185, 'name': 'Out By that Rusted-Out Car'}] |
class Solution:
def amendSentence(self, s):
# code here
ans = ""
string = ""
for i in range(len(s)):
if 97 <= ord(s[i]) <= 122:
string += s[i]
else:
if string:
ans += string
ans += " "
string = ""
string += s[i].lower()
ans += string
return ans
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int(input())
for _ in range(t):
s = input()
solObj = Solution()
print(solObj.amendSentence(s))
# } Driver Code Ends
| class Solution:
def amend_sentence(self, s):
ans = ''
string = ''
for i in range(len(s)):
if 97 <= ord(s[i]) <= 122:
string += s[i]
else:
if string:
ans += string
ans += ' '
string = ''
string += s[i].lower()
ans += string
return ans
if __name__ == '__main__':
t = int(input())
for _ in range(t):
s = input()
sol_obj = solution()
print(solObj.amendSentence(s)) |
# Copyright (c) 2021 Qualcomm Technologies, Inc.
# All Rights Reserved.
def _tb_advance_global_step(module):
if hasattr(module, 'global_step'):
module.global_step += 1
return module
def _tb_advance_token_counters(module, tensor, verbose=False):
token_count = getattr(module, 'tb_token_count', None)
if token_count is not None:
T = tensor.size(1)
if token_count.last != T:
if token_count.last != 0:
token_count.total += token_count.last
token_count.sample_idx += 1
token_count.last = T
if verbose:
print(f'>>> T={T}\tlast_T={token_count.last}\tcumsum_T={token_count.total}')
return module
def _tb_hist(module, tensor, name, verbose=False):
hist_kw = dict(bins='auto')
tb_writer = getattr(module, 'tb_writer', None)
if tb_writer is not None:
if module.layer_idx == module.num_layers - 1:
tensor = tensor[:, 0]
# per-tensor
layer_s = str(1 + module.layer_idx).zfill(2)
full_name = f'{layer_s}/layer/{name}'
global_step = module.global_step
if verbose:
stats = f'min={tensor.min():.1f}, max={tensor.max():.1f}'
info = (
f'TB logging {full_name}\t{tuple(tensor.size())}\t({stats})\t'
f'[global_step={global_step}] ...'
)
print(info)
tb_writer.add_histogram(full_name, tensor, global_step=global_step, **hist_kw)
# per-token
sample_idx_s = str(module.tb_token_count.sample_idx + 1).zfill(2)
T = tensor.size(1)
full_name = f'{layer_s}/token/{sample_idx_s}/{name}'
for i in range(T):
tb_writer.add_histogram(full_name, tensor[0, i], global_step=i, **hist_kw)
| def _tb_advance_global_step(module):
if hasattr(module, 'global_step'):
module.global_step += 1
return module
def _tb_advance_token_counters(module, tensor, verbose=False):
token_count = getattr(module, 'tb_token_count', None)
if token_count is not None:
t = tensor.size(1)
if token_count.last != T:
if token_count.last != 0:
token_count.total += token_count.last
token_count.sample_idx += 1
token_count.last = T
if verbose:
print(f'>>> T={T}\tlast_T={token_count.last}\tcumsum_T={token_count.total}')
return module
def _tb_hist(module, tensor, name, verbose=False):
hist_kw = dict(bins='auto')
tb_writer = getattr(module, 'tb_writer', None)
if tb_writer is not None:
if module.layer_idx == module.num_layers - 1:
tensor = tensor[:, 0]
layer_s = str(1 + module.layer_idx).zfill(2)
full_name = f'{layer_s}/layer/{name}'
global_step = module.global_step
if verbose:
stats = f'min={tensor.min():.1f}, max={tensor.max():.1f}'
info = f'TB logging {full_name}\t{tuple(tensor.size())}\t({stats})\t[global_step={global_step}] ...'
print(info)
tb_writer.add_histogram(full_name, tensor, global_step=global_step, **hist_kw)
sample_idx_s = str(module.tb_token_count.sample_idx + 1).zfill(2)
t = tensor.size(1)
full_name = f'{layer_s}/token/{sample_idx_s}/{name}'
for i in range(T):
tb_writer.add_histogram(full_name, tensor[0, i], global_step=i, **hist_kw) |
def getMapCommon():
common = """SYMBOLSET "./etc/symbols.sym"
FONTSET "./etc/fonts/fonts.list"
IMAGETYPE "png"
"""
return common
def getPng():
output = """OUTPUTFORMAT
NAME "png"
DRIVER "AGG/PNG"
MIMETYPE "image/png"
IMAGEMODE RGB
EXTENSION "png"
END\n"""
return output
def getGif():
output = """OUTPUTFORMAT
NAME "gif"
DRIVER "GD/GIF"
MIMETYPE "image/gif"
IMAGEMODE PC256
EXTENSION "gif"
END\n"""
return output
def getJpeg():
output = """OUTPUTFORMAT
NAME "jpeg"
DRIVER "AGG/JPEG"
MIMETYPE "image/jpeg"
IMAGEMODE RGB
EXTENSION "jpg"
END\n"""
return output
def getScale():
scale = """SCALEBAR
STATUS OFF
UNITS KILOMETERS
INTERVALS 3
TRANSPARENT TRUE
OUTLINECOLOR 0 0 0
END\n"""
return scale
def getLegend():
legend = """LEGEND
STATUS ON
LABEL
COLOR 51 51 51
FONT verdana # font needs to be inside fonts.list
TYPE TRUETYPE
SIZE 8
END
KEYSIZE 24 16
END\n"""
return legend
def getSize(x = 2048, y = 2048):
size = 'SIZE {x} {y}'.format(x=str(x), y=str(y))
return size
def getUnits():
units = 'UNITS METERS'
return units
def getExtent(ext):
extent = 'EXTENT {xmin} {ymin} {xmax} {ymax}'.format(xmin=ext[0], ymin=ext[1], xmax=ext[2], ymax=ext[3])
return extent
def getProjection(epsg):
projection = """PROJECTION
"init=epsg:{epsg}"
END""".format(epsg=epsg)
return projection
def getWeb(title, abstract, keywords):
web = """WEB
IMAGEPATH "/tmp/"
IMAGEURL "/tmp/"
METADATA
"wms_title" "GOV Canada - {title}"
"wms_abstract" "{abstract}"
"wms_server_version" "1.1.1"
"wms_enable_request" "GetCapabilities GetMap GetFeatureInfo GetLegendGraphic"
"wms_formatlist" "image/png,image/gif,image/jpeg"
"wms_format" "image/png"
"wms_feature_info_mime_type" "text/html"
"wms_keywordlist" "Canada,Map,Carte,NRCan,RNCan,Natural Resources Canada,Ressources naturelles Canada,{keywords}"
INCLUDE "./etc/projections.inc"
INCLUDE "./etc/service_metadata_en.inc"
END # metadata
END # web""".format(title=title, abstract=abstract, keywords=keywords)
return web
def getLayerMetadata(name, projection):
meta = """METADATA
"wms_title" "{name}"
"wms_srs" "EPSG:{projection}"
"wms_enable_request" "GetCapabilities GetMap GetFeatureInfo GetLegendGraphic"
END # metadata""".format(name=name, projection=projection)
return meta
def getLayerGeometry(fieldsNode):
poly = False
line = False
if fieldsNode != None:
for elem in fieldsNode:
fieldName = elem.find('./FieldName').text
if 'SHAPE_LENGTH' == fieldName.upper():
line = True
elif 'SHAPE_AREA' == fieldName.upper():
poly = True
if poly:
geom = 'Polygon'
elif line:
geom = 'Line'
else:
# if there is no field description we assume it is a point layer
# TODO: validate the assumption
geom = 'Point'
return geom
def getSeparator():
return '# --------------------------------------------------------------' | def get_map_common():
common = 'SYMBOLSET "./etc/symbols.sym"\n FONTSET "./etc/fonts/fonts.list"\n IMAGETYPE "png"\n '
return common
def get_png():
output = 'OUTPUTFORMAT\n NAME "png"\n DRIVER "AGG/PNG"\n MIMETYPE "image/png"\n IMAGEMODE RGB\n EXTENSION "png"\n END\n'
return output
def get_gif():
output = 'OUTPUTFORMAT\n NAME "gif"\n DRIVER "GD/GIF"\n MIMETYPE "image/gif"\n IMAGEMODE PC256\n EXTENSION "gif"\n END\n'
return output
def get_jpeg():
output = 'OUTPUTFORMAT\n NAME "jpeg"\n DRIVER "AGG/JPEG"\n MIMETYPE "image/jpeg"\n IMAGEMODE RGB\n EXTENSION "jpg"\n END\n'
return output
def get_scale():
scale = 'SCALEBAR\n STATUS OFF\n UNITS KILOMETERS\n INTERVALS 3\n TRANSPARENT TRUE\n OUTLINECOLOR 0 0 0\n END\n'
return scale
def get_legend():
legend = 'LEGEND\n STATUS ON\n LABEL\n COLOR 51 51 51\n FONT verdana # font needs to be inside fonts.list\n TYPE TRUETYPE\n SIZE 8\n END\n KEYSIZE 24 16\n END\n'
return legend
def get_size(x=2048, y=2048):
size = 'SIZE {x} {y}'.format(x=str(x), y=str(y))
return size
def get_units():
units = 'UNITS METERS'
return units
def get_extent(ext):
extent = 'EXTENT {xmin} {ymin} {xmax} {ymax}'.format(xmin=ext[0], ymin=ext[1], xmax=ext[2], ymax=ext[3])
return extent
def get_projection(epsg):
projection = 'PROJECTION\n "init=epsg:{epsg}"\n END'.format(epsg=epsg)
return projection
def get_web(title, abstract, keywords):
web = 'WEB\n IMAGEPATH "/tmp/"\n IMAGEURL "/tmp/"\n METADATA\n "wms_title" "GOV Canada - {title}"\n "wms_abstract" "{abstract}"\n "wms_server_version" "1.1.1"\n "wms_enable_request" "GetCapabilities GetMap GetFeatureInfo GetLegendGraphic"\n "wms_formatlist" "image/png,image/gif,image/jpeg"\n "wms_format" "image/png"\n "wms_feature_info_mime_type" "text/html"\n "wms_keywordlist" "Canada,Map,Carte,NRCan,RNCan,Natural Resources Canada,Ressources naturelles Canada,{keywords}"\n INCLUDE "./etc/projections.inc"\n INCLUDE "./etc/service_metadata_en.inc"\n END # metadata\n END # web'.format(title=title, abstract=abstract, keywords=keywords)
return web
def get_layer_metadata(name, projection):
meta = 'METADATA\n "wms_title" "{name}"\n "wms_srs" "EPSG:{projection}"\n "wms_enable_request" "GetCapabilities GetMap GetFeatureInfo GetLegendGraphic"\n END # metadata'.format(name=name, projection=projection)
return meta
def get_layer_geometry(fieldsNode):
poly = False
line = False
if fieldsNode != None:
for elem in fieldsNode:
field_name = elem.find('./FieldName').text
if 'SHAPE_LENGTH' == fieldName.upper():
line = True
elif 'SHAPE_AREA' == fieldName.upper():
poly = True
if poly:
geom = 'Polygon'
elif line:
geom = 'Line'
else:
geom = 'Point'
return geom
def get_separator():
return '# --------------------------------------------------------------' |
# -*- coding: utf-8 -*-
"""SDP Tango Master Release info."""
__subsystem__ = 'TangoControl'
__service_name__ = 'SDPMaster'
__version_info__ = (0, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
__service_id__ = ':'.join(map(str, (__subsystem__,
__service_name__,
__version__)))
__all__ = [
'__subsystem__',
'__service_name__',
'__version__',
'__service_id__',
]
| """SDP Tango Master Release info."""
__subsystem__ = 'TangoControl'
__service_name__ = 'SDPMaster'
__version_info__ = (0, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
__service_id__ = ':'.join(map(str, (__subsystem__, __service_name__, __version__)))
__all__ = ['__subsystem__', '__service_name__', '__version__', '__service_id__'] |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 10 15:18:19 2021
@author: qizhe
"""
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 1:
return n
pre = 1
cur = 2
for _ in range(2,n):
cur, pre = cur + pre, cur
return cur
if __name__ == '__main__':
solu = Solution()
input_Str = str('hello')
# input_list =
input_List = [5,1,5]
input_Num = 5
# for i in input_List:
result = solu.climbStairs(input_Num)
# output_Str = 'result = ' + solu.intToRoman(input_int)
output_Str = ' result = ' + str(result)
print(output_Str) | """
Created on Fri Sep 10 15:18:19 2021
@author: qizhe
"""
class Solution:
def climb_stairs(self, n: int) -> int:
if n <= 1:
return n
pre = 1
cur = 2
for _ in range(2, n):
(cur, pre) = (cur + pre, cur)
return cur
if __name__ == '__main__':
solu = solution()
input__str = str('hello')
input__list = [5, 1, 5]
input__num = 5
result = solu.climbStairs(input_Num)
output__str = ' result = ' + str(result)
print(output_Str) |
class ExpressionReader:
priorityComparision = ['=']
andOrComparision = ['OR']
operations = []
operations.extend(priorityComparision)
operations.extend(andOrComparision)
def read(expression):
lst = ExpressionReader.__split(expression)
#lst = ExpressionReader.__parsePriorityExpression(lst, ExpressionReader.priorityComparision)
#lst = ExpressionReader.__parseExpression(lst)
return lst
def __split(expression):
lst = []
chars = ''
acceptSpace = False
for char in expression:
if char == '(' or char == ')':
if chars != '':
lst.append(chars)
chars = ''
lst.append(char)
continue
if char == '\'' or char == '\"':
acceptSpace = not acceptSpace
if char == ' ' and acceptSpace == False:
if chars != '':
lst.append(chars)
chars = ''
continue
else:
chars = chars + char
if chars != '':
lst.append(chars)
return lst
def __parsePriorityExpression(lst, operations):
newLst = []
for i in range(0, len(lst) - 1):
if lst[i] in operations:
arguments = []
arguments.append(lst[i-1])
operation = lst[i]
arguments.append(lst[i+1])
dataDriven = ExpressionReader.toDataDrivenStyle(operation, arguments)
if dataDriven is None:
return None
newLst.append(dataDriven)
elif lst[i] in ExpressionReader.operations:
newLst.append(lst[i])
return newLst
def __parseExpression(lst):
if lst is None:
return None
while len(lst) > 1:
arguments = []
arguments.append(lst.pop(0))
operation = lst.pop(0)
arguments.append(lst.pop(0))
dataDriven = ExpressionReader.toDataDrivenStyle(operation, arguments)
if dataDriven is None:
return None
lst.insert(0, dataDriven)
return lst
def toDataDrivenStyle(operation, arguments):
if operation == '=':
return '[\"==\",[\"get\",\"' + arguments[0] + '\"],' + arguments[1] + ']'
if operation == 'OR':
return '[\"any\",' + arguments[0] + ',' + arguments[1] + ']'
return None
# subset = 'loaiDatHT = \'CAN\' OR loaiDatHT = \'COC\' OR loaiDatHT = \'CQP\' OR loaiDatHT = \'DBV\' OR loaiDatHT = \'DCK\' OR loaiDatHT = \'DCH\' OR loaiDatHT = \'DDT\' OR loaiDatHT = \'DGD\' OR loaiDatHT = \'DKH\' OR loaiDatHT = \'DNL\' OR loaiDatHT = \'DSH\' OR loaiDatHT = \'DSN\' OR loaiDatHT = \'DTS\' OR loaiDatHT = \'DTT\' OR loaiDatHT = \'DVH\' OR loaiDatHT = \'DXH\' OR loaiDatHT = \'DYT\' OR loaiDatHT = \'SKC\' OR loaiDatHT = \'SKK\' OR loaiDatHT = \'SKN\' OR loaiDatHT = \'SKX\' OR loaiDatHT = \'TIN\' OR loaiDatHT = \'TMD\' OR loaiDatHT = \'TON\' OR loaiDatHT = \'TSC\' OR loaiDatHT = \'TSN\' OR loaiDatHT = \'SKX\' OR loaiDatHT = \'DRA\' OR loaiDatHT = \'NTD\''
# print(ExpressionReader.read(subset))
testIn = '\"loaiDatHT\" in (\'DGT\')'
print(ExpressionReader.read(testIn)) | class Expressionreader:
priority_comparision = ['=']
and_or_comparision = ['OR']
operations = []
operations.extend(priorityComparision)
operations.extend(andOrComparision)
def read(expression):
lst = ExpressionReader.__split(expression)
return lst
def __split(expression):
lst = []
chars = ''
accept_space = False
for char in expression:
if char == '(' or char == ')':
if chars != '':
lst.append(chars)
chars = ''
lst.append(char)
continue
if char == "'" or char == '"':
accept_space = not acceptSpace
if char == ' ' and acceptSpace == False:
if chars != '':
lst.append(chars)
chars = ''
continue
else:
chars = chars + char
if chars != '':
lst.append(chars)
return lst
def __parse_priority_expression(lst, operations):
new_lst = []
for i in range(0, len(lst) - 1):
if lst[i] in operations:
arguments = []
arguments.append(lst[i - 1])
operation = lst[i]
arguments.append(lst[i + 1])
data_driven = ExpressionReader.toDataDrivenStyle(operation, arguments)
if dataDriven is None:
return None
newLst.append(dataDriven)
elif lst[i] in ExpressionReader.operations:
newLst.append(lst[i])
return newLst
def __parse_expression(lst):
if lst is None:
return None
while len(lst) > 1:
arguments = []
arguments.append(lst.pop(0))
operation = lst.pop(0)
arguments.append(lst.pop(0))
data_driven = ExpressionReader.toDataDrivenStyle(operation, arguments)
if dataDriven is None:
return None
lst.insert(0, dataDriven)
return lst
def to_data_driven_style(operation, arguments):
if operation == '=':
return '["==",["get","' + arguments[0] + '"],' + arguments[1] + ']'
if operation == 'OR':
return '["any",' + arguments[0] + ',' + arguments[1] + ']'
return None
test_in = '"loaiDatHT" in (\'DGT\')'
print(ExpressionReader.read(testIn)) |
'''A large FizzBuzz as an output using small FizzBuzz numbers.(FizzBuzz=FizBuz for better alignment
and make sure your output terminal covers the entire length of the screen to avoid automatic newlines)'''
# Author: @AmanMatrix
def iCheck(i):
if i%15==0:
i='FizBuz'
elif i%3==0:
i='Fizz'
elif i%5==0:
i='Buzz'
else:i=i
return i
for i in range(1,101):
if(i==1):
print("\n",iCheck(i),end=" ")
elif(i<=5):
print(iCheck(i),end=" ")
elif(i==6):
print(" ",iCheck(i),end=" ")
elif(i<=9):
print(iCheck(i),end=" ")
elif(i==10):
print(f"\n {iCheck(i)}",end=" ")
elif(i<=12):
print(iCheck(i),end="")
elif(i==13):
print(" ",iCheck(i),end=" ")
elif(i==14):
print(iCheck(i))
elif(i==15):
print(iCheck(i),end=" ")
elif(i==16):
print(iCheck(i),end=" ")
elif(i<=18):
print(iCheck(i),end=" ")
elif(i==19):
print(f"\n {iCheck(i)}",end=" ")
elif(i<=21):
print(iCheck(i),end=" ")
elif(i==22):
print(f"\n {iCheck(i)}",end=" ")
elif(i<=25):
print(iCheck(i),end=" ")
elif(i==26):
print(" ",iCheck(i),end="")
elif(i<=27):
print(iCheck(i),end=" ")
elif(i==28):
print(iCheck(i),end=" ")
elif(i<=30):
print(iCheck(i),end=" ")
elif(i==31):
print(" ",iCheck(i),end=" ")
elif(i<=33):
print(iCheck(i),end=" ")
elif(i==34):
print(" ",iCheck(i),end=" ")
elif(i<=36):
print(iCheck(i),end="")
elif(i<=37):
print(" ",iCheck(i),end="")
elif(i<=38):
print(" ",iCheck(i),end="")
elif(i==39):
print(" ",iCheck(i),end=" ")
elif(i<=41):
print(iCheck(i),end=" ")
elif(i==42):
print(" ",iCheck(i),end=" ")
elif(i<=44):
print(iCheck(i),end=" ")
elif(i==45):
print(f"\n{iCheck(i)}",end=" ")
elif(i<=47):
print(iCheck(i),end=" ")
elif(i<=49):
print(" ",iCheck(i),end=" ")
elif(i==50):
print(" ",iCheck(i),end=" ")
elif(i==51):
print(" ",iCheck(i),end=" ")
elif(i==52):
print(iCheck(i),end=" ")
elif(i==53):
print(iCheck(i),end=" ")
elif(i<=55):
print(iCheck(i),end=" ")
elif(i==56):
print(f"\n {iCheck(i)}",end=" ")
elif(i<=58):
print(iCheck(i),end="")
elif(i<=60):
print(" ",iCheck(i),end=" ")
elif(i<=61):
print(" ",iCheck(i),end=" ")
elif(i<=62):
print(iCheck(i),end=" ")
elif(i<=64):
print(iCheck(i),end=" ")
elif(i<=66):
print(iCheck(i),end=" ")
elif(i<=67):
print(f"\n {iCheck(i)}",end=" ")
elif(i<=69):
print(iCheck(i),end="")
elif(i<=71):
print(" ",iCheck(i),end=" ")
elif(i<=72):
print(" ",iCheck(i),end=" ")
elif(i<=73):
print(iCheck(i),end=" ")
elif(i<=74):
print(iCheck(i),end=" ")
elif(i<=75):
print(iCheck(i),end=" ")
elif(i<=76):
print(iCheck(i),end=" ")
elif(i<=77):
print(iCheck(i),end=" ")
elif(i<=78):
print(f"\n {iCheck(i)}",end=" ")
elif(i<=80):
print(iCheck(i),end="")
elif(i==81):
print(" ",iCheck(i),end=" ")
elif(i<=83):
print("",iCheck(i),end="")
elif(i<=84):
print(" ",iCheck(i),end=" ")
elif(i<=86):
print(iCheck(i),end="")
elif(i<=87):
print(" ",iCheck(i),end=" ")
elif(i<=89):
print(iCheck(i),end=" ")
elif(i<=90):
print(" ",iCheck(i),end="")
elif(i<=92):
print(iCheck(i),end="")
elif(i<=93):
print(" ",iCheck(i),end="")
elif(i<=95):
print("",iCheck(i),end="")
elif(i<=96):
print(" ",iCheck(i),end="")
elif(i<=99):
print(iCheck(i),end="")
else:
print(" ",iCheck(i)) | """A large FizzBuzz as an output using small FizzBuzz numbers.(FizzBuzz=FizBuz for better alignment
and make sure your output terminal covers the entire length of the screen to avoid automatic newlines)"""
def i_check(i):
if i % 15 == 0:
i = 'FizBuz'
elif i % 3 == 0:
i = 'Fizz'
elif i % 5 == 0:
i = 'Buzz'
else:
i = i
return i
for i in range(1, 101):
if i == 1:
print('\n', i_check(i), end=' ')
elif i <= 5:
print(i_check(i), end=' ')
elif i == 6:
print(' ', i_check(i), end=' ')
elif i <= 9:
print(i_check(i), end=' ')
elif i == 10:
print(f'\n {i_check(i)}', end=' ')
elif i <= 12:
print(i_check(i), end='')
elif i == 13:
print(' ', i_check(i), end=' ')
elif i == 14:
print(i_check(i))
elif i == 15:
print(i_check(i), end=' ')
elif i == 16:
print(i_check(i), end=' ')
elif i <= 18:
print(i_check(i), end=' ')
elif i == 19:
print(f'\n {i_check(i)}', end=' ')
elif i <= 21:
print(i_check(i), end=' ')
elif i == 22:
print(f'\n {i_check(i)}', end=' ')
elif i <= 25:
print(i_check(i), end=' ')
elif i == 26:
print(' ', i_check(i), end='')
elif i <= 27:
print(i_check(i), end=' ')
elif i == 28:
print(i_check(i), end=' ')
elif i <= 30:
print(i_check(i), end=' ')
elif i == 31:
print(' ', i_check(i), end=' ')
elif i <= 33:
print(i_check(i), end=' ')
elif i == 34:
print(' ', i_check(i), end=' ')
elif i <= 36:
print(i_check(i), end='')
elif i <= 37:
print(' ', i_check(i), end='')
elif i <= 38:
print(' ', i_check(i), end='')
elif i == 39:
print(' ', i_check(i), end=' ')
elif i <= 41:
print(i_check(i), end=' ')
elif i == 42:
print(' ', i_check(i), end=' ')
elif i <= 44:
print(i_check(i), end=' ')
elif i == 45:
print(f'\n{i_check(i)}', end=' ')
elif i <= 47:
print(i_check(i), end=' ')
elif i <= 49:
print(' ', i_check(i), end=' ')
elif i == 50:
print(' ', i_check(i), end=' ')
elif i == 51:
print(' ', i_check(i), end=' ')
elif i == 52:
print(i_check(i), end=' ')
elif i == 53:
print(i_check(i), end=' ')
elif i <= 55:
print(i_check(i), end=' ')
elif i == 56:
print(f'\n {i_check(i)}', end=' ')
elif i <= 58:
print(i_check(i), end='')
elif i <= 60:
print(' ', i_check(i), end=' ')
elif i <= 61:
print(' ', i_check(i), end=' ')
elif i <= 62:
print(i_check(i), end=' ')
elif i <= 64:
print(i_check(i), end=' ')
elif i <= 66:
print(i_check(i), end=' ')
elif i <= 67:
print(f'\n {i_check(i)}', end=' ')
elif i <= 69:
print(i_check(i), end='')
elif i <= 71:
print(' ', i_check(i), end=' ')
elif i <= 72:
print(' ', i_check(i), end=' ')
elif i <= 73:
print(i_check(i), end=' ')
elif i <= 74:
print(i_check(i), end=' ')
elif i <= 75:
print(i_check(i), end=' ')
elif i <= 76:
print(i_check(i), end=' ')
elif i <= 77:
print(i_check(i), end=' ')
elif i <= 78:
print(f'\n {i_check(i)}', end=' ')
elif i <= 80:
print(i_check(i), end='')
elif i == 81:
print(' ', i_check(i), end=' ')
elif i <= 83:
print('', i_check(i), end='')
elif i <= 84:
print(' ', i_check(i), end=' ')
elif i <= 86:
print(i_check(i), end='')
elif i <= 87:
print(' ', i_check(i), end=' ')
elif i <= 89:
print(i_check(i), end=' ')
elif i <= 90:
print(' ', i_check(i), end='')
elif i <= 92:
print(i_check(i), end='')
elif i <= 93:
print(' ', i_check(i), end='')
elif i <= 95:
print('', i_check(i), end='')
elif i <= 96:
print(' ', i_check(i), end='')
elif i <= 99:
print(i_check(i), end='')
else:
print(' ', i_check(i)) |
i = 1.0
print(i)
print("Hello world!")
print(type(i))
a = "Hello"
print(type(a))
# print(a+i) <-Error!
a += "world!"
print(a)
print("this is string: {}, {}".format(3, "ala bala"))
print("pi = %f" % 3.14)
| i = 1.0
print(i)
print('Hello world!')
print(type(i))
a = 'Hello'
print(type(a))
a += 'world!'
print(a)
print('this is string: {}, {}'.format(3, 'ala bala'))
print('pi = %f' % 3.14) |
MACHINE_A = 'MachineA'
MACHINE_B = 'MachineB'
INIT = 'Init'
E_STOP = 'stop'
E_INCREASE = 'increase'
E_DECREASE = 'decrease'
| machine_a = 'MachineA'
machine_b = 'MachineB'
init = 'Init'
e_stop = 'stop'
e_increase = 'increase'
e_decrease = 'decrease' |
#=============================================================================
## Automatic Repository Version Generation Utility
## Author: Zhenyu Wu
## Revision 1: Apr 28. 2016 - Initial Implementation
#=============================================================================
__all__ = [ 'VersionLint' ]
| __all__ = ['VersionLint'] |
def fun(f): #string
# Some functions need zero or more
# arguements then we have to use
# *args & **kwargs
def wrapper(*args, **kwargs):
print("Start")
#print(string)
# to return the values that are passed
values = f(*args, **kwargs)
print("End")
return values
# return the wrapper function being called use --> ()
#return wrapper()
return wrapper
@fun
def fun2(x):
print("Funtion 2")
return x
@fun
def fun3():
print("Function 3")
### x = fun(fun2)
##fun(fun2)
##print()
##fun(fun3)
##fun2 = fun(fun2)
##fun3 = fun(fun3)
A = fun2('a')
print()
print(A)
print()
fun3()
| def fun(f):
def wrapper(*args, **kwargs):
print('Start')
values = f(*args, **kwargs)
print('End')
return values
return wrapper
@fun
def fun2(x):
print('Funtion 2')
return x
@fun
def fun3():
print('Function 3')
a = fun2('a')
print()
print(A)
print()
fun3() |
symbols = [
'TSLA',
'GOOG',
'FB',
'NFLX',
'PFE',
'KO',
'AAPL',
'MSFT',
'DIS',
'UBER',
'AMZN',
'TWTR',
'SBUX',
'F',
'XOM',
'GFINBURO.MX',
'BIMBOA.MX',
'GFNORTEO.MX',
'TLEVISACPO.MX',
'AZTECACPO.MX',
'ALSEA.MX',
'ORBIA.MX',
'POSADASA.MX',
'VOLARA.MX',
'LIVEPOLC-1.MX',
'AEROMEX.MX',
'WALMEX.MX',
'PE&OLES.MX',
'BBVA.MX',
'GAPB.MX',
] | symbols = ['TSLA', 'GOOG', 'FB', 'NFLX', 'PFE', 'KO', 'AAPL', 'MSFT', 'DIS', 'UBER', 'AMZN', 'TWTR', 'SBUX', 'F', 'XOM', 'GFINBURO.MX', 'BIMBOA.MX', 'GFNORTEO.MX', 'TLEVISACPO.MX', 'AZTECACPO.MX', 'ALSEA.MX', 'ORBIA.MX', 'POSADASA.MX', 'VOLARA.MX', 'LIVEPOLC-1.MX', 'AEROMEX.MX', 'WALMEX.MX', 'PE&OLES.MX', 'BBVA.MX', 'GAPB.MX'] |
# ADD BINARY LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def addBinary(self, a, b):
# using the 'bin' function to convert each integer into its binary format.
sum = bin(int(a, 2) + int(b, 2))
# returning the value of the sum, while truncating the '0b' prefix.
return sum[2:] | class Solution(object):
def add_binary(self, a, b):
sum = bin(int(a, 2) + int(b, 2))
return sum[2:] |
mywords = ['Krishna', 'Rameshwar Dass', 'Usha', 'Ramesh']
for w in mywords:
print(w, end='')
#Krishna Rameshwar Dass Usha Ramesh | mywords = ['Krishna', 'Rameshwar Dass', 'Usha', 'Ramesh']
for w in mywords:
print(w, end='') |
#!/usr/bin/env python3
SQL92_reserved = [
"ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG",
"BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY",
"CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHAR_LENGTH", "CHARACTER_LENGTH", "CHECK", "CLOSE", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONNECT", "CONNECTION", "CONSTRAINT", "CONSTRAINTS", "CONTINUE", "CONVERT", "CORRESPONDING", "COUNT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR",
"DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DESCRIBE", "DESCRIPTOR", "DIAGNOSTICS", "DISCONNECT", "DISTINCT", "DOMAIN", "DOUBLE", "DROP",
"ELSE", "END", "END-EXEC", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS", "EXTERNAL", "EXTRACT",
"FALSE", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN", "FOUND", "FROM", "FULL",
"GET", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP",
"HAVING", "HOUR",
"IDENTITY", "IMMEDIATE", "IN", "INDICATOR", "INITIALLY", "INNER", "INPUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "IS", "ISOLATION",
"JOIN",
"KEY",
"LANGUAGE", "LAST", "LEADING", "LEFT", "LEVEL", "LIKE", "LOCAL", "LOWER",
"MATCH", "MAX", "MIN", "MINUTE", "MODULE", "MONTH",
"NAMES", "NATIONAL", "NATURAL", "NCHAR", "NEXT", "NO", "NOT", "NULL", "NULLIF", "NUMERIC",
"OCTET_LENGTH", "OF", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "OUTER", "OUTPUT", "OVERLAPS",
"PAD", "PARTIAL", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES",
"PROCEDURE", "PUBLIC",
"READ", "REAL", "REFERENCES", "RELATIVE", "RESTRICT", "REVOKE", "RIGHT", "ROLLBACK", "ROWS",
"SCHEMA", "SCROLL", "SECOND", "SECTION", "SELECT", "SESSION", "SESSION_USER", "SET", "SIZE", "SMALLINT", "SOME", "SPACE", "SQL", "SQLCODE", "SQLERROR", "SQLSTATE", "SUBSTRING", "SUM", "SYSTEM_USER",
"TABLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TRIM", "TRUE",
"UNION", "UNIQUE", "UNKNOWN",
"UPDATE", "UPPER", "USAGE", "USER", "USING",
"VALUE", "VALUES", "VARCHAR", "VARYING", "VIEW",
"WHEN", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE",
"YEAR",
"ZONE",
]
SQL92_non_reserved = [
"ADA",
"C", "CATALOG_NAME", "CHARACTER_SET_CATALOG", "CHARACTER_SET_NAME", "CHARACTER_SET_SCHEMA", "CLASS_ORIGIN", "COBOL", "COLLATION_CATALOG", "COLLATION_NAME", "COLLATION_SCHEMA", "COLUMN_NAME", "COMMAND_FUNCTION", "COMMITTED", "CONDITION_NUMBER", "CONNECTION_NAME", "CONSTRAINT_CATALOG", "CONSTRAINT_NAME", "CONSTRAINT_SCHEMA", "CURSOR_NAME",
"DATA", "DATETIME_INTERVAL_CODE", "DATETIME_INTERVAL_PRECISION", "DYNAMIC_FUNCTION",
"FORTRAN", "LENGTH",
"MESSAGE_LENGTH", "MESSAGE_OCTET_LENGTH", "MESSAGE_TEXT", "MORE", "MUMPS",
"NAME", "NULLABLE", "NUMBER",
"PASCAL", "PLI",
"REPEATABLE", "RETURNED_LENGTH", "RETURNED_OCTET_LENGTH", "RETURNED_SQLSTATE", "ROW_COUNT",
"SCALE", "SCHEMA_NAME", "SERIALIZABLE", "SERVER_NAME", "SUBCLASS_ORIGIN",
"TABLE_NAME", "TYPE",
"UNCOMMITTED", "UNNAMED",
]
if __name__ == '__main__':
print("\t // Reserved Keyword")
for k in SQL92_reserved:
print("\t KEYWORD_{}_TOKEN = \"{}\"".format(k.replace('-', '_'), k))
print("\n")
print("\t // Non Reserved Keyword\n")
for k in SQL92_non_reserved:
print("\t KEYWORD_{}_TOKEN = \"{}\"".format(k.replace('-', '_'), k))
print("\n")
print("---------")
print("\n")
for k in SQL92_reserved:
print("\t \"{}\": KEYWORD_{}_TOKEN,".format(k, k.replace('-', '_')))
print("\n")
print("---------")
print("\n")
for k in SQL92_non_reserved:
print("\t \"{}\": KEYWORD_{}_TOKEN,".format(k, k.replace('-', '_')))
print()
print("\n")
print("---------")
print("\n")
for k in SQL92_reserved:
print("{{\"{}\", token.KEYWORD_{}_TOKEN, \"{}\"}}, ".format(k, k.replace('-', '_'), k))
for k in SQL92_non_reserved:
print("{{\"{}\", token.KEYWORD_{}_TOKEN, \"{}\"}}, ".format(k, k.replace('-', '_'), k))
print()
| sql92_reserved = ['ABSOLUTE', 'ACTION', 'ADD', 'ALL', 'ALLOCATE', 'ALTER', 'AND', 'ANY', 'ARE', 'AS', 'ASC', 'ASSERTION', 'AT', 'AUTHORIZATION', 'AVG', 'BEGIN', 'BETWEEN', 'BIT', 'BIT_LENGTH', 'BOTH', 'BY', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CHAR', 'CHARACTER', 'CHAR_LENGTH', 'CHARACTER_LENGTH', 'CHECK', 'CLOSE', 'COALESCE', 'COLLATE', 'COLLATION', 'COLUMN', 'COMMIT', 'CONNECT', 'CONNECTION', 'CONSTRAINT', 'CONSTRAINTS', 'CONTINUE', 'CONVERT', 'CORRESPONDING', 'COUNT', 'CREATE', 'CROSS', 'CURRENT', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATE', 'DAY', 'DEALLOCATE', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DELETE', 'DESC', 'DESCRIBE', 'DESCRIPTOR', 'DIAGNOSTICS', 'DISCONNECT', 'DISTINCT', 'DOMAIN', 'DOUBLE', 'DROP', 'ELSE', 'END', 'END-EXEC', 'ESCAPE', 'EXCEPT', 'EXCEPTION', 'EXEC', 'EXECUTE', 'EXISTS', 'EXTERNAL', 'EXTRACT', 'FALSE', 'FETCH', 'FIRST', 'FLOAT', 'FOR', 'FOREIGN', 'FOUND', 'FROM', 'FULL', 'GET', 'GLOBAL', 'GO', 'GOTO', 'GRANT', 'GROUP', 'HAVING', 'HOUR', 'IDENTITY', 'IMMEDIATE', 'IN', 'INDICATOR', 'INITIALLY', 'INNER', 'INPUT', 'INSENSITIVE', 'INSERT', 'INT', 'INTEGER', 'INTERSECT', 'INTERVAL', 'INTO', 'IS', 'ISOLATION', 'JOIN', 'KEY', 'LANGUAGE', 'LAST', 'LEADING', 'LEFT', 'LEVEL', 'LIKE', 'LOCAL', 'LOWER', 'MATCH', 'MAX', 'MIN', 'MINUTE', 'MODULE', 'MONTH', 'NAMES', 'NATIONAL', 'NATURAL', 'NCHAR', 'NEXT', 'NO', 'NOT', 'NULL', 'NULLIF', 'NUMERIC', 'OCTET_LENGTH', 'OF', 'ON', 'ONLY', 'OPEN', 'OPTION', 'OR', 'ORDER', 'OUTER', 'OUTPUT', 'OVERLAPS', 'PAD', 'PARTIAL', 'POSITION', 'PRECISION', 'PREPARE', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVILEGES', 'PROCEDURE', 'PUBLIC', 'READ', 'REAL', 'REFERENCES', 'RELATIVE', 'RESTRICT', 'REVOKE', 'RIGHT', 'ROLLBACK', 'ROWS', 'SCHEMA', 'SCROLL', 'SECOND', 'SECTION', 'SELECT', 'SESSION', 'SESSION_USER', 'SET', 'SIZE', 'SMALLINT', 'SOME', 'SPACE', 'SQL', 'SQLCODE', 'SQLERROR', 'SQLSTATE', 'SUBSTRING', 'SUM', 'SYSTEM_USER', 'TABLE', 'TEMPORARY', 'THEN', 'TIME', 'TIMESTAMP', 'TIMEZONE_HOUR', 'TIMEZONE_MINUTE', 'TO', 'TRAILING', 'TRANSACTION', 'TRANSLATE', 'TRANSLATION', 'TRIM', 'TRUE', 'UNION', 'UNIQUE', 'UNKNOWN', 'UPDATE', 'UPPER', 'USAGE', 'USER', 'USING', 'VALUE', 'VALUES', 'VARCHAR', 'VARYING', 'VIEW', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WORK', 'WRITE', 'YEAR', 'ZONE']
sql92_non_reserved = ['ADA', 'C', 'CATALOG_NAME', 'CHARACTER_SET_CATALOG', 'CHARACTER_SET_NAME', 'CHARACTER_SET_SCHEMA', 'CLASS_ORIGIN', 'COBOL', 'COLLATION_CATALOG', 'COLLATION_NAME', 'COLLATION_SCHEMA', 'COLUMN_NAME', 'COMMAND_FUNCTION', 'COMMITTED', 'CONDITION_NUMBER', 'CONNECTION_NAME', 'CONSTRAINT_CATALOG', 'CONSTRAINT_NAME', 'CONSTRAINT_SCHEMA', 'CURSOR_NAME', 'DATA', 'DATETIME_INTERVAL_CODE', 'DATETIME_INTERVAL_PRECISION', 'DYNAMIC_FUNCTION', 'FORTRAN', 'LENGTH', 'MESSAGE_LENGTH', 'MESSAGE_OCTET_LENGTH', 'MESSAGE_TEXT', 'MORE', 'MUMPS', 'NAME', 'NULLABLE', 'NUMBER', 'PASCAL', 'PLI', 'REPEATABLE', 'RETURNED_LENGTH', 'RETURNED_OCTET_LENGTH', 'RETURNED_SQLSTATE', 'ROW_COUNT', 'SCALE', 'SCHEMA_NAME', 'SERIALIZABLE', 'SERVER_NAME', 'SUBCLASS_ORIGIN', 'TABLE_NAME', 'TYPE', 'UNCOMMITTED', 'UNNAMED']
if __name__ == '__main__':
print('\t // Reserved Keyword')
for k in SQL92_reserved:
print('\t KEYWORD_{}_TOKEN = "{}"'.format(k.replace('-', '_'), k))
print('\n')
print('\t // Non Reserved Keyword\n')
for k in SQL92_non_reserved:
print('\t KEYWORD_{}_TOKEN = "{}"'.format(k.replace('-', '_'), k))
print('\n')
print('---------')
print('\n')
for k in SQL92_reserved:
print('\t "{}": KEYWORD_{}_TOKEN,'.format(k, k.replace('-', '_')))
print('\n')
print('---------')
print('\n')
for k in SQL92_non_reserved:
print('\t "{}": KEYWORD_{}_TOKEN,'.format(k, k.replace('-', '_')))
print()
print('\n')
print('---------')
print('\n')
for k in SQL92_reserved:
print('{{"{}", token.KEYWORD_{}_TOKEN, "{}"}}, '.format(k, k.replace('-', '_'), k))
for k in SQL92_non_reserved:
print('{{"{}", token.KEYWORD_{}_TOKEN, "{}"}}, '.format(k, k.replace('-', '_'), k))
print() |
def can_build(env, platform):
return True
def configure(env):
pass
def is_enabled():
# Disabled by default being experimental at the moment.
# Enable manually with `module_gdscript_transpiler_enabled=yes` option.
return False
| def can_build(env, platform):
return True
def configure(env):
pass
def is_enabled():
return False |
class PERIOD:
DAILY = "daily"
WEEKLY = "weekly"
MONTHLY = "monthly"
# Converting BYTES to KB, MB, GB
BYTES_TO_KBYTES = 1024
BYTES_TO_MBYTES = 1048576
BYTES_TO_GBYTES = 1073741824
| class Period:
daily = 'daily'
weekly = 'weekly'
monthly = 'monthly'
bytes_to_kbytes = 1024
bytes_to_mbytes = 1048576
bytes_to_gbytes = 1073741824 |
"""
Job initialization.
"""
class Job():
"""
Performs general statistics over the crowdsourcing jobs.
"""
@staticmethod
def aggregate(units, judgments, config):
"""
Aggregates information about the total number of units, total number of judgments,
total number of workers that provided annotations and the total duration of the job.
Args:
units: Units contained in the job.
judgments: Judgments contained in the job.
config: Job configuration as provided as input for the metrics.
Returns:
A dataframe of one row that stores general stats on the crowdsourcing jobs.
"""
agg = {
'unit' : 'nunique',
'judgment' : 'nunique',
'worker' : 'nunique',
'duration' : 'mean'
}
job = judgments.groupby('job').agg(agg)
# compute job runtime
runtime = (max(judgments['submitted']) - min(judgments['started']))
job['runtime'] = runtime #float(runtime.days) * 24 + float(runtime.seconds) / 3600
job['runtime.per_unit'] = job['runtime'] / job['unit']
job['judgments.per.worker'] = job['judgment'] / job['worker']
metrics = ['unique_annotations', 'annotations']
for metric in metrics:
for col in config.output.values():
# aggregate unit metrics
job[col+'.'+metric] = units[col+'.'+metric].mean()
job = job.reindex(sorted(job.columns), axis=1)
return job
| """
Job initialization.
"""
class Job:
"""
Performs general statistics over the crowdsourcing jobs.
"""
@staticmethod
def aggregate(units, judgments, config):
"""
Aggregates information about the total number of units, total number of judgments,
total number of workers that provided annotations and the total duration of the job.
Args:
units: Units contained in the job.
judgments: Judgments contained in the job.
config: Job configuration as provided as input for the metrics.
Returns:
A dataframe of one row that stores general stats on the crowdsourcing jobs.
"""
agg = {'unit': 'nunique', 'judgment': 'nunique', 'worker': 'nunique', 'duration': 'mean'}
job = judgments.groupby('job').agg(agg)
runtime = max(judgments['submitted']) - min(judgments['started'])
job['runtime'] = runtime
job['runtime.per_unit'] = job['runtime'] / job['unit']
job['judgments.per.worker'] = job['judgment'] / job['worker']
metrics = ['unique_annotations', 'annotations']
for metric in metrics:
for col in config.output.values():
job[col + '.' + metric] = units[col + '.' + metric].mean()
job = job.reindex(sorted(job.columns), axis=1)
return job |
class MyClass:
'''This is the docstring for this class'''
def __init__(self):
# setup per-instance variables
self.x = 1
self.y = 2
self.z = 3
class MySecondClass:
'''This is the docstring for this second class'''
def __init__(self):
# setup per-instance variables
self.p = 1
self.d = 2
self.q = 3
| class Myclass:
"""This is the docstring for this class"""
def __init__(self):
self.x = 1
self.y = 2
self.z = 3
class Mysecondclass:
"""This is the docstring for this second class"""
def __init__(self):
self.p = 1
self.d = 2
self.q = 3 |
# coding: utf8
class InvalidUnitToDXAException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Unit(object):
@classmethod
def to_dxa(cls, val):
if len(val) < 2:
return 0
else:
unit = val[-2:]
val = int(val.rstrip(unit))
if val == 0:
return 0
if unit == 'cm':
return cls.cm_to_dxa(val)
elif unit == 'in':
return cls.in_to_dxa(val)
elif unit == 'pt':
return cls.pt_to_dxa(val)
else:
raise InvalidUnitToDXAException("Unit to DXA should be " +
"Centimeters(cm), " +
"Inches(in) or " +
"Points(pt)")
@classmethod
def pixel_to_emu(cls, pixel):
return int(round(pixel * 12700))
@classmethod
def cm_to_dxa(cls, centimeters):
inches = centimeters / 2.54
points = inches * 72
dxa = points * 20
return dxa
@classmethod
def in_to_dxa(cls, inches):
points = inches * 72
dxa = cls.pt_to_dxa(points)
return dxa
@classmethod
def pt_to_dxa(cls, points):
dxa = points * 20
return dxa
| class Invalidunittodxaexception(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Unit(object):
@classmethod
def to_dxa(cls, val):
if len(val) < 2:
return 0
else:
unit = val[-2:]
val = int(val.rstrip(unit))
if val == 0:
return 0
if unit == 'cm':
return cls.cm_to_dxa(val)
elif unit == 'in':
return cls.in_to_dxa(val)
elif unit == 'pt':
return cls.pt_to_dxa(val)
else:
raise invalid_unit_to_dxa_exception('Unit to DXA should be ' + 'Centimeters(cm), ' + 'Inches(in) or ' + 'Points(pt)')
@classmethod
def pixel_to_emu(cls, pixel):
return int(round(pixel * 12700))
@classmethod
def cm_to_dxa(cls, centimeters):
inches = centimeters / 2.54
points = inches * 72
dxa = points * 20
return dxa
@classmethod
def in_to_dxa(cls, inches):
points = inches * 72
dxa = cls.pt_to_dxa(points)
return dxa
@classmethod
def pt_to_dxa(cls, points):
dxa = points * 20
return dxa |
input = """
c num blocks = 1
c num vars = 150
c minblockids[0] = 1
c maxblockids[0] = 150
p cnf 150 617
90 -20 8 0
-111 -68 -13 0
8 -150 -9 0
-66 63 -93 0
-135 40 81 0
106 -127 134 0
-54 123 45 0
24 -77 59 0
-82 48 71 0
12 75 87 0
127 -29 88 0
-120 -33 60 0
-126 -102 31 0
134 9 -150 0
62 -56 -83 0
92 27 75 0
-133 -52 50 0
-20 97 -13 0
65 55 -17 0
74 -77 -123 0
-11 -125 -98 0
-67 -35 -114 0
134 3 51 0
-113 132 101 0
94 -8 52 0
66 -1 -17 0
40 -21 -55 0
144 -125 -117 0
-28 43 -147 0
76 58 12 0
-2 27 103 0
58 125 7 0
-8 74 -15 0
-123 -46 108 0
98 -112 -92 0
-102 -31 -99 0
-3 116 38 0
-104 11 127 0
63 26 72 0
-97 96 -31 0
-136 132 -85 0
-23 32 -29 0
131 39 -75 0
68 -132 -110 0
-133 93 -28 0
41 32 -142 0
-1 81 -21 0
-59 131 12 0
115 -29 62 0
-117 40 73 0
10 -79 -75 0
-81 -8 117 0
130 -136 -21 0
-133 10 -112 0
29 -57 119 0
-130 112 97 0
37 71 69 0
28 -49 -88 0
-123 86 84 0
135 33 111 0
100 48 17 0
137 -47 -66 0
111 96 -93 0
-141 104 -19 0
-31 65 3 0
101 -3 -91 0
55 -123 -36 0
-90 -95 116 0
-79 137 -107 0
-25 68 -105 0
-66 -42 143 0
42 148 60 0
-31 80 -28 0
-10 -5 -126 0
-45 48 23 0
130 -36 96 0
100 65 -47 0
118 -75 18 0
111 -72 -135 0
143 7 -32 0
-45 83 -95 0
-52 -59 71 0
90 -139 -8 0
114 -95 -38 0
75 -12 116 0
26 15 79 0
-51 -50 -27 0
132 13 -147 0
-17 94 -76 0
106 79 121 0
-5 -43 117 0
53 118 51 0
-128 111 -146 0
45 53 77 0
-75 10 60 0
-10 100 99 0
51 -50 150 0
37 121 -127 0
-131 130 141 0
-75 -123 38 0
-76 -64 112 0
124 -144 138 0
-87 -51 -21 0
-36 -138 -12 0
63 -97 -130 0
-23 64 14 0
22 -143 -71 0
-28 -40 97 0
-35 -50 -22 0
-101 -24 -103 0
-125 -103 -6 0
-35 -16 -124 0
71 42 -48 0
6 11 -148 0
56 -101 -117 0
79 80 -113 0
-144 12 100 0
-99 114 -94 0
-82 -99 22 0
122 -86 137 0
-44 -7 -55 0
110 -120 23 0
-91 -54 131 0
108 -53 -110 0
97 62 -133 0
-37 69 -86 0
-111 68 66 0
-6 -12 -37 0
-136 60 40 0
24 -49 9 0
-64 125 -135 0
-108 -140 113 0
-139 -124 -90 0
24 -63 100 0
-138 -134 63 0
139 -21 -91 0
-53 132 59 0
57 54 -17 0
108 98 124 0
-105 -103 -68 0
-3 -24 84 0
-81 9 150 0
-65 52 -7 0
-123 91 -14 0
133 2 -66 0
-30 -103 -118 0
-136 26 131 0
-29 88 -111 0
148 -110 -41 0
20 10 -83 0
-129 77 -69 0
-65 -99 113 0
-117 107 -64 0
-9 -18 -94 0
23 48 -121 0
24 -145 108 0
65 30 -54 0
53 -87 108 0
-36 13 -76 0
-70 -130 -8 0
-66 -40 -65 0
30 -132 -124 0
-148 -114 -17 0
-116 -105 92 0
97 -14 -60 0
-83 50 -54 0
142 -140 105 0
-28 -142 -137 0
-92 -6 -72 0
109 -121 66 0
-138 -19 93 0
-86 41 46 0
-86 -121 -110 0
79 -85 -143 0
119 -104 -149 0
-139 -121 -42 0
-85 14 -4 0
42 121 -57 0
-5 -140 109 0
56 134 -37 0
-45 140 -73 0
-129 -42 64 0
9 -67 -41 0
127 -50 -46 0
-99 -33 119 0
28 131 -106 0
30 79 48 0
-35 -101 30 0
88 -101 -133 0
-70 -141 -146 0
55 148 -4 0
-63 50 -49 0
-141 105 112 0
72 119 -37 0
127 -75 134 0
49 83 -68 0
30 -51 64 0
125 -37 123 0
26 -60 99 0
82 63 44 0
-120 -75 107 0
18 145 -118 0
-140 5 14 0
-60 -119 132 0
85 29 -79 0
-3 -46 -104 0
-31 42 41 0
131 -51 -96 0
-71 -61 81 0
-55 39 -120 0
67 -73 -58 0
20 -72 -45 0
-122 42 40 0
26 -97 96 0
53 -83 -76 0
53 -100 85 0
-11 67 -26 0
-46 106 30 0
13 -6 -94 0
12 -32 -71 0
-31 33 117 0
104 29 -139 0
85 91 47 0
-90 122 147 0
95 -100 67 0
-50 142 75 0
-95 -83 -97 0
70 -22 -53 0
80 -81 118 0
-147 -28 62 0
52 -143 -54 0
-12 28 -128 0
129 -142 -123 0
-51 42 -113 0
63 121 39 0
45 -17 -1 0
76 22 104 0
-22 114 -127 0
2 86 -6 0
32 -148 59 0
106 -88 102 0
-139 58 137 0
17 38 -78 0
-106 -18 112 0
40 -93 -75 0
-12 121 58 0
-13 83 6 0
-13 -139 -88 0
-72 1 59 0
105 -140 49 0
111 40 -119 0
-105 -121 104 0
-144 -68 53 0
135 122 -106 0
-56 117 98 0
-31 -39 -122 0
-117 -130 -41 0
-150 -86 -3 0
-126 -149 93 0
-40 -29 54 0
32 -10 -2 0
-14 50 139 0
-121 -89 -32 0
-125 90 55 0
60 -107 52 0
66 12 127 0
-115 69 105 0
96 -41 61 0
-79 41 134 0
58 -108 -93 0
-26 -119 57 0
-139 -53 -113 0
-86 142 54 0
99 133 -97 0
82 145 -139 0
-134 -2 -95 0
-12 120 136 0
50 -141 49 0
-16 81 -70 0
-148 149 -12 0
-17 119 128 0
35 115 -58 0
123 4 134 0
123 -34 -109 0
-124 5 -2 0
98 118 -70 0
87 105 -135 0
140 -93 17 0
-102 74 119 0
-32 -20 -48 0
80 -77 134 0
-68 42 -143 0
-66 -73 -109 0
-126 97 -38 0
82 -60 -117 0
112 -88 -106 0
-11 -123 124 0
-84 -106 87 0
-57 118 -102 0
-84 43 61 0
-134 22 -12 0
45 -86 111 0
-37 -10 -124 0
27 -123 70 0
77 38 132 0
-70 37 -12 0
44 -53 -127 0
-139 -6 49 0
-69 -58 90 0
19 68 -112 0
-56 -52 118 0
70 62 147 0
2 -75 -35 0
89 59 -80 0
-13 30 122 0
138 23 28 0
125 35 -14 0
98 -52 18 0
85 -109 -55 0
-98 -112 -33 0
51 -129 35 0
-119 27 148 0
-33 122 104 0
54 -34 -11 0
-15 16 -97 0
75 56 13 0
-35 -126 -120 0
114 -83 -78 0
-36 69 -58 0
-85 125 -89 0
35 -115 133 0
22 -134 67 0
129 6 57 0
-142 -30 98 0
40 -82 21 0
62 53 -101 0
-91 -47 -135 0
84 -58 -50 0
26 19 150 0
-22 -27 -54 0
49 -18 61 0
-146 -35 -46 0
-35 40 -86 0
-110 73 -29 0
-104 112 -149 0
73 -61 90 0
48 -135 -130 0
78 -100 93 0
94 -53 137 0
37 -5 68 0
133 78 -105 0
-71 115 26 0
59 115 -38 0
-148 -40 -23 0
30 -46 109 0
-100 117 -16 0
81 102 -94 0
141 50 -35 0
143 -1 -26 0
-125 10 50 0
58 2 -28 0
128 19 -12 0
-60 121 129 0
53 82 -22 0
-9 -131 -128 0
-42 -88 55 0
-43 70 93 0
-87 15 32 0
143 -93 33 0
-39 -3 -47 0
19 -38 125 0
136 -18 57 0
144 -95 -84 0
-125 -137 -117 0
83 -95 148 0
117 -118 51 0
25 77 -53 0
-8 125 -142 0
-88 -81 -27 0
-98 75 20 0
125 -82 -68 0
133 76 87 0
6 -94 148 0
-110 39 -56 0
-20 11 -122 0
72 -137 118 0
120 -57 -144 0
57 72 -89 0
-82 32 -95 0
136 34 -110 0
-125 110 59 0
-5 -41 -31 0
139 -86 -31 0
49 -12 -84 0
-93 -119 -110 0
-11 -73 20 0
-72 -8 118 0
99 87 114 0
92 -135 121 0
-76 -82 -93 0
119 -116 5 0
82 -106 37 0
-76 84 -136 0
-74 -2 12 0
-45 -60 137 0
114 45 -119 0
-98 76 -79 0
41 -22 -79 0
53 136 112 0
46 -39 127 0
-88 20 2 0
128 -55 64 0
-110 74 -5 0
-64 -137 118 0
45 102 -110 0
57 118 110 0
66 -90 118 0
55 -142 -81 0
57 -108 -93 0
13 -116 54 0
3 -61 10 0
109 113 -147 0
125 24 -91 0
53 107 147 0
6 79 -118 0
23 111 -122 0
-34 -9 -94 0
-15 4 -29 0
-109 32 -35 0
61 30 62 0
-122 -30 92 0
-118 -46 -20 0
23 -37 108 0
-95 6 -57 0
-149 -135 86 0
27 133 -42 0
-81 87 -97 0
102 -51 -107 0
-45 -61 20 0
128 2 46 0
-33 -35 24 0
-133 -54 28 0
-114 -62 53 0
-79 133 22 0
33 -40 -35 0
-13 -111 138 0
-124 21 88 0
84 -50 115 0
30 -3 146 0
21 61 40 0
-74 45 -1 0
-88 74 -121 0
111 44 14 0
77 7 101 0
-68 62 40 0
50 26 -84 0
-72 -55 74 0
92 136 -67 0
-86 -47 -14 0
65 -97 49 0
150 7 -75 0
114 66 85 0
143 106 63 0
-112 89 -3 0
53 7 -2 0
-71 24 -117 0
28 128 85 0
5 89 -56 0
-115 46 -37 0
23 -124 -59 0
83 -39 43 0
-9 -118 145 0
-145 120 -39 0
132 -3 -144 0
-17 -64 -44 0
-128 39 28 0
-142 21 8 0
-20 85 11 0
92 -105 115 0
-77 -104 28 0
15 -102 149 0
-52 82 -22 0
-25 -80 65 0
66 144 71 0
-2 -112 140 0
-105 22 -92 0
-4 -112 -150 0
97 -3 -74 0
-64 80 16 0
118 49 -93 0
-100 -98 -67 0
7 122 46 0
-66 6 -105 0
18 11 -110 0
121 -128 -6 0
129 -12 69 0
110 114 66 0
-120 91 61 0
-108 -118 -31 0
-65 -83 145 0
-74 -79 101 0
49 -75 -133 0
-42 86 -34 0
20 111 -16 0
-125 135 63 0
59 -139 110 0
-74 57 73 0
45 -137 39 0
-15 -132 -28 0
145 105 -88 0
135 22 98 0
-52 -148 -36 0
-143 -102 -121 0
-10 33 139 0
23 69 116 0
-106 -12 11 0
25 -97 105 0
-65 25 43 0
70 72 -40 0
21 81 65 0
43 78 -27 0
132 -32 -135 0
-42 -134 60 0
-30 -17 62 0
127 -122 5 0
-101 140 -132 0
-110 114 19 0
62 83 -108 0
-144 85 16 0
17 -79 -88 0
-42 109 -114 0
108 -86 59 0
79 -62 20 0
56 99 -86 0
142 82 -4 0
-132 128 115 0
107 -6 -7 0
92 -81 -28 0
77 -51 6 0
3 -6 111 0
-129 -62 -52 0
-116 -75 99 0
146 -134 34 0
135 -46 132 0
67 44 8 0
-68 149 119 0
140 111 61 0
71 102 128 0
115 88 50 0
27 53 -58 0
-25 -24 150 0
15 116 -82 0
7 -141 -109 0
-65 -70 -54 0
-2 -36 66 0
133 148 -138 0
96 -116 -64 0
-58 -19 -90 0
49 -77 120 0
10 -58 -101 0
-114 134 -94 0
87 -49 32 0
-25 -74 -91 0
-36 -80 63 0
93 -105 77 0
-53 137 76 0
27 -76 -22 0
-58 -35 -17 0
139 72 15 0
-117 8 -104 0
-132 -114 139 0
32 -9 -72 0
108 -51 115 0
94 -86 128 0
-72 -126 -121 0
144 -95 -4 0
-58 15 -115 0
20 110 -31 0
-145 -110 -49 0
-70 -67 -56 0
33 -52 94 0
-104 -112 -43 0
16 32 29 0
-21 -18 -41 0
45 119 -129 0
-143 -107 -101 0
-42 -20 116 0
134 39 -104 0
148 -34 46 0
112 -96 74 0
96 69 32 0
52 150 87 0
-82 -85 19 0
-42 -40 24 0
26 -22 -123 0
87 45 130 0
49 94 -149 0
144 -40 -61 0
-120 -105 -71 0
-144 -35 16 0
-49 73 -53 0
113 139 20 0
81 -55 61 0
-103 147 -35 0
145 17 33 0
79 -69 150 0
-60 -39 -134 0
43 -114 109 0
-148 5 62 0
-75 -55 128 0
1 -108 -141 0
43 13 -104 0
-17 60 -55 0
128 -127 -53 0
-13 128 121 0
117 -137 -80 0
22 -110 14 0
"""
output = "SAT"
| input = '\nc num blocks = 1\nc num vars = 150\nc minblockids[0] = 1\nc maxblockids[0] = 150\np cnf 150 617\n90 -20 8 0\n-111 -68 -13 0\n8 -150 -9 0\n-66 63 -93 0\n-135 40 81 0\n106 -127 134 0\n-54 123 45 0\n24 -77 59 0\n-82 48 71 0\n12 75 87 0\n127 -29 88 0\n-120 -33 60 0\n-126 -102 31 0\n134 9 -150 0\n62 -56 -83 0\n92 27 75 0\n-133 -52 50 0\n-20 97 -13 0\n65 55 -17 0\n74 -77 -123 0\n-11 -125 -98 0\n-67 -35 -114 0\n134 3 51 0\n-113 132 101 0\n94 -8 52 0\n66 -1 -17 0\n40 -21 -55 0\n144 -125 -117 0\n-28 43 -147 0\n76 58 12 0\n-2 27 103 0\n58 125 7 0\n-8 74 -15 0\n-123 -46 108 0\n98 -112 -92 0\n-102 -31 -99 0\n-3 116 38 0\n-104 11 127 0\n63 26 72 0\n-97 96 -31 0\n-136 132 -85 0\n-23 32 -29 0\n131 39 -75 0\n68 -132 -110 0\n-133 93 -28 0\n41 32 -142 0\n-1 81 -21 0\n-59 131 12 0\n115 -29 62 0\n-117 40 73 0\n10 -79 -75 0\n-81 -8 117 0\n130 -136 -21 0\n-133 10 -112 0\n29 -57 119 0\n-130 112 97 0\n37 71 69 0\n28 -49 -88 0\n-123 86 84 0\n135 33 111 0\n100 48 17 0\n137 -47 -66 0\n111 96 -93 0\n-141 104 -19 0\n-31 65 3 0\n101 -3 -91 0\n55 -123 -36 0\n-90 -95 116 0\n-79 137 -107 0\n-25 68 -105 0\n-66 -42 143 0\n42 148 60 0\n-31 80 -28 0\n-10 -5 -126 0\n-45 48 23 0\n130 -36 96 0\n100 65 -47 0\n118 -75 18 0\n111 -72 -135 0\n143 7 -32 0\n-45 83 -95 0\n-52 -59 71 0\n90 -139 -8 0\n114 -95 -38 0\n75 -12 116 0\n26 15 79 0\n-51 -50 -27 0\n132 13 -147 0\n-17 94 -76 0\n106 79 121 0\n-5 -43 117 0\n53 118 51 0\n-128 111 -146 0\n45 53 77 0\n-75 10 60 0\n-10 100 99 0\n51 -50 150 0\n37 121 -127 0\n-131 130 141 0\n-75 -123 38 0\n-76 -64 112 0\n124 -144 138 0\n-87 -51 -21 0\n-36 -138 -12 0\n63 -97 -130 0\n-23 64 14 0\n22 -143 -71 0\n-28 -40 97 0\n-35 -50 -22 0\n-101 -24 -103 0\n-125 -103 -6 0\n-35 -16 -124 0\n71 42 -48 0\n6 11 -148 0\n56 -101 -117 0\n79 80 -113 0\n-144 12 100 0\n-99 114 -94 0\n-82 -99 22 0\n122 -86 137 0\n-44 -7 -55 0\n110 -120 23 0\n-91 -54 131 0\n108 -53 -110 0\n97 62 -133 0\n-37 69 -86 0\n-111 68 66 0\n-6 -12 -37 0\n-136 60 40 0\n24 -49 9 0\n-64 125 -135 0\n-108 -140 113 0\n-139 -124 -90 0\n24 -63 100 0\n-138 -134 63 0\n139 -21 -91 0\n-53 132 59 0\n57 54 -17 0\n108 98 124 0\n-105 -103 -68 0\n-3 -24 84 0\n-81 9 150 0\n-65 52 -7 0\n-123 91 -14 0\n133 2 -66 0\n-30 -103 -118 0\n-136 26 131 0\n-29 88 -111 0\n148 -110 -41 0\n20 10 -83 0\n-129 77 -69 0\n-65 -99 113 0\n-117 107 -64 0\n-9 -18 -94 0\n23 48 -121 0\n24 -145 108 0\n65 30 -54 0\n53 -87 108 0\n-36 13 -76 0\n-70 -130 -8 0\n-66 -40 -65 0\n30 -132 -124 0\n-148 -114 -17 0\n-116 -105 92 0\n97 -14 -60 0\n-83 50 -54 0\n142 -140 105 0\n-28 -142 -137 0\n-92 -6 -72 0\n109 -121 66 0\n-138 -19 93 0\n-86 41 46 0\n-86 -121 -110 0\n79 -85 -143 0\n119 -104 -149 0\n-139 -121 -42 0\n-85 14 -4 0\n42 121 -57 0\n-5 -140 109 0\n56 134 -37 0\n-45 140 -73 0\n-129 -42 64 0\n9 -67 -41 0\n127 -50 -46 0\n-99 -33 119 0\n28 131 -106 0\n30 79 48 0\n-35 -101 30 0\n88 -101 -133 0\n-70 -141 -146 0\n55 148 -4 0\n-63 50 -49 0\n-141 105 112 0\n72 119 -37 0\n127 -75 134 0\n49 83 -68 0\n30 -51 64 0\n125 -37 123 0\n26 -60 99 0\n82 63 44 0\n-120 -75 107 0\n18 145 -118 0\n-140 5 14 0\n-60 -119 132 0\n85 29 -79 0\n-3 -46 -104 0\n-31 42 41 0\n131 -51 -96 0\n-71 -61 81 0\n-55 39 -120 0\n67 -73 -58 0\n20 -72 -45 0\n-122 42 40 0\n26 -97 96 0\n53 -83 -76 0\n53 -100 85 0\n-11 67 -26 0\n-46 106 30 0\n13 -6 -94 0\n12 -32 -71 0\n-31 33 117 0\n104 29 -139 0\n85 91 47 0\n-90 122 147 0\n95 -100 67 0\n-50 142 75 0\n-95 -83 -97 0\n70 -22 -53 0\n80 -81 118 0\n-147 -28 62 0\n52 -143 -54 0\n-12 28 -128 0\n129 -142 -123 0\n-51 42 -113 0\n63 121 39 0\n45 -17 -1 0\n76 22 104 0\n-22 114 -127 0\n2 86 -6 0\n32 -148 59 0\n106 -88 102 0\n-139 58 137 0\n17 38 -78 0\n-106 -18 112 0\n40 -93 -75 0\n-12 121 58 0\n-13 83 6 0\n-13 -139 -88 0\n-72 1 59 0\n105 -140 49 0\n111 40 -119 0\n-105 -121 104 0\n-144 -68 53 0\n135 122 -106 0\n-56 117 98 0\n-31 -39 -122 0\n-117 -130 -41 0\n-150 -86 -3 0\n-126 -149 93 0\n-40 -29 54 0\n32 -10 -2 0\n-14 50 139 0\n-121 -89 -32 0\n-125 90 55 0\n60 -107 52 0\n66 12 127 0\n-115 69 105 0\n96 -41 61 0\n-79 41 134 0\n58 -108 -93 0\n-26 -119 57 0\n-139 -53 -113 0\n-86 142 54 0\n99 133 -97 0\n82 145 -139 0\n-134 -2 -95 0\n-12 120 136 0\n50 -141 49 0\n-16 81 -70 0\n-148 149 -12 0\n-17 119 128 0\n35 115 -58 0\n123 4 134 0\n123 -34 -109 0\n-124 5 -2 0\n98 118 -70 0\n87 105 -135 0\n140 -93 17 0\n-102 74 119 0\n-32 -20 -48 0\n80 -77 134 0\n-68 42 -143 0\n-66 -73 -109 0\n-126 97 -38 0\n82 -60 -117 0\n112 -88 -106 0\n-11 -123 124 0\n-84 -106 87 0\n-57 118 -102 0\n-84 43 61 0\n-134 22 -12 0\n45 -86 111 0\n-37 -10 -124 0\n27 -123 70 0\n77 38 132 0\n-70 37 -12 0\n44 -53 -127 0\n-139 -6 49 0\n-69 -58 90 0\n19 68 -112 0\n-56 -52 118 0\n70 62 147 0\n2 -75 -35 0\n89 59 -80 0\n-13 30 122 0\n138 23 28 0\n125 35 -14 0\n98 -52 18 0\n85 -109 -55 0\n-98 -112 -33 0\n51 -129 35 0\n-119 27 148 0\n-33 122 104 0\n54 -34 -11 0\n-15 16 -97 0\n75 56 13 0\n-35 -126 -120 0\n114 -83 -78 0\n-36 69 -58 0\n-85 125 -89 0\n35 -115 133 0\n22 -134 67 0\n129 6 57 0\n-142 -30 98 0\n40 -82 21 0\n62 53 -101 0\n-91 -47 -135 0\n84 -58 -50 0\n26 19 150 0\n-22 -27 -54 0\n49 -18 61 0\n-146 -35 -46 0\n-35 40 -86 0\n-110 73 -29 0\n-104 112 -149 0\n73 -61 90 0\n48 -135 -130 0\n78 -100 93 0\n94 -53 137 0\n37 -5 68 0\n133 78 -105 0\n-71 115 26 0\n59 115 -38 0\n-148 -40 -23 0\n30 -46 109 0\n-100 117 -16 0\n81 102 -94 0\n141 50 -35 0\n143 -1 -26 0\n-125 10 50 0\n58 2 -28 0\n128 19 -12 0\n-60 121 129 0\n53 82 -22 0\n-9 -131 -128 0\n-42 -88 55 0\n-43 70 93 0\n-87 15 32 0\n143 -93 33 0\n-39 -3 -47 0\n19 -38 125 0\n136 -18 57 0\n144 -95 -84 0\n-125 -137 -117 0\n83 -95 148 0\n117 -118 51 0\n25 77 -53 0\n-8 125 -142 0\n-88 -81 -27 0\n-98 75 20 0\n125 -82 -68 0\n133 76 87 0\n6 -94 148 0\n-110 39 -56 0\n-20 11 -122 0\n72 -137 118 0\n120 -57 -144 0\n57 72 -89 0\n-82 32 -95 0\n136 34 -110 0\n-125 110 59 0\n-5 -41 -31 0\n139 -86 -31 0\n49 -12 -84 0\n-93 -119 -110 0\n-11 -73 20 0\n-72 -8 118 0\n99 87 114 0\n92 -135 121 0\n-76 -82 -93 0\n119 -116 5 0\n82 -106 37 0\n-76 84 -136 0\n-74 -2 12 0\n-45 -60 137 0\n114 45 -119 0\n-98 76 -79 0\n41 -22 -79 0\n53 136 112 0\n46 -39 127 0\n-88 20 2 0\n128 -55 64 0\n-110 74 -5 0\n-64 -137 118 0\n45 102 -110 0\n57 118 110 0\n66 -90 118 0\n55 -142 -81 0\n57 -108 -93 0\n13 -116 54 0\n3 -61 10 0\n109 113 -147 0\n125 24 -91 0\n53 107 147 0\n6 79 -118 0\n23 111 -122 0\n-34 -9 -94 0\n-15 4 -29 0\n-109 32 -35 0\n61 30 62 0\n-122 -30 92 0\n-118 -46 -20 0\n23 -37 108 0\n-95 6 -57 0\n-149 -135 86 0\n27 133 -42 0\n-81 87 -97 0\n102 -51 -107 0\n-45 -61 20 0\n128 2 46 0\n-33 -35 24 0\n-133 -54 28 0\n-114 -62 53 0\n-79 133 22 0\n33 -40 -35 0\n-13 -111 138 0\n-124 21 88 0\n84 -50 115 0\n30 -3 146 0\n21 61 40 0\n-74 45 -1 0\n-88 74 -121 0\n111 44 14 0\n77 7 101 0\n-68 62 40 0\n50 26 -84 0\n-72 -55 74 0\n92 136 -67 0\n-86 -47 -14 0\n65 -97 49 0\n150 7 -75 0\n114 66 85 0\n143 106 63 0\n-112 89 -3 0\n53 7 -2 0\n-71 24 -117 0\n28 128 85 0\n5 89 -56 0\n-115 46 -37 0\n23 -124 -59 0\n83 -39 43 0\n-9 -118 145 0\n-145 120 -39 0\n132 -3 -144 0\n-17 -64 -44 0\n-128 39 28 0\n-142 21 8 0\n-20 85 11 0\n92 -105 115 0\n-77 -104 28 0\n15 -102 149 0\n-52 82 -22 0\n-25 -80 65 0\n66 144 71 0\n-2 -112 140 0\n-105 22 -92 0\n-4 -112 -150 0\n97 -3 -74 0\n-64 80 16 0\n118 49 -93 0\n-100 -98 -67 0\n7 122 46 0\n-66 6 -105 0\n18 11 -110 0\n121 -128 -6 0\n129 -12 69 0\n110 114 66 0\n-120 91 61 0\n-108 -118 -31 0\n-65 -83 145 0\n-74 -79 101 0\n49 -75 -133 0\n-42 86 -34 0\n20 111 -16 0\n-125 135 63 0\n59 -139 110 0\n-74 57 73 0\n45 -137 39 0\n-15 -132 -28 0\n145 105 -88 0\n135 22 98 0\n-52 -148 -36 0\n-143 -102 -121 0\n-10 33 139 0\n23 69 116 0\n-106 -12 11 0\n25 -97 105 0\n-65 25 43 0\n70 72 -40 0\n21 81 65 0\n43 78 -27 0\n132 -32 -135 0\n-42 -134 60 0\n-30 -17 62 0\n127 -122 5 0\n-101 140 -132 0\n-110 114 19 0\n62 83 -108 0\n-144 85 16 0\n17 -79 -88 0\n-42 109 -114 0\n108 -86 59 0\n79 -62 20 0\n56 99 -86 0\n142 82 -4 0\n-132 128 115 0\n107 -6 -7 0\n92 -81 -28 0\n77 -51 6 0\n3 -6 111 0\n-129 -62 -52 0\n-116 -75 99 0\n146 -134 34 0\n135 -46 132 0\n67 44 8 0\n-68 149 119 0\n140 111 61 0\n71 102 128 0\n115 88 50 0\n27 53 -58 0\n-25 -24 150 0\n15 116 -82 0\n7 -141 -109 0\n-65 -70 -54 0\n-2 -36 66 0\n133 148 -138 0\n96 -116 -64 0\n-58 -19 -90 0\n49 -77 120 0\n10 -58 -101 0\n-114 134 -94 0\n87 -49 32 0\n-25 -74 -91 0\n-36 -80 63 0\n93 -105 77 0\n-53 137 76 0\n27 -76 -22 0\n-58 -35 -17 0\n139 72 15 0\n-117 8 -104 0\n-132 -114 139 0\n32 -9 -72 0\n108 -51 115 0\n94 -86 128 0\n-72 -126 -121 0\n144 -95 -4 0\n-58 15 -115 0\n20 110 -31 0\n-145 -110 -49 0\n-70 -67 -56 0\n33 -52 94 0\n-104 -112 -43 0\n16 32 29 0\n-21 -18 -41 0\n45 119 -129 0\n-143 -107 -101 0\n-42 -20 116 0\n134 39 -104 0\n148 -34 46 0\n112 -96 74 0\n96 69 32 0\n52 150 87 0\n-82 -85 19 0\n-42 -40 24 0\n26 -22 -123 0\n87 45 130 0\n49 94 -149 0\n144 -40 -61 0\n-120 -105 -71 0\n-144 -35 16 0\n-49 73 -53 0\n113 139 20 0\n81 -55 61 0\n-103 147 -35 0\n145 17 33 0\n79 -69 150 0\n-60 -39 -134 0\n43 -114 109 0\n-148 5 62 0\n-75 -55 128 0\n1 -108 -141 0\n43 13 -104 0\n-17 60 -55 0\n128 -127 -53 0\n-13 128 121 0\n117 -137 -80 0\n22 -110 14 0\n'
output = 'SAT' |
def count(word, letter):
count = 0
for i in word:
if i == letter:
count = count + 1
return count
word = input('Enter a word:')
letter = input('Enter a letter to count in word:')
print("There are {} {}'s in your word".format(count(word,letter), letter))
| def count(word, letter):
count = 0
for i in word:
if i == letter:
count = count + 1
return count
word = input('Enter a word:')
letter = input('Enter a letter to count in word:')
print("There are {} {}'s in your word".format(count(word, letter), letter)) |
class Square:
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
def area(self):
return self.side ** 2
pass
class Rectangle:
def __init__(self, width, height):
self.width, self.height = width, height
def perimeter(self):
return self.width * 2 + self.height * 2
def area(self):
return self.width * self.height
q = Square(5)
print(q.perimeter())
print(q.area())
r = Rectangle(5, 10)
print(r.perimeter(), r.area())
| class Square:
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
def area(self):
return self.side ** 2
pass
class Rectangle:
def __init__(self, width, height):
(self.width, self.height) = (width, height)
def perimeter(self):
return self.width * 2 + self.height * 2
def area(self):
return self.width * self.height
q = square(5)
print(q.perimeter())
print(q.area())
r = rectangle(5, 10)
print(r.perimeter(), r.area()) |
def first_function(values):
''' (list of int) -> NoneType
'''
for i in range(len(values)):
if values[i] % 2 == 1:
values[i] += 1
def second_function(value):
''' (int) -> int
'''
if value % 2 == 1:
value += 1
return value
def snippet_1():
a = [1, 2, 3]
b = 1
first_function(a)
second_function(b)
print(a)
print(b)
# output: (2 MARKS)
# [2, 2, 4]
# 1
# why? second_function(1) will not return 2 if we don't print it.
def snippet_2():
a = [1, 2, 3]
b = 1
print(first_function(a))
print(second_function(b))
# output: (2 MARKS)
# None
# 2
| def first_function(values):
""" (list of int) -> NoneType
"""
for i in range(len(values)):
if values[i] % 2 == 1:
values[i] += 1
def second_function(value):
""" (int) -> int
"""
if value % 2 == 1:
value += 1
return value
def snippet_1():
a = [1, 2, 3]
b = 1
first_function(a)
second_function(b)
print(a)
print(b)
def snippet_2():
a = [1, 2, 3]
b = 1
print(first_function(a))
print(second_function(b)) |
# -*- coding: utf-8 -*-
vagrant = 'vagrant'
def up():
return '{} up'.format(vagrant)
def ssh():
return '{} ssh'.format(vagrant)
def suspend():
return '{} suspend'.format(vagrant)
def status():
return '{} status'.format(vagrant)
def halt():
return '{} halt'.format(vagrant)
def destroy(force=False):
options = ''
if force:
options += '--force'
return '{} destroy {}'.format(vagrant, options)
def share(**kwargs):
options = ''
name = kwargs.get('name')
if name:
options += '--name {}'.format(name)
if options != '':
options = ' ' + options
return '{} share{}'.format(vagrant, options)
| vagrant = 'vagrant'
def up():
return '{} up'.format(vagrant)
def ssh():
return '{} ssh'.format(vagrant)
def suspend():
return '{} suspend'.format(vagrant)
def status():
return '{} status'.format(vagrant)
def halt():
return '{} halt'.format(vagrant)
def destroy(force=False):
options = ''
if force:
options += '--force'
return '{} destroy {}'.format(vagrant, options)
def share(**kwargs):
options = ''
name = kwargs.get('name')
if name:
options += '--name {}'.format(name)
if options != '':
options = ' ' + options
return '{} share{}'.format(vagrant, options) |
def split_block (string:str, seps:(str, str)) -> str:
_, content = string.split (seps[0])
block, _ = content.split (seps[1])
return block
def is_not_empty (value):
return value != ''
def contens_colons (value:str) -> bool:
return value.count(":") == 0
content = ""
with open ("examples/add.asm") as f:
content = f.read()
code, data = [*map (lambda x: split_block (content, x), [(".code", ".endcode"), (".data", ".enddata")])]
code = [*filter (is_not_empty, code.split ('\n'))]
data = [*filter (is_not_empty, data.split ('\n'))]
print (code)
print (data)
instructions = [*filter (contens_colons, code)]
markings = [*filter (lambda x: not contens_colons (x), code)]
there_is_instruction = [*map ( lambda x: len (x.split (":")[1].replace (" ", "")) != 0, markings)]
print (instructions)
print (markings)
print (there_is_instruction) | def split_block(string: str, seps: (str, str)) -> str:
(_, content) = string.split(seps[0])
(block, _) = content.split(seps[1])
return block
def is_not_empty(value):
return value != ''
def contens_colons(value: str) -> bool:
return value.count(':') == 0
content = ''
with open('examples/add.asm') as f:
content = f.read()
(code, data) = [*map(lambda x: split_block(content, x), [('.code', '.endcode'), ('.data', '.enddata')])]
code = [*filter(is_not_empty, code.split('\n'))]
data = [*filter(is_not_empty, data.split('\n'))]
print(code)
print(data)
instructions = [*filter(contens_colons, code)]
markings = [*filter(lambda x: not contens_colons(x), code)]
there_is_instruction = [*map(lambda x: len(x.split(':')[1].replace(' ', '')) != 0, markings)]
print(instructions)
print(markings)
print(there_is_instruction) |
class Solution:
def sumOfDistancesInTree(self, N, edges):
"""
:type N: int
:type edges: List[List[int]]
:rtype: List[int]
"""
graph = collections.defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
sums = [0] * N
counts = [1] * N
def dfs1(curr, prev, graph, sums, counts):
for next in graph[curr]:
if next != prev:
dfs1(next, curr, graph, sums, counts)
sums[curr] += sums[next] + counts[next]
counts[curr] += counts[next]
def dfs2(curr, prev, graph, sums, counts):
for next in graph[curr]:
if next != prev:
sums[next] = sums[curr] - counts[next] + len(graph) - counts[next]
dfs2(next, curr, graph, sums, counts)
dfs1(0, -1, graph, sums, counts)
dfs2(0, -1, graph, sums, counts)
return sums
| class Solution:
def sum_of_distances_in_tree(self, N, edges):
"""
:type N: int
:type edges: List[List[int]]
:rtype: List[int]
"""
graph = collections.defaultdict(list)
for (u, v) in edges:
graph[u].append(v)
graph[v].append(u)
sums = [0] * N
counts = [1] * N
def dfs1(curr, prev, graph, sums, counts):
for next in graph[curr]:
if next != prev:
dfs1(next, curr, graph, sums, counts)
sums[curr] += sums[next] + counts[next]
counts[curr] += counts[next]
def dfs2(curr, prev, graph, sums, counts):
for next in graph[curr]:
if next != prev:
sums[next] = sums[curr] - counts[next] + len(graph) - counts[next]
dfs2(next, curr, graph, sums, counts)
dfs1(0, -1, graph, sums, counts)
dfs2(0, -1, graph, sums, counts)
return sums |
class Solution:
# @return an integer
def threeSumClosest(self, num, target):
num.sort()
res = sum(num[:3])
if res > target:
diff = res-target
elif res < target:
diff = target-res
else:
return res
n = len(num)
for i in xrange(n):
j, k = i+1, n-1
while j < k:
s = num[i]+num[j]+num[k]
if s > target:
n_diff = s-target
k -= 1
elif s < target:
n_diff = target-s
j += 1
else:
return s
if n_diff < diff:
res, diff = s, n_diff
return res
| class Solution:
def three_sum_closest(self, num, target):
num.sort()
res = sum(num[:3])
if res > target:
diff = res - target
elif res < target:
diff = target - res
else:
return res
n = len(num)
for i in xrange(n):
(j, k) = (i + 1, n - 1)
while j < k:
s = num[i] + num[j] + num[k]
if s > target:
n_diff = s - target
k -= 1
elif s < target:
n_diff = target - s
j += 1
else:
return s
if n_diff < diff:
(res, diff) = (s, n_diff)
return res |
# -*- encoding:utf-8 -*-
"""Autogenerated file, do not edit. Submit translations on Transifex."""
MESSAGES = {
"%d min remaining to read": "%dminutas de lectura remanente",
"(active)": "(active)",
"Also available in:": "Anque disponibile in:",
"Archive": "Archivo",
"Atom feed": "Fluxo Atom",
"Authors": "Authores",
"Categories": "Categorias",
"Comments": "Commentos",
"LANGUAGE": "Interlingua",
"Languages:": "Linguas:",
"More posts about %s": "Plure entratas super %s",
"Newer posts": "Entratas plus recente",
"Next post": "Entrata successive",
"Next": "Successive",
"No posts found.": "Nulle entrata esseva trovate.",
"Nothing found.": "Nihil esseva trovate.",
"Older posts": "Entratas plus vetule",
"Original site": "Sito original",
"Posted:": "Publicate:",
"Posts about %s": "Entratas super %s",
"Posts by %s": "Entratas per %s",
"Posts for year %s": "Entratas del anno %s",
"Posts for {month_day_year}": "Entratas de {month_day_year}",
"Posts for {month_year}": "Entratas de {month_year}",
"Previous post": "Entrata precedente",
"Previous": "Precendente",
"Publication date": "Data de publication",
"RSS feed": "Fluxo RSS",
"Read in English": "Lege in interlingua",
"Read more": "Lege plus",
"Skip to main content": "Salta al contento principal",
"Source": "Sorgente",
"Subcategories:": "Subcategorias:",
"Tags and Categories": "Etiquettas e categorias",
"Tags": "Etiquettas",
"Toggle navigation": "Commuta navigation",
"Uncategorized": "Sin categoria",
"Up": "In alto",
"Updates": "Actualisationes",
"Write your page here.": "Scribe tu pagina hic.",
"Write your post here.": "Scribe tu entrata hic.",
"old posts, page %d": "Vetule entratas, pagina %d",
"page %d": "pagina %d",
"updated": "actualisate",
}
| """Autogenerated file, do not edit. Submit translations on Transifex."""
messages = {'%d min remaining to read': '%dminutas de lectura remanente', '(active)': '(active)', 'Also available in:': 'Anque disponibile in:', 'Archive': 'Archivo', 'Atom feed': 'Fluxo Atom', 'Authors': 'Authores', 'Categories': 'Categorias', 'Comments': 'Commentos', 'LANGUAGE': 'Interlingua', 'Languages:': 'Linguas:', 'More posts about %s': 'Plure entratas super %s', 'Newer posts': 'Entratas plus recente', 'Next post': 'Entrata successive', 'Next': 'Successive', 'No posts found.': 'Nulle entrata esseva trovate.', 'Nothing found.': 'Nihil esseva trovate.', 'Older posts': 'Entratas plus vetule', 'Original site': 'Sito original', 'Posted:': 'Publicate:', 'Posts about %s': 'Entratas super %s', 'Posts by %s': 'Entratas per %s', 'Posts for year %s': 'Entratas del anno %s', 'Posts for {month_day_year}': 'Entratas de {month_day_year}', 'Posts for {month_year}': 'Entratas de {month_year}', 'Previous post': 'Entrata precedente', 'Previous': 'Precendente', 'Publication date': 'Data de publication', 'RSS feed': 'Fluxo RSS', 'Read in English': 'Lege in interlingua', 'Read more': 'Lege plus', 'Skip to main content': 'Salta al contento principal', 'Source': 'Sorgente', 'Subcategories:': 'Subcategorias:', 'Tags and Categories': 'Etiquettas e categorias', 'Tags': 'Etiquettas', 'Toggle navigation': 'Commuta navigation', 'Uncategorized': 'Sin categoria', 'Up': 'In alto', 'Updates': 'Actualisationes', 'Write your page here.': 'Scribe tu pagina hic.', 'Write your post here.': 'Scribe tu entrata hic.', 'old posts, page %d': 'Vetule entratas, pagina %d', 'page %d': 'pagina %d', 'updated': 'actualisate'} |
'''
Prompt:
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1.
(e.g., "waterbottle" is a rotation of "erbottlewat").
Follow up:
What if you could use one call of a helper method isSubstring?
'''
# Time: O(n), Space: O(n)
def isStringRotation(s1, s2):
if len(s1) != len(s2):
return False
strLength = len(s1) or len(s2)
s1Prefix = []
s1Suffix = [c for c in s1]
s2Prefix = [c for c in s2]
s2Suffix = []
for idx in range(strLength):
if s1Suffix == s2Prefix and s1Prefix == s2Suffix:
return True
s1Prefix.append(s1Suffix.pop(0))
s2Suffix.insert(0, s2Prefix.pop())
return False
'''
Follow up:
Notice that if isStringRotation(s1, s2) == True
Let `p` be the prefix of the string and `s` the suffix.
Then s1 can be broken down into s1=`ps` and s2=`sp`
Therefore, notice that s1s1 = `psps`, so s2 must be a substring.
So: return isSubstring(s1+s1, s2)
'''
print(isStringRotation("waterbottle", "erbottlewat"))
print(isStringRotation("waterbottle", "erbottlewqt"))
print(isStringRotation("waterbottle", "eniottlewdt"))
print(isStringRotation("lucas", "sluca"))
print(isStringRotation("lucas", "wluca"))
| """
Prompt:
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1.
(e.g., "waterbottle" is a rotation of "erbottlewat").
Follow up:
What if you could use one call of a helper method isSubstring?
"""
def is_string_rotation(s1, s2):
if len(s1) != len(s2):
return False
str_length = len(s1) or len(s2)
s1_prefix = []
s1_suffix = [c for c in s1]
s2_prefix = [c for c in s2]
s2_suffix = []
for idx in range(strLength):
if s1Suffix == s2Prefix and s1Prefix == s2Suffix:
return True
s1Prefix.append(s1Suffix.pop(0))
s2Suffix.insert(0, s2Prefix.pop())
return False
'\nFollow up:\nNotice that if isStringRotation(s1, s2) == True\nLet `p` be the prefix of the string and `s` the suffix.\nThen s1 can be broken down into s1=`ps` and s2=`sp`\n\nTherefore, notice that s1s1 = `psps`, so s2 must be a substring.\nSo: return isSubstring(s1+s1, s2)\n'
print(is_string_rotation('waterbottle', 'erbottlewat'))
print(is_string_rotation('waterbottle', 'erbottlewqt'))
print(is_string_rotation('waterbottle', 'eniottlewdt'))
print(is_string_rotation('lucas', 'sluca'))
print(is_string_rotation('lucas', 'wluca')) |
# Instantiate Cache information
n = 10
cache = [None] * (n + 1)
def fib_dyn(n):
# Base Case
if n == 0 or n == 1:
return n
# Check cache
if cache[n] != None:
return cache[n]
# Keep setting cache
cache[n] = fib_dyn(n-1) + fib_dyn(n-2)
return cache[n]
fib_dyn(10) | n = 10
cache = [None] * (n + 1)
def fib_dyn(n):
if n == 0 or n == 1:
return n
if cache[n] != None:
return cache[n]
cache[n] = fib_dyn(n - 1) + fib_dyn(n - 2)
return cache[n]
fib_dyn(10) |
"""
The ``refstate`` module
=========================
Provides integral models for boundary layer computations
Available functions
-------------------
"""
class refstate:
def __init__(self, **kwargs):
self._dict = kwargs
#def Reynolds(self): | """
The ``refstate`` module
=========================
Provides integral models for boundary layer computations
Available functions
-------------------
"""
class Refstate:
def __init__(self, **kwargs):
self._dict = kwargs |
# -*- coding: utf-8 -*-
# TODO: datetime support
###
### DO NOT CHANGE THIS FILE
###
### The code is auto generated, your change will be overwritten by
### code generating.
###
DefinitionsNewrun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, 'fqRegex': {'type': 'string'}, 'star': {'type': 'boolean'}, 'name': {'type': 'string'}, 'fastqc': {'type': 'boolean'}, 'genomeInddex': {'type': 'string'}, 'gtfFile': {'type': 'string'}, 'rnaseqqc': {'type': 'boolean'}, 'fqDirs': {'type': 'string'}, 'sampleNames': {'type': 'string'}, 'fastaRef': {'type': 'string'}, 'extn': {'type': 'string'}, 'fqDir': {'type': 'string'}, 'makeIndices': {'type': 'boolean'}}}
DefinitionsRun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, 'fqRegex': {'type': 'string'}, 'star': {'type': 'boolean'}, 'name': {'type': 'string'}, 'fastqc': {'type': 'boolean'}, 'genomeInddex': {'type': 'string'}, 'gtfFile': {'type': 'string'}, 'rnaseqqc': {'type': 'boolean'}, 'fqDirs': {'type': 'string'}, 'sampleNames': {'type': 'string'}, 'fastaRef': {'type': 'string'}, 'extn': {'type': 'string'}, 'fqDir': {'type': 'string'}, 'makeIndices': {'type': 'boolean'}}}
DefinitionsErrormodel = {'required': ['code', 'message'], 'type': 'object', 'properties': {'message': {'type': 'string'}, 'code': {'type': 'integer', 'format': 'int32'}}}
validators = {
('runs', 'POST'): {'json': DefinitionsNewrun},
}
filters = {
('runs', 'POST'): {200: {'headers': None, 'schema': DefinitionsRun}},
('runs', 'GET'): {200: {'headers': None, 'schema': {'items': DefinitionsRun, 'type': 'array'}}},
}
scopes = {
}
class Security(object):
def __init__(self):
super(Security, self).__init__()
self._loader = lambda: []
@property
def scopes(self):
return self._loader()
def scopes_loader(self, func):
self._loader = func
return func
security = Security()
def merge_default(schema, value):
# TODO: more types support
type_defaults = {
'integer': 9573,
'string': 'something',
'object': {},
'array': [],
'boolean': False
}
return normalize(schema, value, type_defaults)[0]
def normalize(schema, data, required_defaults=None):
if required_defaults is None:
required_defaults = {}
errors = []
class DataWrapper(object):
def __init__(self, data):
super(DataWrapper, self).__init__()
self.data = data
def get(self, key, default=None):
if isinstance(self.data, dict):
return self.data.get(key, default)
if hasattr(self.data, key):
return getattr(self.data, key)
else:
return default
def has(self, key):
if isinstance(self.data, dict):
return key in self.data
return hasattr(self.data, key)
def _normalize_dict(schema, data):
result = {}
data = DataWrapper(data)
for key, _schema in schema.get('properties', {}).iteritems():
# set default
type_ = _schema.get('type', 'object')
if ('default' not in _schema
and key in schema.get('required', [])
and type_ in required_defaults):
_schema['default'] = required_defaults[type_]
# get value
if data.has(key):
result[key] = _normalize(_schema, data.get(key))
elif 'default' in _schema:
result[key] = _schema['default']
elif key in schema.get('required', []):
errors.append(dict(name='property_missing',
message='`%s` is required' % key))
return result
def _normalize_list(schema, data):
result = []
if isinstance(data, (list, tuple)):
for item in data:
result.append(_normalize(schema.get('items'), item))
elif 'default' in schema:
result = schema['default']
return result
def _normalize_default(schema, data):
if data is None:
return schema.get('default')
else:
return data
def _normalize(schema, data):
if not schema:
return None
funcs = {
'object': _normalize_dict,
'array': _normalize_list,
'default': _normalize_default,
}
type_ = schema.get('type', 'object')
if not type_ in funcs:
type_ = 'default'
return funcs[type_](schema, data)
return _normalize(schema, data), errors
| definitions_newrun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, 'fqRegex': {'type': 'string'}, 'star': {'type': 'boolean'}, 'name': {'type': 'string'}, 'fastqc': {'type': 'boolean'}, 'genomeInddex': {'type': 'string'}, 'gtfFile': {'type': 'string'}, 'rnaseqqc': {'type': 'boolean'}, 'fqDirs': {'type': 'string'}, 'sampleNames': {'type': 'string'}, 'fastaRef': {'type': 'string'}, 'extn': {'type': 'string'}, 'fqDir': {'type': 'string'}, 'makeIndices': {'type': 'boolean'}}}
definitions_run = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, 'fqRegex': {'type': 'string'}, 'star': {'type': 'boolean'}, 'name': {'type': 'string'}, 'fastqc': {'type': 'boolean'}, 'genomeInddex': {'type': 'string'}, 'gtfFile': {'type': 'string'}, 'rnaseqqc': {'type': 'boolean'}, 'fqDirs': {'type': 'string'}, 'sampleNames': {'type': 'string'}, 'fastaRef': {'type': 'string'}, 'extn': {'type': 'string'}, 'fqDir': {'type': 'string'}, 'makeIndices': {'type': 'boolean'}}}
definitions_errormodel = {'required': ['code', 'message'], 'type': 'object', 'properties': {'message': {'type': 'string'}, 'code': {'type': 'integer', 'format': 'int32'}}}
validators = {('runs', 'POST'): {'json': DefinitionsNewrun}}
filters = {('runs', 'POST'): {200: {'headers': None, 'schema': DefinitionsRun}}, ('runs', 'GET'): {200: {'headers': None, 'schema': {'items': DefinitionsRun, 'type': 'array'}}}}
scopes = {}
class Security(object):
def __init__(self):
super(Security, self).__init__()
self._loader = lambda : []
@property
def scopes(self):
return self._loader()
def scopes_loader(self, func):
self._loader = func
return func
security = security()
def merge_default(schema, value):
type_defaults = {'integer': 9573, 'string': 'something', 'object': {}, 'array': [], 'boolean': False}
return normalize(schema, value, type_defaults)[0]
def normalize(schema, data, required_defaults=None):
if required_defaults is None:
required_defaults = {}
errors = []
class Datawrapper(object):
def __init__(self, data):
super(DataWrapper, self).__init__()
self.data = data
def get(self, key, default=None):
if isinstance(self.data, dict):
return self.data.get(key, default)
if hasattr(self.data, key):
return getattr(self.data, key)
else:
return default
def has(self, key):
if isinstance(self.data, dict):
return key in self.data
return hasattr(self.data, key)
def _normalize_dict(schema, data):
result = {}
data = data_wrapper(data)
for (key, _schema) in schema.get('properties', {}).iteritems():
type_ = _schema.get('type', 'object')
if 'default' not in _schema and key in schema.get('required', []) and (type_ in required_defaults):
_schema['default'] = required_defaults[type_]
if data.has(key):
result[key] = _normalize(_schema, data.get(key))
elif 'default' in _schema:
result[key] = _schema['default']
elif key in schema.get('required', []):
errors.append(dict(name='property_missing', message='`%s` is required' % key))
return result
def _normalize_list(schema, data):
result = []
if isinstance(data, (list, tuple)):
for item in data:
result.append(_normalize(schema.get('items'), item))
elif 'default' in schema:
result = schema['default']
return result
def _normalize_default(schema, data):
if data is None:
return schema.get('default')
else:
return data
def _normalize(schema, data):
if not schema:
return None
funcs = {'object': _normalize_dict, 'array': _normalize_list, 'default': _normalize_default}
type_ = schema.get('type', 'object')
if not type_ in funcs:
type_ = 'default'
return funcs[type_](schema, data)
return (_normalize(schema, data), errors) |
class Callback(object):
def __init__(self, fire_rate=1.0, fire_interval=None):
self.FireRate = fire_rate
self.NextFire = self.FireInterval = fire_interval
self.FireLevel = 0.0
self.FireCount = 0
def __call__(self, event, *params, **args):
self.FireCount += 1
self.FireLevel += self.FireRate
if self.FireInterval is not None and self.FireCount < self.NextFire:
return
if self.FireLevel < 1.0:
return
if hasattr(self, event):
getattr(self, event)(*params, **args)
self.FireLevel -= 1.0
if self.FireInterval is not None:
self.NextFire += self.FireInterval
class CallbackList(object):
#
# Sends event data to list of Callback objects and to list of callback functions
#
def __init__(self, *callbacks):
self.Callbacks = list(callbacks)
def add(self, *callbacks):
self.Callbacks += list(callbacks)
def __call__(self, event, *params, **args):
for cb in self.Callbacks:
cb(event, *params, **args)
@staticmethod
def convert(arg):
if isinstance(arg, CallbackList):
return arg
elif isinstance(arg, (list, tuple)):
return CallbackList(*arg)
elif arg is None:
return CallbackList() # empty
else:
raise ValueError("Can not convert %s to CallbackList" % (arg,))
| class Callback(object):
def __init__(self, fire_rate=1.0, fire_interval=None):
self.FireRate = fire_rate
self.NextFire = self.FireInterval = fire_interval
self.FireLevel = 0.0
self.FireCount = 0
def __call__(self, event, *params, **args):
self.FireCount += 1
self.FireLevel += self.FireRate
if self.FireInterval is not None and self.FireCount < self.NextFire:
return
if self.FireLevel < 1.0:
return
if hasattr(self, event):
getattr(self, event)(*params, **args)
self.FireLevel -= 1.0
if self.FireInterval is not None:
self.NextFire += self.FireInterval
class Callbacklist(object):
def __init__(self, *callbacks):
self.Callbacks = list(callbacks)
def add(self, *callbacks):
self.Callbacks += list(callbacks)
def __call__(self, event, *params, **args):
for cb in self.Callbacks:
cb(event, *params, **args)
@staticmethod
def convert(arg):
if isinstance(arg, CallbackList):
return arg
elif isinstance(arg, (list, tuple)):
return callback_list(*arg)
elif arg is None:
return callback_list()
else:
raise value_error('Can not convert %s to CallbackList' % (arg,)) |
class A(Exception):
def __init__(s, err, *args):
s.err = err
s.d = 2323
@property
def message(s):
return 'kawabunga'
def __str__(s):
return s.message
class B(A):
pass
try:
raise A('hh', 89)
except B as e:
print(1) | class A(Exception):
def __init__(s, err, *args):
s.err = err
s.d = 2323
@property
def message(s):
return 'kawabunga'
def __str__(s):
return s.message
class B(A):
pass
try:
raise a('hh', 89)
except B as e:
print(1) |
"""Classifier calibration techniques.
https://arxiv.org/pdf/1902.06977.pdf
https://arxiv.org/abs/1706.04599
"""
| """Classifier calibration techniques.
https://arxiv.org/pdf/1902.06977.pdf
https://arxiv.org/abs/1706.04599
""" |
string = input()
for i in range(len(string)):
emoticon = ''
if string[i] == ':':
emoticon += string[i] + string[i + 1]
print(emoticon)
| string = input()
for i in range(len(string)):
emoticon = ''
if string[i] == ':':
emoticon += string[i] + string[i + 1]
print(emoticon) |
# -*- encoding: utf-8 -*-
#######################################################################################################################
# DESCRIPTION:
#######################################################################################################################
# TODO
#######################################################################################################################
# AUTHORS:
#######################################################################################################################
# Carlos Serrada, 13-11347, <cserradag96@gmail.com>
# Juan Ortiz, 13-11021 <ortiz.juan14@gmail.com>
#######################################################################################################################
# CLASS DECLARATION:
#######################################################################################################################
class CNF:
def __init__(self):
self.clauses = []
self.variables = []
self.map = {}
def add(self, clause):
for term in clause.terms:
name = term.name
if not (name in self.map):
self.map[name] = len(self.variables)
self.variables.append(name)
self.clauses.append(clause)
def __str__(self):
header = "p cnf " + str(len(self.variables)) + " " + str(len(self.clauses)) + "\n"
cnf = ""
for clause in self.clauses:
for term in clause.terms:
cnf += ("-" if term.negative else "") + str(self.map[term.name] + 1) + " "
cnf += "0\n"
return header + cnf
def parse(self, file_path):
variables = []
with open(file_path) as file:
for index, line in enumerate(file):
if index == 1:
variables = [x > 0 for x in list(map(int, line.split(' ')))[:-1]]
return variables
def solve(self, file_path):
values = self.parse(file_path)
solution = {}
for i in range(len(values)):
solution[self.variables[i]] = values[i]
return solution
#######################################################################################################################
# :)
#######################################################################################################################
| class Cnf:
def __init__(self):
self.clauses = []
self.variables = []
self.map = {}
def add(self, clause):
for term in clause.terms:
name = term.name
if not name in self.map:
self.map[name] = len(self.variables)
self.variables.append(name)
self.clauses.append(clause)
def __str__(self):
header = 'p cnf ' + str(len(self.variables)) + ' ' + str(len(self.clauses)) + '\n'
cnf = ''
for clause in self.clauses:
for term in clause.terms:
cnf += ('-' if term.negative else '') + str(self.map[term.name] + 1) + ' '
cnf += '0\n'
return header + cnf
def parse(self, file_path):
variables = []
with open(file_path) as file:
for (index, line) in enumerate(file):
if index == 1:
variables = [x > 0 for x in list(map(int, line.split(' ')))[:-1]]
return variables
def solve(self, file_path):
values = self.parse(file_path)
solution = {}
for i in range(len(values)):
solution[self.variables[i]] = values[i]
return solution |
"""7. Reverse Integer
https://leetcode.com/problems/reverse-integer/
Given a signed 32-bit integer x, return x with its digits reversed. If
reversing x causes the value to go outside the signed 32-bit integer range
[-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or
unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-2^31 <= x <= 2^31 - 1
"""
class Solution:
def reverse(self, x: int) -> int:
maxsize = 2 ** 31 - 1
if x < 0:
return -self.reverse(-x)
string = str(x)
reversed_string = string[::-1]
ans = 0
for c in reversed_string:
ans = ans * 10 + int(c)
if ans > maxsize:
return 0
return ans
def reverse2(self, x: int) -> int:
if x < 0:
return -self.reverse2(-x)
ans = 0
maxsize = 2 ** 31 - 1
while x != 0:
x, y = divmod(x, 10)
ans = ans * 10 + y
return ans if ans <= maxsize else 0
| """7. Reverse Integer
https://leetcode.com/problems/reverse-integer/
Given a signed 32-bit integer x, return x with its digits reversed. If
reversing x causes the value to go outside the signed 32-bit integer range
[-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or
unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-2^31 <= x <= 2^31 - 1
"""
class Solution:
def reverse(self, x: int) -> int:
maxsize = 2 ** 31 - 1
if x < 0:
return -self.reverse(-x)
string = str(x)
reversed_string = string[::-1]
ans = 0
for c in reversed_string:
ans = ans * 10 + int(c)
if ans > maxsize:
return 0
return ans
def reverse2(self, x: int) -> int:
if x < 0:
return -self.reverse2(-x)
ans = 0
maxsize = 2 ** 31 - 1
while x != 0:
(x, y) = divmod(x, 10)
ans = ans * 10 + y
return ans if ans <= maxsize else 0 |
"""
Given an integer array with even length, where different numbers in this array represent different
kinds of candies. Each number means one candy of the corresponding kind. You need to distribute
these candies equally in number to brother and sister. Return the maximum number of kinds of
candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3],
too. The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The
sister has two different kinds of candies, the brother has only one kind of candies.
Note:
1. The length of the given array is in range [2, 10000], and will be even.
2. The number in given array is in range [-100000, 100000].
"""
class Solution:
def distributeCandies(self, candies):
return min(len(set(candies)), len(candies) // 2)
| """
Given an integer array with even length, where different numbers in this array represent different
kinds of candies. Each number means one candy of the corresponding kind. You need to distribute
these candies equally in number to brother and sister. Return the maximum number of kinds of
candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3],
too. The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The
sister has two different kinds of candies, the brother has only one kind of candies.
Note:
1. The length of the given array is in range [2, 10000], and will be even.
2. The number in given array is in range [-100000, 100000].
"""
class Solution:
def distribute_candies(self, candies):
return min(len(set(candies)), len(candies) // 2) |
'''
For a string sequence, a string word is k-repeating if word
concatenated k times is a substring of sequence. The word's
maximum k-repeating value is the highest value k where word
is k-repeating in sequence. If word is not a substring of
sequence, word's maximum k-repeating value is 0.
Given strings sequence and word, return the maximum
k-repeating value of word in sequence.
Example:
Input: sequence = "ababc", word = "ab"
Output: 2
Explanation: "abab" is a substring in "ababc".
Example:
Input: sequence = "ababc", word = "ba"
Output: 1
Explanation: "ba" is a substring in "ababc". "baba" is not
a substring in "ababc".
Example:
Input: sequence = "ababc", word = "ac"
Output: 0
Explanation: "ac" is not a substring in "ababc".
Constraints:
- 1 <= sequence.length <= 100
- 1 <= word.length <= 100
- sequence and word contains only lowercase English
letters.
'''
#Difficulty: Easy
#211 / 211 test cases passed.
#Runtime: 24 ms
#Memory Usage: 14.2 MB
#Runtime: 24 ms, faster than 96.10% of Python3 online submissions for Maximum Repeating Substring.
#Memory Usage: 14.2 MB, less than 75.28% of Python3 online submissions for Maximum Repeating Substring.
class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
x = 1
while word*x in sequence:
x += 1
return x-1
| """
For a string sequence, a string word is k-repeating if word
concatenated k times is a substring of sequence. The word's
maximum k-repeating value is the highest value k where word
is k-repeating in sequence. If word is not a substring of
sequence, word's maximum k-repeating value is 0.
Given strings sequence and word, return the maximum
k-repeating value of word in sequence.
Example:
Input: sequence = "ababc", word = "ab"
Output: 2
Explanation: "abab" is a substring in "ababc".
Example:
Input: sequence = "ababc", word = "ba"
Output: 1
Explanation: "ba" is a substring in "ababc". "baba" is not
a substring in "ababc".
Example:
Input: sequence = "ababc", word = "ac"
Output: 0
Explanation: "ac" is not a substring in "ababc".
Constraints:
- 1 <= sequence.length <= 100
- 1 <= word.length <= 100
- sequence and word contains only lowercase English
letters.
"""
class Solution:
def max_repeating(self, sequence: str, word: str) -> int:
x = 1
while word * x in sequence:
x += 1
return x - 1 |
altPulo, qntdCano = map(int, input().split())
canos = list(map(int, input().split()))
atual = canos.pop(0)
for cano in canos:
if max([cano, atual]) - min([cano, atual]) > altPulo:
print('GAME OVER')
quit()
atual = cano
print('YOU WIN')
| (alt_pulo, qntd_cano) = map(int, input().split())
canos = list(map(int, input().split()))
atual = canos.pop(0)
for cano in canos:
if max([cano, atual]) - min([cano, atual]) > altPulo:
print('GAME OVER')
quit()
atual = cano
print('YOU WIN') |
# this graph to check the algorithm
graph={
'S':['B','D','A'],
'A':['C'],
'B':['D'],
'C':['G','D'],
'S':['G'],
}
#function of BFS
def BFS(graph,start,goal):
Visited=[]
queue=[[start]]
while queue:
path=queue.pop(0)
node=path[-1]
if node in Visited:
continue
Visited.append(node)
if node==goal:
return path
else:
adjecent_nodes=graph.get(node,[])
for node2 in adjecent_nodes:
new_path=path.copy()
new_path.append(node2)
queue.append(new_path)
Solution=BFS(graph,'S','G')
print('Solution is ',Solution)
| graph = {'S': ['B', 'D', 'A'], 'A': ['C'], 'B': ['D'], 'C': ['G', 'D'], 'S': ['G']}
def bfs(graph, start, goal):
visited = []
queue = [[start]]
while queue:
path = queue.pop(0)
node = path[-1]
if node in Visited:
continue
Visited.append(node)
if node == goal:
return path
else:
adjecent_nodes = graph.get(node, [])
for node2 in adjecent_nodes:
new_path = path.copy()
new_path.append(node2)
queue.append(new_path)
solution = bfs(graph, 'S', 'G')
print('Solution is ', Solution) |
"""
1184. Distance Between Bus Stops
Easy
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination stops.
Example 1:
Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
Example 2:
Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
Example 3:
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
"""
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
a, b = min(start, destination), max(start, destination)
return min(sum(distance[a:b]), sum(distance)-sum(distance[a:b])) | """
1184. Distance Between Bus Stops
Easy
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination stops.
Example 1:
Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
Example 2:
Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
Example 3:
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
"""
class Solution:
def distance_between_bus_stops(self, distance: List[int], start: int, destination: int) -> int:
(a, b) = (min(start, destination), max(start, destination))
return min(sum(distance[a:b]), sum(distance) - sum(distance[a:b])) |
class Solution:
def solve(self, nums):
sameIndexAfterSortingCount = 0
sortedNums = sorted(nums)
for i in range(len(nums)):
if sortedNums[i] == nums[i]:
sameIndexAfterSortingCount += 1
return sameIndexAfterSortingCount
| class Solution:
def solve(self, nums):
same_index_after_sorting_count = 0
sorted_nums = sorted(nums)
for i in range(len(nums)):
if sortedNums[i] == nums[i]:
same_index_after_sorting_count += 1
return sameIndexAfterSortingCount |
S = 'shrubbery'
L = list(S)
print('L', L)
| s = 'shrubbery'
l = list(S)
print('L', L) |
def get_binary_nmubmer(decimal_number):
assert isinstance(decimal_number, int)
return bin(decimal_number)
print(get_binary_nmubmer(10.5)) | def get_binary_nmubmer(decimal_number):
assert isinstance(decimal_number, int)
return bin(decimal_number)
print(get_binary_nmubmer(10.5)) |
def is_kadomatsu(a):
if a[0] == a[1] or a[1] == a[2] or a[0] == a[2]:
return False
return min(a) == a[1] or max(a) == a[1]
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(3):
for j in range(3):
a[i], b[j] = b[j], a[i]
if is_kadomatsu(a) and is_kadomatsu(b):
print('Yes')
exit()
a[i], b[j] = b[j], a[i]
print('No')
| def is_kadomatsu(a):
if a[0] == a[1] or a[1] == a[2] or a[0] == a[2]:
return False
return min(a) == a[1] or max(a) == a[1]
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(3):
for j in range(3):
(a[i], b[j]) = (b[j], a[i])
if is_kadomatsu(a) and is_kadomatsu(b):
print('Yes')
exit()
(a[i], b[j]) = (b[j], a[i])
print('No') |
class Tesla:
# WRITE YOUR CODE HERE
def __init__(self, model: str, color: str, autopilot: bool = False, seats_count: int = 5, is_locked: bool = True, battery_charge: float = 99.9, efficiency: float = 0.3):
self.__model = model
self.__color = color
self.__autopilot = autopilot
self.__battery_charge = battery_charge
self.__is_locked = is_locked
self.__seats_count = seats_count
self.__efficiency = efficiency
@property
def color(self) -> str:
return self.__color
@property
def autopilot(self) -> str:
return self.__autopilot
@property
def seats_count(self) -> int:
return self.__seats_count
@property
def is_locked(self) -> bool:
return self.__is_locked
@property
def battery_charge(self) -> int:
return self.__battery_charge
@color.setter
def color(self, new_color: str) -> None:
self.__color = new_color
@autopilot.setter
def autopilot(self, autopilot: bool) -> None:
self.__autopilot = autopilot
@seats_count.setter
def seats_count(self, seats: int) -> None:
if(seats < 2):
return "Seats count cannot be lower than 2!"
self.__seats_count = seats
@is_locked.setter
def is_locked(self) -> None:
self.is_locked = True
def autopilot(self, obsticle: str) -> str:
'''
Takes in an obsticle object as string, returns string information about successfully avoiding the object or string information about availability of autopilot.
Parameters:
obsticle (str): An real world object that needs to be manuverd
Returns:
success (str): String informing about avoided obsticle
fail (str): String warning that the car does not have autopilot
'''
if self.__autopilot:
return f"Tesla model {self.__model} avoids {obsticle}"
return "Autopilot is not available"
#unlocking car
def unlock(self) -> None:
self.__is_locked = False
# opening doors
def open_doors(self) -> str:
'''
Returns string information about opening the doors of the car.
Parameters:
None
Returns:
success (str): String informing that the doors are opening
fail (str): String warning that the car is locked
'''
if(self.__is_locked):
return "Car is locked!"
return "Doors opens sideways"
# checking battery
def check_battery_level(self) -> str:
return f"Battery charge level is {self.__battery_charge}%"
# charging battery
def charge_battery(self) -> None:
self.__battery_charge = 100
# driving the car
def drive(self, travel_range: float):
'''
Takes in the travel distance number, returns remaining battery life or not enough battery warning.
Parameters:
travel_range (float): A float number
Returns:
battery_charge_level (str): String informing about remaining battery life
String warning (str): String warning that there is not enough battery to complete the travel distance
'''
battery_discharge_percent = travel_range * self.__efficiency
# COMPLETE THE FUNCTION
if self.__battery_charge - battery_discharge_percent >= 0:
self.__battery_charge = self.__battery_charge - battery_discharge_percent
return self.check_battery_level()
else:
return "Battery charge level is too low!"
def welcome(self) -> str:
raise NotImplementedError
| class Tesla:
def __init__(self, model: str, color: str, autopilot: bool=False, seats_count: int=5, is_locked: bool=True, battery_charge: float=99.9, efficiency: float=0.3):
self.__model = model
self.__color = color
self.__autopilot = autopilot
self.__battery_charge = battery_charge
self.__is_locked = is_locked
self.__seats_count = seats_count
self.__efficiency = efficiency
@property
def color(self) -> str:
return self.__color
@property
def autopilot(self) -> str:
return self.__autopilot
@property
def seats_count(self) -> int:
return self.__seats_count
@property
def is_locked(self) -> bool:
return self.__is_locked
@property
def battery_charge(self) -> int:
return self.__battery_charge
@color.setter
def color(self, new_color: str) -> None:
self.__color = new_color
@autopilot.setter
def autopilot(self, autopilot: bool) -> None:
self.__autopilot = autopilot
@seats_count.setter
def seats_count(self, seats: int) -> None:
if seats < 2:
return 'Seats count cannot be lower than 2!'
self.__seats_count = seats
@is_locked.setter
def is_locked(self) -> None:
self.is_locked = True
def autopilot(self, obsticle: str) -> str:
"""
Takes in an obsticle object as string, returns string information about successfully avoiding the object or string information about availability of autopilot.
Parameters:
obsticle (str): An real world object that needs to be manuverd
Returns:
success (str): String informing about avoided obsticle
fail (str): String warning that the car does not have autopilot
"""
if self.__autopilot:
return f'Tesla model {self.__model} avoids {obsticle}'
return 'Autopilot is not available'
def unlock(self) -> None:
self.__is_locked = False
def open_doors(self) -> str:
"""
Returns string information about opening the doors of the car.
Parameters:
None
Returns:
success (str): String informing that the doors are opening
fail (str): String warning that the car is locked
"""
if self.__is_locked:
return 'Car is locked!'
return 'Doors opens sideways'
def check_battery_level(self) -> str:
return f'Battery charge level is {self.__battery_charge}%'
def charge_battery(self) -> None:
self.__battery_charge = 100
def drive(self, travel_range: float):
"""
Takes in the travel distance number, returns remaining battery life or not enough battery warning.
Parameters:
travel_range (float): A float number
Returns:
battery_charge_level (str): String informing about remaining battery life
String warning (str): String warning that there is not enough battery to complete the travel distance
"""
battery_discharge_percent = travel_range * self.__efficiency
if self.__battery_charge - battery_discharge_percent >= 0:
self.__battery_charge = self.__battery_charge - battery_discharge_percent
return self.check_battery_level()
else:
return 'Battery charge level is too low!'
def welcome(self) -> str:
raise NotImplementedError |
def sum(*args):
total_sum = 0
for number in args:
total_sum += number
return total_sum
result = sum(1, 3, 4, 5, 8, 9, 16)
print({ 'result': result })
| def sum(*args):
total_sum = 0
for number in args:
total_sum += number
return total_sum
result = sum(1, 3, 4, 5, 8, 9, 16)
print({'result': result}) |
class VangError(Exception):
def __init__(self, msg=None, key=None):
self.msg = msg or {}
self.key = key
class InitError(Exception):
pass
| class Vangerror(Exception):
def __init__(self, msg=None, key=None):
self.msg = msg or {}
self.key = key
class Initerror(Exception):
pass |
BOS_TOKEN = '[unused98]'
EOS_TOKEN = '[unused99]'
CLS_TOKEN = '[CLS]'
SPACE_TOKEN = '[unused1]'
UNK_TOKEN = '[UNK]'
SPECIAL_TOKENS = [BOS_TOKEN, EOS_TOKEN, CLS_TOKEN, SPACE_TOKEN, UNK_TOKEN]
TRAIN = 'train'
EVAL = 'eval'
PREDICT = 'infer'
MODAL_LIST = ['image', 'others']
| bos_token = '[unused98]'
eos_token = '[unused99]'
cls_token = '[CLS]'
space_token = '[unused1]'
unk_token = '[UNK]'
special_tokens = [BOS_TOKEN, EOS_TOKEN, CLS_TOKEN, SPACE_TOKEN, UNK_TOKEN]
train = 'train'
eval = 'eval'
predict = 'infer'
modal_list = ['image', 'others'] |
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
ans = []
i = 0
while i < len(s):
di = min(len(s) - i, k)
ans.append(s[i:i + di][::-1])
i += di
di = min(len(s) - i, k)
ans.append(s[i:i + di])
i += di
return ''.join(ans) | class Solution:
def reverse_str(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
ans = []
i = 0
while i < len(s):
di = min(len(s) - i, k)
ans.append(s[i:i + di][::-1])
i += di
di = min(len(s) - i, k)
ans.append(s[i:i + di])
i += di
return ''.join(ans) |
def saveHigh(whatyouwant):
file = open('HighPriorityIssues.txt', 'a')
file.write(formatError(whatyouwant))
file.close()
def saveMedium(whatyouwant):
file = open('MediumPriorityIssues.txt', 'a')
file.write(formatError(whatyouwant))
file.close()
def saveLow(whatyouwant):
file = open('LowPriorityIssues.txt', 'a')
file.write(formatError(whatyouwant))
file.close()
def formatError(input):
if not isinstance(input, str):
return repr(input)
return input
| def save_high(whatyouwant):
file = open('HighPriorityIssues.txt', 'a')
file.write(format_error(whatyouwant))
file.close()
def save_medium(whatyouwant):
file = open('MediumPriorityIssues.txt', 'a')
file.write(format_error(whatyouwant))
file.close()
def save_low(whatyouwant):
file = open('LowPriorityIssues.txt', 'a')
file.write(format_error(whatyouwant))
file.close()
def format_error(input):
if not isinstance(input, str):
return repr(input)
return input |
#!/usr/bin/python3
def add(*matrices):
def check(data):
if data == 1:
return True
else:
raise ValueError
return [[sum(slice) for slice in zip(*row) if check(len(set(map(len, row))))]
for row in zip(*matrices) if check(len(set(map(len, matrices))))]
| def add(*matrices):
def check(data):
if data == 1:
return True
else:
raise ValueError
return [[sum(slice) for slice in zip(*row) if check(len(set(map(len, row))))] for row in zip(*matrices) if check(len(set(map(len, matrices))))] |
"""
:py:mod:`pypara` is a Python library for
- encoding currencies and monetary value objects,
- performing monetary arithmetic and conversions, and
- running rudimentary accounting operations.
Furthermore, there are some type convenience for general use.
The source code is organised in sub-packages and sub-modules.
"""
#: Defines the version of the package.
__version__ = "0.0.27.dev0"
| """
:py:mod:`pypara` is a Python library for
- encoding currencies and monetary value objects,
- performing monetary arithmetic and conversions, and
- running rudimentary accounting operations.
Furthermore, there are some type convenience for general use.
The source code is organised in sub-packages and sub-modules.
"""
__version__ = '0.0.27.dev0' |
# By Websten from forums
#
# Given your birthday and the current date, calculate your age in days.
# Account for leap days.
#
# Assume that the birthday and current date are correct dates (and no
# time travel).
#
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0]
if isLeap(year1):
daysOfMonths[1] = 29
else:
daysOfMonths[1] = 28
if year1 == year2:
return (daysOfMonths[month1-1] - day1) + sum(daysOfMonths[month1:month2-1]) + day2
totalDays = 0
for year in range(year1, year2 + 1):
if isLeap(year):
daysOfMonths[1] = 29
else:
daysOfMonths[1] = 28
if year == year1:
totalDays += (daysOfMonths[month1-1] - day1) + sum(daysOfMonths[month1:])
elif year == year2:
totalDays += day2 + sum(daysOfMonths[:month2 - 1])
else:
totalDays += sum(daysOfMonths)
return totalDays
# Test routine
def isLeap(year):
return (year % 100 == 0 and year % 400 == 0 ) or (year % 4 == 0 and year % 100 != 0)
#if year % 4 == 0:
#if year % 100 == 0:
#if year % 400 == 0:
#return True
#else:
#return False
#return True
#return False
def test():
test_cases = [((2012,1,1,2012,2,28), 58),
((2012,1,1,2012,3,1), 60),
((2011,6,30,2012,6,30), 366),
((2011,1,1,2012,8,8), 585 ),
((1900,1,1,1999,12,31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print ("Test with data:", args, "failed")
else:
print ("Test case passed!")
#test()
print(daysBetweenDates(1973,7,28,2018,1,13))
| def days_between_dates(year1, month1, day1, year2, month2, day2):
days_of_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0]
if is_leap(year1):
daysOfMonths[1] = 29
else:
daysOfMonths[1] = 28
if year1 == year2:
return daysOfMonths[month1 - 1] - day1 + sum(daysOfMonths[month1:month2 - 1]) + day2
total_days = 0
for year in range(year1, year2 + 1):
if is_leap(year):
daysOfMonths[1] = 29
else:
daysOfMonths[1] = 28
if year == year1:
total_days += daysOfMonths[month1 - 1] - day1 + sum(daysOfMonths[month1:])
elif year == year2:
total_days += day2 + sum(daysOfMonths[:month2 - 1])
else:
total_days += sum(daysOfMonths)
return totalDays
def is_leap(year):
return year % 100 == 0 and year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
def test():
test_cases = [((2012, 1, 1, 2012, 2, 28), 58), ((2012, 1, 1, 2012, 3, 1), 60), ((2011, 6, 30, 2012, 6, 30), 366), ((2011, 1, 1, 2012, 8, 8), 585), ((1900, 1, 1, 1999, 12, 31), 36523)]
for (args, answer) in test_cases:
result = days_between_dates(*args)
if result != answer:
print('Test with data:', args, 'failed')
else:
print('Test case passed!')
print(days_between_dates(1973, 7, 28, 2018, 1, 13)) |
class HWriter(object):
def __init__(self):
self.__bIsNewLine = True # are we at a new line position?
self.__bHasContent = False # do we already have content in this line?
self.__allParts = []
self.__prefix = ""
self.__nIndent = 0
#
def incrementIndent(self):
self.__nIndent += 1
if self.__nIndent > len(self.__prefix):
self.__prefix += "\t"
#
def decrementIndent(self):
if self.__nIndent == 0:
raise Exception("Indentation error!")
self.__nIndent -= 1
#
def write(self, *items):
# print("write( " + repr(items) + " )")
if self.__bIsNewLine:
self.__bIsNewLine = False
for item in items:
if hasattr(type(item), "__iter__"):
for i in item:
if len(i) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(i)
self.__bHasContent = True
else:
if len(item) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(item)
self.__bHasContent = True
#
def writeLn(self, *items):
# print("writeLn( " + repr(items) + " )")
if self.__bIsNewLine:
self.__bIsNewLine = False
for item in items:
if hasattr(type(item), "__iter__"):
for i in item:
if len(i) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(i)
self.__bHasContent = True
else:
if len(item) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(item)
self.__bHasContent = True
self.lineBreak()
#
#
# Add a line break if (and only if) the last item was not a line break.
# Typically you won't want to use this method but <c>writeLn</c> instead.
# <c>writeLn</c> will add a line in any case.
#
def lineBreak(self):
if not self.__bIsNewLine:
self.__bHasContent = False
self.__allParts.append("\n")
self.__bIsNewLine = True
#
#
# Get a list of lines (without line breaks).
#
def getLines(self) -> list:
ret = []
iStart = 0
iMax = len(self.__allParts)
for i in range(0, iMax):
if self.__allParts[i] == "\n":
ret.append("".join(self.__allParts[iStart:i]))
iStart = i + 1
if iMax > iStart:
ret.append("".join(self.__allParts[iStart:]))
return ret
#
def toString(self) -> str:
self.lineBreak()
return "".join(self.__allParts)
#
def __str__(self):
self.lineBreak()
return "".join(self.__allParts)
#
def __repr__(self):
return "HWriter<" + str(len(self.__allParts)) + " parts>"
#
#
| class Hwriter(object):
def __init__(self):
self.__bIsNewLine = True
self.__bHasContent = False
self.__allParts = []
self.__prefix = ''
self.__nIndent = 0
def increment_indent(self):
self.__nIndent += 1
if self.__nIndent > len(self.__prefix):
self.__prefix += '\t'
def decrement_indent(self):
if self.__nIndent == 0:
raise exception('Indentation error!')
self.__nIndent -= 1
def write(self, *items):
if self.__bIsNewLine:
self.__bIsNewLine = False
for item in items:
if hasattr(type(item), '__iter__'):
for i in item:
if len(i) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(i)
self.__bHasContent = True
elif len(item) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(item)
self.__bHasContent = True
def write_ln(self, *items):
if self.__bIsNewLine:
self.__bIsNewLine = False
for item in items:
if hasattr(type(item), '__iter__'):
for i in item:
if len(i) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(i)
self.__bHasContent = True
elif len(item) > 0:
if not self.__bHasContent:
self.__allParts.append(self.__prefix[:self.__nIndent])
self.__allParts.append(item)
self.__bHasContent = True
self.lineBreak()
def line_break(self):
if not self.__bIsNewLine:
self.__bHasContent = False
self.__allParts.append('\n')
self.__bIsNewLine = True
def get_lines(self) -> list:
ret = []
i_start = 0
i_max = len(self.__allParts)
for i in range(0, iMax):
if self.__allParts[i] == '\n':
ret.append(''.join(self.__allParts[iStart:i]))
i_start = i + 1
if iMax > iStart:
ret.append(''.join(self.__allParts[iStart:]))
return ret
def to_string(self) -> str:
self.lineBreak()
return ''.join(self.__allParts)
def __str__(self):
self.lineBreak()
return ''.join(self.__allParts)
def __repr__(self):
return 'HWriter<' + str(len(self.__allParts)) + ' parts>' |
class Symbol:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
class SymbolTable:
def __init__(self):
self._symbol_table = dict()
def put_symbol(self, symbol):
self._symbol_table[symbol] = 1
def get_symbol(self, symbol):
return self._symbol_table[symbol]
| class Symbol:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
class Symboltable:
def __init__(self):
self._symbol_table = dict()
def put_symbol(self, symbol):
self._symbol_table[symbol] = 1
def get_symbol(self, symbol):
return self._symbol_table[symbol] |
"""
Chovin Carlson - House by the Waves:
https://www.youtube.com/watch?v=nkU8r5QKN3Y
How to:
- Run the statements line by line (alt+enter),
go to the next one whenever you feel like
- The "#### > run block <" blocks should be
executed together (ctrl+enter)
- If you want to fast-forward through the song,
just execute the blocks together (ctrl+enter)
from the beginning, so you don't have to go
through every variation of each instrument
- Enjoy ! :+1:
"""
n1 >> noise(PSine(32),)
n1 >> noise(P(PSine(32),PSine(24)),)
n1 >> noise(P(PSine(32),PSine(24),PSine(27)),)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7),)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,formant=(linvar([1,3],48),linvar([3,1],53)),)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,formant=(linvar([1,3],48),linvar([3,1],53)),chop=16,)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,formant=(linvar([1,3],48),linvar([3,1],53)),chop=16,lpf=1200,lpr=(linvar([0,6],64),linvar([3,0],53))+PSine(5)*.7)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,formant=(linvar([1,3],48),linvar([3,1],53)),chop=0,lpf=1200,lpr=(linvar([0,6],64),linvar([3,0],53))+PSine(5)*.7)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,formant=(linvar([1,3],48),linvar([3,1],53)),chop=2,lpf=1200,lpr=(linvar([0,6],64),linvar([3,0],53))+PSine(5)*.7)
n1 >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,formant=(linvar([1,3],48),linvar([3,1],53)),chop=linvar([0,16],65),lpf=1200,lpr=(linvar([0,6],64),linvar([3,0],53)))
n1.reset() >> noise(P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),amp=P(.8,.7,.8,.7,.9)*.4,dur=.5,formant=(linvar([1,3],48),linvar([3,1],53)),chop=16,lpf=1200,lpr=(linvar([0,6],64),linvar([3,0],53)))
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12),)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.5,)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.5,delay=(0,PRand(b1.dur)/8),)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.5,delay=(0,PRand(b1.dur)/8),amp=.8,)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.5,delay=(0,PRand(b1.dur)/8),amp=.8,formant=1,)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.5,delay=(0,PRand(b1.dur)/8),amp=.8,formant=2,)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.5,delay=(0,PRand(b1.dur)/8),amp=.6,formant=2,)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.5,delay=(0,PRand([0,PRand(b1.dur)/8])),amp=.6,formant=2,)
b2 >> bell(0,dur=PRand(20)+.125,delay=(0,PRand([0,PRand(b2.dur)/3])),)
b2 >> bell(0,dur=PRand(20)+.125,delay=(0,PRand([0,PRand(b2.dur)/3])),amp=linvar([.25,.5],PRand(8,32)),)
b2 >> bell(0,dur=PRand(20)+.125,delay=(0,PRand([0,PRand(b2.dur)/3])),amp=linvar([.25,.5],PRand(8,32)),lpf=linvar([2200,4000],PRand(36)),)
b2 >> bell(0,dur=PRand(20)+.125,delay=(0,PRand([0,PRand(b2.dur)/3])),amp=linvar([.25,.5],PRand(8,32)),lpf=linvar([2200,4000],PRand(36)),oct=PRand([5,6]),)
b2 >> bell(0,dur=PRand(20)*1.25+.125,delay=(0,PRand([0,PRand(b2.dur)/3])),amp=linvar([.25,.5],PRand(8,32)),lpf=linvar([2200,4000],PRand(36)),oct=PRand([5,6]),)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.25,delay=(0,PRand([0,PRand(b1.dur)/8])),amp=.6,formant=2,)
s1 >> soprano([0,4,(3,1),2],dur=8,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,amp=.6,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,amp=.6,lpf=1200,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,amp=.2,lpf=1200,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,amp=.4,lpf=1200,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,amp=.6,lpf=1200,)
s2 >> spark((7,5,[4,9]),dur=PRand(6,24),)
s2 >> spark((7,5,[4,9]),dur=PRand(6,24),delay=P(0,.125,.25),)
s2 >> spark((7,5,[4,9]),dur=PRand(6,24),delay=P(0,.125,.25),sus=.15,)
s2 >> spark((7,5,[4,9]),dur=PRand(6,24),delay=P(0,.125,.25),sus=.15,chop=1,)
s2 >> spark((7,5,[4,9]),dur=PRand(6,24),delay=P(0,.125,.25),sus=.15,chop=1,amp=.8,)
s2 >> spark((7,5,[4,9]),dur=PRand(6,24),delay=P(0,.125,.25)*.8,sus=.15,chop=1,amp=.8,)
s2 >> spark((7,5,[4,[9,10]]),dur=PRand(6,24),delay=P(0,.125,.25)*.8,sus=.15,chop=1,amp=.8,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,0,0,0),dur=4,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,0,0,0),dur=4,amp=P(PRange(4,0,-1)/8+.25),)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,0,0,0),dur=4,amp=P(PRange(4,0,-1)/8+.25),delay=P(PRange(4,0,-1)/4),)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,0,0,0),dur=4,amp=P(PRange(4,0,-1)/8+.25),delay=P(PRange(4,0,-1)/4),formant=1,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,0,0,0),dur=4,amp=P(PRange(4,0,-1)/8+.25),delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,0,0,0),dur=4,amp=P(PRange(4,0,-1)/8+.25),delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,2),dur=4,amp=P(PRange(4,0,-1)/8+.25),delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=4,amp=P(PRange(4,0,-1)/8+.25),delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=4,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=.4,)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=.4,echo=1,)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=.4,echo=1,decay=1,)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=.4,echo=1,decay=1,sus=b3.dur-1.5,)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=.4,echo=1,decay=1,sus=b3.dur-1.5,formant=1,)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=.4,echo=1,decay=1,sus=b3.dur-1.5,formant=(0,1),)
b1 >> blip(PRand(8)+(0,PRand(4)),dur=PRand(2,12)*1.25,delay=(0,PRand([0,PRand(b1.dur)/8])),amp=.5,formant=2,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,amp=.5,lpf=1200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=3,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=2.5,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=2,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=1.5,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=1,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=.75,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=.5,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=.25,amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
#### > run block <
piv = [1,1.5,2,2.5,3,3,4,4]
piv.extend(piv[::-1])
pivd = 16
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=var(piv,pivd),amp=P(PRange(4,0,-1)/8+.25)*.6,delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
#### > run block <
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=.3,echo=1,decay=1,sus=b3.dur-1.5,formant=(0,1),)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=(.4,.3),echo=1,decay=1,sus=b3.dur-1.5,formant=(0,1),)
#### > run block < danger
piv = [0.25,0.25,1/3,1/3,0.5,0.625,0.75,0.875,1,1.5,2,2.5,3,3,4,4]
piv.extend(piv[::-1])
pivd = 8
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=var(piv,pivd),amp=P(PRange(4,0,-1)/8+.25)*linvar([.4,.6,.4],[[pivd*2]+[pivd*(len(piv)-4)]+[pivd*2]]),delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
#### > run block <
p1 >> pluck(var([9,7,3,4,2,1],8) + (0,2,0,[4,5,6]),dur=Pvar([linvar(piv,pivd),var(piv,pivd)],len(piv)*pivd),amp=P(PRange(4,0,-1)/8+.25)*linvar([.4,.6,.4],[[pivd*2]+[pivd*(len(piv)-4)]+[pivd*2]]),delay=P(PRange(4,0,-1)/4),formant=1,lpf=1500,hpf=200,)
s1 >> soprano([0,4,(3,1),2],dur=8,sus=s1.dur/2,amp=.6,lpf=1200,)
b3 >> bass((p1.degree-1)+(0,2),dur=8,amp=(.4,.3),echo=1,decay=1,sus=b3.dur-1.5,formant=(0,1),)
Group(p1).amplify = 0.9
Group(p1).amplify = 0.8
Group(p1).amplify = 0.7
Group(p1,s2).amplify = 0.7
Group(p1,s2,b1).amplify = 0.7
Group(p1,s2,b1).amplify = 0.6
Group(p1,s2,b1,s1).amplify = 0.6
Group(p1,s2,b1,s1,b2).amplify = 0.6
Group(p1,s2,b1,s1,b2).amplify = 0.5
Group(p1,s2,b1,s1,b2,n1).amplify = 0.5
Group(p1,s2,b1,s1,b2,n1).amplify = 0.4
Group(p1,s2,b1,s1,b2,n1).amplify = 0.3
Group(p1,s2,b1,s1,b2,n1).amplify = 0.2
Group(p1,s2,b1,s1,b2,n1,b3).amplify = 0.2
Group(p1,s2,b1,s1,b2,n1,b3).amplify = 0.4
Group(p1,s2,b1,s1,b2,n1,b3).amplify = 0
| """
Chovin Carlson - House by the Waves:
https://www.youtube.com/watch?v=nkU8r5QKN3Y
How to:
- Run the statements line by line (alt+enter),
go to the next one whenever you feel like
- The "#### > run block <" blocks should be
executed together (ctrl+enter)
- If you want to fast-forward through the song,
just execute the blocks together (ctrl+enter)
from the beginning, so you don't have to go
through every variation of each instrument
- Enjoy ! :+1:
"""
n1 >> noise(p_sine(32))
n1 >> noise(p(p_sine(32), p_sine(24)))
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27)))
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7))
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)))
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4)
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5)
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5, formant=(linvar([1, 3], 48), linvar([3, 1], 53)))
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5, formant=(linvar([1, 3], 48), linvar([3, 1], 53)), chop=16)
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5, formant=(linvar([1, 3], 48), linvar([3, 1], 53)), chop=16, lpf=1200, lpr=(linvar([0, 6], 64), linvar([3, 0], 53)) + p_sine(5) * 0.7)
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5, formant=(linvar([1, 3], 48), linvar([3, 1], 53)), chop=0, lpf=1200, lpr=(linvar([0, 6], 64), linvar([3, 0], 53)) + p_sine(5) * 0.7)
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5, formant=(linvar([1, 3], 48), linvar([3, 1], 53)), chop=2, lpf=1200, lpr=(linvar([0, 6], 64), linvar([3, 0], 53)) + p_sine(5) * 0.7)
n1 >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5, formant=(linvar([1, 3], 48), linvar([3, 1], 53)), chop=linvar([0, 16], 65), lpf=1200, lpr=(linvar([0, 6], 64), linvar([3, 0], 53)))
n1.reset() >> noise(p(p_sine(32), p_sine(24), p_sine(27), p_sine(18) * 0.7, p_sine(45)), amp=p(0.8, 0.7, 0.8, 0.7, 0.9) * 0.4, dur=0.5, formant=(linvar([1, 3], 48), linvar([3, 1], 53)), chop=16, lpf=1200, lpr=(linvar([0, 6], 64), linvar([3, 0], 53)))
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12))
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.5)
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.5, delay=(0, p_rand(b1.dur) / 8))
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.5, delay=(0, p_rand(b1.dur) / 8), amp=0.8)
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.5, delay=(0, p_rand(b1.dur) / 8), amp=0.8, formant=1)
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.5, delay=(0, p_rand(b1.dur) / 8), amp=0.8, formant=2)
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.5, delay=(0, p_rand(b1.dur) / 8), amp=0.6, formant=2)
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.5, delay=(0, p_rand([0, p_rand(b1.dur) / 8])), amp=0.6, formant=2)
b2 >> bell(0, dur=p_rand(20) + 0.125, delay=(0, p_rand([0, p_rand(b2.dur) / 3])))
b2 >> bell(0, dur=p_rand(20) + 0.125, delay=(0, p_rand([0, p_rand(b2.dur) / 3])), amp=linvar([0.25, 0.5], p_rand(8, 32)))
b2 >> bell(0, dur=p_rand(20) + 0.125, delay=(0, p_rand([0, p_rand(b2.dur) / 3])), amp=linvar([0.25, 0.5], p_rand(8, 32)), lpf=linvar([2200, 4000], p_rand(36)))
b2 >> bell(0, dur=p_rand(20) + 0.125, delay=(0, p_rand([0, p_rand(b2.dur) / 3])), amp=linvar([0.25, 0.5], p_rand(8, 32)), lpf=linvar([2200, 4000], p_rand(36)), oct=p_rand([5, 6]))
b2 >> bell(0, dur=p_rand(20) * 1.25 + 0.125, delay=(0, p_rand([0, p_rand(b2.dur) / 3])), amp=linvar([0.25, 0.5], p_rand(8, 32)), lpf=linvar([2200, 4000], p_rand(36)), oct=p_rand([5, 6]))
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.25, delay=(0, p_rand([0, p_rand(b1.dur) / 8])), amp=0.6, formant=2)
s1 >> soprano([0, 4, (3, 1), 2], dur=8)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2, amp=0.6)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2, amp=0.6, lpf=1200)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2, amp=0.2, lpf=1200)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2, amp=0.4, lpf=1200)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2, amp=0.6, lpf=1200)
s2 >> spark((7, 5, [4, 9]), dur=p_rand(6, 24))
s2 >> spark((7, 5, [4, 9]), dur=p_rand(6, 24), delay=p(0, 0.125, 0.25))
s2 >> spark((7, 5, [4, 9]), dur=p_rand(6, 24), delay=p(0, 0.125, 0.25), sus=0.15)
s2 >> spark((7, 5, [4, 9]), dur=p_rand(6, 24), delay=p(0, 0.125, 0.25), sus=0.15, chop=1)
s2 >> spark((7, 5, [4, 9]), dur=p_rand(6, 24), delay=p(0, 0.125, 0.25), sus=0.15, chop=1, amp=0.8)
s2 >> spark((7, 5, [4, 9]), dur=p_rand(6, 24), delay=p(0, 0.125, 0.25) * 0.8, sus=0.15, chop=1, amp=0.8)
s2 >> spark((7, 5, [4, [9, 10]]), dur=p_rand(6, 24), delay=p(0, 0.125, 0.25) * 0.8, sus=0.15, chop=1, amp=0.8)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 0, 0, 0), dur=4)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 0, 0, 0), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25))
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 0, 0, 0), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25), delay=p(p_range(4, 0, -1) / 4))
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 0, 0, 0), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25), delay=p(p_range(4, 0, -1) / 4), formant=1)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 0, 0, 0), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25), delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 0, 0, 0), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25), delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, 2), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25), delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25), delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=4, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=0.4)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=0.4, echo=1)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=0.4, echo=1, decay=1)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=0.4, echo=1, decay=1, sus=b3.dur - 1.5)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=0.4, echo=1, decay=1, sus=b3.dur - 1.5, formant=1)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=0.4, echo=1, decay=1, sus=b3.dur - 1.5, formant=(0, 1))
b1 >> blip(p_rand(8) + (0, p_rand(4)), dur=p_rand(2, 12) * 1.25, delay=(0, p_rand([0, p_rand(b1.dur) / 8])), amp=0.5, formant=2)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2, amp=0.5, lpf=1200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=3, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=2.5, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=2, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=1.5, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=1, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=0.75, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=0.5, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=0.25, amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
piv = [1, 1.5, 2, 2.5, 3, 3, 4, 4]
piv.extend(piv[::-1])
pivd = 16
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=var(piv, pivd), amp=p(p_range(4, 0, -1) / 8 + 0.25) * 0.6, delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=0.3, echo=1, decay=1, sus=b3.dur - 1.5, formant=(0, 1))
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=(0.4, 0.3), echo=1, decay=1, sus=b3.dur - 1.5, formant=(0, 1))
piv = [0.25, 0.25, 1 / 3, 1 / 3, 0.5, 0.625, 0.75, 0.875, 1, 1.5, 2, 2.5, 3, 3, 4, 4]
piv.extend(piv[::-1])
pivd = 8
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=var(piv, pivd), amp=p(p_range(4, 0, -1) / 8 + 0.25) * linvar([0.4, 0.6, 0.4], [[pivd * 2] + [pivd * (len(piv) - 4)] + [pivd * 2]]), delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
p1 >> pluck(var([9, 7, 3, 4, 2, 1], 8) + (0, 2, 0, [4, 5, 6]), dur=pvar([linvar(piv, pivd), var(piv, pivd)], len(piv) * pivd), amp=p(p_range(4, 0, -1) / 8 + 0.25) * linvar([0.4, 0.6, 0.4], [[pivd * 2] + [pivd * (len(piv) - 4)] + [pivd * 2]]), delay=p(p_range(4, 0, -1) / 4), formant=1, lpf=1500, hpf=200)
s1 >> soprano([0, 4, (3, 1), 2], dur=8, sus=s1.dur / 2, amp=0.6, lpf=1200)
b3 >> bass(p1.degree - 1 + (0, 2), dur=8, amp=(0.4, 0.3), echo=1, decay=1, sus=b3.dur - 1.5, formant=(0, 1))
group(p1).amplify = 0.9
group(p1).amplify = 0.8
group(p1).amplify = 0.7
group(p1, s2).amplify = 0.7
group(p1, s2, b1).amplify = 0.7
group(p1, s2, b1).amplify = 0.6
group(p1, s2, b1, s1).amplify = 0.6
group(p1, s2, b1, s1, b2).amplify = 0.6
group(p1, s2, b1, s1, b2).amplify = 0.5
group(p1, s2, b1, s1, b2, n1).amplify = 0.5
group(p1, s2, b1, s1, b2, n1).amplify = 0.4
group(p1, s2, b1, s1, b2, n1).amplify = 0.3
group(p1, s2, b1, s1, b2, n1).amplify = 0.2
group(p1, s2, b1, s1, b2, n1, b3).amplify = 0.2
group(p1, s2, b1, s1, b2, n1, b3).amplify = 0.4
group(p1, s2, b1, s1, b2, n1, b3).amplify = 0 |
#Max retorna o maior numero de um iteravel ou o maior de 2 ou mais elementos
#Min retorna o menor numero de um iteravel ou o menor de 2 ou mais elementos
lista=[9,5,2,1,4,5,3,6,21,5,4,55,0]
print(max(lista))
print(max(8,9,5,7,4,5,6))
dicionario={'a':0,'b':1,'f':51,'g':12,'q':5,'u':3,'d':2}
print(max(dicionario))
print(max(dicionario.values()))
print(min(lista))
print(min(8,9,5,7,4,5,6))
dicionario1={'a':0,'b':1,'f':51,'g':12,'q':5,'u':3,'d':2}
print(min(dicionario1))
print(min(dicionario1.values()))
nomes=['alexandre', 'maiure','joselito']
print(min(nomes)) #pela ordem alfabetica
print(max(nomes)) #pela ordem alfabetica | lista = [9, 5, 2, 1, 4, 5, 3, 6, 21, 5, 4, 55, 0]
print(max(lista))
print(max(8, 9, 5, 7, 4, 5, 6))
dicionario = {'a': 0, 'b': 1, 'f': 51, 'g': 12, 'q': 5, 'u': 3, 'd': 2}
print(max(dicionario))
print(max(dicionario.values()))
print(min(lista))
print(min(8, 9, 5, 7, 4, 5, 6))
dicionario1 = {'a': 0, 'b': 1, 'f': 51, 'g': 12, 'q': 5, 'u': 3, 'd': 2}
print(min(dicionario1))
print(min(dicionario1.values()))
nomes = ['alexandre', 'maiure', 'joselito']
print(min(nomes))
print(max(nomes)) |
# Input your Wi-Fi credentials here, if applicable, and rename to "secrets.py"
ssid = ''
wpa = ''
| ssid = ''
wpa = '' |
# To use this bot you need to set up the bot in here,
# You need to decide the prefix you want to use,
# and you need your Token and Application ID from
# the discord page where you manage your apps and bots.
# You need your User ID which you can get from the
# context menu on your name in discord under Copy ID.
# if you want to make more than 30 requests per hour to
# data.gov apis like nasa you will need to get an api key to
# replace "DEMO_KEY" below. The openweathermap (!wx),
# wolframalpha (!ask) and exchangerate-api.com apis need a
# free key from their websites to function.
# Add QRZ username and password for callsign lookup function
BOT_PREFIX = ("YOUR_BOT_PREFIX_HERE")
TOKEN = "YOUR_TOKEN_HERE"
APPLICATION_ID = "YOUR_APPLICATION_ID"
OWNERS = [123456789, 987654321]
DATA_GOV_API_KEY = "DEMO_KEY"
OPENWEATHER_API_KEY = "YOUR_API_KEY_HERE"
WOLFRAMALPHA_API_KEY = "YOUR_API_KEY_HERE"
EXCHANGERATE_API_KEY = "YOUR_API_KEY_HERE"
#QRZ_USERNAME = "YOUR_QRZ_USERNAME" #only used if using direct qrz access instead of qrmbot qrz
#QRZ_PASSWORD = "YOUR_QRZ_PASSWORD"
GOOGLEGEO_API_KEY = "YOUR_API_KEY_HERE"
WEBHOOK_URL = "https://webhookurl.here/"
APRS_FI_API_KEY = "YOUR_API_KEY_HERE"
APRS_FI_HTTP_AGENT = "lidbot/current (+https://github.com/vk3dan/sturdy-lidbot)"
BLACKLIST = []
# Default cogs that I use in the bot at the moment
STARTUP_COGS = [
"cogs.general", "cogs.help", "cogs.owner", "cogs.ham", "cogs.gonkphone"
] | bot_prefix = 'YOUR_BOT_PREFIX_HERE'
token = 'YOUR_TOKEN_HERE'
application_id = 'YOUR_APPLICATION_ID'
owners = [123456789, 987654321]
data_gov_api_key = 'DEMO_KEY'
openweather_api_key = 'YOUR_API_KEY_HERE'
wolframalpha_api_key = 'YOUR_API_KEY_HERE'
exchangerate_api_key = 'YOUR_API_KEY_HERE'
googlegeo_api_key = 'YOUR_API_KEY_HERE'
webhook_url = 'https://webhookurl.here/'
aprs_fi_api_key = 'YOUR_API_KEY_HERE'
aprs_fi_http_agent = 'lidbot/current (+https://github.com/vk3dan/sturdy-lidbot)'
blacklist = []
startup_cogs = ['cogs.general', 'cogs.help', 'cogs.owner', 'cogs.ham', 'cogs.gonkphone'] |
# Constants
VERSION = '2.0'
STATUS_GREY = 'lair-grey'
STATUS_BLUE = 'lair-blue'
STATUS_GREEN = 'lair-greeen'
STATUS_ORANGE = 'lair-orange'
STATUS_RED = 'lair-red'
STATUS_MAP = [STATUS_GREY, STATUS_BLUE, STATUS_GREEN, STATUS_ORANGE, STATUS_RED]
PROTOCOL_TCP = 'tcp'
PROTOCOL_UDP = 'udp'
PROTOCOL_ICMP = 'icmp'
PRODUCT_UNKNOWN = 'unknown'
SERVICE_UNKNOWN = 'unknown'
RATING_HIGH = 'high'
RATING_MEDIUM = 'medium'
RATING_LOW = 'low'
# Main dictionary used to relate all data
project = {
'_id': '',
'name': '',
'industry': '',
'createdAt': '',
'description': '',
'owner': '',
'contributors': [], # List of strings
'commands': [], # List of 'command' items
'notes': [], # List of 'note' items
'droneLog': [], # List of strings
'tool': '',
'hosts': [], # List of 'host' items
'issues': [], # List of 'issue' items
'authInterfaces': [], # List of 'auth_interface' items
'netblocks': [], # List of 'netblock' items
'people': [], # List of 'person' items
'credentials': [] # List of 'credential' items
}
# Represents a single host
host = {
'_id': '',
'projectId': '',
'longIpv4Addr': 0, # Integer version of IP address
'ipv4': '',
'mac': '',
'hostnames': [], # List of strings
'os': dict(), # 'os' item
'notes': [], # List of 'note' items
'statusMessage': '', # Used to label host in Lair, can be arbitrary
'tags': [], # List of strings
'status': '', # See the STATUS_* constants for allowable strings
'lastModifiedBy': '',
'isFlagged': False,
'files': [], # List of 'file' items
'webDirectories': [], # List of 'web_directory' items
'services': [] # List of 'service' items
}
# Represents a single service/port
service = {
'_id': '',
'projectId': '',
'hostId': '',
'port': 0,
'protocol': PROTOCOL_TCP, # See the PROTOCOL_* constants for allowable strings
'service': '',
'product': '',
'status': '', # See the STATUS_* constants for allowable strings
'isFlagged': False,
'lastModifiedBy': '',
'notes': [], # List of 'note' items
'files': [], # List of 'file' items
}
# Represents a single issue
issue = {
'_id': '',
'projectId': '',
'title': '',
'cvss': 0.0,
'rating': '', # See the RATING_* constants for allowable strings
'isConfirmed': False,
'description': '',
'evidence': '',
'solution': '',
'hosts': [], # List of 'issue_host' items
'pluginIds': [], # List of 'plugin_id' items
'cves': [], # List of strings
'references': [], # List of 'issue_reference' items
'identifiedBy': dict(), # 'identified_by' object
'isFlagged': False,
'status': '', # See the STATUS_* constants for allowable strings
'lastModifiedBy': '',
'notes': [], # List of 'note' items
'files': [] # List of 'file' items
}
# Represents an authentication interface
auth_interface = {
'_id': '',
'projectId': '',
'isMultifactor': False,
'kind': '', # What type of interface (e.g. Cisco, Juniper)
'url': '',
'description': ''
}
# Represents a single netblock
netblock = {
'_id': '',
'projectId': '',
'asn': '',
'asnCountryCode': '',
'asnCidr': '',
'asnDate': '',
'asnRegistry': '',
'cidr': '',
'abuseEmails': '',
'miscEmails': '',
'techEmails': '',
'name': '',
'address': '',
'city': '',
'state': '',
'country': '',
'postalCode': '',
'created': '',
'updated': '',
'description': '',
'handle': ''
}
# Represents a single person
person = {
'_id': '',
'projectId': '',
'principalName': '',
'samAccountName': '',
'distinguishedName': '',
'firstName': '',
'middleName': '',
'lastName': '',
'displayName': '',
'department': '',
'description': '',
'address': '',
'emails': [], # List of strings
'phones': [], # List of strings
'references': [], # List of 'person_reference' items
'groups': [], # List of strings
'lastLogon': '',
'lastLogoff': '',
'loggedIn': [] # List of strings
}
# Represents a single credentials
credential = {
'_id': '',
'projectId': '',
'username': '',
'password': '',
'format': '',
'hash': '',
'host': '', # Free-form value of host
'service': '' # Free-form value of service
}
# Represents an operating system
os = {
'tool': '',
'weight': 0, # Confidence level between 0-100
'fingerprint': 'unknown'
}
# Represents a web directory
web_directory = {
'_id': '',
'projectId': '',
'hostId': '',
'path': '',
'port': 0,
'responseCode': '404', # String version of HTTP response code.
'lastModifiedBy': '',
'isFlagged': False
}
# Dictionary used to represent a specific command run by a tool
command = {
'tool': '',
'command': ''
}
# Dictionariy used to represent a note.
note = {
'title': '',
'content': '',
'lastModifiedBy': ''
}
# Represents a file object
file = {
'fileName': '',
'url': ''
}
# Represents a reference to a host. Used for correlating an issue
# to a specific host.
issue_host = {
'ipv4': '',
'port': 0,
'protocol': PROTOCOL_TCP # See PROTOCOL_* constants for allowable values
}
# Represents a plugin (a unique identifier for a specific tool)
plugin_id = {
'tool': '',
'id': ''
}
# Represents a reference to a 3rd party site that contains issue details
issue_reference = {
'link': '', # Target URL
'name': '' # Link display
}
# Represents the tool that identified a specific issue
identified_by = {
'tool': ''
}
# Represents a reference from a person to a third party site
person_reference = {
'description': '',
'username': '',
'link': '' # Target URL
}
| version = '2.0'
status_grey = 'lair-grey'
status_blue = 'lair-blue'
status_green = 'lair-greeen'
status_orange = 'lair-orange'
status_red = 'lair-red'
status_map = [STATUS_GREY, STATUS_BLUE, STATUS_GREEN, STATUS_ORANGE, STATUS_RED]
protocol_tcp = 'tcp'
protocol_udp = 'udp'
protocol_icmp = 'icmp'
product_unknown = 'unknown'
service_unknown = 'unknown'
rating_high = 'high'
rating_medium = 'medium'
rating_low = 'low'
project = {'_id': '', 'name': '', 'industry': '', 'createdAt': '', 'description': '', 'owner': '', 'contributors': [], 'commands': [], 'notes': [], 'droneLog': [], 'tool': '', 'hosts': [], 'issues': [], 'authInterfaces': [], 'netblocks': [], 'people': [], 'credentials': []}
host = {'_id': '', 'projectId': '', 'longIpv4Addr': 0, 'ipv4': '', 'mac': '', 'hostnames': [], 'os': dict(), 'notes': [], 'statusMessage': '', 'tags': [], 'status': '', 'lastModifiedBy': '', 'isFlagged': False, 'files': [], 'webDirectories': [], 'services': []}
service = {'_id': '', 'projectId': '', 'hostId': '', 'port': 0, 'protocol': PROTOCOL_TCP, 'service': '', 'product': '', 'status': '', 'isFlagged': False, 'lastModifiedBy': '', 'notes': [], 'files': []}
issue = {'_id': '', 'projectId': '', 'title': '', 'cvss': 0.0, 'rating': '', 'isConfirmed': False, 'description': '', 'evidence': '', 'solution': '', 'hosts': [], 'pluginIds': [], 'cves': [], 'references': [], 'identifiedBy': dict(), 'isFlagged': False, 'status': '', 'lastModifiedBy': '', 'notes': [], 'files': []}
auth_interface = {'_id': '', 'projectId': '', 'isMultifactor': False, 'kind': '', 'url': '', 'description': ''}
netblock = {'_id': '', 'projectId': '', 'asn': '', 'asnCountryCode': '', 'asnCidr': '', 'asnDate': '', 'asnRegistry': '', 'cidr': '', 'abuseEmails': '', 'miscEmails': '', 'techEmails': '', 'name': '', 'address': '', 'city': '', 'state': '', 'country': '', 'postalCode': '', 'created': '', 'updated': '', 'description': '', 'handle': ''}
person = {'_id': '', 'projectId': '', 'principalName': '', 'samAccountName': '', 'distinguishedName': '', 'firstName': '', 'middleName': '', 'lastName': '', 'displayName': '', 'department': '', 'description': '', 'address': '', 'emails': [], 'phones': [], 'references': [], 'groups': [], 'lastLogon': '', 'lastLogoff': '', 'loggedIn': []}
credential = {'_id': '', 'projectId': '', 'username': '', 'password': '', 'format': '', 'hash': '', 'host': '', 'service': ''}
os = {'tool': '', 'weight': 0, 'fingerprint': 'unknown'}
web_directory = {'_id': '', 'projectId': '', 'hostId': '', 'path': '', 'port': 0, 'responseCode': '404', 'lastModifiedBy': '', 'isFlagged': False}
command = {'tool': '', 'command': ''}
note = {'title': '', 'content': '', 'lastModifiedBy': ''}
file = {'fileName': '', 'url': ''}
issue_host = {'ipv4': '', 'port': 0, 'protocol': PROTOCOL_TCP}
plugin_id = {'tool': '', 'id': ''}
issue_reference = {'link': '', 'name': ''}
identified_by = {'tool': ''}
person_reference = {'description': '', 'username': '', 'link': ''} |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/996/A
total = int(input())
bills = [100,20,10,5,1]
nob = 0
for b in bills:
nob += total//b
total = total%b
if total == 0:
break
print(nob)
| total = int(input())
bills = [100, 20, 10, 5, 1]
nob = 0
for b in bills:
nob += total // b
total = total % b
if total == 0:
break
print(nob) |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 2 11:25:48 2020
@author: Tarun Jaiswal
"""
'''
a=int(input("A= "))
b=int(input("B= "))
c=int(input("C= "))
d=int(input("D= "))
max=a
variablename="a= "
if b>max:
variablename="b= "
max=b
if c>max:
variablename="c= "
max=c
if d>max:
variablename="d= "
max=d
print(variablename, max)
'''
a=int(input("A= "))
b=int(input("B= "))
c=int(input("C= "))
d=int(input("D= "))
e=int(input("E= "))
max=a
Variablename="a= "
if b>max:
Variablename="b= "
max=b
if c>max:
variablename="c= "
max=c
if d>max:
Variablename="d= "
max=d
if e>max:
variablename="e= "
max=e
print(variablename, max) | """
Created on Fri Oct 2 11:25:48 2020
@author: Tarun Jaiswal
"""
'\na=int(input("A= "))\nb=int(input("B= "))\nc=int(input("C= "))\nd=int(input("D= "))\nmax=a\nvariablename="a= "\nif b>max:\n variablename="b= "\n max=b\nif c>max:\n variablename="c= "\n max=c\nif d>max:\n variablename="d= "\n max=d\nprint(variablename, max)\n \n'
a = int(input('A= '))
b = int(input('B= '))
c = int(input('C= '))
d = int(input('D= '))
e = int(input('E= '))
max = a
variablename = 'a= '
if b > max:
variablename = 'b= '
max = b
if c > max:
variablename = 'c= '
max = c
if d > max:
variablename = 'd= '
max = d
if e > max:
variablename = 'e= '
max = e
print(variablename, max) |
# Copyright (c) 2020 Anastasiia Birillo
class VkCity:
def __init__(self, data: dict) -> None:
self.id = data['id']
self.title = data.get('title')
def __str__(self):
return f"[{', '.join(map(lambda key: f'{key}={self.__dict__[key]}', self.__dict__))}]"
class VkUser:
def __init__(self, data: dict) -> None:
self.id = data['id']
self.first_name = data.get('first_name')
self.last_name = data.get('last_name')
self.sex = data.get('sex')
self.domain = data.get('domain')
self.city = data.get('about')
self.city = VkCity(data.get('city')) if data.get('city') is not None else None
def __str__(self):
return f"[{', '.join(map(lambda key: f'{key}={self.__dict__[key]}', self.__dict__))}]" | class Vkcity:
def __init__(self, data: dict) -> None:
self.id = data['id']
self.title = data.get('title')
def __str__(self):
return f"[{', '.join(map(lambda key: f'{key}={self.__dict__[key]}', self.__dict__))}]"
class Vkuser:
def __init__(self, data: dict) -> None:
self.id = data['id']
self.first_name = data.get('first_name')
self.last_name = data.get('last_name')
self.sex = data.get('sex')
self.domain = data.get('domain')
self.city = data.get('about')
self.city = vk_city(data.get('city')) if data.get('city') is not None else None
def __str__(self):
return f"[{', '.join(map(lambda key: f'{key}={self.__dict__[key]}', self.__dict__))}]" |
GENDER_VALUES = (('M', 'Male'),
('F', 'Female'),
('TG', 'Transgender'))
MARITAL_STATUS_VALUES = (('M', 'Married'),
('S', 'Single'),
('U', 'Unknown'))
CATEGORY_VALUES = (('BR', 'Bramhachari'),
('FTT', 'Full Time Teacher'),
('PTT', 'Part Time Teacher'),
('FTV', 'Full Time Volunteer'),
('VOL', 'Volunteer'),
('STAFF', 'Staff'),
('SEV', 'Sevadhar'))
STATUS_VALUES = (('ACTV', 'Active'),
('INACTV', 'Inactive'),
('EXPD', 'Deceased'))
ID_PROOF_VALUES = (('DL', 'Driving License'),
('PP', 'Passport'),
('RC', 'Ration Card'),
('VC', 'Voters ID'),
('AA', 'Aadhaar'),
('PC', 'PAN Card'),
('OT', 'Other Government Issued'))
ROLE_LEVEL_CHOICES = (('ZO', 'Zone'),
('SC', 'Sector'),
('CE', 'Center'),)
NOTE_TYPE_VALUES = (('IN', 'Information Note'),
('SC', 'Status Change'),
('CN', 'Critical Note'),
('MN', 'Medical Note'),
)
ADDRESS_TYPE_VALUES = (('WO', 'Work'),
('HO', 'Home'))
CENTER_CATEGORY_VALUES = (('A', 'A Center'),
('B', 'B Center'),
('C', 'C Center'),) | gender_values = (('M', 'Male'), ('F', 'Female'), ('TG', 'Transgender'))
marital_status_values = (('M', 'Married'), ('S', 'Single'), ('U', 'Unknown'))
category_values = (('BR', 'Bramhachari'), ('FTT', 'Full Time Teacher'), ('PTT', 'Part Time Teacher'), ('FTV', 'Full Time Volunteer'), ('VOL', 'Volunteer'), ('STAFF', 'Staff'), ('SEV', 'Sevadhar'))
status_values = (('ACTV', 'Active'), ('INACTV', 'Inactive'), ('EXPD', 'Deceased'))
id_proof_values = (('DL', 'Driving License'), ('PP', 'Passport'), ('RC', 'Ration Card'), ('VC', 'Voters ID'), ('AA', 'Aadhaar'), ('PC', 'PAN Card'), ('OT', 'Other Government Issued'))
role_level_choices = (('ZO', 'Zone'), ('SC', 'Sector'), ('CE', 'Center'))
note_type_values = (('IN', 'Information Note'), ('SC', 'Status Change'), ('CN', 'Critical Note'), ('MN', 'Medical Note'))
address_type_values = (('WO', 'Work'), ('HO', 'Home'))
center_category_values = (('A', 'A Center'), ('B', 'B Center'), ('C', 'C Center')) |
"""Brain Games.
This is my Python course level 1 project. Nothing special, it's just
a bundle of mini-games with common CLI.
"""
| """Brain Games.
This is my Python course level 1 project. Nothing special, it's just
a bundle of mini-games with common CLI.
""" |
input = """
8 2 2 3 0 0
1 4 2 1 3 2
1 4 2 2 2 3
6 0 1 0 4 3
0
4 c
3 b
2 a
0
B+
0
B-
1
0
1
"""
output = """
COST 0@1
"""
| input = '\n8 2 2 3 0 0\n1 4 2 1 3 2\n1 4 2 2 2 3\n6 0 1 0 4 3\n0\n4 c\n3 b\n2 a\n0\nB+\n0\nB-\n1\n0\n1\n'
output = '\nCOST 0@1\n' |
"""
LeetCode Problem: 215. Kth Largest Element in an Array
Link: https://leetcode.com/problems/kth-largest-element-in-an-array/
Language: Python
Written by: Mostofa Adib Shakib
"""
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort(reverse=True)
count = 0
for i in range(k):
count = nums[i]
return count | """
LeetCode Problem: 215. Kth Largest Element in an Array
Link: https://leetcode.com/problems/kth-largest-element-in-an-array/
Language: Python
Written by: Mostofa Adib Shakib
"""
class Solution(object):
def find_kth_largest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort(reverse=True)
count = 0
for i in range(k):
count = nums[i]
return count |
def solution(S):
# write your code in Python 3.6
if not S:
return 1
stack = []
for s in S:
if s == '(':
stack.append(s)
else:
if not stack:
return 0
else:
stack.pop()
if stack:
return 0
return 1
| def solution(S):
if not S:
return 1
stack = []
for s in S:
if s == '(':
stack.append(s)
elif not stack:
return 0
else:
stack.pop()
if stack:
return 0
return 1 |
class DistributionDiscriminator:
def __init__(self, dataset=None, extractor=None, criterion=None, **kwargs):
super().__init__(**kwargs)
self.dataset = dataset
self.extractor = extractor
self.criterion = criterion
def judge(self, samples):
return self.extractor.extract(samples)
def compare(self, features, dataset):
raise NotImplementedError
| class Distributiondiscriminator:
def __init__(self, dataset=None, extractor=None, criterion=None, **kwargs):
super().__init__(**kwargs)
self.dataset = dataset
self.extractor = extractor
self.criterion = criterion
def judge(self, samples):
return self.extractor.extract(samples)
def compare(self, features, dataset):
raise NotImplementedError |
class Solution:
def stack(self, s: str) -> list:
st = []
for x in s:
if x == '#':
if len(st) != 0:
st.pop()
continue
st.append(x)
return st
def backspaceCompare(self, S: str, T: str) -> bool:
s = self.stack(S)
t = self.stack(T)
if len(s) != len(t):
return False
for i, c in enumerate(s):
if c != t[i]:
return False
return True
| class Solution:
def stack(self, s: str) -> list:
st = []
for x in s:
if x == '#':
if len(st) != 0:
st.pop()
continue
st.append(x)
return st
def backspace_compare(self, S: str, T: str) -> bool:
s = self.stack(S)
t = self.stack(T)
if len(s) != len(t):
return False
for (i, c) in enumerate(s):
if c != t[i]:
return False
return True |
connections = {}
connections["Joj"] = []
connections["Emily"] = ["Joj","Jeph","Jeff"]
connections["Jeph"] = ["Joj","Geoff"]
connections["Jeff"] = ["Joj","Judge"]
connections["Geoff"] = ["Joj","Jebb"]
connections["Jebb"] = ["Joj","Emily"]
connections["Judge"] = ["Joj","Judy"]
connections["Jodge"] = ["Joj","Jebb","Stephan","Judy"]
connections["Judy"] = ["Joj","Judge"]
connections["Stephan"] = ["Joj","Jodge"]
names = ["Emily","Jeph","Jeff","Geoff","Jebb","Judge","Jodge","Judy", "Joj","Stephan"]
candidate = names[0]
for i in range(1, len(names)):
if names[i] in connections[candidate]:
candidate = names[i]
print("Our best candidate is {0}".format(candidate))
for name in names:
if name != candidate and name in connections[candidate]:
print("The candidate is a lie!")
exit()
elif name != candidate and candidate not in connections[name]:
print("The candidate is a lie, they are not known by somebody!")
exit()
print("We made it to the end, the celebrity is the real deal.")
| connections = {}
connections['Joj'] = []
connections['Emily'] = ['Joj', 'Jeph', 'Jeff']
connections['Jeph'] = ['Joj', 'Geoff']
connections['Jeff'] = ['Joj', 'Judge']
connections['Geoff'] = ['Joj', 'Jebb']
connections['Jebb'] = ['Joj', 'Emily']
connections['Judge'] = ['Joj', 'Judy']
connections['Jodge'] = ['Joj', 'Jebb', 'Stephan', 'Judy']
connections['Judy'] = ['Joj', 'Judge']
connections['Stephan'] = ['Joj', 'Jodge']
names = ['Emily', 'Jeph', 'Jeff', 'Geoff', 'Jebb', 'Judge', 'Jodge', 'Judy', 'Joj', 'Stephan']
candidate = names[0]
for i in range(1, len(names)):
if names[i] in connections[candidate]:
candidate = names[i]
print('Our best candidate is {0}'.format(candidate))
for name in names:
if name != candidate and name in connections[candidate]:
print('The candidate is a lie!')
exit()
elif name != candidate and candidate not in connections[name]:
print('The candidate is a lie, they are not known by somebody!')
exit()
print('We made it to the end, the celebrity is the real deal.') |
class Constants:
def __init__(self):
pass
SIMPLE_CONFIG_DIR = "/etc/simple_grid"
GIT_PKG_NAME = "git"
DOCKER_PKG_NAME = "docker"
BOLT_PKG_NAME = "bolt"
| class Constants:
def __init__(self):
pass
simple_config_dir = '/etc/simple_grid'
git_pkg_name = 'git'
docker_pkg_name = 'docker'
bolt_pkg_name = 'bolt' |
class Solution:
def longestPrefix(self, s: str) -> str:
pi = [0]*len(s)
for i in range(1, len(s)):
k = pi[i-1]
while k > 0 and s[i] != s[k]:
k = pi[k-1]
if s[i] == s[k]:
k += 1
pi[i] = k
print('pi is: ', pi)
return s[len(s)-pi[-1]:]
# i, j = 1, 0
# table = [0]
# while i < len(s):
# while j and s[i] != s[j]:
# j = table[j-1]
# if s[i] == s[j]:
# j += 1
# table.append(j+1)
# else:
# table.append(0)
# j = 0
# i += 1
# print('table: ', table)
# return s[len(s) - table[-1]]
| class Solution:
def longest_prefix(self, s: str) -> str:
pi = [0] * len(s)
for i in range(1, len(s)):
k = pi[i - 1]
while k > 0 and s[i] != s[k]:
k = pi[k - 1]
if s[i] == s[k]:
k += 1
pi[i] = k
print('pi is: ', pi)
return s[len(s) - pi[-1]:] |
def _update_doc_distribution(
X,
exp_topic_word_distr,
doc_topic_prior,
max_doc_update_iter,
mean_change_tol,
cal_sstats,
random_state,
):
is_sparse_x = sp.issparse(X)
n_samples, n_features = X.shape
n_topics = exp_topic_word_distr.shape[0]
if random_state:
doc_topic_distr = random_state.gamma(100.0, 0.01, (n_samples, n_topics))
else:
doc_topic_distr = np.ones((n_samples, n_topics))
# In the literature, this is `exp(E[log(theta)])`
exp_doc_topic = np.exp(_dirichlet_expectation_2d(doc_topic_distr))
# diff on `component_` (only calculate it when `cal_diff` is True)
suff_stats = np.zeros(exp_topic_word_distr.shape) if cal_sstats else None
if is_sparse_x:
X_data = X.data
X_indices = X.indices
X_indptr = X.indptr
for idx_d in range(n_samples):
if is_sparse_x:
ids = X_indices[X_indptr[idx_d] : X_indptr[idx_d + 1]]
cnts = X_data[X_indptr[idx_d] : X_indptr[idx_d + 1]]
else:
ids = np.nonzero(X[idx_d, :])[0]
cnts = X[idx_d, ids]
doc_topic_d = doc_topic_distr[idx_d, :]
# The next one is a copy, since the inner loop overwrites it.
exp_doc_topic_d = exp_doc_topic[idx_d, :].copy()
exp_topic_word_d = exp_topic_word_distr[:, ids]
# Iterate between `doc_topic_d` and `norm_phi` until convergence
for _ in range(0, max_doc_update_iter):
last_d = doc_topic_d
# The optimal phi_{dwk} is proportional to
# exp(E[log(theta_{dk})]) * exp(E[log(beta_{dw})]).
norm_phi = np.dot(exp_doc_topic_d, exp_topic_word_d) + EPS
doc_topic_d = exp_doc_topic_d * np.dot(cnts / norm_phi, exp_topic_word_d.T)
# Note: adds doc_topic_prior to doc_topic_d, in-place.
_dirichlet_expectation_1d(doc_topic_d, doc_topic_prior, exp_doc_topic_d)
if mean_change(last_d, doc_topic_d) < mean_change_tol:
break
doc_topic_distr[idx_d, :] = doc_topic_d
# Contribution of document d to the expected sufficient
# statistics for the M step.
if cal_sstats:
norm_phi = np.dot(exp_doc_topic_d, exp_topic_word_d) + EPS
suff_stats[:, ids] += np.outer(exp_doc_topic_d, cnts / norm_phi) | def _update_doc_distribution(X, exp_topic_word_distr, doc_topic_prior, max_doc_update_iter, mean_change_tol, cal_sstats, random_state):
is_sparse_x = sp.issparse(X)
(n_samples, n_features) = X.shape
n_topics = exp_topic_word_distr.shape[0]
if random_state:
doc_topic_distr = random_state.gamma(100.0, 0.01, (n_samples, n_topics))
else:
doc_topic_distr = np.ones((n_samples, n_topics))
exp_doc_topic = np.exp(_dirichlet_expectation_2d(doc_topic_distr))
suff_stats = np.zeros(exp_topic_word_distr.shape) if cal_sstats else None
if is_sparse_x:
x_data = X.data
x_indices = X.indices
x_indptr = X.indptr
for idx_d in range(n_samples):
if is_sparse_x:
ids = X_indices[X_indptr[idx_d]:X_indptr[idx_d + 1]]
cnts = X_data[X_indptr[idx_d]:X_indptr[idx_d + 1]]
else:
ids = np.nonzero(X[idx_d, :])[0]
cnts = X[idx_d, ids]
doc_topic_d = doc_topic_distr[idx_d, :]
exp_doc_topic_d = exp_doc_topic[idx_d, :].copy()
exp_topic_word_d = exp_topic_word_distr[:, ids]
for _ in range(0, max_doc_update_iter):
last_d = doc_topic_d
norm_phi = np.dot(exp_doc_topic_d, exp_topic_word_d) + EPS
doc_topic_d = exp_doc_topic_d * np.dot(cnts / norm_phi, exp_topic_word_d.T)
_dirichlet_expectation_1d(doc_topic_d, doc_topic_prior, exp_doc_topic_d)
if mean_change(last_d, doc_topic_d) < mean_change_tol:
break
doc_topic_distr[idx_d, :] = doc_topic_d
if cal_sstats:
norm_phi = np.dot(exp_doc_topic_d, exp_topic_word_d) + EPS
suff_stats[:, ids] += np.outer(exp_doc_topic_d, cnts / norm_phi) |
def read_convert(input: str) -> list:
dict_list = []
input = input.split("__::__")
for lines in input:
line_dict = {}
line = lines.split("__$$__")
for l in line:
dict_value = l.split("__=__")
key = dict_value[0]
if len(dict_value) == 1:
value = ""
else:
value = dict_value[1]
line_dict[key] = value
dict_list.append(line_dict)
return dict_list
def write_convert(input: list) -> str:
output_str = ""
for dicts in input:
for key, value in dicts.items():
output_str = output_str + key + "__=__" + value
output_str = output_str + "__$$__"
output_str = output_str[:len(output_str) - 6]
output_str = output_str + "__::__"
output_str = output_str[:len(output_str) - 6]
return output_str
if __name__ == "__main__":
loans = "Processor__=____$$__Loan_Number__=__2501507794__$$__Underwriter__=____$$__Borrower__=__CREDCO,BARRY__$$__Purpose__=__Construction/Perm__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2020-09-25 00:00:00__$$__Program__=__One Close Construction Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__PPB__$$__risk_level__=__3__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__$$____::__Processor__=__Carmen Medrano__$$__Loan_Number__=__2501666460__$$__Underwriter__=__Erica Lopes__$$__Borrower__=__Credco,Barry__$$__Purpose__=__Purchase__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-03-29 00:00:00__$$__Program__=__Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__Joy Swift-Greiff__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__PCB__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__::__Processor__=____$$__Loan_Number__=__2501679729__$$__Underwriter__=____$$__Borrower__=__Credco,Barry__$$__Purpose__=__Refinance__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-04-24 00:00:00__$$__Program__=__BMO Harris ReadyLine Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__SMU__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__::__Processor__=____$$__Loan_Number__=__2501682907__$$__Underwriter__=____$$__Borrower__=__Firstimer,Alice__$$__Purpose__=__Purchase__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-05-01 00:00:00__$$__Program__=__BMO Harris ReadyLine Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__PCB__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__::__Processor__=__Carmen Medrano__$$__Loan_Number__=__2501682635__$$__Underwriter__=____$$__Borrower__=__Credco,Barry__$$__Purpose__=__Purchase__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-04-30 00:00:00__$$__Program__=__Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__SMU__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0"
dicts = read_convert(loans)
outputstr = write_convert(dicts)
converted = read_convert(outputstr)
print(dicts == converted) | def read_convert(input: str) -> list:
dict_list = []
input = input.split('__::__')
for lines in input:
line_dict = {}
line = lines.split('__$$__')
for l in line:
dict_value = l.split('__=__')
key = dict_value[0]
if len(dict_value) == 1:
value = ''
else:
value = dict_value[1]
line_dict[key] = value
dict_list.append(line_dict)
return dict_list
def write_convert(input: list) -> str:
output_str = ''
for dicts in input:
for (key, value) in dicts.items():
output_str = output_str + key + '__=__' + value
output_str = output_str + '__$$__'
output_str = output_str[:len(output_str) - 6]
output_str = output_str + '__::__'
output_str = output_str[:len(output_str) - 6]
return output_str
if __name__ == '__main__':
loans = 'Processor__=____$$__Loan_Number__=__2501507794__$$__Underwriter__=____$$__Borrower__=__CREDCO,BARRY__$$__Purpose__=__Construction/Perm__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2020-09-25 00:00:00__$$__Program__=__One Close Construction Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__PPB__$$__risk_level__=__3__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__$$____::__Processor__=__Carmen Medrano__$$__Loan_Number__=__2501666460__$$__Underwriter__=__Erica Lopes__$$__Borrower__=__Credco,Barry__$$__Purpose__=__Purchase__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-03-29 00:00:00__$$__Program__=__Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__Joy Swift-Greiff__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__PCB__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__::__Processor__=____$$__Loan_Number__=__2501679729__$$__Underwriter__=____$$__Borrower__=__Credco,Barry__$$__Purpose__=__Refinance__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-04-24 00:00:00__$$__Program__=__BMO Harris ReadyLine Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__SMU__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__::__Processor__=____$$__Loan_Number__=__2501682907__$$__Underwriter__=____$$__Borrower__=__Firstimer,Alice__$$__Purpose__=__Purchase__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-05-01 00:00:00__$$__Program__=__BMO Harris ReadyLine Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__PCB__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0__::__Processor__=__Carmen Medrano__$$__Loan_Number__=__2501682635__$$__Underwriter__=____$$__Borrower__=__Credco,Barry__$$__Purpose__=__Purchase__$$__Loan_Type__=__Conventional-Conf__$$__Est_Closing_Date__=__2021-04-30 00:00:00__$$__Program__=__Conf__$$__processor_manager__=__No contact selected__$$__underwriter_manager__=__No contact selected__$$__e_consent__=____$$__processor_note__=____$$__investor_category__=__SMU__$$__risk_level__=__1__$$__sample_status__=____$$__rush_status__=____$$__type__=__New__$$__sampled_date__=__2021-03-25 12:21:58.0__$$__update_date__=__2021-03-25 12:21:58.0'
dicts = read_convert(loans)
outputstr = write_convert(dicts)
converted = read_convert(outputstr)
print(dicts == converted) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def preorderTraversal(self, root):
self.preorder = []
self.traverse(root)
return self.preorder
def traverse(self, root):
if root:
self.preorder.append(root.val)
self.traverse(root.left)
self.traverse(root.right)
| class Solution:
def preorder_traversal(self, root):
self.preorder = []
self.traverse(root)
return self.preorder
def traverse(self, root):
if root:
self.preorder.append(root.val)
self.traverse(root.left)
self.traverse(root.right) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"websites_url": "01-training-data.ipynb",
"m": "01-training-data.ipynb",
"piece_dirs": "01-training-data.ipynb",
"assert_coord": "01-training-data.ipynb",
"Board": "01-training-data.ipynb",
"Boards": "01-training-data.ipynb",
"boards": "01-training-data.ipynb",
"PieceSet": "01-training-data.ipynb",
"PieceSets": "01-training-data.ipynb",
"pieces": "01-training-data.ipynb",
"FEN": "01-training-data.ipynb",
"FENs": "01-training-data.ipynb",
"fens": "01-training-data.ipynb",
"pgn_url": "01-training-data.ipynb",
"pgn": "01-training-data.ipynb",
"small": "01-training-data.ipynb",
"GameBoard": "01-training-data.ipynb",
"sites": "01-training-data.ipynb",
"FileNamer": "01-training-data.ipynb",
"Render": "01-training-data.ipynb",
"NoLabelBBoxLabeler": "03-learner.ipynb",
"BBoxTruth": "03-learner.ipynb",
"iou": "03-learner.ipynb",
"NoLabelBBoxBlock": "03-learner.ipynb",
"Coord": "95-piece-classifier.ipynb",
"CropBox": "95-piece-classifier.ipynb",
"Color": "95-piece-classifier.ipynb",
"Piece": "95-piece-classifier.ipynb",
"BoardImage": "95-piece-classifier.ipynb",
"get_coord": "95-piece-classifier.ipynb",
"Hough": "96_hough.py.ipynb",
"URLs.chess_small": "99_preprocess.ipynb",
"URLs.website": "99_preprocess.ipynb",
"toPIL": "99_preprocess.ipynb",
"color_to_gray": "99_preprocess.ipynb",
"gray_to_bw": "99_preprocess.ipynb",
"is_bw": "99_preprocess.ipynb",
"contourFilter": "99_preprocess.ipynb",
"drawContour": "99_preprocess.ipynb",
"bw_to_contours": "99_preprocess.ipynb",
"draw_hough_lines": "99_preprocess.ipynb",
"draw_hough_linesp": "99_preprocess.ipynb",
"contour_to_hough": "99_preprocess.ipynb",
"color_to_contours": "99_preprocess.ipynb",
"Lines": "99_preprocess.ipynb"}
modules = ["training.py",
"learner.py",
"classifier.py",
"hough.py",
"preprocess.py"]
doc_url = "https://idrisr.github.io/chessocr/"
git_url = "https://github.com/idrisr/chessocr/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'websites_url': '01-training-data.ipynb', 'm': '01-training-data.ipynb', 'piece_dirs': '01-training-data.ipynb', 'assert_coord': '01-training-data.ipynb', 'Board': '01-training-data.ipynb', 'Boards': '01-training-data.ipynb', 'boards': '01-training-data.ipynb', 'PieceSet': '01-training-data.ipynb', 'PieceSets': '01-training-data.ipynb', 'pieces': '01-training-data.ipynb', 'FEN': '01-training-data.ipynb', 'FENs': '01-training-data.ipynb', 'fens': '01-training-data.ipynb', 'pgn_url': '01-training-data.ipynb', 'pgn': '01-training-data.ipynb', 'small': '01-training-data.ipynb', 'GameBoard': '01-training-data.ipynb', 'sites': '01-training-data.ipynb', 'FileNamer': '01-training-data.ipynb', 'Render': '01-training-data.ipynb', 'NoLabelBBoxLabeler': '03-learner.ipynb', 'BBoxTruth': '03-learner.ipynb', 'iou': '03-learner.ipynb', 'NoLabelBBoxBlock': '03-learner.ipynb', 'Coord': '95-piece-classifier.ipynb', 'CropBox': '95-piece-classifier.ipynb', 'Color': '95-piece-classifier.ipynb', 'Piece': '95-piece-classifier.ipynb', 'BoardImage': '95-piece-classifier.ipynb', 'get_coord': '95-piece-classifier.ipynb', 'Hough': '96_hough.py.ipynb', 'URLs.chess_small': '99_preprocess.ipynb', 'URLs.website': '99_preprocess.ipynb', 'toPIL': '99_preprocess.ipynb', 'color_to_gray': '99_preprocess.ipynb', 'gray_to_bw': '99_preprocess.ipynb', 'is_bw': '99_preprocess.ipynb', 'contourFilter': '99_preprocess.ipynb', 'drawContour': '99_preprocess.ipynb', 'bw_to_contours': '99_preprocess.ipynb', 'draw_hough_lines': '99_preprocess.ipynb', 'draw_hough_linesp': '99_preprocess.ipynb', 'contour_to_hough': '99_preprocess.ipynb', 'color_to_contours': '99_preprocess.ipynb', 'Lines': '99_preprocess.ipynb'}
modules = ['training.py', 'learner.py', 'classifier.py', 'hough.py', 'preprocess.py']
doc_url = 'https://idrisr.github.io/chessocr/'
git_url = 'https://github.com/idrisr/chessocr/tree/master/'
def custom_doc_links(name):
return None |
n = int(input())
i = 5
while i > 0:
root = 1
while root ** i < n:
root = root + 1
if root ** i == n:
print(root, i)
i = i - 1
| n = int(input())
i = 5
while i > 0:
root = 1
while root ** i < n:
root = root + 1
if root ** i == n:
print(root, i)
i = i - 1 |
# -*- coding: utf-8 -*-
# Authors: Y. Jia <ytjia.zju@gmail.com>
"""
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and
return its area.
https://leetcode.com/problems/maximal-square/description/
"""
class Solution(object):
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
max_side_length = 0
if matrix is None:
return max_side_length
n_row = len(matrix)
if n_row == 0:
return max_side_length
n_col = len(matrix[0])
dp = list()
for r in range(n_row):
dp.append(list())
for c in range(n_col):
dp[r].append(0)
for r in range(n_row):
dp[r][0] = int(matrix[r][0])
max_side_length = max(dp[r][0], max_side_length)
for c in range(n_col):
dp[0][c] = int(matrix[0][c])
max_side_length = max(dp[0][c], max_side_length)
for r in range(1, n_row):
for c in range(1, n_col):
if matrix[r][c] == '1':
dp[r][c] = min(dp[r - 1][c - 1], dp[r - 1][c], dp[r][c - 1]) + 1
max_side_length = max(dp[r][c], max_side_length)
else:
dp[r][c] = 0
return max_side_length * max_side_length
| """
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and
return its area.
https://leetcode.com/problems/maximal-square/description/
"""
class Solution(object):
def maximal_square(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
max_side_length = 0
if matrix is None:
return max_side_length
n_row = len(matrix)
if n_row == 0:
return max_side_length
n_col = len(matrix[0])
dp = list()
for r in range(n_row):
dp.append(list())
for c in range(n_col):
dp[r].append(0)
for r in range(n_row):
dp[r][0] = int(matrix[r][0])
max_side_length = max(dp[r][0], max_side_length)
for c in range(n_col):
dp[0][c] = int(matrix[0][c])
max_side_length = max(dp[0][c], max_side_length)
for r in range(1, n_row):
for c in range(1, n_col):
if matrix[r][c] == '1':
dp[r][c] = min(dp[r - 1][c - 1], dp[r - 1][c], dp[r][c - 1]) + 1
max_side_length = max(dp[r][c], max_side_length)
else:
dp[r][c] = 0
return max_side_length * max_side_length |
a = [1, 2, 3, 4, 5]
print(a[0] + 1)
#length of list
x = len(a)
print(x)
print(a[-1])
#splicing
print(a[0:3])
print(a[0:])
b = "test"
print(b[0:1])
| a = [1, 2, 3, 4, 5]
print(a[0] + 1)
x = len(a)
print(x)
print(a[-1])
print(a[0:3])
print(a[0:])
b = 'test'
print(b[0:1]) |
def extgcd(a, b):
"""solve ax + by = gcd(a, b)
return x, y, gcd(a, b)
used in NTL1E(AOJ)
"""
g = a
if b == 0:
x, y = 1, 0
else:
x, y, g = extgcd(b, a % b)
x, y = y, x - a // b * y
return x, y, g
| def extgcd(a, b):
"""solve ax + by = gcd(a, b)
return x, y, gcd(a, b)
used in NTL1E(AOJ)
"""
g = a
if b == 0:
(x, y) = (1, 0)
else:
(x, y, g) = extgcd(b, a % b)
(x, y) = (y, x - a // b * y)
return (x, y, g) |
class Solution(object):
def toGoatLatin(self, sentence):
"""
:type sentence: str
:rtype: str
"""
count = 0
res = []
for w in sentence.split():
count += 1
if w[0].lower() in ['a', 'e', 'i', 'o', 'u']:
res.append(w+"ma"+'a'*count)
else:
res.append(w[1:]+w[0]+"ma"+'a'*count)
return " ".join(res)
| class Solution(object):
def to_goat_latin(self, sentence):
"""
:type sentence: str
:rtype: str
"""
count = 0
res = []
for w in sentence.split():
count += 1
if w[0].lower() in ['a', 'e', 'i', 'o', 'u']:
res.append(w + 'ma' + 'a' * count)
else:
res.append(w[1:] + w[0] + 'ma' + 'a' * count)
return ' '.join(res) |
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
count = 0
prefix_sum = 0
dic = {0: 1}
for i in range(len(nums)):
prefix_sum += nums[i]
if prefix_sum - k in dic:
count += dic[prefix_sum - k]
if prefix_sum in dic:
dic[prefix_sum] += 1
else:
dic[prefix_sum] = 1
return count
| class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
count = 0
prefix_sum = 0
dic = {0: 1}
for i in range(len(nums)):
prefix_sum += nums[i]
if prefix_sum - k in dic:
count += dic[prefix_sum - k]
if prefix_sum in dic:
dic[prefix_sum] += 1
else:
dic[prefix_sum] = 1
return count |
"""
https://leetcode.com/problems/detect-capital/
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
"""
# time complexity: O(n), space complexity: O(1)
class Solution:
def detectCapitalUse(self, word: str) -> bool:
if len(word) == 1:
return True
if len(word) == 2:
if ord('A') <= ord(word[0]) <= ord('Z'):
return True
elif ord('a') <= ord(word[1]) <= ord('z'):
return True
else:
return False
# len == 3
if ord('A') <= ord(word[0]) <= ord('Z'):
i = 1
while i < len(word):
if ord('A') <= ord(word[i]) <= ord('Z') and ord('A') <= ord(word[1]) <= ord('Z') or ord('a') <= ord(
word[i]) <= ord('z') and ord('a') <= ord(word[1]) <= ord('z'):
i += 1
else:
return False
if i == len(word):
return True
else:
i = 1
while i < len(word):
if ord('a') <= ord(word[i]) <= ord('z'):
i += 1
else:
return False
if i == len(word):
return True
| """
https://leetcode.com/problems/detect-capital/
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
"""
class Solution:
def detect_capital_use(self, word: str) -> bool:
if len(word) == 1:
return True
if len(word) == 2:
if ord('A') <= ord(word[0]) <= ord('Z'):
return True
elif ord('a') <= ord(word[1]) <= ord('z'):
return True
else:
return False
if ord('A') <= ord(word[0]) <= ord('Z'):
i = 1
while i < len(word):
if ord('A') <= ord(word[i]) <= ord('Z') and ord('A') <= ord(word[1]) <= ord('Z') or (ord('a') <= ord(word[i]) <= ord('z') and ord('a') <= ord(word[1]) <= ord('z')):
i += 1
else:
return False
if i == len(word):
return True
else:
i = 1
while i < len(word):
if ord('a') <= ord(word[i]) <= ord('z'):
i += 1
else:
return False
if i == len(word):
return True |
n = int(input())
a = list(map(int,input().split()))
q,w=0,0
for i in a:
if i ==25:q+=1
elif i==50:q-=1;w+=1
else:
if w>0:w-=1;q-=1
else:q-=3
if q<0 or w<0:n=0;break
if n==0:print("NO")
else:print("YES") | n = int(input())
a = list(map(int, input().split()))
(q, w) = (0, 0)
for i in a:
if i == 25:
q += 1
elif i == 50:
q -= 1
w += 1
elif w > 0:
w -= 1
q -= 1
else:
q -= 3
if q < 0 or w < 0:
n = 0
break
if n == 0:
print('NO')
else:
print('YES') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.