content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class CidrMaskConvert:
def cidr_to_mask(self, val):
val = int(val)
if 1 > val or val > 32:
return "Invalid"
val = '.'.join([str((0xffffffff << (32 - val) >> i) & 0xff)
for i in [24, 16, 8, 0]])
return val
def mask_to_cidr(self, val):
mask_list = val.split(".")
check = IpValidate().ipv4_validation(val)
binary = [bin(int(i))[2:].count('1') for i in mask_list]
if not check or binary[0] ==3:
return 'Invalid'
val = sum(binary) if sum(binary) > 0 else 'Invalid'
return str(val)
class IpValidate:
def ipv4_validation(self, val):
octets = val.split(".")
return len(octets) == 4 and \
all(o.isdigit() and 0 <= int(o) < 256 for o in octets) | class Cidrmaskconvert:
def cidr_to_mask(self, val):
val = int(val)
if 1 > val or val > 32:
return 'Invalid'
val = '.'.join([str(4294967295 << 32 - val >> i & 255) for i in [24, 16, 8, 0]])
return val
def mask_to_cidr(self, val):
mask_list = val.split('.')
check = ip_validate().ipv4_validation(val)
binary = [bin(int(i))[2:].count('1') for i in mask_list]
if not check or binary[0] == 3:
return 'Invalid'
val = sum(binary) if sum(binary) > 0 else 'Invalid'
return str(val)
class Ipvalidate:
def ipv4_validation(self, val):
octets = val.split('.')
return len(octets) == 4 and all((o.isdigit() and 0 <= int(o) < 256 for o in octets)) |
# name = input("Enter your name: ")
# age = input("Enter your age: ")
# print("Hello " + name + "! You are " + age)
# create a calculator, be careful the input is a string
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
# int does not work for decimal numbers
result1 = int(num1) + int(num2)
result2 = float(num1) + float(num2)
result = int(num1) + int(num2)
print(result1)
print(result2)
print(result)
| num1 = input('Enter a number: ')
num2 = input('Enter a number: ')
result1 = int(num1) + int(num2)
result2 = float(num1) + float(num2)
result = int(num1) + int(num2)
print(result1)
print(result2)
print(result) |
class Solution:
# @param A : string
# @return an integer
def solve(self, s):
n = len(s)
lps = [0]*n
i,l = 1,0
while i < n:
if s[i]==s[l]:
lps[i] = l+1
l+=1
i+=1
elif l > 0:
l = lps[l-1]
else:
i+=1
ans = n
for i in range(n):
x = i-lps[i]
if lps[i]>=x:
ans = n-i-1
return ans
| class Solution:
def solve(self, s):
n = len(s)
lps = [0] * n
(i, l) = (1, 0)
while i < n:
if s[i] == s[l]:
lps[i] = l + 1
l += 1
i += 1
elif l > 0:
l = lps[l - 1]
else:
i += 1
ans = n
for i in range(n):
x = i - lps[i]
if lps[i] >= x:
ans = n - i - 1
return ans |
"""
Platform for DS-AIR of Daikin
https://www.daikin-china.com.cn/newha/products/4/19/DS-AIR/
"""
| """
Platform for DS-AIR of Daikin
https://www.daikin-china.com.cn/newha/products/4/19/DS-AIR/
""" |
# formatting
menu = [
["egg", "bacon"],
["egg", "bacon", "sausage"],
["egg", "spam"],
["egg", "spam", "tomato"],
["egg", "spam", "tomato", "spam", "tomato"],
]
for meal in menu:
if "spam" in meal:
print("Yeah, not there")
else:
print("{0} has the spam score of {1}"
.format(meal, meal.count("spam")))
# challenge: print all the values just not spam
for meal in menu:
if "spam" in meal:
meal.remove("spam")
print(meal)
| menu = [['egg', 'bacon'], ['egg', 'bacon', 'sausage'], ['egg', 'spam'], ['egg', 'spam', 'tomato'], ['egg', 'spam', 'tomato', 'spam', 'tomato']]
for meal in menu:
if 'spam' in meal:
print('Yeah, not there')
else:
print('{0} has the spam score of {1}'.format(meal, meal.count('spam')))
for meal in menu:
if 'spam' in meal:
meal.remove('spam')
print(meal) |
class RandomResponseFrequency:
"""A RandomResponseFrequency is an object used to define frequency over a range of modes.
This page discusses:
Attributes
----------
lower: float
A Float specifying the lower limit of the frequency range in cycles per time.
upper: float
A Float specifying the upper limit of the frequency range in cycles per time.
nCalcs: int
An Int specifying the number of points between eigenfrequencies at which the response
should be calculated.
bias: float
A Float specifying the bias parameter.
Notes
-----
This object can be accessed by:
.. code-block:: python
import step
mdb.models[name].steps[name].freq[i]
"""
# A Float specifying the lower limit of the frequency range in cycles per time.
lower: float = None
# A Float specifying the upper limit of the frequency range in cycles per time.
upper: float = None
# An Int specifying the number of points between eigenfrequencies at which the response
# should be calculated.
nCalcs: int = None
# A Float specifying the bias parameter.
bias: float = None
| class Randomresponsefrequency:
"""A RandomResponseFrequency is an object used to define frequency over a range of modes.
This page discusses:
Attributes
----------
lower: float
A Float specifying the lower limit of the frequency range in cycles per time.
upper: float
A Float specifying the upper limit of the frequency range in cycles per time.
nCalcs: int
An Int specifying the number of points between eigenfrequencies at which the response
should be calculated.
bias: float
A Float specifying the bias parameter.
Notes
-----
This object can be accessed by:
.. code-block:: python
import step
mdb.models[name].steps[name].freq[i]
"""
lower: float = None
upper: float = None
n_calcs: int = None
bias: float = None |
#
# coding=utf-8
def normalize(block):
""" Normalize a block of text to perform comparison.
Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace
from each line.
"""
assert isinstance(block, str)
block = block.strip('\n')
return [line.rstrip() for line in block.splitlines()]
def run_cmd(app, cmd):
""" Clear StdSim buffer, run the command, extract the buffer contents, """
app.stdout.clear()
app.onecmd_plus_hooks(cmd)
out = app.stdout.getvalue()
app.stdout.clear()
return normalize(out)
| def normalize(block):
""" Normalize a block of text to perform comparison.
Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace
from each line.
"""
assert isinstance(block, str)
block = block.strip('\n')
return [line.rstrip() for line in block.splitlines()]
def run_cmd(app, cmd):
""" Clear StdSim buffer, run the command, extract the buffer contents, """
app.stdout.clear()
app.onecmd_plus_hooks(cmd)
out = app.stdout.getvalue()
app.stdout.clear()
return normalize(out) |
"""
Swap two variables' contents without using a 3rd variable.
Not really useful in Python since you can do: `a, b = b, a`.
Author:
Christos Nitsas
(nitsas)
(nitsas.chris)
Language:
Python 3(.4)
Date:
April, 2016
"""
__all__ = ['xor_swap']
def xor_swap(a, b):
a ^= b # invert those bits of a where b has 1s
b ^= a # reverse the above and store in b
# current b is the original a
# current a still has the result of the 1st operation
# but viewed differently:
# current a is original b with inverted bits where original a had 1s
a ^= b # use b (original a) to invert 1st operation & get original b
return a, b
| """
Swap two variables' contents without using a 3rd variable.
Not really useful in Python since you can do: `a, b = b, a`.
Author:
Christos Nitsas
(nitsas)
(nitsas.chris)
Language:
Python 3(.4)
Date:
April, 2016
"""
__all__ = ['xor_swap']
def xor_swap(a, b):
a ^= b
b ^= a
a ^= b
return (a, b) |
class Solution(object):
def strWithout3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
if A >= 2*B:
return 'aab'* B + 'a'* (A-2*B)
elif A >= B:
return 'aab' * (A-B) + 'ab' * (2*B - A)
elif B >= 2*A:
return 'bba' * A + 'b' *(B-2*A)
else:
return 'bba' * (B-A) + 'ab' * (2*A - B)
'''
class Solution {
public String strWithout3a3b(int A, int B) {
StringBuilder res = new StringBuilder(A + B);
char a = 'a', b = 'b';
int i = A, j = B;
if (B > A) { a = 'b'; b = 'a'; i = B; j = A; }
while (i-- > 0) {
res.append(a);
if (i > j) { res.append(a); --i; }
if (j-- > 0) res.append(b);
}
return res.toString();
}
}
''' | class Solution(object):
def str_without3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
if A >= 2 * B:
return 'aab' * B + 'a' * (A - 2 * B)
elif A >= B:
return 'aab' * (A - B) + 'ab' * (2 * B - A)
elif B >= 2 * A:
return 'bba' * A + 'b' * (B - 2 * A)
else:
return 'bba' * (B - A) + 'ab' * (2 * A - B)
"\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder res = new StringBuilder(A + B);\n char a = 'a', b = 'b';\n int i = A, j = B;\n if (B > A) { a = 'b'; b = 'a'; i = B; j = A; }\n while (i-- > 0) {\n res.append(a);\n if (i > j) { res.append(a); --i; }\n if (j-- > 0) res.append(b);\n }\n return res.toString();\n }\n}\n" |
class Database:
'''
A generic database that must implement at least the two methods declared below.
The specific implementation of the database is left to Admin, but it can be any typical SQL or other database so long as it can implement a table where the key is a Hashable type and the value is Any type.
A database instance is exposed to the origin server (and is only exposed to the origin server) by passing the instance to the Origin constructor.
'''
def get(self, key):
'''
Translates to a query where the key is the given parameter key.
'''
pass
def put(self, key, value):
'''
Translates to a database insert if the key is not already in the database, or a database update if the key is already in the database.
'''
pass | class Database:
"""
A generic database that must implement at least the two methods declared below.
The specific implementation of the database is left to Admin, but it can be any typical SQL or other database so long as it can implement a table where the key is a Hashable type and the value is Any type.
A database instance is exposed to the origin server (and is only exposed to the origin server) by passing the instance to the Origin constructor.
"""
def get(self, key):
"""
Translates to a query where the key is the given parameter key.
"""
pass
def put(self, key, value):
"""
Translates to a database insert if the key is not already in the database, or a database update if the key is already in the database.
"""
pass |
# 190. Reverse Bits
class Solution:
def reverseBits(self, n: int) -> int:
bin_num = format(n, 'b')
res = '0' * (32-len(bin_num)) + bin_num
return int('0b' + res[::-1], 2)
| class Solution:
def reverse_bits(self, n: int) -> int:
bin_num = format(n, 'b')
res = '0' * (32 - len(bin_num)) + bin_num
return int('0b' + res[::-1], 2) |
T = int(input())
a=list(map(int,input().split()))
for i in range(0,T):
b = input()
if(b == '+'):
print(a[0]+a[1])
elif(b == '-'):
print(a[0]-a[1])
elif(b == '*'):
print(a[0]*a[1])
elif(b == '/'):
print(a[0]//a[1])
elif(b == '%'):
print(a[0]%a[1])
| t = int(input())
a = list(map(int, input().split()))
for i in range(0, T):
b = input()
if b == '+':
print(a[0] + a[1])
elif b == '-':
print(a[0] - a[1])
elif b == '*':
print(a[0] * a[1])
elif b == '/':
print(a[0] // a[1])
elif b == '%':
print(a[0] % a[1]) |
name = input("whats your name\n")
bebe = "october"
print(bebe)
print("hi")
print (name)
print("?!")
print("tova")
# pavtuk smiatam
h = 2
c = 2
d = h*2 + c
print(d) | name = input('whats your name\n')
bebe = 'october'
print(bebe)
print('hi')
print(name)
print('?!')
print('tova')
h = 2
c = 2
d = h * 2 + c
print(d) |
"""
Connected components and graph resilience
"""
def bfs_visited(ugraph, start_node):
"""
Takes the undirected graph ugraph and the node start_node and returns
the set consisting of all nodes that are visited by a breadth-first search
that starts at start_node.
"""
visited = set()
stack = [start_node]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(ugraph[vertex] - visited)
return visited
def cc_visited(ugraph):
"""
Takes the undirected graph ugraph and returns a list of sets,
where each set consists of all the nodes (and nothing else)
in a connected component, and there is exactly one set in the list
for each connected component in ugraph and nothing else.
"""
ccc = []
remaining_nodes = ugraph.keys()
while remaining_nodes:
node = remaining_nodes.pop()
www = bfs_visited(ugraph, node)
if www not in ccc:
ccc.append(www)
return ccc
def largest_cc_size(ugraph):
"""
Takes the undirected graph ugraph and returns the size (an integer)
of the largest connected component in ugraph.
"""
ccc = cc_visited(ugraph)
max_cc = 0
for elem in ccc:
if len(elem) > max_cc:
max_cc = len(elem)
return max_cc
def compute_resilience(ugraph, attack_order):
"""
Takes the undirected graph ugraph, a list of nodes attack_order
and iterates through the nodes in attack_order. For each node in the list,
the function removes the given node and its edges from the graph and then
computes the size of the largest connected component for the resulting graph.
"""
resilience = []
resilience.append(largest_cc_size(ugraph))
for removed_node in attack_order:
del ugraph[removed_node]
for node in ugraph:
if removed_node in ugraph[node]:
ugraph[node].remove(removed_node)
resilience.append(largest_cc_size(ugraph))
return resilience
GRAPH0 = {0: set([1]),
1: set([0, 2]),
2: set([1, 3]),
3: set([2])}
GRAPH1 = {0: set([1, 2, 3, 4]),
1: set([0, 2, 3, 4]),
2: set([0, 1, 3, 4]),
3: set([0, 1, 2, 4]),
4: set([0, 1, 2, 3])}
GRAPH2 = {1: set([2, 4, 6, 8]),
2: set([1, 3, 5, 7]),
3: set([2, 4, 6, 8]),
4: set([1, 3, 5, 7]),
5: set([2, 4, 6, 8]),
6: set([1, 3, 5, 7]),
7: set([2, 4, 6, 8]),
8: set([1, 3, 5, 7])}
GRAPH3 = {0: set([]),
1: set([2]),
2: set([1]),
3: set([4]),
4: set([3])}
GRAPH4 = {0: set([1, 2, 3, 4]),
1: set([0]),
2: set([0]),
3: set([0]),
4: set([0]),
5: set([6, 7]),
6: set([5]),
7: set([5])}
GRAPH5 = {"dog": set(["cat"]),
"cat": set(["dog"]),
"monkey": set(["banana"]),
"banana": set(["monkey", "ape"]),
"ape": set(["banana"])}
GRAPH6 = {1: set([2, 5]),
2: set([1, 7]),
3: set([4, 6, 9]),
4: set([3, 6, 9]),
5: set([1, 7]),
6: set([3, 4, 9]),
7: set([2, 5]),
9: set([3, 4, 6])}
GRAPH7 = {0: set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
1: set([0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
2: set([0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
3: set([0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
4: set([0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
5: set([0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
6: set([0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
7: set([0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
8: set([0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
9: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
10: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
11: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
12: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
13: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
14: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
15: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
16: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
17: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
18: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
19: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
20: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
21: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
22: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
23: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
24: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
25: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
26: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
27: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
28: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
29: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
30: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
31: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
32: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
33: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
34: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
35: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
36: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
37: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
38: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
39: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
40: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
41: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49]),
42: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49]),
43: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49]),
44: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49]),
45: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49]),
46: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 47, 48, 49]),
47: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 48, 49]),
48: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49]),
49: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48])}
GRAPH8 = {0: set([]),
1: set([]),
2: set([]),
3: set([]),
4: set([]),
5: set([]),
6: set([]),
7: set([]),
8: set([]),
9: set([]),
10: set([]),
11: set([]),
12: set([]),
13: set([]),
14: set([]),
15: set([]),
16: set([]),
17: set([]),
18: set([]),
19: set([]),
20: set([]),
21: set([]),
22: set([]),
23: set([]),
24: set([]),
25: set([]),
26: set([]),
27: set([]),
28: set([]),
29: set([]),
30: set([]),
31: set([]),
32: set([]),
33: set([]),
34: set([]),
35: set([]),
36: set([]),
37: set([]),
38: set([]),
39: set([]),
40: set([]),
41: set([]),
42: set([]),
43: set([]),
44: set([]),
45: set([]),
46: set([]),
47: set([]),
48: set([]),
49: set([])}
GRAPH9 = {0: set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),
1: set([0, 3, 4, 7, 8, 9, 10]),
2: set([0, 5, 6, 11, 12, 13, 14]),
3: set([0, 1, 7, 8]),
4: set([0, 1, 9, 10]),
5: set([0, 2, 11, 12]),
6: set([0, 2, 13, 14]),
7: set([0, 1, 3]),
8: set([0, 1, 3]),
9: set([0, 1, 4]),
10: set([0, 1, 4]),
11: set([0, 2, 5]),
12: set([0, 2, 5]),
13: set([0, 2, 6]),
14: set([0, 2, 6])}
GRAPH10 = {0: set([1, 2]),
1: set([0]),
2: set([0, 3, 4]),
3: set([2]),
4: set([2, 5, 6,]),
5: set([4]),
6: set([4, 7, 8]),
7: set([6]),
8: set([6, 9 , 10]),
9: set([8]),
10: set([8, 11, 12]),
11: set([10]),
12: set([10,13, 14]),
13: set([12]),
14: set([12, 15, 16]),
15: set([14]),
16: set([14, 17, 18]),
17: set([16]),
18: set([16, 19, 20]),
19: set([18]),
20: set([18])}
#print cc_visited(GRAPH0)
#print cc_visited(GRAPH1)
#print cc_visited(GRAPH2)
#print cc_visited(GRAPH3)
#print cc_visited(GRAPH4)
#print cc_visited(GRAPH5)
#print cc_visited(GRAPH6)
#print cc_visited(GRAPH7)
#print cc_visited(GRAPH8)
#print cc_visited(GRAPH9)
#print cc_visited(GRAPH10)
#print bfs_visited(GRAPH0, 0)
#print bfs_visited(GRAPH0, 1)
#print bfs_visited(GRAPH0, 2)
#print bfs_visited(GRAPH0, 3)
#print largest_cc_size(GRAPH0)
#print compute_resilience(GRAPH0, [1, 2])
| """
Connected components and graph resilience
"""
def bfs_visited(ugraph, start_node):
"""
Takes the undirected graph ugraph and the node start_node and returns
the set consisting of all nodes that are visited by a breadth-first search
that starts at start_node.
"""
visited = set()
stack = [start_node]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(ugraph[vertex] - visited)
return visited
def cc_visited(ugraph):
"""
Takes the undirected graph ugraph and returns a list of sets,
where each set consists of all the nodes (and nothing else)
in a connected component, and there is exactly one set in the list
for each connected component in ugraph and nothing else.
"""
ccc = []
remaining_nodes = ugraph.keys()
while remaining_nodes:
node = remaining_nodes.pop()
www = bfs_visited(ugraph, node)
if www not in ccc:
ccc.append(www)
return ccc
def largest_cc_size(ugraph):
"""
Takes the undirected graph ugraph and returns the size (an integer)
of the largest connected component in ugraph.
"""
ccc = cc_visited(ugraph)
max_cc = 0
for elem in ccc:
if len(elem) > max_cc:
max_cc = len(elem)
return max_cc
def compute_resilience(ugraph, attack_order):
"""
Takes the undirected graph ugraph, a list of nodes attack_order
and iterates through the nodes in attack_order. For each node in the list,
the function removes the given node and its edges from the graph and then
computes the size of the largest connected component for the resulting graph.
"""
resilience = []
resilience.append(largest_cc_size(ugraph))
for removed_node in attack_order:
del ugraph[removed_node]
for node in ugraph:
if removed_node in ugraph[node]:
ugraph[node].remove(removed_node)
resilience.append(largest_cc_size(ugraph))
return resilience
graph0 = {0: set([1]), 1: set([0, 2]), 2: set([1, 3]), 3: set([2])}
graph1 = {0: set([1, 2, 3, 4]), 1: set([0, 2, 3, 4]), 2: set([0, 1, 3, 4]), 3: set([0, 1, 2, 4]), 4: set([0, 1, 2, 3])}
graph2 = {1: set([2, 4, 6, 8]), 2: set([1, 3, 5, 7]), 3: set([2, 4, 6, 8]), 4: set([1, 3, 5, 7]), 5: set([2, 4, 6, 8]), 6: set([1, 3, 5, 7]), 7: set([2, 4, 6, 8]), 8: set([1, 3, 5, 7])}
graph3 = {0: set([]), 1: set([2]), 2: set([1]), 3: set([4]), 4: set([3])}
graph4 = {0: set([1, 2, 3, 4]), 1: set([0]), 2: set([0]), 3: set([0]), 4: set([0]), 5: set([6, 7]), 6: set([5]), 7: set([5])}
graph5 = {'dog': set(['cat']), 'cat': set(['dog']), 'monkey': set(['banana']), 'banana': set(['monkey', 'ape']), 'ape': set(['banana'])}
graph6 = {1: set([2, 5]), 2: set([1, 7]), 3: set([4, 6, 9]), 4: set([3, 6, 9]), 5: set([1, 7]), 6: set([3, 4, 9]), 7: set([2, 5]), 9: set([3, 4, 6])}
graph7 = {0: set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 1: set([0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 2: set([0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 3: set([0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 4: set([0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 5: set([0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 6: set([0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 7: set([0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 8: set([0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 9: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 10: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 11: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 12: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 13: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 14: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 15: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 16: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 17: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 18: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 19: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 20: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 21: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 22: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 23: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 24: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 25: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 26: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 27: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 28: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 29: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 30: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 31: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 32: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 33: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 34: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 35: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 36: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 37: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 38: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 39: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 40: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 41: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49]), 42: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49]), 43: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49]), 44: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49]), 45: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49]), 46: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 47, 48, 49]), 47: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 48, 49]), 48: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49]), 49: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48])}
graph8 = {0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([]), 10: set([]), 11: set([]), 12: set([]), 13: set([]), 14: set([]), 15: set([]), 16: set([]), 17: set([]), 18: set([]), 19: set([]), 20: set([]), 21: set([]), 22: set([]), 23: set([]), 24: set([]), 25: set([]), 26: set([]), 27: set([]), 28: set([]), 29: set([]), 30: set([]), 31: set([]), 32: set([]), 33: set([]), 34: set([]), 35: set([]), 36: set([]), 37: set([]), 38: set([]), 39: set([]), 40: set([]), 41: set([]), 42: set([]), 43: set([]), 44: set([]), 45: set([]), 46: set([]), 47: set([]), 48: set([]), 49: set([])}
graph9 = {0: set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]), 1: set([0, 3, 4, 7, 8, 9, 10]), 2: set([0, 5, 6, 11, 12, 13, 14]), 3: set([0, 1, 7, 8]), 4: set([0, 1, 9, 10]), 5: set([0, 2, 11, 12]), 6: set([0, 2, 13, 14]), 7: set([0, 1, 3]), 8: set([0, 1, 3]), 9: set([0, 1, 4]), 10: set([0, 1, 4]), 11: set([0, 2, 5]), 12: set([0, 2, 5]), 13: set([0, 2, 6]), 14: set([0, 2, 6])}
graph10 = {0: set([1, 2]), 1: set([0]), 2: set([0, 3, 4]), 3: set([2]), 4: set([2, 5, 6]), 5: set([4]), 6: set([4, 7, 8]), 7: set([6]), 8: set([6, 9, 10]), 9: set([8]), 10: set([8, 11, 12]), 11: set([10]), 12: set([10, 13, 14]), 13: set([12]), 14: set([12, 15, 16]), 15: set([14]), 16: set([14, 17, 18]), 17: set([16]), 18: set([16, 19, 20]), 19: set([18]), 20: set([18])} |
calories_per_click = dict([(str(index + 1), int(calories)) for index, calories in enumerate(input().split())])
total_calories_burned = sum([calories_per_click[c] for c in input()])
print(total_calories_burned)
| calories_per_click = dict([(str(index + 1), int(calories)) for (index, calories) in enumerate(input().split())])
total_calories_burned = sum([calories_per_click[c] for c in input()])
print(total_calories_burned) |
# Notation x.y.z:
# x: major release
# y: minor release / new feature
# z: build number / bug maintenance
version = '0.5.1'
| version = '0.5.1' |
"""
Utilities for VCF files.
"""
def walk_together(*readers, **kwargs):
"""
Simultaneously iteratate over two or more VCF readers. For each
genomic position with a variant, return a list of size equal to the number
of VCF readers. This list contains the VCF record from readers that have
this variant, and None for readers that don't have it.
The caller must make sure that inputs are sorted in the same way and use the
same reference otherwise behaviour is undefined.
Args:
vcf_record_sort_key: function that takes a VCF record and returns a
tuple that can be used as a key for comparing and sorting VCF
records across all readers. This tuple defines what it means for two
variants to be equal (eg. whether it's only their position or also
their allele values), and implicitly determines the chromosome
ordering since the tuple's 1st element is typically the chromosome
name (or calculated from it).
"""
if 'vcf_record_sort_key' in kwargs:
get_key = kwargs['vcf_record_sort_key']
else:
get_key = lambda r: (r.CHROM, r.POS) #, r.REF, r.ALT)
nexts = []
for reader in readers:
try:
nexts.append(reader.next())
except StopIteration:
nexts.append(None)
min_k = (None,) # keep track of the previous min key's contig
while any([r is not None for r in nexts]):
next_idx_to_k = dict(
(i, get_key(r)) for i, r in enumerate(nexts) if r is not None)
keys_with_prev_contig = [
k for k in next_idx_to_k.values() if k[0] == min_k[0]]
if any(keys_with_prev_contig):
min_k = min(keys_with_prev_contig) # finish previous contig
else:
min_k = min(next_idx_to_k.values()) # move on to next contig
min_k_idxs = set([i for i, k in next_idx_to_k.items() if k == min_k])
yield [nexts[i] if i in min_k_idxs else None for i in range(len(nexts))]
for i in min_k_idxs:
try:
nexts[i] = readers[i].next()
except StopIteration:
nexts[i] = None
def trim_common_suffix(*sequences):
"""
Trim a list of sequences by removing the longest common suffix while
leaving all of them at least one character in length.
Standard convention with VCF is to place an indel at the left-most
position, but some tools add additional context to the right of the
sequences (e.g. samtools). These common suffixes are undesirable when
comparing variants, for example in variant databases.
>>> trim_common_suffix('TATATATA', 'TATATA')
['TAT', 'T']
>>> trim_common_suffix('ACCCCC', 'ACCCCCCCC', 'ACCCCCCC', 'ACCCCCCCCC')
['A', 'ACCC', 'ACC', 'ACCCC']
"""
if not sequences:
return []
reverses = [seq[::-1] for seq in sequences]
rev_min = min(reverses)
rev_max = max(reverses)
if len(rev_min) < 2:
return sequences
for i, c in enumerate(rev_min[:-1]):
if c != rev_max[i]:
if i == 0:
return sequences
return [seq[:-i] for seq in sequences]
return [seq[:-(i + 1)] for seq in sequences]
| """
Utilities for VCF files.
"""
def walk_together(*readers, **kwargs):
"""
Simultaneously iteratate over two or more VCF readers. For each
genomic position with a variant, return a list of size equal to the number
of VCF readers. This list contains the VCF record from readers that have
this variant, and None for readers that don't have it.
The caller must make sure that inputs are sorted in the same way and use the
same reference otherwise behaviour is undefined.
Args:
vcf_record_sort_key: function that takes a VCF record and returns a
tuple that can be used as a key for comparing and sorting VCF
records across all readers. This tuple defines what it means for two
variants to be equal (eg. whether it's only their position or also
their allele values), and implicitly determines the chromosome
ordering since the tuple's 1st element is typically the chromosome
name (or calculated from it).
"""
if 'vcf_record_sort_key' in kwargs:
get_key = kwargs['vcf_record_sort_key']
else:
get_key = lambda r: (r.CHROM, r.POS)
nexts = []
for reader in readers:
try:
nexts.append(reader.next())
except StopIteration:
nexts.append(None)
min_k = (None,)
while any([r is not None for r in nexts]):
next_idx_to_k = dict(((i, get_key(r)) for (i, r) in enumerate(nexts) if r is not None))
keys_with_prev_contig = [k for k in next_idx_to_k.values() if k[0] == min_k[0]]
if any(keys_with_prev_contig):
min_k = min(keys_with_prev_contig)
else:
min_k = min(next_idx_to_k.values())
min_k_idxs = set([i for (i, k) in next_idx_to_k.items() if k == min_k])
yield [nexts[i] if i in min_k_idxs else None for i in range(len(nexts))]
for i in min_k_idxs:
try:
nexts[i] = readers[i].next()
except StopIteration:
nexts[i] = None
def trim_common_suffix(*sequences):
"""
Trim a list of sequences by removing the longest common suffix while
leaving all of them at least one character in length.
Standard convention with VCF is to place an indel at the left-most
position, but some tools add additional context to the right of the
sequences (e.g. samtools). These common suffixes are undesirable when
comparing variants, for example in variant databases.
>>> trim_common_suffix('TATATATA', 'TATATA')
['TAT', 'T']
>>> trim_common_suffix('ACCCCC', 'ACCCCCCCC', 'ACCCCCCC', 'ACCCCCCCCC')
['A', 'ACCC', 'ACC', 'ACCCC']
"""
if not sequences:
return []
reverses = [seq[::-1] for seq in sequences]
rev_min = min(reverses)
rev_max = max(reverses)
if len(rev_min) < 2:
return sequences
for (i, c) in enumerate(rev_min[:-1]):
if c != rev_max[i]:
if i == 0:
return sequences
return [seq[:-i] for seq in sequences]
return [seq[:-(i + 1)] for seq in sequences] |
class EvaluateConfig:
def __init__(self):
self.game_num = 100
self.replace_rate = 0.55
self.play_config = PlayConfig()
self.play_config.c_puct = 1
self.play_config.change_tau_turn = 0
self.play_config.noise_eps = 0
self.evaluate_latest_first = True
class PlayDataConfig:
def __init__(self):
self.nb_game_in_file = 100
self.max_file_num = 10
self.save_policy_of_tau_1 = True
class PlayConfig:
def __init__(self):
self.simulation_num_per_move = 10
self.share_mtcs_info_in_self_play = True
self.reset_mtcs_info_per_game = 10
self.thinking_loop = 1
self.logging_thinking = False
self.c_puct = 5
self.noise_eps = 0.25
self.dirichlet_alpha = 0.5
self.dirichlet_noise_only_for_legal_moves = True
self.change_tau_turn = 10
self.virtual_loss = 3
self.prediction_queue_size = 16
self.parallel_search_num = 4
self.prediction_worker_sleep_sec = 0.00001
self.wait_for_expanding_sleep_sec = 0.000001
self.resign_threshold = -0.8
self.allowed_resign_turn = 30
self.disable_resignation_rate = 0.1
self.false_positive_threshold = 0.05
self.resign_threshold_delta = 0.01
self.use_newest_next_generation_model = True
self.simulation_num_per_move_schedule = [
(300, 8),
(500, 20),
]
class TrainerConfig:
def __init__(self):
self.batch_size = 2048
self.min_data_size_to_learn = 100
self.epoch_to_checkpoint = 1
self.start_total_steps = 0
self.save_model_steps = 200
self.lr_schedules = [
(0, 0.01),
(100000, 0.001),
(200000, 0.0001)
]
class ModelConfig:
cnn_filter_num = 16
cnn_filter_size = 3
res_layer_num = 1
l2_reg = 1e-4
value_fc_size = 16
| class Evaluateconfig:
def __init__(self):
self.game_num = 100
self.replace_rate = 0.55
self.play_config = play_config()
self.play_config.c_puct = 1
self.play_config.change_tau_turn = 0
self.play_config.noise_eps = 0
self.evaluate_latest_first = True
class Playdataconfig:
def __init__(self):
self.nb_game_in_file = 100
self.max_file_num = 10
self.save_policy_of_tau_1 = True
class Playconfig:
def __init__(self):
self.simulation_num_per_move = 10
self.share_mtcs_info_in_self_play = True
self.reset_mtcs_info_per_game = 10
self.thinking_loop = 1
self.logging_thinking = False
self.c_puct = 5
self.noise_eps = 0.25
self.dirichlet_alpha = 0.5
self.dirichlet_noise_only_for_legal_moves = True
self.change_tau_turn = 10
self.virtual_loss = 3
self.prediction_queue_size = 16
self.parallel_search_num = 4
self.prediction_worker_sleep_sec = 1e-05
self.wait_for_expanding_sleep_sec = 1e-06
self.resign_threshold = -0.8
self.allowed_resign_turn = 30
self.disable_resignation_rate = 0.1
self.false_positive_threshold = 0.05
self.resign_threshold_delta = 0.01
self.use_newest_next_generation_model = True
self.simulation_num_per_move_schedule = [(300, 8), (500, 20)]
class Trainerconfig:
def __init__(self):
self.batch_size = 2048
self.min_data_size_to_learn = 100
self.epoch_to_checkpoint = 1
self.start_total_steps = 0
self.save_model_steps = 200
self.lr_schedules = [(0, 0.01), (100000, 0.001), (200000, 0.0001)]
class Modelconfig:
cnn_filter_num = 16
cnn_filter_size = 3
res_layer_num = 1
l2_reg = 0.0001
value_fc_size = 16 |
class FakeSingleton:
def __init__(self, payload):
self._payload = payload
def instance(self):
return self._payload
| class Fakesingleton:
def __init__(self, payload):
self._payload = payload
def instance(self):
return self._payload |
""" This module has various utilities for managing the CTCP protocol. It is
is responsible for parsing CTCP data and making data ready to be sent
via CTCP.
"""
X_DELIM = "\x01"
M_QUOTE = "\x10"
X_QUOTE = "\\"
commands = ["ACTION", "VERSION", "USERINFO", "CLIENTINFO", "ERRMSG", "PING",
"TIME", "FINGER"]
_ctcp_level_quote_map = [
("\\", "\\\\"),
("\x01", "\\a")
]
_low_level_quote_map = [
("\x10", "\x10\x10"),
("\x00", "\x100"),
("\n", "\x10n"),
("\r", "\x10r")
]
def tag(message):
""" Wraps an X-DELIM (``\\x01``) around a message to indicate that it needs
to be CTCP tagged.
"""
return X_DELIM + message + X_DELIM
def low_level_quote(text):
""" Performs a low-level quoting in order to escape characters that could
otherwise not be represented in the typical IRC protocol.
"""
# TODO: Strip cases where M_QUOTE is on its own
for (search, replace) in _low_level_quote_map:
text = text.replace(search, replace)
return text
def low_level_dequote(text):
""" Performs the complete opposite of ``low_level_quote`` as it converts the
quoted character back to their original forms.
"""
# TODO: Strip cases where M_QUOTE is on its own
for (replace, search) in reversed(_low_level_quote_map):
text = text.replace(search, replace)
return text
def quote(text):
""" This is CTCP-level quoting. It's only purpose is to quote out ``\\x01``
characters so they can be represented INSIDE tagged CTCP data.
"""
for (search, replace) in _ctcp_level_quote_map:
text = text.replace(search, replace)
return text
def dequote(text):
""" Performs the opposite of ``quote()`` as it will essentially strip the
quote character.
"""
for (replace, search) in reversed(_ctcp_level_quote_map):
text = text.replace(search, replace)
return text
def extract(message):
""" Splits a message between the actual message and any CTCP requests.
It returns a 2-part tuple of ``(message, ctcp_requests)`` where
``ctcp_requests`` is a list of requests.
"""
stripped_message = []
ctcp_requests = []
in_tag = False
index = 0
while index < len(message):
if in_tag:
ctcp_request = []
while index < len(message) and message[index] != X_DELIM:
ctcp_request.append(message[index])
index += 1
ctcp_requests.append(_parse_request("".join(ctcp_request)))
in_tag = False
else:
while index < len(message) and message[index] != X_DELIM:
stripped_message.append(message[index])
index += 1
in_tag = True
index += 1
return "".join(stripped_message), ctcp_requests
def _parse_request(section):
""" This function takes a CTCP-tagged section of a message and breaks it in
to a two-part tuple in the form of ``(command, parameters)`` where
``command`` is a string and ``parameters`` is a tuple.
"""
sections = section.split(" ")
if len(sections) > 1:
command, params = (sections[0], tuple(sections[1:]))
else:
command, params = (sections[0], tuple())
return command, params | """ This module has various utilities for managing the CTCP protocol. It is
is responsible for parsing CTCP data and making data ready to be sent
via CTCP.
"""
x_delim = '\x01'
m_quote = '\x10'
x_quote = '\\'
commands = ['ACTION', 'VERSION', 'USERINFO', 'CLIENTINFO', 'ERRMSG', 'PING', 'TIME', 'FINGER']
_ctcp_level_quote_map = [('\\', '\\\\'), ('\x01', '\\a')]
_low_level_quote_map = [('\x10', '\x10\x10'), ('\x00', '\x100'), ('\n', '\x10n'), ('\r', '\x10r')]
def tag(message):
""" Wraps an X-DELIM (``\\x01``) around a message to indicate that it needs
to be CTCP tagged.
"""
return X_DELIM + message + X_DELIM
def low_level_quote(text):
""" Performs a low-level quoting in order to escape characters that could
otherwise not be represented in the typical IRC protocol.
"""
for (search, replace) in _low_level_quote_map:
text = text.replace(search, replace)
return text
def low_level_dequote(text):
""" Performs the complete opposite of ``low_level_quote`` as it converts the
quoted character back to their original forms.
"""
for (replace, search) in reversed(_low_level_quote_map):
text = text.replace(search, replace)
return text
def quote(text):
""" This is CTCP-level quoting. It's only purpose is to quote out ``\\x01``
characters so they can be represented INSIDE tagged CTCP data.
"""
for (search, replace) in _ctcp_level_quote_map:
text = text.replace(search, replace)
return text
def dequote(text):
""" Performs the opposite of ``quote()`` as it will essentially strip the
quote character.
"""
for (replace, search) in reversed(_ctcp_level_quote_map):
text = text.replace(search, replace)
return text
def extract(message):
""" Splits a message between the actual message and any CTCP requests.
It returns a 2-part tuple of ``(message, ctcp_requests)`` where
``ctcp_requests`` is a list of requests.
"""
stripped_message = []
ctcp_requests = []
in_tag = False
index = 0
while index < len(message):
if in_tag:
ctcp_request = []
while index < len(message) and message[index] != X_DELIM:
ctcp_request.append(message[index])
index += 1
ctcp_requests.append(_parse_request(''.join(ctcp_request)))
in_tag = False
else:
while index < len(message) and message[index] != X_DELIM:
stripped_message.append(message[index])
index += 1
in_tag = True
index += 1
return (''.join(stripped_message), ctcp_requests)
def _parse_request(section):
""" This function takes a CTCP-tagged section of a message and breaks it in
to a two-part tuple in the form of ``(command, parameters)`` where
``command`` is a string and ``parameters`` is a tuple.
"""
sections = section.split(' ')
if len(sections) > 1:
(command, params) = (sections[0], tuple(sections[1:]))
else:
(command, params) = (sections[0], tuple())
return (command, params) |
'''
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to check multiple ifs?
You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine.
There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this.
Instead, you can use what is called the "elif" here in python... which is short for "else if"
'''
x = 5
y = 10
z = 22
# first run the default like this, then
# change the x > y to x < y...
# then change both of these to an ==
if x > y:
print('x is greater than y')
elif x < z:
print('x is less than z')
else:
print('if and elif never ran...')
| """
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to check multiple ifs?
You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine.
There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this.
Instead, you can use what is called the "elif" here in python... which is short for "else if"
"""
x = 5
y = 10
z = 22
if x > y:
print('x is greater than y')
elif x < z:
print('x is less than z')
else:
print('if and elif never ran...') |
steps = 363
buffer = [0]
currentValue = 1
currentPosition = 0
for i in range(1, 2018):
currentPosition = (currentPosition+steps)%len(buffer)
buffer.insert(currentPosition+1, currentValue)
currentValue += 1
currentPosition += 1
print(buffer[(currentPosition+1)%len(buffer)])
| steps = 363
buffer = [0]
current_value = 1
current_position = 0
for i in range(1, 2018):
current_position = (currentPosition + steps) % len(buffer)
buffer.insert(currentPosition + 1, currentValue)
current_value += 1
current_position += 1
print(buffer[(currentPosition + 1) % len(buffer)]) |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Distance
# {"feature": "Coupon", "instances": 51, "metric_value": 0.9931, "depth": 1}
if obj[0]>1:
# {"feature": "Occupation", "instances": 36, "metric_value": 0.9183, "depth": 2}
if obj[2]<=19:
# {"feature": "Education", "instances": 33, "metric_value": 0.8454, "depth": 3}
if obj[1]<=2:
# {"feature": "Distance", "instances": 26, "metric_value": 0.7063, "depth": 4}
if obj[3]<=2:
return 'True'
elif obj[3]>2:
return 'True'
else: return 'True'
elif obj[1]>2:
# {"feature": "Distance", "instances": 7, "metric_value": 0.9852, "depth": 4}
if obj[3]<=2:
return 'True'
elif obj[3]>2:
return 'False'
else: return 'False'
else: return 'False'
elif obj[2]>19:
return 'False'
else: return 'False'
elif obj[0]<=1:
# {"feature": "Occupation", "instances": 15, "metric_value": 0.8366, "depth": 2}
if obj[2]<=6:
# {"feature": "Education", "instances": 11, "metric_value": 0.9457, "depth": 3}
if obj[1]<=3:
# {"feature": "Distance", "instances": 10, "metric_value": 0.8813, "depth": 4}
if obj[3]<=1:
return 'False'
elif obj[3]>1:
return 'True'
else: return 'True'
elif obj[1]>3:
return 'True'
else: return 'True'
elif obj[2]>6:
return 'False'
else: return 'False'
else: return 'False'
| def find_decision(obj):
if obj[0] > 1:
if obj[2] <= 19:
if obj[1] <= 2:
if obj[3] <= 2:
return 'True'
elif obj[3] > 2:
return 'True'
else:
return 'True'
elif obj[1] > 2:
if obj[3] <= 2:
return 'True'
elif obj[3] > 2:
return 'False'
else:
return 'False'
else:
return 'False'
elif obj[2] > 19:
return 'False'
else:
return 'False'
elif obj[0] <= 1:
if obj[2] <= 6:
if obj[1] <= 3:
if obj[3] <= 1:
return 'False'
elif obj[3] > 1:
return 'True'
else:
return 'True'
elif obj[1] > 3:
return 'True'
else:
return 'True'
elif obj[2] > 6:
return 'False'
else:
return 'False'
else:
return 'False' |
class JSONWriter:
def __init__(self, alerts, row_parser):
self.alerts = alerts
self.row_parser = row_parser
def parse_alerts(self, vendor, url,product, webpage_name):
collection = list()
alerts_list = self.alerts
failed_count = 0
skipped_count = 0
for alert in alerts_list:
row = self.row_parser.parse(
alert, vendor, url,product, webpage_name)
if row == "Skipped":
skipped_count += 1
break
elif row is not None:
collection.append(row)
else:
failed_count += 1
return (collection, failed_count, skipped_count)
| class Jsonwriter:
def __init__(self, alerts, row_parser):
self.alerts = alerts
self.row_parser = row_parser
def parse_alerts(self, vendor, url, product, webpage_name):
collection = list()
alerts_list = self.alerts
failed_count = 0
skipped_count = 0
for alert in alerts_list:
row = self.row_parser.parse(alert, vendor, url, product, webpage_name)
if row == 'Skipped':
skipped_count += 1
break
elif row is not None:
collection.append(row)
else:
failed_count += 1
return (collection, failed_count, skipped_count) |
class Partisan_Gauge:
def __init__(self):
self.cultural_axis = 0
self.economic_axis = 0
self.authoritarian_axis = 0
def set_cultural_axis(self,cultural_axis):
self.cultural_axis = cultural_axis
def set_cultural_axis(self,cultural_axis):
self.cultural_axis = cultural_axis
def set_cultural_axis(self,cultural_axis):
self.cultural_axis = cultural_axis
class DogWhistles:
def __init__(self):
self.whistles = {}
def add_whistle(self, whistle_name, whistle_description, found_on_node):
whistle_name = str(whistle_name)
whistle_description = str(whistle_description)
self.whistles[whistle_name] = whistle_description
class ProperNouns:
def __init__(self):
self.proper_nouns = {}
def add_noun(self, noun_name, noun_description, found_on_node):
whistle_name = str(noun_name)
whistle_description = str(noun_description)
self.proper_nouns[noun_name] = noun_description
| class Partisan_Gauge:
def __init__(self):
self.cultural_axis = 0
self.economic_axis = 0
self.authoritarian_axis = 0
def set_cultural_axis(self, cultural_axis):
self.cultural_axis = cultural_axis
def set_cultural_axis(self, cultural_axis):
self.cultural_axis = cultural_axis
def set_cultural_axis(self, cultural_axis):
self.cultural_axis = cultural_axis
class Dogwhistles:
def __init__(self):
self.whistles = {}
def add_whistle(self, whistle_name, whistle_description, found_on_node):
whistle_name = str(whistle_name)
whistle_description = str(whistle_description)
self.whistles[whistle_name] = whistle_description
class Propernouns:
def __init__(self):
self.proper_nouns = {}
def add_noun(self, noun_name, noun_description, found_on_node):
whistle_name = str(noun_name)
whistle_description = str(noun_description)
self.proper_nouns[noun_name] = noun_description |
# Write your solution for 1.3 here!
n = 0
i = 1
while i < 10000:
n = n + i
i = i + 1
print(i)
| n = 0
i = 1
while i < 10000:
n = n + i
i = i + 1
print(i) |
"""Windchill module.
Connect to Windchill server, use workspaces (create/delete/list)
List files and checkout status.
"""
def authorize(client, user, password):
"""Set user's Windchill login/password.
Args:
client (obj): creopyson Client
user (str): user name
password (str): password
Returns:
None
"""
data = {"user": user, "password": password}
return client._creoson_post("windchill", "authorize", data)
def clear_workspace(client, workspace=None, filenames=None):
"""Clear a workspace on the active server.
Args:
client (obj):
creopyson Client
workspace (str, optionnal):
Workspace name. Default is current workspace.
filenames (str|list, optionnal):
List of files to delete from the workspace.
Default: All files are deleted.
Returns:
None
"""
active_workspace = client.windchill_get_workspace()
data = {"workspace": active_workspace}
if workspace:
data["workspace"] = workspace
if filenames:
data["filenames"] = filenames
return client._creoson_post("windchill", "clear_workspace", data)
def create_workspace(client, workspace, context_name):
"""Create a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
context_name (str): Context name
Returns:
None
"""
data = {"workspace": workspace, "context": context_name}
return client._creoson_post("windchill", "create_workspace", data)
def delete_workspace(client, workspace):
"""Delete a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
None
"""
data = {"workspace": workspace}
return client._creoson_post("windchill", "delete_workspace", data)
def file_checked_out(client, filename, workspace=None):
"""Check whether a file is checked out in a workspace on the active server.
Args:
client (obj):
creopyson Client
filename (str):
File name
workspace (str, optionnal):
Workspace name. Default is current workspace.
Returns:
Boolean: Whether the file is checked out in the workspace.
"""
active_workspace = client.windchill_get_workspace()
data = {"workspace": active_workspace, "filename": filename}
if workspace:
data["workspace"] = workspace
return client._creoson_post("windchill", "file_checked_out", data, "checked_out")
def get_workspace(client):
"""Retrieve the name of the active workspace on the active server.
Args:
client (obj): creopyson Client
Returns:
str: Active Workspace name.
"""
return client._creoson_post("windchill", "get_workspace", key_data="workspace")
def list_workspace_files(client, workspace=None, filename=None):
"""Get a list of files in a workspace on the active server.
Args:
client (obj):
creopyson Client
workspace (str, optionnal):
Workspace name. Default is current workspace.
filename (str, optional):
File name or search. Default is all files.
ex: `*.asm`, `screw_*.prt`
Returns:
list: List of files in the workspace correspnding to the data.
"""
active_workspace = client.windchill_get_workspace()
data = {"workspace": active_workspace, "filename": "*"}
if workspace:
data["workspace"] = workspace
if filename:
data["filename"] = filename
return client._creoson_post("windchill", "list_workspace_files", data, "filelist")
def list_workspaces(client):
"""Get a list of workspaces the user can access on the active server.
Args:
client (obj): creopyson Client
Returns:
list: List of workspaces
"""
return client._creoson_post("windchill", "list_workspaces", key_data="workspaces")
def server_exists(client, server_url):
"""Check whether a server exists.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
Boolean: Whether the server exists
"""
data = {"server_url": server_url}
return client._creoson_post("windchill", "server_exists", data, "exists")
def set_server(client, server_url):
"""Select a Windchill server.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
None
"""
data = {"server_url": server_url}
return client._creoson_post("windchill", "set_server", data)
def set_workspace(client, workspace):
"""Select a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
None
"""
data = {"workspace": workspace}
return client._creoson_post("windchill", "set_workspace", data)
def workspace_exists(client, workspace):
"""Check whether a workspace exists on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
Boolean: Whether the workspace exists
"""
data = {"workspace": workspace}
return client._creoson_post("windchill", "workspace_exists", data, "exists")
| """Windchill module.
Connect to Windchill server, use workspaces (create/delete/list)
List files and checkout status.
"""
def authorize(client, user, password):
"""Set user's Windchill login/password.
Args:
client (obj): creopyson Client
user (str): user name
password (str): password
Returns:
None
"""
data = {'user': user, 'password': password}
return client._creoson_post('windchill', 'authorize', data)
def clear_workspace(client, workspace=None, filenames=None):
"""Clear a workspace on the active server.
Args:
client (obj):
creopyson Client
workspace (str, optionnal):
Workspace name. Default is current workspace.
filenames (str|list, optionnal):
List of files to delete from the workspace.
Default: All files are deleted.
Returns:
None
"""
active_workspace = client.windchill_get_workspace()
data = {'workspace': active_workspace}
if workspace:
data['workspace'] = workspace
if filenames:
data['filenames'] = filenames
return client._creoson_post('windchill', 'clear_workspace', data)
def create_workspace(client, workspace, context_name):
"""Create a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
context_name (str): Context name
Returns:
None
"""
data = {'workspace': workspace, 'context': context_name}
return client._creoson_post('windchill', 'create_workspace', data)
def delete_workspace(client, workspace):
"""Delete a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
None
"""
data = {'workspace': workspace}
return client._creoson_post('windchill', 'delete_workspace', data)
def file_checked_out(client, filename, workspace=None):
"""Check whether a file is checked out in a workspace on the active server.
Args:
client (obj):
creopyson Client
filename (str):
File name
workspace (str, optionnal):
Workspace name. Default is current workspace.
Returns:
Boolean: Whether the file is checked out in the workspace.
"""
active_workspace = client.windchill_get_workspace()
data = {'workspace': active_workspace, 'filename': filename}
if workspace:
data['workspace'] = workspace
return client._creoson_post('windchill', 'file_checked_out', data, 'checked_out')
def get_workspace(client):
"""Retrieve the name of the active workspace on the active server.
Args:
client (obj): creopyson Client
Returns:
str: Active Workspace name.
"""
return client._creoson_post('windchill', 'get_workspace', key_data='workspace')
def list_workspace_files(client, workspace=None, filename=None):
"""Get a list of files in a workspace on the active server.
Args:
client (obj):
creopyson Client
workspace (str, optionnal):
Workspace name. Default is current workspace.
filename (str, optional):
File name or search. Default is all files.
ex: `*.asm`, `screw_*.prt`
Returns:
list: List of files in the workspace correspnding to the data.
"""
active_workspace = client.windchill_get_workspace()
data = {'workspace': active_workspace, 'filename': '*'}
if workspace:
data['workspace'] = workspace
if filename:
data['filename'] = filename
return client._creoson_post('windchill', 'list_workspace_files', data, 'filelist')
def list_workspaces(client):
"""Get a list of workspaces the user can access on the active server.
Args:
client (obj): creopyson Client
Returns:
list: List of workspaces
"""
return client._creoson_post('windchill', 'list_workspaces', key_data='workspaces')
def server_exists(client, server_url):
"""Check whether a server exists.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
Boolean: Whether the server exists
"""
data = {'server_url': server_url}
return client._creoson_post('windchill', 'server_exists', data, 'exists')
def set_server(client, server_url):
"""Select a Windchill server.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
None
"""
data = {'server_url': server_url}
return client._creoson_post('windchill', 'set_server', data)
def set_workspace(client, workspace):
"""Select a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
None
"""
data = {'workspace': workspace}
return client._creoson_post('windchill', 'set_workspace', data)
def workspace_exists(client, workspace):
"""Check whether a workspace exists on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
Boolean: Whether the workspace exists
"""
data = {'workspace': workspace}
return client._creoson_post('windchill', 'workspace_exists', data, 'exists') |
with open('./6/input_a.txt', 'r') as f:
input = list(map(int,f.readline().strip().split(',')))
fish = list([0,0,0,0,0,0,0,0,0])
for i in range(0,8):
fish[i] = sum([1 for a in input if a == i])
def observe(days):
for d in range(0,days):
newfish = fish[0]
for i in range(0,8):
fish[i] = fish[i+1] + (newfish if i == 6 else 0)
fish[8] = newfish
return sum([a for a in fish])
print(f'Part A: after 80 days {observe(80)} lanternfish remaining')
print(f'Part B: after 256 days {observe(256-80)} lanternfish remaining') | with open('./6/input_a.txt', 'r') as f:
input = list(map(int, f.readline().strip().split(',')))
fish = list([0, 0, 0, 0, 0, 0, 0, 0, 0])
for i in range(0, 8):
fish[i] = sum([1 for a in input if a == i])
def observe(days):
for d in range(0, days):
newfish = fish[0]
for i in range(0, 8):
fish[i] = fish[i + 1] + (newfish if i == 6 else 0)
fish[8] = newfish
return sum([a for a in fish])
print(f'Part A: after 80 days {observe(80)} lanternfish remaining')
print(f'Part B: after 256 days {observe(256 - 80)} lanternfish remaining') |
def center_text(*args, sep=' ', end='\n', file=None, flush=False):
text=''
for arg in args:
text += str(arg) + sep
left_margin = (80 - len(text)) // 2
print(" " * left_margin, text, end=end, file=file, flush=flush)
# calling the function
center_text("spams and eggs")
center_text(12)
center_text("first", "second", 3, 4)
| def center_text(*args, sep=' ', end='\n', file=None, flush=False):
text = ''
for arg in args:
text += str(arg) + sep
left_margin = (80 - len(text)) // 2
print(' ' * left_margin, text, end=end, file=file, flush=flush)
center_text('spams and eggs')
center_text(12)
center_text('first', 'second', 3, 4) |
"""
Design your implementation of the circular queue. The circular queue is a
linear data structure in which the operations are performed based on FIFO
(First In First Out) principle and the last position is connected back to
the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the
spaces in front of the queue. In a normal queue, once the queue becomes
full, we cannot insert the next element even if there is a space in front
of the queue. But using the circular queue, we can use the space to store
new values.
Your implementation should support following operations:
MyCircularQueue(k): Constructor, set the size of the queue to be k.
Front: Get the front item from the queue. If the queue is empty, return -1.
Rear: Get the last item from the queue. If the queue is empty, return -1.
enQueue(value): Insert an element into the circular queue. Return true if
the operation is successful.
deQueue(): Delete an element from the circular queue. Return true if the
operation is successful.
isEmpty(): Checks whether the circular queue is empty or not.
isFull(): Checks whether the circular queue is full or not.
Example:
MyCircularQueue circularQueue = new MyCircularQueue(3);
// set the size to be 3
circularQueue.enQueue(1); // return true
circularQueue.enQueue(2); // return true
circularQueue.enQueue(3); // return true
circularQueue.enQueue(4); // return false, the queue is full
circularQueue.Rear(); // return 3
circularQueue.isFull(); // return true
circularQueue.deQueue(); // return true
circularQueue.enQueue(4); // return true
circularQueue.Rear(); // return 4
Note:
All values will be in the range of [0, 1000].
The number of operations will be in the range of [1, 1000].
Please do not use the built-in Queue library.
"""
#Difficulty: Medium
#52 / 52 test cases passed.
#Runtime: 100 ms
#Memory Usage: 14 MB
#Runtime: 100 ms, faster than 9.41% of Python3 online submissions for Design Circular Queue.
#Memory Usage: 14 MB, less than 5.26% of Python3 online submissions for Design Circular Queue.
class MyCircularQueue: # First time. Solved by myself without theory
def __init__(self, k: int):
self.k = k - 1
self.front = self.rear = -1
self.queue = [None] * k
def enQueue(self, value: int) -> bool:
r = False
if self.isFull():
return r
if self.rear == -1:
self.front += 1
self.rear += 1
self.queue[self.rear] = value
r = True
elif self.rear != self.k:
self.rear += 1
self.queue[self.rear] = value
r = True
elif self.rear == self.k and not self.isFull():
self.rear = 0
self.queue[self.rear] = value
r = True
return r
def deQueue(self) -> bool:
r = False
if self.front == -1 or self.isEmpty():
return r
elif self.front != self.k:
self.queue[self.front] = None
self.front += 1
if self.isEmpty():
self.front = -1
self.rear = -1
r = True
elif self.front == self.k and not self.isEmpty():
self.queue[self.front] = None
self.front = 0
r = True
return r
def Front(self) -> int:
if self.isEmpty():
self.front = -1
self.rear = -1
return self.front
return self.queue[self.front]
def Rear(self) -> int:
if self.isEmpty():
self.front = -1
self.rear = -1
return self.rear
return self.queue[self.rear]
def isEmpty(self) -> bool:
return True if self.queue.count(None) == self.k + 1 else False
def isFull(self) -> bool:
return True if None not in self.queue else False
| """
Design your implementation of the circular queue. The circular queue is a
linear data structure in which the operations are performed based on FIFO
(First In First Out) principle and the last position is connected back to
the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the
spaces in front of the queue. In a normal queue, once the queue becomes
full, we cannot insert the next element even if there is a space in front
of the queue. But using the circular queue, we can use the space to store
new values.
Your implementation should support following operations:
MyCircularQueue(k): Constructor, set the size of the queue to be k.
Front: Get the front item from the queue. If the queue is empty, return -1.
Rear: Get the last item from the queue. If the queue is empty, return -1.
enQueue(value): Insert an element into the circular queue. Return true if
the operation is successful.
deQueue(): Delete an element from the circular queue. Return true if the
operation is successful.
isEmpty(): Checks whether the circular queue is empty or not.
isFull(): Checks whether the circular queue is full or not.
Example:
MyCircularQueue circularQueue = new MyCircularQueue(3);
// set the size to be 3
circularQueue.enQueue(1); // return true
circularQueue.enQueue(2); // return true
circularQueue.enQueue(3); // return true
circularQueue.enQueue(4); // return false, the queue is full
circularQueue.Rear(); // return 3
circularQueue.isFull(); // return true
circularQueue.deQueue(); // return true
circularQueue.enQueue(4); // return true
circularQueue.Rear(); // return 4
Note:
All values will be in the range of [0, 1000].
The number of operations will be in the range of [1, 1000].
Please do not use the built-in Queue library.
"""
class Mycircularqueue:
def __init__(self, k: int):
self.k = k - 1
self.front = self.rear = -1
self.queue = [None] * k
def en_queue(self, value: int) -> bool:
r = False
if self.isFull():
return r
if self.rear == -1:
self.front += 1
self.rear += 1
self.queue[self.rear] = value
r = True
elif self.rear != self.k:
self.rear += 1
self.queue[self.rear] = value
r = True
elif self.rear == self.k and (not self.isFull()):
self.rear = 0
self.queue[self.rear] = value
r = True
return r
def de_queue(self) -> bool:
r = False
if self.front == -1 or self.isEmpty():
return r
elif self.front != self.k:
self.queue[self.front] = None
self.front += 1
if self.isEmpty():
self.front = -1
self.rear = -1
r = True
elif self.front == self.k and (not self.isEmpty()):
self.queue[self.front] = None
self.front = 0
r = True
return r
def front(self) -> int:
if self.isEmpty():
self.front = -1
self.rear = -1
return self.front
return self.queue[self.front]
def rear(self) -> int:
if self.isEmpty():
self.front = -1
self.rear = -1
return self.rear
return self.queue[self.rear]
def is_empty(self) -> bool:
return True if self.queue.count(None) == self.k + 1 else False
def is_full(self) -> bool:
return True if None not in self.queue else False |
#!/usr/bin/env python
# encoding: utf-8
name = "R_Addition_COm/groups"
shortDesc = u""
longDesc = u"""
"""
template(reactants=["COm", "Y_rad"], products=["YC.=O"], ownReverse=False)
reverse = "COM_Elimination_From_Carbonyl"
recipe(actions=[
['LOSE_PAIR', '*1', '1'],
['CHANGE_BOND', '*1', -1, '*3'],
['GAIN_PAIR', '*3', '1'],
['GAIN_RADICAL', '*1', '1'],
['FORM_BOND', '*1', 1, '*2'],
['LOSE_RADICAL', '*2', '1'],
])
entry(
index = 1,
label = "COm",
group =
"""
1 *1 C2tc u0 p1 c-1 {2,T}
2 *3 O4tc u0 p1 c+1 {1,T}
""",
kinetics = None,
)
entry(
index = 2,
label = "Y_rad",
group =
"""
1 *2 R u1
""",
kinetics = None,
)
entry(
index = 3,
label = "H_rad",
group =
"""
1 *2 H u1
""",
kinetics = None,
)
entry(
index = 4,
label = "O_rad",
group =
"""
1 *2 O u1
""",
kinetics = None,
)
entry(
index = 5,
label = "O_pri_rad",
group =
"""
1 *2 O u1 {2,S}
2 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 6,
label = "O_sec_rad",
group =
"""
1 *2 O u1 {2,S}
2 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 7,
label = "O_rad/NonDe",
group =
"""
1 *2 O u1 {2,S}
2 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 8,
label = "O_rad/OneDe",
group =
"""
1 *2 O u1 {2,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 9,
label = "Ct_rad",
group =
"""
1 *2 C u1 {2,T}
2 C u0 {1,T}
""",
kinetics = None,
)
entry(
index = 10,
label = "CO_rad",
group =
"""
1 *2 C u1 {2,D}
2 O u0 {1,D}
""",
kinetics = None,
)
entry(
index = 11,
label = "CO_pri_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 O u0 {1,D}
3 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 12,
label = "CO_sec_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 O u0 {1,D}
3 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 70,
label = "CS_rad",
group =
"""
1 *2 C u1 {2,D}
2 S u0 {1,D}
""",
kinetics = None,
)
entry(
index = 71,
label = "CS_pri_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 S u0 {1,D}
3 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 72,
label = "CS_sec_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 S u0 {1,D}
3 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 13,
label = "Cd_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 R u0 {1,S}
""",
kinetics = None,
)
entry(
index = 14,
label = "Cd_pri_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 15,
label = "Cd_sec_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 16,
label = "Cd_rad/NonDe",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 17,
label = "Cd_rad/OneDe",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 18,
label = "Cb_rad",
group =
"""
1 *2 Cb u1 {2,B} {3,B}
2 [Cb,Cbf] u0 {1,B}
3 [Cb,Cbf] u0 {1,B}
""",
kinetics = None,
)
entry(
index = 19,
label = "Cs_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 R u0 {1,S}
3 R u0 {1,S}
4 R u0 {1,S}
""",
kinetics = None,
)
entry(
index = 20,
label = "C_methyl",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 21,
label = "C_pri_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 22,
label = "C_rad/H2/Cs",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cs u0 {1,S}
""",
kinetics = None,
)
entry(
index = 23,
label = "CH2CH3",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cs u0 {1,S} {5,S} {6,S} {7,S}
5 H u0 {4,S}
6 H u0 {4,S}
7 H u0 {4,S}
""",
kinetics = None,
)
entry(
index = 24,
label = "CH2CH2CH3",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cs u0 {1,S} {5,S} {6,S} {7,S}
5 H u0 {4,S}
6 H u0 {4,S}
7 C u0 {4,S} {8,S} {9,S} {10,S}
8 H u0 {7,S}
9 H u0 {7,S}
10 H u0 {7,S}
""",
kinetics = None,
)
entry(
index = 25,
label = "C_rad/H2/Cd",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cd u0 {1,S}
""",
kinetics = None,
)
entry(
index = 26,
label = "C_rad/H2/Ct",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Ct u0 {1,S}
""",
kinetics = None,
)
entry(
index = 27,
label = "C_rad/H2/Cb",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cb u0 {1,S}
""",
kinetics = None,
)
entry(
index = 28,
label = "C_rad/H2/CO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 CO u0 {1,S}
""",
kinetics = None,
)
entry(
index = 29,
label = "C_rad/H2/O",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 O u0 {1,S}
""",
kinetics = None,
)
entry(
index = 72,
label = "C_rad/H2/CS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 CS u0 {1,S}
""",
kinetics = None,
)
entry(
index = 73,
label = "C_rad/H2/S",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 S u0 {1,S}
""",
kinetics = None,
)
entry(
index = 30,
label = "C_sec_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 R!H u0 {1,S}
4 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 31,
label = "C_rad/H/NonDeC",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S}
4 Cs u0 {1,S}
""",
kinetics = None,
)
entry(
index = 32,
label = "CH(CH3)2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S} {5,S} {6,S} {7,S}
4 Cs u0 {1,S} {8,S} {9,S} {10,S}
5 H u0 {3,S}
6 H u0 {3,S}
7 H u0 {3,S}
8 H u0 {4,S}
9 H u0 {4,S}
10 H u0 {4,S}
""",
kinetics = None,
)
entry(
index = 33,
label = "C_rad/H/NonDeO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 O u0 {1,S}
4 [Cs,O] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 34,
label = "C_rad/H/CsO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S}
4 O u0 {1,S}
""",
kinetics = None,
)
entry(
index = 35,
label = "C_rad/H/O2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 O u0 {1,S}
4 O u0 {1,S}
""",
kinetics = None,
)
entry(
index = 74,
label = "C_rad/H/NonDeS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [S,C] u0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 75,
label = "C_rad/H/CsS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S}
4 S2s u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 76,
label = "C_rad/H/S2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 S u0 {1,S}
4 [O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 36,
label = "C_rad/H/OneDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 37,
label = "C_rad/H/OneDeC",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 38,
label = "C_rad/H/OneDeO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 O u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 77,
label = "C_rad/H/OneDeS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 S2s u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 39,
label = "C_rad/H/TwoDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 40,
label = "C_ter_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 R!H u0 {1,S}
3 R!H u0 {1,S}
4 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 41,
label = "C_rad/NonDeC",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cs,O,S2s] u0 px c0 {1,S}
3 [Cs,O,S2s] u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 42,
label = "C_rad/Cs3",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 Cs u0 px c0 {1,S}
3 Cs u0 px c0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 43,
label = "C_rad/NDMustO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 O u0 px c0 {1,S}
3 [Cs,O] u0 px c0 {1,S}
4 [Cs,O] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 78,
label = "C_rad/NDMustS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 S2s u0 px c0 {1,S}
3 [Cs,O,S2s] u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 44,
label = "C_rad/OneDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cs,O,S2s] u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 45,
label = "C_rad/OD_Cs2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 Cs u0 px c0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 46,
label = "C_rad/ODMustO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 O u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 47,
label = "C_rad/TwoDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 48,
label = "C_rad/TD_Cs",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 49,
label = "C_rad/TDMustO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 O u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 50,
label = "C_rad/ThreeDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 51,
label = "S_rad",
group =
"""
1 *2 S u1
""",
kinetics = None,
)
entry(
index = 52,
label = "S_pri_rad",
group =
"""
1 *2 S u1 {2,S}
2 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 53,
label = "S_sec_rad",
group =
"""
1 *2 S u1 {2,S}
2 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 54,
label = "S_rad/NonDe",
group =
"""
1 *2 S u1 {2,S}
2 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 55,
label = "S_rad/OneDe",
group =
"""
1 *2 S u1 {2,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
tree(
"""
L1: COm
L1: Y_rad
L2: H_rad
L2: O_rad
L3: O_pri_rad
L3: O_sec_rad
L4: O_rad/NonDe
L4: O_rad/OneDe
L2: S_rad
L3: S_pri_rad
L3: S_sec_rad
L4: S_rad/NonDe
L4: S_rad/OneDe
L2: Ct_rad
L2: CO_rad
L3: CO_pri_rad
L3: CO_sec_rad
L2: CS_rad
L3: CS_pri_rad
L3: CS_sec_rad
L2: Cd_rad
L3: Cd_pri_rad
L3: Cd_sec_rad
L4: Cd_rad/NonDe
L4: Cd_rad/OneDe
L2: Cb_rad
L2: Cs_rad
L3: C_methyl
L3: C_pri_rad
L4: C_rad/H2/Cs
L5: CH2CH3
L5: CH2CH2CH3
L4: C_rad/H2/Cd
L4: C_rad/H2/Ct
L4: C_rad/H2/Cb
L4: C_rad/H2/CO
L4: C_rad/H2/O
L4: C_rad/H2/CS
L4: C_rad/H2/S
L3: C_sec_rad
L4: C_rad/H/NonDeC
L5: CH(CH3)2
L4: C_rad/H/NonDeO
L5: C_rad/H/CsO
L5: C_rad/H/O2
L4: C_rad/H/NonDeS
L5: C_rad/H/CsS
L5: C_rad/H/S2
L5: C_rad/H/OneDe
L6: C_rad/H/OneDeC
L6: C_rad/H/OneDeO
L6: C_rad/H/OneDeS
L4: C_rad/H/TwoDe
L3: C_ter_rad
L4: C_rad/NonDeC
L5: C_rad/Cs3
L5: C_rad/NDMustO
L5: C_rad/NDMustS
L4: C_rad/OneDe
L5: C_rad/OD_Cs2
L5: C_rad/ODMustO
L4: C_rad/TwoDe
L5: C_rad/TD_Cs
L5: C_rad/TDMustO
L4: C_rad/ThreeDe
"""
)
forbidden(
label = "O2_birad",
group =
"""
1 *2 O u1 p2 {2,S}
2 O u1 p2 {1,S}
""",
shortDesc = u"""""",
longDesc =
u"""
""",
)
| name = 'R_Addition_COm/groups'
short_desc = u''
long_desc = u'\n\n'
template(reactants=['COm', 'Y_rad'], products=['YC.=O'], ownReverse=False)
reverse = 'COM_Elimination_From_Carbonyl'
recipe(actions=[['LOSE_PAIR', '*1', '1'], ['CHANGE_BOND', '*1', -1, '*3'], ['GAIN_PAIR', '*3', '1'], ['GAIN_RADICAL', '*1', '1'], ['FORM_BOND', '*1', 1, '*2'], ['LOSE_RADICAL', '*2', '1']])
entry(index=1, label='COm', group='\n1 *1 C2tc u0 p1 c-1 {2,T}\n2 *3 O4tc u0 p1 c+1 {1,T}\n', kinetics=None)
entry(index=2, label='Y_rad', group='\n1 *2 R u1\n', kinetics=None)
entry(index=3, label='H_rad', group='\n1 *2 H u1\n', kinetics=None)
entry(index=4, label='O_rad', group='\n1 *2 O u1\n', kinetics=None)
entry(index=5, label='O_pri_rad', group='\n1 *2 O u1 {2,S}\n2 H u0 {1,S}\n', kinetics=None)
entry(index=6, label='O_sec_rad', group='\n1 *2 O u1 {2,S}\n2 R!H u0 {1,S}\n', kinetics=None)
entry(index=7, label='O_rad/NonDe', group='\n1 *2 O u1 {2,S}\n2 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=8, label='O_rad/OneDe', group='\n1 *2 O u1 {2,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n', kinetics=None)
entry(index=9, label='Ct_rad', group='\n1 *2 C u1 {2,T}\n2 C u0 {1,T}\n', kinetics=None)
entry(index=10, label='CO_rad', group='\n1 *2 C u1 {2,D}\n2 O u0 {1,D}\n', kinetics=None)
entry(index=11, label='CO_pri_rad', group='\n1 *2 C u1 {2,D} {3,S}\n2 O u0 {1,D}\n3 H u0 {1,S}\n', kinetics=None)
entry(index=12, label='CO_sec_rad', group='\n1 *2 C u1 {2,D} {3,S}\n2 O u0 {1,D}\n3 R!H u0 {1,S}\n', kinetics=None)
entry(index=70, label='CS_rad', group='\n1 *2 C u1 {2,D}\n2 S u0 {1,D}\n', kinetics=None)
entry(index=71, label='CS_pri_rad', group='\n1 *2 C u1 {2,D} {3,S}\n2 S u0 {1,D}\n3 H u0 {1,S}\n', kinetics=None)
entry(index=72, label='CS_sec_rad', group='\n1 *2 C u1 {2,D} {3,S}\n2 S u0 {1,D}\n3 R!H u0 {1,S}\n', kinetics=None)
entry(index=13, label='Cd_rad', group='\n1 *2 C u1 {2,D} {3,S}\n2 C u0 {1,D}\n3 R u0 {1,S}\n', kinetics=None)
entry(index=14, label='Cd_pri_rad', group='\n1 *2 C u1 {2,D} {3,S}\n2 C u0 {1,D}\n3 H u0 {1,S}\n', kinetics=None)
entry(index=15, label='Cd_sec_rad', group='\n1 *2 C u1 {2,D} {3,S}\n2 C u0 {1,D}\n3 R!H u0 {1,S}\n', kinetics=None)
entry(index=16, label='Cd_rad/NonDe', group='\n1 *2 C u1 {2,D} {3,S}\n2 C u0 {1,D}\n3 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=17, label='Cd_rad/OneDe', group='\n1 *2 C u1 {2,D} {3,S}\n2 C u0 {1,D}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n', kinetics=None)
entry(index=18, label='Cb_rad', group='\n1 *2 Cb u1 {2,B} {3,B}\n2 [Cb,Cbf] u0 {1,B}\n3 [Cb,Cbf] u0 {1,B}\n', kinetics=None)
entry(index=19, label='Cs_rad', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 R u0 {1,S}\n3 R u0 {1,S}\n4 R u0 {1,S}\n', kinetics=None)
entry(index=20, label='C_methyl', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 H u0 {1,S}\n', kinetics=None)
entry(index=21, label='C_pri_rad', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 R!H u0 {1,S}\n', kinetics=None)
entry(index=22, label='C_rad/H2/Cs', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 Cs u0 {1,S}\n', kinetics=None)
entry(index=23, label='CH2CH3', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 Cs u0 {1,S} {5,S} {6,S} {7,S}\n5 H u0 {4,S}\n6 H u0 {4,S}\n7 H u0 {4,S}\n', kinetics=None)
entry(index=24, label='CH2CH2CH3', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 Cs u0 {1,S} {5,S} {6,S} {7,S}\n5 H u0 {4,S}\n6 H u0 {4,S}\n7 C u0 {4,S} {8,S} {9,S} {10,S}\n8 H u0 {7,S}\n9 H u0 {7,S}\n10 H u0 {7,S}\n', kinetics=None)
entry(index=25, label='C_rad/H2/Cd', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 Cd u0 {1,S}\n', kinetics=None)
entry(index=26, label='C_rad/H2/Ct', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 Ct u0 {1,S}\n', kinetics=None)
entry(index=27, label='C_rad/H2/Cb', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 Cb u0 {1,S}\n', kinetics=None)
entry(index=28, label='C_rad/H2/CO', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 CO u0 {1,S}\n', kinetics=None)
entry(index=29, label='C_rad/H2/O', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 O u0 {1,S}\n', kinetics=None)
entry(index=72, label='C_rad/H2/CS', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 CS u0 {1,S}\n', kinetics=None)
entry(index=73, label='C_rad/H2/S', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 H u0 {1,S}\n4 S u0 {1,S}\n', kinetics=None)
entry(index=30, label='C_sec_rad', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 R!H u0 {1,S}\n4 R!H u0 {1,S}\n', kinetics=None)
entry(index=31, label='C_rad/H/NonDeC', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 Cs u0 {1,S}\n4 Cs u0 {1,S}\n', kinetics=None)
entry(index=32, label='CH(CH3)2', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 Cs u0 {1,S} {5,S} {6,S} {7,S}\n4 Cs u0 {1,S} {8,S} {9,S} {10,S}\n5 H u0 {3,S}\n6 H u0 {3,S}\n7 H u0 {3,S}\n8 H u0 {4,S}\n9 H u0 {4,S}\n10 H u0 {4,S}\n', kinetics=None)
entry(index=33, label='C_rad/H/NonDeO', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 O u0 {1,S}\n4 [Cs,O] u0 {1,S}\n', kinetics=None)
entry(index=34, label='C_rad/H/CsO', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 Cs u0 {1,S}\n4 O u0 {1,S}\n', kinetics=None)
entry(index=35, label='C_rad/H/O2', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 O u0 {1,S}\n4 O u0 {1,S}\n', kinetics=None)
entry(index=74, label='C_rad/H/NonDeS', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 [S,C] u0 {1,S}\n4 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=75, label='C_rad/H/CsS', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 Cs u0 {1,S}\n4 S2s u0 px c0 {1,S}\n', kinetics=None)
entry(index=76, label='C_rad/H/S2', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 S u0 {1,S}\n4 [O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=36, label='C_rad/H/OneDe', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=37, label='C_rad/H/OneDeC', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 Cs u0 px c0 {1,S}\n', kinetics=None)
entry(index=38, label='C_rad/H/OneDeO', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 O u0 px c0 {1,S}\n', kinetics=None)
entry(index=77, label='C_rad/H/OneDeS', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 S2s u0 px c0 {1,S}\n', kinetics=None)
entry(index=39, label='C_rad/H/TwoDe', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 H u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n', kinetics=None)
entry(index=40, label='C_ter_rad', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 R!H u0 {1,S}\n3 R!H u0 {1,S}\n4 R!H u0 {1,S}\n', kinetics=None)
entry(index=41, label='C_rad/NonDeC', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cs,O,S2s] u0 px c0 {1,S}\n3 [Cs,O,S2s] u0 px c0 {1,S}\n4 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=42, label='C_rad/Cs3', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 Cs u0 px c0 {1,S}\n3 Cs u0 px c0 {1,S}\n4 Cs u0 px c0 {1,S}\n', kinetics=None)
entry(index=43, label='C_rad/NDMustO', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 O u0 px c0 {1,S}\n3 [Cs,O] u0 px c0 {1,S}\n4 [Cs,O] u0 px c0 {1,S}\n', kinetics=None)
entry(index=78, label='C_rad/NDMustS', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 S2s u0 px c0 {1,S}\n3 [Cs,O,S2s] u0 px c0 {1,S}\n4 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=44, label='C_rad/OneDe', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n3 [Cs,O,S2s] u0 px c0 {1,S}\n4 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=45, label='C_rad/OD_Cs2', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n3 Cs u0 px c0 {1,S}\n4 Cs u0 px c0 {1,S}\n', kinetics=None)
entry(index=46, label='C_rad/ODMustO', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n3 O u0 px c0 {1,S}\n4 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=47, label='C_rad/TwoDe', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=48, label='C_rad/TD_Cs', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 Cs u0 px c0 {1,S}\n', kinetics=None)
entry(index=49, label='C_rad/TDMustO', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 O u0 px c0 {1,S}\n', kinetics=None)
entry(index=50, label='C_rad/ThreeDe', group='\n1 *2 C u1 {2,S} {3,S} {4,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n3 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n4 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n', kinetics=None)
entry(index=51, label='S_rad', group='\n1 *2 S u1\n', kinetics=None)
entry(index=52, label='S_pri_rad', group='\n1 *2 S u1 {2,S}\n2 H u0 {1,S}\n', kinetics=None)
entry(index=53, label='S_sec_rad', group='\n1 *2 S u1 {2,S}\n2 R!H u0 {1,S}\n', kinetics=None)
entry(index=54, label='S_rad/NonDe', group='\n1 *2 S u1 {2,S}\n2 [Cs,O,S2s] u0 px c0 {1,S}\n', kinetics=None)
entry(index=55, label='S_rad/OneDe', group='\n1 *2 S u1 {2,S}\n2 [Cd,Ct,Cb,CO,CS] u0 {1,S}\n', kinetics=None)
tree('\nL1: COm\nL1: Y_rad\n L2: H_rad\n L2: O_rad\n L3: O_pri_rad\n L3: O_sec_rad\n L4: O_rad/NonDe\n L4: O_rad/OneDe\n L2: S_rad\n L3: S_pri_rad\n L3: S_sec_rad\n L4: S_rad/NonDe\n L4: S_rad/OneDe\n L2: Ct_rad\n L2: CO_rad\n L3: CO_pri_rad\n L3: CO_sec_rad\n L2: CS_rad\n L3: CS_pri_rad\n L3: CS_sec_rad\n L2: Cd_rad\n L3: Cd_pri_rad\n L3: Cd_sec_rad\n L4: Cd_rad/NonDe\n L4: Cd_rad/OneDe\n L2: Cb_rad\n L2: Cs_rad\n L3: C_methyl\n L3: C_pri_rad\n L4: C_rad/H2/Cs\n L5: CH2CH3\n L5: CH2CH2CH3\n L4: C_rad/H2/Cd\n L4: C_rad/H2/Ct\n L4: C_rad/H2/Cb\n L4: C_rad/H2/CO\n L4: C_rad/H2/O\n L4: C_rad/H2/CS\n L4: C_rad/H2/S\n L3: C_sec_rad\n L4: C_rad/H/NonDeC\n L5: CH(CH3)2\n L4: C_rad/H/NonDeO\n L5: C_rad/H/CsO\n L5: C_rad/H/O2\n L4: C_rad/H/NonDeS\n L5: C_rad/H/CsS\n L5: C_rad/H/S2\n L5: C_rad/H/OneDe\n L6: C_rad/H/OneDeC\n L6: C_rad/H/OneDeO\n L6: C_rad/H/OneDeS\n L4: C_rad/H/TwoDe\n L3: C_ter_rad\n L4: C_rad/NonDeC\n L5: C_rad/Cs3\n L5: C_rad/NDMustO\n L5: C_rad/NDMustS\n L4: C_rad/OneDe\n L5: C_rad/OD_Cs2\n L5: C_rad/ODMustO\n L4: C_rad/TwoDe\n L5: C_rad/TD_Cs\n L5: C_rad/TDMustO\n L4: C_rad/ThreeDe\n')
forbidden(label='O2_birad', group='\n1 *2 O u1 p2 {2,S}\n2 O u1 p2 {1,S}\n', shortDesc=u'', longDesc=u'\n\n') |
# ceasar_cypher_encryptor
# rotate each letter by k
# wrap around alphabet
def ceasar_cypher_encryptor(s, k):
ciphered = []
overflow_adjust = ord('z') - ord('a')
for c in s:
new_c = ord(c) + k
if new_c > ord('z'): # overflow adjustment
new_c = new_c - overflow_adjust
ciphered.append(chr(new_c))
return "".join(ciphered)
def main():
res = ceasar_cypher_encryptor("abcdefgxyz", 2)
print(f'{res}')
if __name__ == "__main__":
main() | def ceasar_cypher_encryptor(s, k):
ciphered = []
overflow_adjust = ord('z') - ord('a')
for c in s:
new_c = ord(c) + k
if new_c > ord('z'):
new_c = new_c - overflow_adjust
ciphered.append(chr(new_c))
return ''.join(ciphered)
def main():
res = ceasar_cypher_encryptor('abcdefgxyz', 2)
print(f'{res}')
if __name__ == '__main__':
main() |
# Write a program to read through the mbox-short.txt
# and figure out the distribution by hour of the day
# for each of the messages. You can pull the hour out
# from the 'From ' line by finding the time and then
# splitting the string a second time using a colon.
#
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
#
# Once you have accumulated the counts for each hour,
# print out the counts, sorted by hour as shown below.
name = input("Enter file:")
handle = open(name)
hours = {}
for line in handle:
line = line.strip()
if line.find('From ') == 0:
hour_sent = line[line.find(':')-2:line.find(':')]
# use dict get method to retrieve each hour_sent, or add it
# to the dict if it isn't present already (with default value of 0).
# Then set the value to value + 1
hours[hour_sent] = hours.get(hour_sent, 0) + 1
tups = hours.items() # get keys/values from hours as list of tuples
tups.sort() # sort by keys (first item in each tuple)
for tup in tups:
print(tup[0], str(tup[1]))
| name = input('Enter file:')
handle = open(name)
hours = {}
for line in handle:
line = line.strip()
if line.find('From ') == 0:
hour_sent = line[line.find(':') - 2:line.find(':')]
hours[hour_sent] = hours.get(hour_sent, 0) + 1
tups = hours.items()
tups.sort()
for tup in tups:
print(tup[0], str(tup[1])) |
def foo(a = 1, b = 2):
return a + b
price = foo(b = 4)
for item in [[1, 2, 3], [4, 5, 6]]:
print(item[0])
mylist = [['abc'], ['def', 'ghi']]
mylist[-1][-1][-1]
def eur_to_usd(euros, rate=0.8):
return euros * rate
print(eur_to_usd(10))
weight = input("How many kg?")
price = weight * 2.5
print(price)
x = [len(item) for item in ['abc', 'def', 'ghi']]
y = [i * 2 if i > 0 else 0 for i in [1, -2, 10]]
def foo(x):
return x ** 2
print(foo("Hello"))
def foo(a = 1, b = 'John'):
return a + b
foo() | def foo(a=1, b=2):
return a + b
price = foo(b=4)
for item in [[1, 2, 3], [4, 5, 6]]:
print(item[0])
mylist = [['abc'], ['def', 'ghi']]
mylist[-1][-1][-1]
def eur_to_usd(euros, rate=0.8):
return euros * rate
print(eur_to_usd(10))
weight = input('How many kg?')
price = weight * 2.5
print(price)
x = [len(item) for item in ['abc', 'def', 'ghi']]
y = [i * 2 if i > 0 else 0 for i in [1, -2, 10]]
def foo(x):
return x ** 2
print(foo('Hello'))
def foo(a=1, b='John'):
return a + b
foo() |
class RawNode(object):
def __init__(self, chunk):
self.chunk = chunk
def render(self, ctx={}):
return str(self.chunk) | class Rawnode(object):
def __init__(self, chunk):
self.chunk = chunk
def render(self, ctx={}):
return str(self.chunk) |
RegionsVariablesMap = {
"Zarem": {
"Apple": {
"Wofost": "Supply of apple zr",
"Vensim": "apple zr",
"KeyInVensimModel": "apple_zr"
},
"Rice": {
"Wofost": "supply of rice zr",
"Vensim": "rice zr",
"KeyInVensimModel": "rice_zr"
},
"Citrus": {
"Wofost": "Supply of citrus zr",
"Vensim": "citrus zr",
"KeyInVensimModel": "citrus_zr"
},
"Rapeseed": {
"Wofost": "Supply of rapeseed zr",
"Vensim": "rapeseed zr",
"KeyInVensimModel": "rapeseed_zr"
}
},
"Finesk": {
"Tomato": {
"Wofost": "supply of tomato",
"Vensim": "tomato",
"KeyInVensimModel": "tomato"
},
"Rapeseed": {
"Wofost": "Supply of rapeseed",
"Vensim": "rapeseed",
"KeyInVensimModel": "rapeseed"
},
"Apple": {
"Wofost": "Supply of apple",
"Vensim": "apple",
"KeyInVensimModel": "apple"
},
"Citrus": {
"Wofost": "Supply of citrus",
"Vensim": "citrus",
"KeyInVensimModel": "citrus"
},
"Grainmaize": {
"Wofost": "Supply grainmaize",
"Vensim": "grainmaize",
"KeyInVensimModel": "grainmaize"
},
"Wheat": {
"Wofost": "Supply of wheat",
"Vensim": "wheat",
"KeyInVensimModel": "wheat"
},
"Chickpea": {
"Wofost": "Supply of chickpea",
"Vensim": "chickpea",
"KeyInVensimModel": "chickpea"
},
"Rice": {
"Wofost": "Supply of rice",
"Vensim": "rice",
"KeyInVensimModel": "rice"
}
},
"shah R D": {
"Rice": {
"Wofost": "Supply of Rice Tj",
"Vensim": "Rice Tj",
"KeyInVensimModel": "Rice_Tj"
},
"Apple": {
"Wofost": "Supply of apple Tj",
"Vensim": "apple Tj",
"KeyInVensimModel": "apple_Tj"
},
"Citrus": {
"Wofost": "Supply of Citrus Tj",
"Vensim": "citrs_tj",
"KeyInVensimModel": "Citrs_Tj"
},
"Tomato": {
"Wofost": "Supply of tomato tj",
"Vensim": "tomato tj",
"KeyInVensimModel": "tomato_Tj"
},
"Wheat": {
"Wofost": "Supply of wheat Tj",
"Vensim": "wheat Tj",
"KeyInVensimModel": "wheat_Tj"
},
"Rapeseed": {
"Wofost": "Supply of rapeseed Tj",
"Vensim": "Rapeseed Tj",
"KeyInVensimModel": "Rapeseed_Tj"
}
},
"Tj dd":
{
"Rice": {
"Wofost": "Sup- Rice tjj dd",
"Vensim": "rice tjj dd",
"KeyInVensimModel": "rice_tjj_dd"
},
"Citrus": {
"Wofost": "sup-Citrus tjj dd",
"Vensim": "citrud tjj dd",
"KeyInVensimModel": "citrud_tjj_dd"
},
"Apple": {
"Wofost": "sup-Apple tjj dd",
"Vensim": "apple tjj dd",
"KeyInVensimModel": "apple_tjj_dd"
},
"Sorgum": {
"Wofost": "sup-Sorgum tjdd",
"Vensim": "sorgum tjj dd",
"KeyInVensimModel": "sorgum_tjj_dd"
},
"Wheat": {
"Wofost": "sup-Wheat tjj dd",
"Vensim": "wheat tjj dd",
"KeyInVensimModel": "wheat_tjj_dd"
},
"Rapeseed": {
"Wofost": "sup-Rapeseed tjdd",
"Vensim": "rapeseed tjj dd",
"KeyInVensimModel": "rapeseed_tjj_dd"
},
"Grainmaize": {
"Wofost": "Sup-grainmaize Tjdd",
"Vensim": "grain maiz tjj dd",
"KeyInVensimModel": "grain_maiz_tjj_dd"
},
"Tomato": {
"Wofost": "Sup-tomato tjdd",
"Vensim": "tomato tjj dd",
"KeyInVensimModel": "tomato_tjj_dd"
}
}
}
CropNameMaps = {
"Apple": "APP301 - TJ.CAB",
"Chickpea": "CHICKPEA - TJ.W41",
"Citrus": "CIT301 - TJ.CAB",
"Grainmaize": "MAIZ - TJ.W41",
"Tomato": "POT701-TJ.CAB",
"Rice": "RIC501 - TJ.CAB",
"Rapeseed": "SOYBEAN - TJ.W41",
"Wheat": "WWH101 - TJ.CAB",
"Sorgum": "MAIZ - TJ.W41"
}
MeteoNameMaps = {
"Apple": "SAP2.014",
"Chickpea": "SCK2.014",
"Citrus": "SCT2.014",
"Grainmaize": "SMZ2.014",
"Tomato": "SPT2.014",
"Rice": "SRC2.014",
"Rapeseed": "SRP2.014",
"rapeseed": "SRP2.014", # added for fixing key error
"Wheat": "SWT2.014",
"Sorgum": "SMZ2.014"
}
Coefficient: dict = {
"Tomato": {
"Finesk": 0.02782949291,
"Zarem": 0,
"Tj dd": 0.000234943,
"shah R D": 0.0000351
},
"Chickpea": {
"Finesk": 0.000061,
"Zarem": 0,
"Tj dd": 0,
"shah R D": 0
},
"Rapeseed": {
"Finesk": 0.00013,
"Zarem": 0.000017,
"Tj dd": 0.004354075,
"shah R D": 0.000003
},
"Grainmaize": {
"Finesk": 0.00001,
"Zarem": 0, # 0.000017,
"Tj dd": 0.003685,
"shah R D": 0
},
"Apple": {
"Finesk": 0.02752754991,
"Zarem": 0.041570141,
"Tj dd": 0.03405931491,
"shah R D": 0.005011631
},
"Rice": {
"Finesk": 0.019067016,
"Zarem": 0.0097329009,
"Tj dd": 0.2196073774,
"shah R D": 0.0105982088
},
"Wheat": {
"Finesk": 0.009012,
"Zarem": 0,
"Tj dd": 0.017090164,
"shah R D": 0.000008
},
"Citrus": {
"Finesk": 0.0009526,
"Zarem": 0.001605887,
"Tj dd": 0.1293910401,
"shah R D": 0.00038915
},
"Sorgum": {
"Finesk": 0, # 0.00001,
"Zarem": 0, # 0.000017,
"Tj dd": 0.01708,
"shah R D": 0
}
}
Regions = {
"Finesk",
"Zarem",
"Tj dd",
"shah R D"
}
keys_in_vensim_output = [
'"sup-Wheat tjj dd"',
'"sup-Citrus tjj dd"',
'"Sup- Rice tjj dd"',
'"sup-Apple tjj dd"',
'"sup-Sorgum tjdd"',
'"Sup-grainmaize Tjdd"',
'"Sup-tomato tjdd"',
'"sup-Rapeseed tjdd"',
"supply of tomato tj",
"supply of apple Tj",
"supply of Rice Tj",
"supply of citrus Tj",
"spply of wheat Tj",
"supply of rapeseed Tj",
"supply of rice zr",
"supply of citrus zr",
"supply of rapeseed zr",
"Supply of apple zr",
"supply of wheat",
"supply of apple",
"supply of tomato",
"supply of grainmaize",
"supply of chickpea",
"supply of rice",
"supply of rapeseed",
"supply of citrus",
]
WeatherContainerRanges = {"LAT": (-90., 90.),
"LON": (-180., 180.),
"ELEV": (-300, 6000),
"IRRAD": (0., 40e30),
"TMIN": (-50., 60.),
"TMAX": (-50., 60.),
"VAP": (0.06, 2000000.3),
"RAIN": (0, 25),
"E0": (0., 20000000.5),
"ES0": (0., 2000000.5),
"ET0": (0., 2000000.5),
"WIND": (0., 100.),
"SNOWDEPTH": (0., 250.),
"TEMP": (-50., 60.),
"TMINRA": (-50., 60.)}
ArgoMap = {
"Apple": "apple_calendar.agro",
"Chickpea": "chickpea_calendar.agro",
"Citrus": "citrus_calendar.agro",
"Grainmaize": "grainmaiz_calendar.agro",
"Sorgum": "grainmaiz_calendar.agro",
"Tomato": "potato_calendar.agro",
"Rice": "rice_calendar.agro",
"Rapeseed": "rapeseed_calendar.agro",
"Wheat": 'wheat_calendar.agro'
}
SoilMap = {
"Soil": "EC11.NEW"
}
| regions_variables_map = {'Zarem': {'Apple': {'Wofost': 'Supply of apple zr', 'Vensim': 'apple zr', 'KeyInVensimModel': 'apple_zr'}, 'Rice': {'Wofost': 'supply of rice zr', 'Vensim': 'rice zr', 'KeyInVensimModel': 'rice_zr'}, 'Citrus': {'Wofost': 'Supply of citrus zr', 'Vensim': 'citrus zr', 'KeyInVensimModel': 'citrus_zr'}, 'Rapeseed': {'Wofost': 'Supply of rapeseed zr', 'Vensim': 'rapeseed zr', 'KeyInVensimModel': 'rapeseed_zr'}}, 'Finesk': {'Tomato': {'Wofost': 'supply of tomato', 'Vensim': 'tomato', 'KeyInVensimModel': 'tomato'}, 'Rapeseed': {'Wofost': 'Supply of rapeseed', 'Vensim': 'rapeseed', 'KeyInVensimModel': 'rapeseed'}, 'Apple': {'Wofost': 'Supply of apple', 'Vensim': 'apple', 'KeyInVensimModel': 'apple'}, 'Citrus': {'Wofost': 'Supply of citrus', 'Vensim': 'citrus', 'KeyInVensimModel': 'citrus'}, 'Grainmaize': {'Wofost': 'Supply grainmaize', 'Vensim': 'grainmaize', 'KeyInVensimModel': 'grainmaize'}, 'Wheat': {'Wofost': 'Supply of wheat', 'Vensim': 'wheat', 'KeyInVensimModel': 'wheat'}, 'Chickpea': {'Wofost': 'Supply of chickpea', 'Vensim': 'chickpea', 'KeyInVensimModel': 'chickpea'}, 'Rice': {'Wofost': 'Supply of rice', 'Vensim': 'rice', 'KeyInVensimModel': 'rice'}}, 'shah R D': {'Rice': {'Wofost': 'Supply of Rice Tj', 'Vensim': 'Rice Tj', 'KeyInVensimModel': 'Rice_Tj'}, 'Apple': {'Wofost': 'Supply of apple Tj', 'Vensim': 'apple Tj', 'KeyInVensimModel': 'apple_Tj'}, 'Citrus': {'Wofost': 'Supply of Citrus Tj', 'Vensim': 'citrs_tj', 'KeyInVensimModel': 'Citrs_Tj'}, 'Tomato': {'Wofost': 'Supply of tomato tj', 'Vensim': 'tomato tj', 'KeyInVensimModel': 'tomato_Tj'}, 'Wheat': {'Wofost': 'Supply of wheat Tj', 'Vensim': 'wheat Tj', 'KeyInVensimModel': 'wheat_Tj'}, 'Rapeseed': {'Wofost': 'Supply of rapeseed Tj', 'Vensim': 'Rapeseed Tj', 'KeyInVensimModel': 'Rapeseed_Tj'}}, 'Tj dd': {'Rice': {'Wofost': 'Sup- Rice tjj dd', 'Vensim': 'rice tjj dd', 'KeyInVensimModel': 'rice_tjj_dd'}, 'Citrus': {'Wofost': 'sup-Citrus tjj dd', 'Vensim': 'citrud tjj dd', 'KeyInVensimModel': 'citrud_tjj_dd'}, 'Apple': {'Wofost': 'sup-Apple tjj dd', 'Vensim': 'apple tjj dd', 'KeyInVensimModel': 'apple_tjj_dd'}, 'Sorgum': {'Wofost': 'sup-Sorgum tjdd', 'Vensim': 'sorgum tjj dd', 'KeyInVensimModel': 'sorgum_tjj_dd'}, 'Wheat': {'Wofost': 'sup-Wheat tjj dd', 'Vensim': 'wheat tjj dd', 'KeyInVensimModel': 'wheat_tjj_dd'}, 'Rapeseed': {'Wofost': 'sup-Rapeseed tjdd', 'Vensim': 'rapeseed tjj dd', 'KeyInVensimModel': 'rapeseed_tjj_dd'}, 'Grainmaize': {'Wofost': 'Sup-grainmaize Tjdd', 'Vensim': 'grain maiz tjj dd', 'KeyInVensimModel': 'grain_maiz_tjj_dd'}, 'Tomato': {'Wofost': 'Sup-tomato tjdd', 'Vensim': 'tomato tjj dd', 'KeyInVensimModel': 'tomato_tjj_dd'}}}
crop_name_maps = {'Apple': 'APP301 - TJ.CAB', 'Chickpea': 'CHICKPEA - TJ.W41', 'Citrus': 'CIT301 - TJ.CAB', 'Grainmaize': 'MAIZ - TJ.W41', 'Tomato': 'POT701-TJ.CAB', 'Rice': 'RIC501 - TJ.CAB', 'Rapeseed': 'SOYBEAN - TJ.W41', 'Wheat': 'WWH101 - TJ.CAB', 'Sorgum': 'MAIZ - TJ.W41'}
meteo_name_maps = {'Apple': 'SAP2.014', 'Chickpea': 'SCK2.014', 'Citrus': 'SCT2.014', 'Grainmaize': 'SMZ2.014', 'Tomato': 'SPT2.014', 'Rice': 'SRC2.014', 'Rapeseed': 'SRP2.014', 'rapeseed': 'SRP2.014', 'Wheat': 'SWT2.014', 'Sorgum': 'SMZ2.014'}
coefficient: dict = {'Tomato': {'Finesk': 0.02782949291, 'Zarem': 0, 'Tj dd': 0.000234943, 'shah R D': 3.51e-05}, 'Chickpea': {'Finesk': 6.1e-05, 'Zarem': 0, 'Tj dd': 0, 'shah R D': 0}, 'Rapeseed': {'Finesk': 0.00013, 'Zarem': 1.7e-05, 'Tj dd': 0.004354075, 'shah R D': 3e-06}, 'Grainmaize': {'Finesk': 1e-05, 'Zarem': 0, 'Tj dd': 0.003685, 'shah R D': 0}, 'Apple': {'Finesk': 0.02752754991, 'Zarem': 0.041570141, 'Tj dd': 0.03405931491, 'shah R D': 0.005011631}, 'Rice': {'Finesk': 0.019067016, 'Zarem': 0.0097329009, 'Tj dd': 0.2196073774, 'shah R D': 0.0105982088}, 'Wheat': {'Finesk': 0.009012, 'Zarem': 0, 'Tj dd': 0.017090164, 'shah R D': 8e-06}, 'Citrus': {'Finesk': 0.0009526, 'Zarem': 0.001605887, 'Tj dd': 0.1293910401, 'shah R D': 0.00038915}, 'Sorgum': {'Finesk': 0, 'Zarem': 0, 'Tj dd': 0.01708, 'shah R D': 0}}
regions = {'Finesk', 'Zarem', 'Tj dd', 'shah R D'}
keys_in_vensim_output = ['"sup-Wheat tjj dd"', '"sup-Citrus tjj dd"', '"Sup- Rice tjj dd"', '"sup-Apple tjj dd"', '"sup-Sorgum tjdd"', '"Sup-grainmaize Tjdd"', '"Sup-tomato tjdd"', '"sup-Rapeseed tjdd"', 'supply of tomato tj', 'supply of apple Tj', 'supply of Rice Tj', 'supply of citrus Tj', 'spply of wheat Tj', 'supply of rapeseed Tj', 'supply of rice zr', 'supply of citrus zr', 'supply of rapeseed zr', 'Supply of apple zr', 'supply of wheat', 'supply of apple', 'supply of tomato', 'supply of grainmaize', 'supply of chickpea', 'supply of rice', 'supply of rapeseed', 'supply of citrus']
weather_container_ranges = {'LAT': (-90.0, 90.0), 'LON': (-180.0, 180.0), 'ELEV': (-300, 6000), 'IRRAD': (0.0, 4e+31), 'TMIN': (-50.0, 60.0), 'TMAX': (-50.0, 60.0), 'VAP': (0.06, 2000000.3), 'RAIN': (0, 25), 'E0': (0.0, 20000000.5), 'ES0': (0.0, 2000000.5), 'ET0': (0.0, 2000000.5), 'WIND': (0.0, 100.0), 'SNOWDEPTH': (0.0, 250.0), 'TEMP': (-50.0, 60.0), 'TMINRA': (-50.0, 60.0)}
argo_map = {'Apple': 'apple_calendar.agro', 'Chickpea': 'chickpea_calendar.agro', 'Citrus': 'citrus_calendar.agro', 'Grainmaize': 'grainmaiz_calendar.agro', 'Sorgum': 'grainmaiz_calendar.agro', 'Tomato': 'potato_calendar.agro', 'Rice': 'rice_calendar.agro', 'Rapeseed': 'rapeseed_calendar.agro', 'Wheat': 'wheat_calendar.agro'}
soil_map = {'Soil': 'EC11.NEW'} |
ctx.rule(u'START',u'{PROGRAM}')
ctx.rule(u'PROGRAM',u'{STATEMENT}\n{PROGRAM}')
ctx.rule(u'PROGRAM',u'')
ctx.rule(u'STATEMENT',u';')
ctx.rule(u'STATEMENT',u'')
ctx.rule(u'STATEMENT',u'break')
ctx.rule(u'STATEMENT',u'{VAR} = {EXPR}')
ctx.rule(u'STATEMENT',u'local {VARLIST} = {EXPRLIST}')
ctx.rule(u'STATEMENT',u'{FUNCTION}')
ctx.rule(u'STATEMENT',u'{COROUTINE}')
ctx.rule(u'STATEMENT',u'{CONDITIONAL}')
ctx.rule(u'STATEMENT',u'{LOOP}')
ctx.rule(u'STATEMENT',u'return {EXPRLIST}')
ctx.rule(u'STATEMENT',u'goto {LABELNAME}')
ctx.rule(u'STATEMENT',u'::{LABELNAME}::')
ctx.rule(u'LABELNAME',u'labela')
ctx.rule(u'LABELNAME',u'labelb')
ctx.rule(u'FUNCTION',u'{FUNCDEF} ({FUNCTION_ARGS}) {PROGRAM}\nend')
ctx.rule(u'FUNCDEF',u'function {VAR}.{IDENTIFIER}')
ctx.rule(u'FUNCDEF',u'function {VAR}:{IDENTIFIER}')
ctx.rule(u'FUNCDEF',u'function {IDENTIFIER}')
ctx.rule(u'LAMBDA',u'function ({FUNCTION_ARGS}) {PROGRAM} end')
ctx.rule(u'FUNCTION_ARGS',u'')
ctx.rule(u'FUNCTION_ARGS',u'{FUNCTION_ARGLIST}')
ctx.rule(u'FUNCTION_ARGLIST',u'{VAR}, {FUNCTION_ARGLIST}')
ctx.rule(u'FUNCTION_ARGLIST',u'{VAR}')
ctx.rule(u'FUNCTION_ARGLIST',u'...')
ctx.rule(u'COROUTINE',u'{VAR} = coroutine.create({LAMBDA})')
ctx.rule(u'COROUTINE',u'{VAR} = coroutine.wrap({LAMBDA})')
ctx.rule(u'COROUTINE',u'coroutine.resume({VAR}, {ARGS})')
ctx.rule(u'COROUTINE',u'coroutine.yield({ARGS})')
ctx.rule(u'FUNCTIONCALL',u'{IDENTIFIER} {ARGS}')
ctx.rule(u'FUNCTIONCALL',u'{EXPR}:{IDENTIFIER} {ARGS}')
ctx.rule(u'FUNCTIONCALL',u'{EXPR}.{IDENTIFIER} {ARGS}')
ctx.rule(u'ARGS',u'({EXPRLIST})')
ctx.rule(u'ARGS',u'{TABLECONSTRUCTOR}')
ctx.rule(u'ARGS',u'{LITERALSTRING}')
ctx.rule(u'CONDITIONAL',u'if {EXPR} then\n{PROGRAM}\nend')
ctx.rule(u'CONDITIONAL',u'if {EXPR} then\n{PROGRAM}\nelse\n{PROGRAM}\nend')
ctx.rule(u'LOOP',u'while ({EXPR})\ndo\n{PROGRAM}\nend')
ctx.rule(u'LOOP',u'for {VAR}={EXPR}, {EXPR}, {EXPR}\ndo\n{PROGRAM}\nend')
ctx.rule(u'LOOP',u'repeat\n{PROGRAM}\nuntil ({EXPR})')
ctx.rule(u'EXPRLIST',u'{EXPR}, {EXPRLIST}')
ctx.rule(u'EXPRLIST',u'{EXPR}')
ctx.rule(u'EXPR',u'(nil)')
ctx.rule(u'EXPR',u'(false)')
ctx.rule(u'EXPR',u'(true)')
ctx.rule(u'EXPR',u'({NUMERAL})')
ctx.rule(u'EXPR',u'{LITERALSTRING}')
ctx.rule(u'EXPR',u'{TABLECONSTRUCTOR}')
ctx.rule(u'EXPR',u'({VAR}[{EXPR}])')
ctx.rule(u'EXPR',u'({EXPR}{BINOP}{EXPR})')
ctx.rule(u'EXPR',u'({UNOP}{EXPR})')
ctx.rule(u'EXPR',u'{LAMBDA}')
ctx.rule(u'EXPR',u'{VAR}')
ctx.rule(u'EXPR',u'{FUNCTIONCALL}')
ctx.rule(u'EXPR',u'({EXPR})')
ctx.rule(u'EXPR',u'...')
ctx.rule(u'BINOP',u'+')
ctx.rule(u'BINOP',u'-')
ctx.rule(u'BINOP',u'*')
ctx.rule(u'BINOP',u'/')
ctx.rule(u'BINOP',u'//')
ctx.rule(u'BINOP',u'^')
ctx.rule(u'BINOP',u'%')
ctx.rule(u'BINOP',u'&')
ctx.rule(u'BINOP',u'~')
ctx.rule(u'BINOP',u'|')
ctx.rule(u'BINOP',u'>>')
ctx.rule(u'BINOP',u'<<')
ctx.rule(u'BINOP',u' .. ')
ctx.rule(u'BINOP',u'<')
ctx.rule(u'BINOP',u'<=')
ctx.rule(u'BINOP',u'>')
ctx.rule(u'BINOP',u'>=')
ctx.rule(u'BINOP',u'==')
ctx.rule(u'BINOP',u'~=')
ctx.rule(u'BINOP',u' and ')
ctx.rule(u'BINOP',u' or ')
ctx.rule(u'UNOP',u'-')
ctx.rule(u'UNOP',u' not ')
ctx.rule(u'UNOP',u'#')
ctx.rule(u'UNOP',u'~')
ctx.rule(u'TABLECONSTRUCTOR',u'\\{{FIELDLIST}\\}')
ctx.rule(u'METATABLE',u'{VAR} = setmetatable({VAR}, {TABLECONSTRUCTOR})')
ctx.rule(u'FIELDLIST',u'{FIELD},{FIELDLIST}')
ctx.rule(u'FIELDLIST',u'{FIELD}')
ctx.rule(u'FIELD',u'[{EXPR}]={EXPR}')
ctx.rule(u'FIELD',u'{IDENTIFIER}={EXPR}')
ctx.rule(u'FIELD',u'{EXPR}')
ctx.rule(u'VARLIST',u'{VAR}, {VARLIST}')
ctx.rule(u'VARLIST',u'{VAR}')
ctx.rule(u'VAR',u'a')
ctx.rule(u'VAR',u'b')
ctx.rule(u'VAR',u'c')
ctx.rule(u'VAR',u'd')
ctx.rule(u'VAR',u'e')
ctx.rule(u'VAR',u'coroutine')
ctx.rule(u'VAR',u'debug')
ctx.rule(u'VAR',u'math')
ctx.rule(u'VAR',u'io')
ctx.rule(u'VAR',u'os')
ctx.rule(u'VAR',u'package')
ctx.rule(u'VAR',u'string')
ctx.rule(u'VAR',u'table')
ctx.rule(u'VAR',u'utf8')
ctx.rule(u'VAR',u'self')
ctx.rule(u'LITERALSTRING',u'"{STRING}"')
ctx.rule(u'LITERALSTRING',u'[[{STRING}]]')
ctx.rule(u'STRING',u'')
ctx.rule(u'STRING',u'{STRCHR}{STRING}')
ctx.rule(u'STRCHR',u'\n')
ctx.rule(u'STRCHR',u'\r')
ctx.rule(u'STRCHR',u' ')
ctx.rule(u'STRCHR',u'\t')
ctx.rule(u'STRCHR',u'0')
ctx.rule(u'STRCHR',u'a')
ctx.rule(u'STRCHR',u'/')
ctx.rule(u'STRCHR',u'.')
ctx.rule(u'STRCHR',u'$')
ctx.rule(u'STRCHR',u'{ESCAPESEQUENCE}')
ctx.rule(u'ESCAPESEQUENCE',u'\\a')
ctx.rule(u'ESCAPESEQUENCE',u'\\b')
ctx.rule(u'ESCAPESEQUENCE',u'\\f')
ctx.rule(u'ESCAPESEQUENCE',u'\\n')
ctx.rule(u'ESCAPESEQUENCE',u'\\r')
ctx.rule(u'ESCAPESEQUENCE',u'\\t')
ctx.rule(u'ESCAPESEQUENCE',u'\\v')
ctx.rule(u'ESCAPESEQUENCE',u'\\z')
ctx.rule(u'ESCAPESEQUENCE',u'\n')
ctx.rule(u'ESCAPESEQUENCE',u'\\x{HEXADECIMAL}')
ctx.rule(u'ESCAPESEQUENCE',u'\\u\\{{HEXADECIMAL}\\}')
ctx.rule(u'NUMERAL',u'{DECIMAL}')
ctx.rule(u'NUMERAL',u'0x{HEXADECIMAL}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}e{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}e-{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}e{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}e-{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}p{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}p-{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}p{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}p-{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'DECIMALDIGITS',u'{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMALDIGITS',u'')
ctx.rule(u'HEXDIGITS',u'{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXDIGITS',u'')
ctx.rule(u'DECIMALDIGIT',u'0')
ctx.rule(u'DECIMALDIGIT',u'1')
ctx.rule(u'DECIMALDIGIT',u'2')
ctx.rule(u'DECIMALDIGIT',u'3')
ctx.rule(u'DECIMALDIGIT',u'4')
ctx.rule(u'DECIMALDIGIT',u'5')
ctx.rule(u'DECIMALDIGIT',u'6')
ctx.rule(u'DECIMALDIGIT',u'7')
ctx.rule(u'DECIMALDIGIT',u'8')
ctx.rule(u'DECIMALDIGIT',u'9')
ctx.rule(u'HEXDIGIT',u'a')
ctx.rule(u'HEXDIGIT',u'b')
ctx.rule(u'HEXDIGIT',u'c')
ctx.rule(u'HEXDIGIT',u'd')
ctx.rule(u'HEXDIGIT',u'e')
ctx.rule(u'HEXDIGIT',u'f')
ctx.rule(u'HEXDIGIT',u'A')
ctx.rule(u'HEXDIGIT',u'B')
ctx.rule(u'HEXDIGIT',u'C')
ctx.rule(u'HEXDIGIT',u'D')
ctx.rule(u'HEXDIGIT',u'E')
ctx.rule(u'HEXDIGIT',u'F')
ctx.rule(u'HEXDIGIT',u'{DECIMALDIGIT}')
ctx.rule(u'IDENTIFIER',u'self')
ctx.rule(u'IDENTIFIER',u'G')
ctx.rule(u'IDENTIFIER',u'_VERSION')
ctx.rule(u'IDENTIFIER',u'assert')
ctx.rule(u'IDENTIFIER',u'collectgarbage')
ctx.rule(u'IDENTIFIER',u'dofile')
ctx.rule(u'IDENTIFIER',u'error')
ctx.rule(u'IDENTIFIER',u'getmetatable')
ctx.rule(u'IDENTIFIER',u'ipairs')
ctx.rule(u'IDENTIFIER',u'load')
ctx.rule(u'IDENTIFIER',u'loadfile')
ctx.rule(u'IDENTIFIER',u'next')
ctx.rule(u'IDENTIFIER',u'pairs')
ctx.rule(u'IDENTIFIER',u'pcall')
ctx.rule(u'IDENTIFIER',u'print')
ctx.rule(u'IDENTIFIER',u'rawequal')
ctx.rule(u'IDENTIFIER',u'rawget')
ctx.rule(u'IDENTIFIER',u'rawlen')
ctx.rule(u'IDENTIFIER',u'rawset')
ctx.rule(u'IDENTIFIER',u'require')
ctx.rule(u'IDENTIFIER',u'select')
ctx.rule(u'IDENTIFIER',u'setmetatable')
ctx.rule(u'IDENTIFIER',u'tonumber')
ctx.rule(u'IDENTIFIER',u'tostring')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'xpcall')
ctx.rule(u'IDENTIFIER',u'coroutine')
ctx.rule(u'IDENTIFIER',u'create')
ctx.rule(u'IDENTIFIER',u'isyieldable')
ctx.rule(u'IDENTIFIER',u'resume')
ctx.rule(u'IDENTIFIER',u'running')
ctx.rule(u'IDENTIFIER',u'status')
ctx.rule(u'IDENTIFIER',u'wrap')
ctx.rule(u'IDENTIFIER',u'yield')
ctx.rule(u'IDENTIFIER',u'debug')
ctx.rule(u'IDENTIFIER',u'debug')
ctx.rule(u'IDENTIFIER',u'gethook')
ctx.rule(u'IDENTIFIER',u'getinfo')
ctx.rule(u'IDENTIFIER',u'getlocal')
ctx.rule(u'IDENTIFIER',u'getmetatable')
ctx.rule(u'IDENTIFIER',u'getregistry')
ctx.rule(u'IDENTIFIER',u'getupvalue')
ctx.rule(u'IDENTIFIER',u'getuservalue')
ctx.rule(u'IDENTIFIER',u'sethook')
ctx.rule(u'IDENTIFIER',u'setlocal')
ctx.rule(u'IDENTIFIER',u'setmetatable')
ctx.rule(u'IDENTIFIER',u'setupvalue')
ctx.rule(u'IDENTIFIER',u'setuservalue')
ctx.rule(u'IDENTIFIER',u'traceback')
ctx.rule(u'IDENTIFIER',u'upvalueid')
ctx.rule(u'IDENTIFIER',u'upvaluejoin')
ctx.rule(u'IDENTIFIER',u'io')
ctx.rule(u'IDENTIFIER',u'close')
ctx.rule(u'IDENTIFIER',u'flush')
ctx.rule(u'IDENTIFIER',u'input')
ctx.rule(u'IDENTIFIER',u'lines')
ctx.rule(u'IDENTIFIER',u'open')
ctx.rule(u'IDENTIFIER',u'output')
ctx.rule(u'IDENTIFIER',u'popen')
ctx.rule(u'IDENTIFIER',u'read')
ctx.rule(u'IDENTIFIER',u'stderr')
ctx.rule(u'IDENTIFIER',u'stdin')
ctx.rule(u'IDENTIFIER',u'stdout')
ctx.rule(u'IDENTIFIER',u'tmpfile')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'write')
ctx.rule(u'IDENTIFIER',u'math')
ctx.rule(u'IDENTIFIER',u'abs')
ctx.rule(u'IDENTIFIER',u'acos')
ctx.rule(u'IDENTIFIER',u'asin')
ctx.rule(u'IDENTIFIER',u'atan')
ctx.rule(u'IDENTIFIER',u'ceil')
ctx.rule(u'IDENTIFIER',u'cos')
ctx.rule(u'IDENTIFIER',u'deg')
ctx.rule(u'IDENTIFIER',u'exp')
ctx.rule(u'IDENTIFIER',u'floor')
ctx.rule(u'IDENTIFIER',u'fmod')
ctx.rule(u'IDENTIFIER',u'huge')
ctx.rule(u'IDENTIFIER',u'log')
ctx.rule(u'IDENTIFIER',u'max')
ctx.rule(u'IDENTIFIER',u'maxinteger')
ctx.rule(u'IDENTIFIER',u'min')
ctx.rule(u'IDENTIFIER',u'mininteger')
ctx.rule(u'IDENTIFIER',u'modf')
ctx.rule(u'IDENTIFIER',u'pi')
ctx.rule(u'IDENTIFIER',u'rad')
ctx.rule(u'IDENTIFIER',u'random')
ctx.rule(u'IDENTIFIER',u'randomseed')
ctx.rule(u'IDENTIFIER',u'sin')
ctx.rule(u'IDENTIFIER',u'sqrt')
ctx.rule(u'IDENTIFIER',u'tan')
ctx.rule(u'IDENTIFIER',u'tointeger')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'ult')
ctx.rule(u'IDENTIFIER',u'os')
ctx.rule(u'IDENTIFIER',u'clock')
ctx.rule(u'IDENTIFIER',u'date')
ctx.rule(u'IDENTIFIER',u'difftime')
ctx.rule(u'IDENTIFIER',u'exit')
ctx.rule(u'IDENTIFIER',u'getenv')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'rename')
ctx.rule(u'IDENTIFIER',u'setlocale')
ctx.rule(u'IDENTIFIER',u'time')
ctx.rule(u'IDENTIFIER',u'tmpname')
ctx.rule(u'IDENTIFIER',u'package')
ctx.rule(u'IDENTIFIER',u'config')
ctx.rule(u'IDENTIFIER',u'cpath')
ctx.rule(u'IDENTIFIER',u'loaded')
ctx.rule(u'IDENTIFIER',u'loadlib')
ctx.rule(u'IDENTIFIER',u'path')
ctx.rule(u'IDENTIFIER',u'preload')
ctx.rule(u'IDENTIFIER',u'searchers')
ctx.rule(u'IDENTIFIER',u'searchpath')
ctx.rule(u'IDENTIFIER',u'string')
ctx.rule(u'IDENTIFIER',u'byte')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'dump')
ctx.rule(u'IDENTIFIER',u'find')
ctx.rule(u'IDENTIFIER',u'format')
ctx.rule(u'IDENTIFIER',u'gmatch')
ctx.rule(u'IDENTIFIER',u'gsub')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'lower')
ctx.rule(u'IDENTIFIER',u'match')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'packsize')
ctx.rule(u'IDENTIFIER',u'rep')
ctx.rule(u'IDENTIFIER',u'reverse')
ctx.rule(u'IDENTIFIER',u'sub')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'upper')
ctx.rule(u'IDENTIFIER',u'table')
ctx.rule(u'IDENTIFIER',u'concat')
ctx.rule(u'IDENTIFIER',u'insert')
ctx.rule(u'IDENTIFIER',u'move')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'sort')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'utf8')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'charpattern')
ctx.rule(u'IDENTIFIER',u'codepoint')
ctx.rule(u'IDENTIFIER',u'codes')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'offset')
ctx.rule(u'IDENTIFIER',u'create')
ctx.rule(u'IDENTIFIER',u'isyieldable')
ctx.rule(u'IDENTIFIER',u'resume')
ctx.rule(u'IDENTIFIER',u'running')
ctx.rule(u'IDENTIFIER',u'status')
ctx.rule(u'IDENTIFIER',u'wrap')
ctx.rule(u'IDENTIFIER',u'yield')
ctx.rule(u'IDENTIFIER',u'debug')
ctx.rule(u'IDENTIFIER',u'gethook')
ctx.rule(u'IDENTIFIER',u'getinfo')
ctx.rule(u'IDENTIFIER',u'getlocal')
ctx.rule(u'IDENTIFIER',u'getmetatable')
ctx.rule(u'IDENTIFIER',u'getregistry')
ctx.rule(u'IDENTIFIER',u'getupvalue')
ctx.rule(u'IDENTIFIER',u'getuservalue')
ctx.rule(u'IDENTIFIER',u'sethook')
ctx.rule(u'IDENTIFIER',u'setlocal')
ctx.rule(u'IDENTIFIER',u'setmetatable')
ctx.rule(u'IDENTIFIER',u'setupvalue')
ctx.rule(u'IDENTIFIER',u'setuservalue')
ctx.rule(u'IDENTIFIER',u'traceback')
ctx.rule(u'IDENTIFIER',u'upvalueid')
ctx.rule(u'IDENTIFIER',u'upvaluejoin')
ctx.rule(u'IDENTIFIER',u'close')
ctx.rule(u'IDENTIFIER',u'flush')
ctx.rule(u'IDENTIFIER',u'input')
ctx.rule(u'IDENTIFIER',u'lines')
ctx.rule(u'IDENTIFIER',u'open')
ctx.rule(u'IDENTIFIER',u'output')
ctx.rule(u'IDENTIFIER',u'popen')
ctx.rule(u'IDENTIFIER',u'read')
ctx.rule(u'IDENTIFIER',u'stderr')
ctx.rule(u'IDENTIFIER',u'stdin')
ctx.rule(u'IDENTIFIER',u'stdout')
ctx.rule(u'IDENTIFIER',u'tmpfile')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'write')
ctx.rule(u'IDENTIFIER',u'close')
ctx.rule(u'IDENTIFIER',u'flush')
ctx.rule(u'IDENTIFIER',u'lines')
ctx.rule(u'IDENTIFIER',u'read')
ctx.rule(u'IDENTIFIER',u'seek')
ctx.rule(u'IDENTIFIER',u'setvbuf')
ctx.rule(u'IDENTIFIER',u'write')
ctx.rule(u'IDENTIFIER',u'abs')
ctx.rule(u'IDENTIFIER',u'acos')
ctx.rule(u'IDENTIFIER',u'asin')
ctx.rule(u'IDENTIFIER',u'atan')
ctx.rule(u'IDENTIFIER',u'ceil')
ctx.rule(u'IDENTIFIER',u'cos')
ctx.rule(u'IDENTIFIER',u'deg')
ctx.rule(u'IDENTIFIER',u'exp')
ctx.rule(u'IDENTIFIER',u'floor')
ctx.rule(u'IDENTIFIER',u'fmod')
ctx.rule(u'IDENTIFIER',u'huge')
ctx.rule(u'IDENTIFIER',u'log')
ctx.rule(u'IDENTIFIER',u'max')
ctx.rule(u'IDENTIFIER',u'maxinteger')
ctx.rule(u'IDENTIFIER',u'min')
ctx.rule(u'IDENTIFIER',u'mininteger')
ctx.rule(u'IDENTIFIER',u'modf')
ctx.rule(u'IDENTIFIER',u'pi')
ctx.rule(u'IDENTIFIER',u'rad')
ctx.rule(u'IDENTIFIER',u'random')
ctx.rule(u'IDENTIFIER',u'randomseed')
ctx.rule(u'IDENTIFIER',u'sin')
ctx.rule(u'IDENTIFIER',u'sqrt')
ctx.rule(u'IDENTIFIER',u'tan')
ctx.rule(u'IDENTIFIER',u'tointeger')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'ult')
ctx.rule(u'IDENTIFIER',u'clock')
ctx.rule(u'IDENTIFIER',u'date')
ctx.rule(u'IDENTIFIER',u'difftime')
ctx.rule(u'IDENTIFIER',u'exit')
ctx.rule(u'IDENTIFIER',u'getenv')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'rename')
ctx.rule(u'IDENTIFIER',u'setlocale')
ctx.rule(u'IDENTIFIER',u'time')
ctx.rule(u'IDENTIFIER',u'tmpname')
ctx.rule(u'IDENTIFIER',u'config')
ctx.rule(u'IDENTIFIER',u'cpath')
ctx.rule(u'IDENTIFIER',u'loaded')
ctx.rule(u'IDENTIFIER',u'loadlib')
ctx.rule(u'IDENTIFIER',u'path')
ctx.rule(u'IDENTIFIER',u'preload')
ctx.rule(u'IDENTIFIER',u'searchers')
ctx.rule(u'IDENTIFIER',u'searchpath')
ctx.rule(u'IDENTIFIER',u'byte')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'dump')
ctx.rule(u'IDENTIFIER',u'find')
ctx.rule(u'IDENTIFIER',u'format')
ctx.rule(u'IDENTIFIER',u'gmatch')
ctx.rule(u'IDENTIFIER',u'gsub')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'lower')
ctx.rule(u'IDENTIFIER',u'match')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'packsize')
ctx.rule(u'IDENTIFIER',u'rep')
ctx.rule(u'IDENTIFIER',u'reverse')
ctx.rule(u'IDENTIFIER',u'sub')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'upper')
ctx.rule(u'IDENTIFIER',u'concat')
ctx.rule(u'IDENTIFIER',u'insert')
ctx.rule(u'IDENTIFIER',u'move')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'sort')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'charpattern')
ctx.rule(u'IDENTIFIER',u'codepoint')
ctx.rule(u'IDENTIFIER',u'codes')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'offset')
ctx.rule(u'IDENTIFIER',u'__index')
ctx.rule(u'IDENTIFIER',u'__newindex')
ctx.rule(u'IDENTIFIER',u'__add')
ctx.rule(u'IDENTIFIER',u'__sub')
ctx.rule(u'IDENTIFIER',u'__mul')
ctx.rule(u'IDENTIFIER',u'__div')
ctx.rule(u'IDENTIFIER',u'__mod')
ctx.rule(u'IDENTIFIER',u'__unm')
ctx.rule(u'IDENTIFIER',u'__concat')
ctx.rule(u'IDENTIFIER',u'__eq')
ctx.rule(u'IDENTIFIER',u'__lt')
ctx.rule(u'IDENTIFIER',u'__le')
ctx.rule(u'IDENTIFIER',u'__call')
ctx.rule(u'IDENTIFIER',u'__tostring')
| ctx.rule(u'START', u'{PROGRAM}')
ctx.rule(u'PROGRAM', u'{STATEMENT}\n{PROGRAM}')
ctx.rule(u'PROGRAM', u'')
ctx.rule(u'STATEMENT', u';')
ctx.rule(u'STATEMENT', u'')
ctx.rule(u'STATEMENT', u'break')
ctx.rule(u'STATEMENT', u'{VAR} = {EXPR}')
ctx.rule(u'STATEMENT', u'local {VARLIST} = {EXPRLIST}')
ctx.rule(u'STATEMENT', u'{FUNCTION}')
ctx.rule(u'STATEMENT', u'{COROUTINE}')
ctx.rule(u'STATEMENT', u'{CONDITIONAL}')
ctx.rule(u'STATEMENT', u'{LOOP}')
ctx.rule(u'STATEMENT', u'return {EXPRLIST}')
ctx.rule(u'STATEMENT', u'goto {LABELNAME}')
ctx.rule(u'STATEMENT', u'::{LABELNAME}::')
ctx.rule(u'LABELNAME', u'labela')
ctx.rule(u'LABELNAME', u'labelb')
ctx.rule(u'FUNCTION', u'{FUNCDEF} ({FUNCTION_ARGS}) {PROGRAM}\nend')
ctx.rule(u'FUNCDEF', u'function {VAR}.{IDENTIFIER}')
ctx.rule(u'FUNCDEF', u'function {VAR}:{IDENTIFIER}')
ctx.rule(u'FUNCDEF', u'function {IDENTIFIER}')
ctx.rule(u'LAMBDA', u'function ({FUNCTION_ARGS}) {PROGRAM} end')
ctx.rule(u'FUNCTION_ARGS', u'')
ctx.rule(u'FUNCTION_ARGS', u'{FUNCTION_ARGLIST}')
ctx.rule(u'FUNCTION_ARGLIST', u'{VAR}, {FUNCTION_ARGLIST}')
ctx.rule(u'FUNCTION_ARGLIST', u'{VAR}')
ctx.rule(u'FUNCTION_ARGLIST', u'...')
ctx.rule(u'COROUTINE', u'{VAR} = coroutine.create({LAMBDA})')
ctx.rule(u'COROUTINE', u'{VAR} = coroutine.wrap({LAMBDA})')
ctx.rule(u'COROUTINE', u'coroutine.resume({VAR}, {ARGS})')
ctx.rule(u'COROUTINE', u'coroutine.yield({ARGS})')
ctx.rule(u'FUNCTIONCALL', u'{IDENTIFIER} {ARGS}')
ctx.rule(u'FUNCTIONCALL', u'{EXPR}:{IDENTIFIER} {ARGS}')
ctx.rule(u'FUNCTIONCALL', u'{EXPR}.{IDENTIFIER} {ARGS}')
ctx.rule(u'ARGS', u'({EXPRLIST})')
ctx.rule(u'ARGS', u'{TABLECONSTRUCTOR}')
ctx.rule(u'ARGS', u'{LITERALSTRING}')
ctx.rule(u'CONDITIONAL', u'if {EXPR} then\n{PROGRAM}\nend')
ctx.rule(u'CONDITIONAL', u'if {EXPR} then\n{PROGRAM}\nelse\n{PROGRAM}\nend')
ctx.rule(u'LOOP', u'while ({EXPR})\ndo\n{PROGRAM}\nend')
ctx.rule(u'LOOP', u'for {VAR}={EXPR}, {EXPR}, {EXPR}\ndo\n{PROGRAM}\nend')
ctx.rule(u'LOOP', u'repeat\n{PROGRAM}\nuntil ({EXPR})')
ctx.rule(u'EXPRLIST', u'{EXPR}, {EXPRLIST}')
ctx.rule(u'EXPRLIST', u'{EXPR}')
ctx.rule(u'EXPR', u'(nil)')
ctx.rule(u'EXPR', u'(false)')
ctx.rule(u'EXPR', u'(true)')
ctx.rule(u'EXPR', u'({NUMERAL})')
ctx.rule(u'EXPR', u'{LITERALSTRING}')
ctx.rule(u'EXPR', u'{TABLECONSTRUCTOR}')
ctx.rule(u'EXPR', u'({VAR}[{EXPR}])')
ctx.rule(u'EXPR', u'({EXPR}{BINOP}{EXPR})')
ctx.rule(u'EXPR', u'({UNOP}{EXPR})')
ctx.rule(u'EXPR', u'{LAMBDA}')
ctx.rule(u'EXPR', u'{VAR}')
ctx.rule(u'EXPR', u'{FUNCTIONCALL}')
ctx.rule(u'EXPR', u'({EXPR})')
ctx.rule(u'EXPR', u'...')
ctx.rule(u'BINOP', u'+')
ctx.rule(u'BINOP', u'-')
ctx.rule(u'BINOP', u'*')
ctx.rule(u'BINOP', u'/')
ctx.rule(u'BINOP', u'//')
ctx.rule(u'BINOP', u'^')
ctx.rule(u'BINOP', u'%')
ctx.rule(u'BINOP', u'&')
ctx.rule(u'BINOP', u'~')
ctx.rule(u'BINOP', u'|')
ctx.rule(u'BINOP', u'>>')
ctx.rule(u'BINOP', u'<<')
ctx.rule(u'BINOP', u' .. ')
ctx.rule(u'BINOP', u'<')
ctx.rule(u'BINOP', u'<=')
ctx.rule(u'BINOP', u'>')
ctx.rule(u'BINOP', u'>=')
ctx.rule(u'BINOP', u'==')
ctx.rule(u'BINOP', u'~=')
ctx.rule(u'BINOP', u' and ')
ctx.rule(u'BINOP', u' or ')
ctx.rule(u'UNOP', u'-')
ctx.rule(u'UNOP', u' not ')
ctx.rule(u'UNOP', u'#')
ctx.rule(u'UNOP', u'~')
ctx.rule(u'TABLECONSTRUCTOR', u'\\{{FIELDLIST}\\}')
ctx.rule(u'METATABLE', u'{VAR} = setmetatable({VAR}, {TABLECONSTRUCTOR})')
ctx.rule(u'FIELDLIST', u'{FIELD},{FIELDLIST}')
ctx.rule(u'FIELDLIST', u'{FIELD}')
ctx.rule(u'FIELD', u'[{EXPR}]={EXPR}')
ctx.rule(u'FIELD', u'{IDENTIFIER}={EXPR}')
ctx.rule(u'FIELD', u'{EXPR}')
ctx.rule(u'VARLIST', u'{VAR}, {VARLIST}')
ctx.rule(u'VARLIST', u'{VAR}')
ctx.rule(u'VAR', u'a')
ctx.rule(u'VAR', u'b')
ctx.rule(u'VAR', u'c')
ctx.rule(u'VAR', u'd')
ctx.rule(u'VAR', u'e')
ctx.rule(u'VAR', u'coroutine')
ctx.rule(u'VAR', u'debug')
ctx.rule(u'VAR', u'math')
ctx.rule(u'VAR', u'io')
ctx.rule(u'VAR', u'os')
ctx.rule(u'VAR', u'package')
ctx.rule(u'VAR', u'string')
ctx.rule(u'VAR', u'table')
ctx.rule(u'VAR', u'utf8')
ctx.rule(u'VAR', u'self')
ctx.rule(u'LITERALSTRING', u'"{STRING}"')
ctx.rule(u'LITERALSTRING', u'[[{STRING}]]')
ctx.rule(u'STRING', u'')
ctx.rule(u'STRING', u'{STRCHR}{STRING}')
ctx.rule(u'STRCHR', u'\n')
ctx.rule(u'STRCHR', u'\r')
ctx.rule(u'STRCHR', u' ')
ctx.rule(u'STRCHR', u'\t')
ctx.rule(u'STRCHR', u'0')
ctx.rule(u'STRCHR', u'a')
ctx.rule(u'STRCHR', u'/')
ctx.rule(u'STRCHR', u'.')
ctx.rule(u'STRCHR', u'$')
ctx.rule(u'STRCHR', u'{ESCAPESEQUENCE}')
ctx.rule(u'ESCAPESEQUENCE', u'\\a')
ctx.rule(u'ESCAPESEQUENCE', u'\\b')
ctx.rule(u'ESCAPESEQUENCE', u'\\f')
ctx.rule(u'ESCAPESEQUENCE', u'\\n')
ctx.rule(u'ESCAPESEQUENCE', u'\\r')
ctx.rule(u'ESCAPESEQUENCE', u'\\t')
ctx.rule(u'ESCAPESEQUENCE', u'\\v')
ctx.rule(u'ESCAPESEQUENCE', u'\\z')
ctx.rule(u'ESCAPESEQUENCE', u'\n')
ctx.rule(u'ESCAPESEQUENCE', u'\\x{HEXADECIMAL}')
ctx.rule(u'ESCAPESEQUENCE', u'\\u\\{{HEXADECIMAL}\\}')
ctx.rule(u'NUMERAL', u'{DECIMAL}')
ctx.rule(u'NUMERAL', u'0x{HEXADECIMAL}')
ctx.rule(u'DECIMAL', u'{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL', u'{DECIMALDIGIT}{DECIMALDIGITS}e{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL', u'{DECIMALDIGIT}{DECIMALDIGITS}e-{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL', u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL', u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}e{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL', u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}e-{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'HEXADECIMAL', u'{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL', u'{HEXDIGIT}{HEXDIGITS}p{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL', u'{HEXDIGIT}{HEXDIGITS}p-{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL', u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL', u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}p{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL', u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}p-{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'DECIMALDIGITS', u'{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMALDIGITS', u'')
ctx.rule(u'HEXDIGITS', u'{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXDIGITS', u'')
ctx.rule(u'DECIMALDIGIT', u'0')
ctx.rule(u'DECIMALDIGIT', u'1')
ctx.rule(u'DECIMALDIGIT', u'2')
ctx.rule(u'DECIMALDIGIT', u'3')
ctx.rule(u'DECIMALDIGIT', u'4')
ctx.rule(u'DECIMALDIGIT', u'5')
ctx.rule(u'DECIMALDIGIT', u'6')
ctx.rule(u'DECIMALDIGIT', u'7')
ctx.rule(u'DECIMALDIGIT', u'8')
ctx.rule(u'DECIMALDIGIT', u'9')
ctx.rule(u'HEXDIGIT', u'a')
ctx.rule(u'HEXDIGIT', u'b')
ctx.rule(u'HEXDIGIT', u'c')
ctx.rule(u'HEXDIGIT', u'd')
ctx.rule(u'HEXDIGIT', u'e')
ctx.rule(u'HEXDIGIT', u'f')
ctx.rule(u'HEXDIGIT', u'A')
ctx.rule(u'HEXDIGIT', u'B')
ctx.rule(u'HEXDIGIT', u'C')
ctx.rule(u'HEXDIGIT', u'D')
ctx.rule(u'HEXDIGIT', u'E')
ctx.rule(u'HEXDIGIT', u'F')
ctx.rule(u'HEXDIGIT', u'{DECIMALDIGIT}')
ctx.rule(u'IDENTIFIER', u'self')
ctx.rule(u'IDENTIFIER', u'G')
ctx.rule(u'IDENTIFIER', u'_VERSION')
ctx.rule(u'IDENTIFIER', u'assert')
ctx.rule(u'IDENTIFIER', u'collectgarbage')
ctx.rule(u'IDENTIFIER', u'dofile')
ctx.rule(u'IDENTIFIER', u'error')
ctx.rule(u'IDENTIFIER', u'getmetatable')
ctx.rule(u'IDENTIFIER', u'ipairs')
ctx.rule(u'IDENTIFIER', u'load')
ctx.rule(u'IDENTIFIER', u'loadfile')
ctx.rule(u'IDENTIFIER', u'next')
ctx.rule(u'IDENTIFIER', u'pairs')
ctx.rule(u'IDENTIFIER', u'pcall')
ctx.rule(u'IDENTIFIER', u'print')
ctx.rule(u'IDENTIFIER', u'rawequal')
ctx.rule(u'IDENTIFIER', u'rawget')
ctx.rule(u'IDENTIFIER', u'rawlen')
ctx.rule(u'IDENTIFIER', u'rawset')
ctx.rule(u'IDENTIFIER', u'require')
ctx.rule(u'IDENTIFIER', u'select')
ctx.rule(u'IDENTIFIER', u'setmetatable')
ctx.rule(u'IDENTIFIER', u'tonumber')
ctx.rule(u'IDENTIFIER', u'tostring')
ctx.rule(u'IDENTIFIER', u'type')
ctx.rule(u'IDENTIFIER', u'xpcall')
ctx.rule(u'IDENTIFIER', u'coroutine')
ctx.rule(u'IDENTIFIER', u'create')
ctx.rule(u'IDENTIFIER', u'isyieldable')
ctx.rule(u'IDENTIFIER', u'resume')
ctx.rule(u'IDENTIFIER', u'running')
ctx.rule(u'IDENTIFIER', u'status')
ctx.rule(u'IDENTIFIER', u'wrap')
ctx.rule(u'IDENTIFIER', u'yield')
ctx.rule(u'IDENTIFIER', u'debug')
ctx.rule(u'IDENTIFIER', u'debug')
ctx.rule(u'IDENTIFIER', u'gethook')
ctx.rule(u'IDENTIFIER', u'getinfo')
ctx.rule(u'IDENTIFIER', u'getlocal')
ctx.rule(u'IDENTIFIER', u'getmetatable')
ctx.rule(u'IDENTIFIER', u'getregistry')
ctx.rule(u'IDENTIFIER', u'getupvalue')
ctx.rule(u'IDENTIFIER', u'getuservalue')
ctx.rule(u'IDENTIFIER', u'sethook')
ctx.rule(u'IDENTIFIER', u'setlocal')
ctx.rule(u'IDENTIFIER', u'setmetatable')
ctx.rule(u'IDENTIFIER', u'setupvalue')
ctx.rule(u'IDENTIFIER', u'setuservalue')
ctx.rule(u'IDENTIFIER', u'traceback')
ctx.rule(u'IDENTIFIER', u'upvalueid')
ctx.rule(u'IDENTIFIER', u'upvaluejoin')
ctx.rule(u'IDENTIFIER', u'io')
ctx.rule(u'IDENTIFIER', u'close')
ctx.rule(u'IDENTIFIER', u'flush')
ctx.rule(u'IDENTIFIER', u'input')
ctx.rule(u'IDENTIFIER', u'lines')
ctx.rule(u'IDENTIFIER', u'open')
ctx.rule(u'IDENTIFIER', u'output')
ctx.rule(u'IDENTIFIER', u'popen')
ctx.rule(u'IDENTIFIER', u'read')
ctx.rule(u'IDENTIFIER', u'stderr')
ctx.rule(u'IDENTIFIER', u'stdin')
ctx.rule(u'IDENTIFIER', u'stdout')
ctx.rule(u'IDENTIFIER', u'tmpfile')
ctx.rule(u'IDENTIFIER', u'type')
ctx.rule(u'IDENTIFIER', u'write')
ctx.rule(u'IDENTIFIER', u'math')
ctx.rule(u'IDENTIFIER', u'abs')
ctx.rule(u'IDENTIFIER', u'acos')
ctx.rule(u'IDENTIFIER', u'asin')
ctx.rule(u'IDENTIFIER', u'atan')
ctx.rule(u'IDENTIFIER', u'ceil')
ctx.rule(u'IDENTIFIER', u'cos')
ctx.rule(u'IDENTIFIER', u'deg')
ctx.rule(u'IDENTIFIER', u'exp')
ctx.rule(u'IDENTIFIER', u'floor')
ctx.rule(u'IDENTIFIER', u'fmod')
ctx.rule(u'IDENTIFIER', u'huge')
ctx.rule(u'IDENTIFIER', u'log')
ctx.rule(u'IDENTIFIER', u'max')
ctx.rule(u'IDENTIFIER', u'maxinteger')
ctx.rule(u'IDENTIFIER', u'min')
ctx.rule(u'IDENTIFIER', u'mininteger')
ctx.rule(u'IDENTIFIER', u'modf')
ctx.rule(u'IDENTIFIER', u'pi')
ctx.rule(u'IDENTIFIER', u'rad')
ctx.rule(u'IDENTIFIER', u'random')
ctx.rule(u'IDENTIFIER', u'randomseed')
ctx.rule(u'IDENTIFIER', u'sin')
ctx.rule(u'IDENTIFIER', u'sqrt')
ctx.rule(u'IDENTIFIER', u'tan')
ctx.rule(u'IDENTIFIER', u'tointeger')
ctx.rule(u'IDENTIFIER', u'type')
ctx.rule(u'IDENTIFIER', u'ult')
ctx.rule(u'IDENTIFIER', u'os')
ctx.rule(u'IDENTIFIER', u'clock')
ctx.rule(u'IDENTIFIER', u'date')
ctx.rule(u'IDENTIFIER', u'difftime')
ctx.rule(u'IDENTIFIER', u'exit')
ctx.rule(u'IDENTIFIER', u'getenv')
ctx.rule(u'IDENTIFIER', u'remove')
ctx.rule(u'IDENTIFIER', u'rename')
ctx.rule(u'IDENTIFIER', u'setlocale')
ctx.rule(u'IDENTIFIER', u'time')
ctx.rule(u'IDENTIFIER', u'tmpname')
ctx.rule(u'IDENTIFIER', u'package')
ctx.rule(u'IDENTIFIER', u'config')
ctx.rule(u'IDENTIFIER', u'cpath')
ctx.rule(u'IDENTIFIER', u'loaded')
ctx.rule(u'IDENTIFIER', u'loadlib')
ctx.rule(u'IDENTIFIER', u'path')
ctx.rule(u'IDENTIFIER', u'preload')
ctx.rule(u'IDENTIFIER', u'searchers')
ctx.rule(u'IDENTIFIER', u'searchpath')
ctx.rule(u'IDENTIFIER', u'string')
ctx.rule(u'IDENTIFIER', u'byte')
ctx.rule(u'IDENTIFIER', u'char')
ctx.rule(u'IDENTIFIER', u'dump')
ctx.rule(u'IDENTIFIER', u'find')
ctx.rule(u'IDENTIFIER', u'format')
ctx.rule(u'IDENTIFIER', u'gmatch')
ctx.rule(u'IDENTIFIER', u'gsub')
ctx.rule(u'IDENTIFIER', u'len')
ctx.rule(u'IDENTIFIER', u'lower')
ctx.rule(u'IDENTIFIER', u'match')
ctx.rule(u'IDENTIFIER', u'pack')
ctx.rule(u'IDENTIFIER', u'packsize')
ctx.rule(u'IDENTIFIER', u'rep')
ctx.rule(u'IDENTIFIER', u'reverse')
ctx.rule(u'IDENTIFIER', u'sub')
ctx.rule(u'IDENTIFIER', u'unpack')
ctx.rule(u'IDENTIFIER', u'upper')
ctx.rule(u'IDENTIFIER', u'table')
ctx.rule(u'IDENTIFIER', u'concat')
ctx.rule(u'IDENTIFIER', u'insert')
ctx.rule(u'IDENTIFIER', u'move')
ctx.rule(u'IDENTIFIER', u'pack')
ctx.rule(u'IDENTIFIER', u'remove')
ctx.rule(u'IDENTIFIER', u'sort')
ctx.rule(u'IDENTIFIER', u'unpack')
ctx.rule(u'IDENTIFIER', u'utf8')
ctx.rule(u'IDENTIFIER', u'char')
ctx.rule(u'IDENTIFIER', u'charpattern')
ctx.rule(u'IDENTIFIER', u'codepoint')
ctx.rule(u'IDENTIFIER', u'codes')
ctx.rule(u'IDENTIFIER', u'len')
ctx.rule(u'IDENTIFIER', u'offset')
ctx.rule(u'IDENTIFIER', u'create')
ctx.rule(u'IDENTIFIER', u'isyieldable')
ctx.rule(u'IDENTIFIER', u'resume')
ctx.rule(u'IDENTIFIER', u'running')
ctx.rule(u'IDENTIFIER', u'status')
ctx.rule(u'IDENTIFIER', u'wrap')
ctx.rule(u'IDENTIFIER', u'yield')
ctx.rule(u'IDENTIFIER', u'debug')
ctx.rule(u'IDENTIFIER', u'gethook')
ctx.rule(u'IDENTIFIER', u'getinfo')
ctx.rule(u'IDENTIFIER', u'getlocal')
ctx.rule(u'IDENTIFIER', u'getmetatable')
ctx.rule(u'IDENTIFIER', u'getregistry')
ctx.rule(u'IDENTIFIER', u'getupvalue')
ctx.rule(u'IDENTIFIER', u'getuservalue')
ctx.rule(u'IDENTIFIER', u'sethook')
ctx.rule(u'IDENTIFIER', u'setlocal')
ctx.rule(u'IDENTIFIER', u'setmetatable')
ctx.rule(u'IDENTIFIER', u'setupvalue')
ctx.rule(u'IDENTIFIER', u'setuservalue')
ctx.rule(u'IDENTIFIER', u'traceback')
ctx.rule(u'IDENTIFIER', u'upvalueid')
ctx.rule(u'IDENTIFIER', u'upvaluejoin')
ctx.rule(u'IDENTIFIER', u'close')
ctx.rule(u'IDENTIFIER', u'flush')
ctx.rule(u'IDENTIFIER', u'input')
ctx.rule(u'IDENTIFIER', u'lines')
ctx.rule(u'IDENTIFIER', u'open')
ctx.rule(u'IDENTIFIER', u'output')
ctx.rule(u'IDENTIFIER', u'popen')
ctx.rule(u'IDENTIFIER', u'read')
ctx.rule(u'IDENTIFIER', u'stderr')
ctx.rule(u'IDENTIFIER', u'stdin')
ctx.rule(u'IDENTIFIER', u'stdout')
ctx.rule(u'IDENTIFIER', u'tmpfile')
ctx.rule(u'IDENTIFIER', u'type')
ctx.rule(u'IDENTIFIER', u'write')
ctx.rule(u'IDENTIFIER', u'close')
ctx.rule(u'IDENTIFIER', u'flush')
ctx.rule(u'IDENTIFIER', u'lines')
ctx.rule(u'IDENTIFIER', u'read')
ctx.rule(u'IDENTIFIER', u'seek')
ctx.rule(u'IDENTIFIER', u'setvbuf')
ctx.rule(u'IDENTIFIER', u'write')
ctx.rule(u'IDENTIFIER', u'abs')
ctx.rule(u'IDENTIFIER', u'acos')
ctx.rule(u'IDENTIFIER', u'asin')
ctx.rule(u'IDENTIFIER', u'atan')
ctx.rule(u'IDENTIFIER', u'ceil')
ctx.rule(u'IDENTIFIER', u'cos')
ctx.rule(u'IDENTIFIER', u'deg')
ctx.rule(u'IDENTIFIER', u'exp')
ctx.rule(u'IDENTIFIER', u'floor')
ctx.rule(u'IDENTIFIER', u'fmod')
ctx.rule(u'IDENTIFIER', u'huge')
ctx.rule(u'IDENTIFIER', u'log')
ctx.rule(u'IDENTIFIER', u'max')
ctx.rule(u'IDENTIFIER', u'maxinteger')
ctx.rule(u'IDENTIFIER', u'min')
ctx.rule(u'IDENTIFIER', u'mininteger')
ctx.rule(u'IDENTIFIER', u'modf')
ctx.rule(u'IDENTIFIER', u'pi')
ctx.rule(u'IDENTIFIER', u'rad')
ctx.rule(u'IDENTIFIER', u'random')
ctx.rule(u'IDENTIFIER', u'randomseed')
ctx.rule(u'IDENTIFIER', u'sin')
ctx.rule(u'IDENTIFIER', u'sqrt')
ctx.rule(u'IDENTIFIER', u'tan')
ctx.rule(u'IDENTIFIER', u'tointeger')
ctx.rule(u'IDENTIFIER', u'type')
ctx.rule(u'IDENTIFIER', u'ult')
ctx.rule(u'IDENTIFIER', u'clock')
ctx.rule(u'IDENTIFIER', u'date')
ctx.rule(u'IDENTIFIER', u'difftime')
ctx.rule(u'IDENTIFIER', u'exit')
ctx.rule(u'IDENTIFIER', u'getenv')
ctx.rule(u'IDENTIFIER', u'remove')
ctx.rule(u'IDENTIFIER', u'rename')
ctx.rule(u'IDENTIFIER', u'setlocale')
ctx.rule(u'IDENTIFIER', u'time')
ctx.rule(u'IDENTIFIER', u'tmpname')
ctx.rule(u'IDENTIFIER', u'config')
ctx.rule(u'IDENTIFIER', u'cpath')
ctx.rule(u'IDENTIFIER', u'loaded')
ctx.rule(u'IDENTIFIER', u'loadlib')
ctx.rule(u'IDENTIFIER', u'path')
ctx.rule(u'IDENTIFIER', u'preload')
ctx.rule(u'IDENTIFIER', u'searchers')
ctx.rule(u'IDENTIFIER', u'searchpath')
ctx.rule(u'IDENTIFIER', u'byte')
ctx.rule(u'IDENTIFIER', u'char')
ctx.rule(u'IDENTIFIER', u'dump')
ctx.rule(u'IDENTIFIER', u'find')
ctx.rule(u'IDENTIFIER', u'format')
ctx.rule(u'IDENTIFIER', u'gmatch')
ctx.rule(u'IDENTIFIER', u'gsub')
ctx.rule(u'IDENTIFIER', u'len')
ctx.rule(u'IDENTIFIER', u'lower')
ctx.rule(u'IDENTIFIER', u'match')
ctx.rule(u'IDENTIFIER', u'pack')
ctx.rule(u'IDENTIFIER', u'packsize')
ctx.rule(u'IDENTIFIER', u'rep')
ctx.rule(u'IDENTIFIER', u'reverse')
ctx.rule(u'IDENTIFIER', u'sub')
ctx.rule(u'IDENTIFIER', u'unpack')
ctx.rule(u'IDENTIFIER', u'upper')
ctx.rule(u'IDENTIFIER', u'concat')
ctx.rule(u'IDENTIFIER', u'insert')
ctx.rule(u'IDENTIFIER', u'move')
ctx.rule(u'IDENTIFIER', u'pack')
ctx.rule(u'IDENTIFIER', u'remove')
ctx.rule(u'IDENTIFIER', u'sort')
ctx.rule(u'IDENTIFIER', u'unpack')
ctx.rule(u'IDENTIFIER', u'char')
ctx.rule(u'IDENTIFIER', u'charpattern')
ctx.rule(u'IDENTIFIER', u'codepoint')
ctx.rule(u'IDENTIFIER', u'codes')
ctx.rule(u'IDENTIFIER', u'len')
ctx.rule(u'IDENTIFIER', u'offset')
ctx.rule(u'IDENTIFIER', u'__index')
ctx.rule(u'IDENTIFIER', u'__newindex')
ctx.rule(u'IDENTIFIER', u'__add')
ctx.rule(u'IDENTIFIER', u'__sub')
ctx.rule(u'IDENTIFIER', u'__mul')
ctx.rule(u'IDENTIFIER', u'__div')
ctx.rule(u'IDENTIFIER', u'__mod')
ctx.rule(u'IDENTIFIER', u'__unm')
ctx.rule(u'IDENTIFIER', u'__concat')
ctx.rule(u'IDENTIFIER', u'__eq')
ctx.rule(u'IDENTIFIER', u'__lt')
ctx.rule(u'IDENTIFIER', u'__le')
ctx.rule(u'IDENTIFIER', u'__call')
ctx.rule(u'IDENTIFIER', u'__tostring') |
def detectHashtag(inputs):
data = []
for tweet in inputs:
hashtag = tweet.entities['hashtags']
for hash in hashtag:
if hash['text'].lower() == 'testtweet':
data.append(tweet)
return data
def interact(inputs, api, FILE_NAME):
data = detectHashtag(inputs)
for i in data[::-1]:
api.update_status("Hello @" + i.user.screen_name + ", this is an automated response to your tweet. ", i.id)
api.create_favorite(i.id)
api.retweet(i.id)
store_last_seen(FILE_NAME, i.id)
def read_last_seen(FILE_NAME):
file_read = open(FILE_NAME, 'r')
last_seen_id = int(file_read.read().strip())
file_read.close()
return last_seen_id
def store_last_seen(FILE_NAME, last_seen_id):
file_write = open(FILE_NAME, 'w')
file_write.write(str(last_seen_id))
file_write.close()
| def detect_hashtag(inputs):
data = []
for tweet in inputs:
hashtag = tweet.entities['hashtags']
for hash in hashtag:
if hash['text'].lower() == 'testtweet':
data.append(tweet)
return data
def interact(inputs, api, FILE_NAME):
data = detect_hashtag(inputs)
for i in data[::-1]:
api.update_status('Hello @' + i.user.screen_name + ', this is an automated response to your tweet. ', i.id)
api.create_favorite(i.id)
api.retweet(i.id)
store_last_seen(FILE_NAME, i.id)
def read_last_seen(FILE_NAME):
file_read = open(FILE_NAME, 'r')
last_seen_id = int(file_read.read().strip())
file_read.close()
return last_seen_id
def store_last_seen(FILE_NAME, last_seen_id):
file_write = open(FILE_NAME, 'w')
file_write.write(str(last_seen_id))
file_write.close() |
class Element:
__slots__ = ('attributes', 'children')
name = 'element'
def __init__(self, *args, **kwargs):
self.attributes = {k.replace('_', '-'): v for k, v in kwargs.items()}
self.children = []
for item in args:
if type(item) in (list, tuple):
self.children.extend(item)
elif isinstance(item, dict):
self.attributes.update(item)
elif isinstance(item, Element):
self.children.append(item)
else:
self.children.append(str(item))
def __str__(self):
if self.attributes:
opener = '<{} {}>'.format(self.name, ' '.join('{}="{}"'.format(key, value) for key, value in self.attributes.items()))
else:
opener = '<{}>'.format(self.name)
closer = '</{0}>'.format(self.name)
descendants = self.descendants
if descendants == 0:
return opener[:-1] + '/>'
elif descendants == 1:
return opener + str(self.children[0]) + closer
else:
return '{}\n{}\n{}'.format(
opener,
indent_string('\n'.join(
str(child) for child in self.children
)),
closer
)
@property
def descendants(self):
total = 0
for child in self.children:
total += 1
if not isinstance(child, str):
total += child.descendants
return total
class Html(Element):
name = 'html'
def __str__(self):
return '<!DOCTYPE html>\n' + super().__str__()
class A(Element):
name = 'a'
class P(Element):
name = 'p'
class H1(Element):
name = 'h1'
class H2(Element):
name = 'h2'
class H3(Element):
name = 'h3'
class H4(Element):
name = 'h4'
class H5(Element):
name = 'h5'
class H6(Element):
name = 'h6'
class Br(Element):
name = 'br'
class Tr(Element):
name = 'tr'
class Th(Element):
name = 'th'
class Td(Element):
name = 'td'
class Table(Element):
name = 'table'
class Head(Element):
name = 'head'
class Body(Element):
name = 'body'
class Div(Element):
name = 'div'
class Span(Element):
name = 'span'
class Meta(Element):
name = 'meta'
class Title(Element):
name = 'title'
class Link(Element):
name = 'link'
class Script(Element):
name = 'script'
def indent_string(s, level=1):
indent = ' '*level
return indent + s.replace('\n', '\n' + indent)
| class Element:
__slots__ = ('attributes', 'children')
name = 'element'
def __init__(self, *args, **kwargs):
self.attributes = {k.replace('_', '-'): v for (k, v) in kwargs.items()}
self.children = []
for item in args:
if type(item) in (list, tuple):
self.children.extend(item)
elif isinstance(item, dict):
self.attributes.update(item)
elif isinstance(item, Element):
self.children.append(item)
else:
self.children.append(str(item))
def __str__(self):
if self.attributes:
opener = '<{} {}>'.format(self.name, ' '.join(('{}="{}"'.format(key, value) for (key, value) in self.attributes.items())))
else:
opener = '<{}>'.format(self.name)
closer = '</{0}>'.format(self.name)
descendants = self.descendants
if descendants == 0:
return opener[:-1] + '/>'
elif descendants == 1:
return opener + str(self.children[0]) + closer
else:
return '{}\n{}\n{}'.format(opener, indent_string('\n'.join((str(child) for child in self.children))), closer)
@property
def descendants(self):
total = 0
for child in self.children:
total += 1
if not isinstance(child, str):
total += child.descendants
return total
class Html(Element):
name = 'html'
def __str__(self):
return '<!DOCTYPE html>\n' + super().__str__()
class A(Element):
name = 'a'
class P(Element):
name = 'p'
class H1(Element):
name = 'h1'
class H2(Element):
name = 'h2'
class H3(Element):
name = 'h3'
class H4(Element):
name = 'h4'
class H5(Element):
name = 'h5'
class H6(Element):
name = 'h6'
class Br(Element):
name = 'br'
class Tr(Element):
name = 'tr'
class Th(Element):
name = 'th'
class Td(Element):
name = 'td'
class Table(Element):
name = 'table'
class Head(Element):
name = 'head'
class Body(Element):
name = 'body'
class Div(Element):
name = 'div'
class Span(Element):
name = 'span'
class Meta(Element):
name = 'meta'
class Title(Element):
name = 'title'
class Link(Element):
name = 'link'
class Script(Element):
name = 'script'
def indent_string(s, level=1):
indent = ' ' * level
return indent + s.replace('\n', '\n' + indent) |
# factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial
def factorial(n: int) -> int:
"""
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(20))
True
>>> factorial(0.1)
Traceback (most recent call last):
...
ValueError: factorial() only accepts integral values
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: factorial() not defined for negative values
"""
if n != int(n):
raise ValueError("factorial() only accepts integral values")
if n < 0:
raise ValueError("factorial() not defined for negative values")
value = 1
for i in range(1, n + 1):
value *= i
return value
if __name__ == "__main__":
n = int(input("Enter a positive integer: ").strip() or 0)
print(f"factorial{n} is {factorial(n)}")
| def factorial(n: int) -> int:
"""
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(20))
True
>>> factorial(0.1)
Traceback (most recent call last):
...
ValueError: factorial() only accepts integral values
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: factorial() not defined for negative values
"""
if n != int(n):
raise value_error('factorial() only accepts integral values')
if n < 0:
raise value_error('factorial() not defined for negative values')
value = 1
for i in range(1, n + 1):
value *= i
return value
if __name__ == '__main__':
n = int(input('Enter a positive integer: ').strip() or 0)
print(f'factorial{n} is {factorial(n)}') |
class FileExtensions:
"""
Class containing names for
valid File Extensions
"""
spark: str = "spark"
keras: str = "h5"
h2o: str = "h2o"
sklearn: str = "pkl"
@staticmethod
def get_valid() -> tuple:
"""
Return a tuple of the valid file extensions
in Database
:return: (tuple) valid statuses
"""
return (
FileExtensions.spark, FileExtensions.keras, FileExtensions.h2o, FileExtensions.sklearn
)
@staticmethod
def map_from_mlflow_flavor(flavor: str):
return {
'spark': 'spark',
'h2o': 'h2o',
'keras': 'h5',
'sklearn': 'pkl'
}[flavor]
@staticmethod
def map_to_module(flavor: str):
"""
Maps the flavor to the module that is imported
:param flavor: Mlflow flavor
:return: Python module string
"""
return {
'spark': 'pyspark',
'h2o': 'h2o',
'keras': 'tensorflow.keras',
'sklearn': 'sklearn'
}[flavor]
class DatabaseSupportedLibs:
"""
Class containing supported model libraries for native database model deployment
"""
@staticmethod
def get_valid():
return (
'spark', 'h2o', 'sklearn', 'keras'
)
class ModelStatuses:
"""
Class containing names
for In Database Model Deployments
"""
deployed: str = 'DEPLOYED'
deleted: str = 'DELETED'
SUPPORTED_STATUSES = [deployed, deleted]
| class Fileextensions:
"""
Class containing names for
valid File Extensions
"""
spark: str = 'spark'
keras: str = 'h5'
h2o: str = 'h2o'
sklearn: str = 'pkl'
@staticmethod
def get_valid() -> tuple:
"""
Return a tuple of the valid file extensions
in Database
:return: (tuple) valid statuses
"""
return (FileExtensions.spark, FileExtensions.keras, FileExtensions.h2o, FileExtensions.sklearn)
@staticmethod
def map_from_mlflow_flavor(flavor: str):
return {'spark': 'spark', 'h2o': 'h2o', 'keras': 'h5', 'sklearn': 'pkl'}[flavor]
@staticmethod
def map_to_module(flavor: str):
"""
Maps the flavor to the module that is imported
:param flavor: Mlflow flavor
:return: Python module string
"""
return {'spark': 'pyspark', 'h2o': 'h2o', 'keras': 'tensorflow.keras', 'sklearn': 'sklearn'}[flavor]
class Databasesupportedlibs:
"""
Class containing supported model libraries for native database model deployment
"""
@staticmethod
def get_valid():
return ('spark', 'h2o', 'sklearn', 'keras')
class Modelstatuses:
"""
Class containing names
for In Database Model Deployments
"""
deployed: str = 'DEPLOYED'
deleted: str = 'DELETED'
supported_statuses = [deployed, deleted] |
class Solution:
"""
@param nums: the gievn integers
@return: the total Hamming distance between all pairs of the given numbers
@ Time O(32*n) ~= O(n)
@ for i in range(32):
mask = 1 << i
print(i)
print("{0:b}".format(mask))
"""
def totalHammingDistance(self, nums):
# Write your code here
ans = 0
for i in range(32):
zero = one = 0
mask = 1 << i
for num in nums:
if mask & num:
one += 1
else:
zero += 1
ans += one * zero
return ans | class Solution:
"""
@param nums: the gievn integers
@return: the total Hamming distance between all pairs of the given numbers
@ Time O(32*n) ~= O(n)
@ for i in range(32):
mask = 1 << i
print(i)
print("{0:b}".format(mask))
"""
def total_hamming_distance(self, nums):
ans = 0
for i in range(32):
zero = one = 0
mask = 1 << i
for num in nums:
if mask & num:
one += 1
else:
zero += 1
ans += one * zero
return ans |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Copyright Zeta Co., Ltd.
## written by @moeseth based on research by @aye_hnin_khine
class MatchedWord():
def __init__(self, word, start):
self.word = word
self.start = start
| class Matchedword:
def __init__(self, word, start):
self.word = word
self.start = start |
'''
LEGACY CODE
Only use this to steal ideas from
import time
import hashlib
import sys
import json
import os
import secrets
import string
import base64
import ecdsa
import secrets
import string
import logging
# Node's blockchain copy
""" Stores the transactions that this node has in a list.
If the node you sent the transaction adds a block
it will get accepted, but there is a chance it gets
discarded and your transaction goes back as if it was never
processed"""
NODE_PENDING_TRANSACTIONS = []
BLOCKCHAIN = []
ROOT = False
if len(PEER_NODES) == 0:
ROOT = True
BLOCKCHAIN.append(create_genesis_block())
def proof_of_work(a,last_block, data):
start_time = time.time()
global ROOT
if ROOT:
new_block_index = last_block.index + 1
new_block_timestamp = time.time()
NODE_PENDING_TRANSACTIONS = []
lead = 0
if ROOT:
effort, pow_hash = genhash()
global WORK
lead = leadingzeroes(pow_hash.digest())
while lead < WORK:
if len(BLOCKCHAIN) == 0:
ROOT = False
# Check if any node found the solution every 60 seconds
if not ROOT or int((time.time() - start_time) % 60) == 0:
ROOT = True
# If any other node got the proof, stop searching
new_blockchain = consensus(a)
if new_blockchain:
return False, new_blockchain
# generate new hash for next time
effort, pow_hash = genhash()
lead = leadingzeroes(pow_hash.digest())
if not a.empty():
qget = a.get()
qfrom = qget[0]
new_block = qget[1]
print("received a block",qfrom)
if validate(new_block) and new_block.previous_hash == BLOCKCHAIN[len(BLOCKCHAIN) - 1].previous_hash:
BLOCKCHAIN.append(new_block)
return False, BLOCKCHAIN
# Once that hash is found, we can return it as a proof of our work
mined_block = Block(new_block_index, new_block_timestamp, pow_hash.hexdigest(),effort, data, last_block.hash)
return True, mined_block
def mine(a, blockchain, node_pending_transactions):
global BLOCKCHAIN
global WORK
NODE_PENDING_TRANSACTIONS = node_pending_transactions
while True:
"""Mining_classes is the only way that new coins can be created.
In order to prevent too many coins to be created, the process
is slowed down by a proof of work algorithm.
"""
# Get the last proof of work
last_block = None
new_block_data = None
if ROOT:
last_block = BLOCKCHAIN[len(BLOCKCHAIN) - 1]
NODE_PENDING_TRANSACTIONS = requests.get(
"http://" + MINER_NODE_URL + ":" + str(PORT) + "/txion?update=" + user.public_key).content
NODE_PENDING_TRANSACTIONS = json.loads(NODE_PENDING_TRANSACTIONS)
# Then we add the mining reward
NODE_PENDING_TRANSACTIONS.append({
"from": "network",
"to": user.public_key,
"amount": 1.0})
new_block_data = {"transactions": list(NODE_PENDING_TRANSACTIONS)}
proof = proof_of_work(a,last_block, new_block_data)
if not proof[0]:
BLOCKCHAIN = proof[1]
continue
else:
mined_block = proof[1]
String
print("#",mined_block)
String
REPR
# print("b{} = ".format(mined_block.index), repr(mined_block))
# if last_block.index == 1:
# print('work = {}'.format(work))
# print("blockchain = [", end="")
# for i in range(0, len(BLOCKCHAIN)+1):
# print("b{}".format(i), end=",")
# print("]")
# sys.exit()
END REPR
BLOCKCHAIN.append(mined_block)
a.put(["mined_lower",BLOCKCHAIN])
requests.get("http://" + MINER_NODE_URL + ":" + str(PORT) + "/blocks?update=" + user.public_key)
for node in PEER_NODES:
url = "http://" + node + ":" + str(PORT) + "/block"
headers = {"Content-Type": "application/json"}
data = mined_block.exportjson();
requests.post(url,json = data, headers = headers)
'''
| '''
LEGACY CODE
Only use this to steal ideas from
import time
import hashlib
import sys
import json
import os
import secrets
import string
import base64
import ecdsa
import secrets
import string
import logging
# Node's blockchain copy
""" Stores the transactions that this node has in a list.
If the node you sent the transaction adds a block
it will get accepted, but there is a chance it gets
discarded and your transaction goes back as if it was never
processed"""
NODE_PENDING_TRANSACTIONS = []
BLOCKCHAIN = []
ROOT = False
if len(PEER_NODES) == 0:
ROOT = True
BLOCKCHAIN.append(create_genesis_block())
def proof_of_work(a,last_block, data):
start_time = time.time()
global ROOT
if ROOT:
new_block_index = last_block.index + 1
new_block_timestamp = time.time()
NODE_PENDING_TRANSACTIONS = []
lead = 0
if ROOT:
effort, pow_hash = genhash()
global WORK
lead = leadingzeroes(pow_hash.digest())
while lead < WORK:
if len(BLOCKCHAIN) == 0:
ROOT = False
# Check if any node found the solution every 60 seconds
if not ROOT or int((time.time() - start_time) % 60) == 0:
ROOT = True
# If any other node got the proof, stop searching
new_blockchain = consensus(a)
if new_blockchain:
return False, new_blockchain
# generate new hash for next time
effort, pow_hash = genhash()
lead = leadingzeroes(pow_hash.digest())
if not a.empty():
qget = a.get()
qfrom = qget[0]
new_block = qget[1]
print("received a block",qfrom)
if validate(new_block) and new_block.previous_hash == BLOCKCHAIN[len(BLOCKCHAIN) - 1].previous_hash:
BLOCKCHAIN.append(new_block)
return False, BLOCKCHAIN
# Once that hash is found, we can return it as a proof of our work
mined_block = Block(new_block_index, new_block_timestamp, pow_hash.hexdigest(),effort, data, last_block.hash)
return True, mined_block
def mine(a, blockchain, node_pending_transactions):
global BLOCKCHAIN
global WORK
NODE_PENDING_TRANSACTIONS = node_pending_transactions
while True:
"""Mining_classes is the only way that new coins can be created.
In order to prevent too many coins to be created, the process
is slowed down by a proof of work algorithm.
"""
# Get the last proof of work
last_block = None
new_block_data = None
if ROOT:
last_block = BLOCKCHAIN[len(BLOCKCHAIN) - 1]
NODE_PENDING_TRANSACTIONS = requests.get(
"http://" + MINER_NODE_URL + ":" + str(PORT) + "/txion?update=" + user.public_key).content
NODE_PENDING_TRANSACTIONS = json.loads(NODE_PENDING_TRANSACTIONS)
# Then we add the mining reward
NODE_PENDING_TRANSACTIONS.append({
"from": "network",
"to": user.public_key,
"amount": 1.0})
new_block_data = {"transactions": list(NODE_PENDING_TRANSACTIONS)}
proof = proof_of_work(a,last_block, new_block_data)
if not proof[0]:
BLOCKCHAIN = proof[1]
continue
else:
mined_block = proof[1]
String
print("#",mined_block)
String
REPR
# print("b{} = ".format(mined_block.index), repr(mined_block))
# if last_block.index == 1:
# print('work = {}'.format(work))
# print("blockchain = [", end="")
# for i in range(0, len(BLOCKCHAIN)+1):
# print("b{}".format(i), end=",")
# print("]")
# sys.exit()
END REPR
BLOCKCHAIN.append(mined_block)
a.put(["mined_lower",BLOCKCHAIN])
requests.get("http://" + MINER_NODE_URL + ":" + str(PORT) + "/blocks?update=" + user.public_key)
for node in PEER_NODES:
url = "http://" + node + ":" + str(PORT) + "/block"
headers = {"Content-Type": "application/json"}
data = mined_block.exportjson();
requests.post(url,json = data, headers = headers)
''' |
# https://leetcode.com/problems/remove-element/description/
#
# algorithms
# Easy (41.9%)
# Total Accepted: 312.2k
# Total Submissions: 745.1k
# beats 100.00% of python submissions
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
length = len(nums)
head, tail = 0, length - 1
while head <= tail:
if nums[head] == val:
while head <= tail and nums[tail] == val:
tail -= 1
if head < tail:
nums[head], nums[tail] = nums[tail], nums[head]
tail -= 1
head += 1
return tail + 1
| class Solution(object):
def remove_element(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
length = len(nums)
(head, tail) = (0, length - 1)
while head <= tail:
if nums[head] == val:
while head <= tail and nums[tail] == val:
tail -= 1
if head < tail:
(nums[head], nums[tail]) = (nums[tail], nums[head])
tail -= 1
head += 1
return tail + 1 |
NPep = int(input())
NLKgH = []
LKgH = []
rank = []
for each in range(NPep):
KgH = list(input("The format should be: mass, height ").split(" "))
LKgH.append(KgH[0])
LKgH.append(KgH[1])
NLKgH.append(LKgH)
LKgH = []
for each in range(1, len(LKgH)):
rank.append(each)
for each in range(1, len(rank)-1):
if NLKgH[each][0] > NLKgH[each-1][0] and NLKgH[each][1] < NLKgH[each-1][1]:
rank[each] = rank[each-1]
elif NLKgH[each][0] < NLKgH[each-1][0] and NLKgH[each][1] > NLKgH[each-1][1]:
rank[each] = rank[each-1]
elif NLKgH[each][0] > NLKgH[each-1][0] and NLKgH[each][1] > NLKgH[each-1][1]:
pass
for i in rank:
print(i) | n_pep = int(input())
nl_kg_h = []
l_kg_h = []
rank = []
for each in range(NPep):
kg_h = list(input('The format should be: mass, height ').split(' '))
LKgH.append(KgH[0])
LKgH.append(KgH[1])
NLKgH.append(LKgH)
l_kg_h = []
for each in range(1, len(LKgH)):
rank.append(each)
for each in range(1, len(rank) - 1):
if NLKgH[each][0] > NLKgH[each - 1][0] and NLKgH[each][1] < NLKgH[each - 1][1]:
rank[each] = rank[each - 1]
elif NLKgH[each][0] < NLKgH[each - 1][0] and NLKgH[each][1] > NLKgH[each - 1][1]:
rank[each] = rank[each - 1]
elif NLKgH[each][0] > NLKgH[each - 1][0] and NLKgH[each][1] > NLKgH[each - 1][1]:
pass
for i in rank:
print(i) |
def lower_bound(nums, target):
l, r = 0, len(nums)
while l < r:
mid = (l + r) // 2
if nums[mid] < target:
l = mid + 1
else:
r = mid
return l
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:
l, r = lower_bound(nums, lower), lower_bound(nums, upper)
# print(l, r)
if lower == upper:
if l == len(nums) or (l < len(nums) and nums[l] != lower):
return [str(lower)]
else:
return []
if lower > upper:
return []
if r == 0:
if len(nums) > 0 and nums[0] == upper:
upper -= 1
if lower == upper:
return [str(lower)]
return ['{}->{}'.format(lower, upper)]
if l == len(nums):
return ['{}->{}'.format(lower, upper)]
ret = []
if nums[l] > lower:
_upnum = nums[l] - 1
if lower == _upnum:
ret.append(str(lower))
else:
ret.append('{}->{}'.format(lower, _upnum))
while l + 1 < r:
_lower = nums[l] + 1
_upper = nums[l + 1] - 1
if _lower < _upper:
ret.append('{}->{}'.format(_lower, _upper))
elif _lower == _upper:
ret.append(str(_lower))
l += 1
if r < len(nums) and upper == nums[r]:
upper -= 1
_lower = nums[l] + 1
_upper = upper
if _lower < _upper:
ret.append('{}->{}'.format(_lower, _upper))
elif _lower == _upper:
ret.append(str(_lower))
return ret
| def lower_bound(nums, target):
(l, r) = (0, len(nums))
while l < r:
mid = (l + r) // 2
if nums[mid] < target:
l = mid + 1
else:
r = mid
return l
class Solution:
def find_missing_ranges(self, nums: List[int], lower: int, upper: int) -> List[str]:
(l, r) = (lower_bound(nums, lower), lower_bound(nums, upper))
if lower == upper:
if l == len(nums) or (l < len(nums) and nums[l] != lower):
return [str(lower)]
else:
return []
if lower > upper:
return []
if r == 0:
if len(nums) > 0 and nums[0] == upper:
upper -= 1
if lower == upper:
return [str(lower)]
return ['{}->{}'.format(lower, upper)]
if l == len(nums):
return ['{}->{}'.format(lower, upper)]
ret = []
if nums[l] > lower:
_upnum = nums[l] - 1
if lower == _upnum:
ret.append(str(lower))
else:
ret.append('{}->{}'.format(lower, _upnum))
while l + 1 < r:
_lower = nums[l] + 1
_upper = nums[l + 1] - 1
if _lower < _upper:
ret.append('{}->{}'.format(_lower, _upper))
elif _lower == _upper:
ret.append(str(_lower))
l += 1
if r < len(nums) and upper == nums[r]:
upper -= 1
_lower = nums[l] + 1
_upper = upper
if _lower < _upper:
ret.append('{}->{}'.format(_lower, _upper))
elif _lower == _upper:
ret.append(str(_lower))
return ret |
""" Apache Avro dependencies. """
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def avro_repositories():
http_file(
name = "avro_tools",
sha256 = "ab158f4af8f767d2358a29d8678939b2a0f96017490acfb4e7ed0708cea07913",
urls = ["https://archive.apache.org/dist/avro/avro-1.10.2/java/avro-tools-1.10.2.jar"],
)
AVRO_ARTIFACTS = ["org.apache.avro:avro:1.10.2"]
| """ Apache Avro dependencies. """
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def avro_repositories():
http_file(name='avro_tools', sha256='ab158f4af8f767d2358a29d8678939b2a0f96017490acfb4e7ed0708cea07913', urls=['https://archive.apache.org/dist/avro/avro-1.10.2/java/avro-tools-1.10.2.jar'])
avro_artifacts = ['org.apache.avro:avro:1.10.2'] |
number = int(input("Number? "))
factorial = 1
while number > 0:
factorial += factorial * (number - 1)
number -= 1
print("Factorial: " + str(factorial)) | number = int(input('Number? '))
factorial = 1
while number > 0:
factorial += factorial * (number - 1)
number -= 1
print('Factorial: ' + str(factorial)) |
## Multiply
## 8 kyu
## https://www.codewars.com//kata/50654ddff44f800200000004
def multiply(a, b):
return a * b | def multiply(a, b):
return a * b |
def get_value_from_node_by_name(node, value_name):
tmp_value_name = value_name
if value_name == 'Color' and node.type == 'BSDF_PRINCIPLED':
tmp_value_name = "Base Color"
if tmp_value_name in node.inputs.keys():
if node.inputs[tmp_value_name].type == 'RGBA':
r, g, b, a = node.inputs[tmp_value_name].default_value
return [r, g, b, a]
else:
return node.inputs[value_name].default_value
| def get_value_from_node_by_name(node, value_name):
tmp_value_name = value_name
if value_name == 'Color' and node.type == 'BSDF_PRINCIPLED':
tmp_value_name = 'Base Color'
if tmp_value_name in node.inputs.keys():
if node.inputs[tmp_value_name].type == 'RGBA':
(r, g, b, a) = node.inputs[tmp_value_name].default_value
return [r, g, b, a]
else:
return node.inputs[value_name].default_value |
class ExamRoom:
def __init__(self, n: int):
self.occupied = []
self.n = n
def seat(self) -> int:
if not self.occupied:
self.occupied.append(0)
return 0
left, right = -self.occupied[0], self.occupied[0]
maximum = (right - left) // 2
for start, end in zip(self.occupied, self.occupied[1:] + [2* self.n - 2 - self.occupied[-1]]):
if (end - start) // 2 > maximum:
left, right = start, end
maximum = (right - left) //2
bisect.insort(self.occupied, left + maximum)
return left + maximum
def leave(self, p: int) -> None:
self.occupied.remove(p)
# Your ExamRoom object will be instantiated and called as such:
# obj = ExamRoom(n)
# param_1 = obj.seat()
# obj.leave(p)
| class Examroom:
def __init__(self, n: int):
self.occupied = []
self.n = n
def seat(self) -> int:
if not self.occupied:
self.occupied.append(0)
return 0
(left, right) = (-self.occupied[0], self.occupied[0])
maximum = (right - left) // 2
for (start, end) in zip(self.occupied, self.occupied[1:] + [2 * self.n - 2 - self.occupied[-1]]):
if (end - start) // 2 > maximum:
(left, right) = (start, end)
maximum = (right - left) // 2
bisect.insort(self.occupied, left + maximum)
return left + maximum
def leave(self, p: int) -> None:
self.occupied.remove(p) |
DATA_DIR = './data/'
SAVE_DIR = './pts/'
DATA_FPATH = 'ml-100k/u.data'
DATA_COLS = ['user_id', 'item_id', 'rating', 'timestamp']
POS_THRESH = 3.5
TRAIN_PATH = DATA_DIR + 'train.dat'
VALID_PATH = DATA_DIR + 'valid.txt'
| data_dir = './data/'
save_dir = './pts/'
data_fpath = 'ml-100k/u.data'
data_cols = ['user_id', 'item_id', 'rating', 'timestamp']
pos_thresh = 3.5
train_path = DATA_DIR + 'train.dat'
valid_path = DATA_DIR + 'valid.txt' |
# -*- Python -*-
# Given a source file, generate a test name.
# i.e. "common_runtime/direct_session_test.cc" becomes
# "common_runtime_direct_session_test"
load("@local_config_cuda//cuda:build_defs.bzl", "if_cuda", "cuda_default_copts")
# Sanitize a dependency so that it works correctly from code that includes
# TensorFlow as a submodule.
def clean_dep(dep):
return str(Label(dep))
# LINT.IfChange
def tf_copts():
return ([
"-DEIGEN_AVOID_STL_ARRAY",
"-Iexternal/gemmlowp",
"-Wno-sign-compare",
"-fno-exceptions",
] + if_cuda(["-DGOOGLE_CUDA=1"]))
def _cuda_copts():
"""Gets the appropriate set of copts for (maybe) CUDA compilation.
If we're doing CUDA compilation, returns copts for our particular CUDA
compiler. If we're not doing CUDA compilation, returns an empty list.
"""
return cuda_default_copts() + select({
"//conditions:default": [],
"@local_config_cuda//cuda:using_nvcc": ([
"-nvcc_options=relaxed-constexpr",
"-nvcc_options=ftz=true",
]),
"@local_config_cuda//cuda:using_clang": ([
"-fcuda-flush-denormals-to-zero",
]),
})
def tf_cuda_library(deps=None, cuda_deps=None, copts=None, **kwargs):
"""Generate a cc_library with a conditional set of CUDA dependencies.
When the library is built with --config=cuda:
- both deps and cuda_deps are used as dependencies
- the cuda runtime is added as a dependency (if necessary)
- The library additionally passes -DGOOGLE_CUDA=1 to the list of copts
Args:
- cuda_deps: BUILD dependencies which will be linked if and only if:
'--config=cuda' is passed to the bazel command line.
- deps: dependencies which will always be linked.
- copts: copts always passed to the cc_library.
- kwargs: Any other argument to cc_library.
"""
if not deps:
deps = []
if not cuda_deps:
cuda_deps = []
if not copts:
copts = []
native.cc_library(
deps=deps + if_cuda(cuda_deps + [
# clean_dep("//tensorflow/core:cuda"),
"@local_config_cuda//cuda:cuda_headers"
]),
copts=copts + if_cuda(["-DGOOGLE_CUDA=1"]),
**kwargs)
# When this target is built using --config=cuda, a cc_library is built
# that passes -DGOOGLE_CUDA=1 and '-x cuda', linking in additional
# libraries needed by GPU kernels.
def tf_gpu_kernel_library(srcs,
copts=[],
cuda_copts=[],
deps=[],
hdrs=[],
**kwargs):
copts = copts + _cuda_copts() + if_cuda(cuda_copts) + tf_copts()
native.cc_library(
srcs=srcs,
hdrs=hdrs,
copts=copts,
deps=deps + if_cuda([
# clean_dep("//tensorflow/core:cuda"),
# clean_dep("//tensorflow/core:gpu_lib"),
"@local_config_cuda//cuda:cuda_headers"
]),
alwayslink=1,
**kwargs)
| load('@local_config_cuda//cuda:build_defs.bzl', 'if_cuda', 'cuda_default_copts')
def clean_dep(dep):
return str(label(dep))
def tf_copts():
return ['-DEIGEN_AVOID_STL_ARRAY', '-Iexternal/gemmlowp', '-Wno-sign-compare', '-fno-exceptions'] + if_cuda(['-DGOOGLE_CUDA=1'])
def _cuda_copts():
"""Gets the appropriate set of copts for (maybe) CUDA compilation.
If we're doing CUDA compilation, returns copts for our particular CUDA
compiler. If we're not doing CUDA compilation, returns an empty list.
"""
return cuda_default_copts() + select({'//conditions:default': [], '@local_config_cuda//cuda:using_nvcc': ['-nvcc_options=relaxed-constexpr', '-nvcc_options=ftz=true'], '@local_config_cuda//cuda:using_clang': ['-fcuda-flush-denormals-to-zero']})
def tf_cuda_library(deps=None, cuda_deps=None, copts=None, **kwargs):
"""Generate a cc_library with a conditional set of CUDA dependencies.
When the library is built with --config=cuda:
- both deps and cuda_deps are used as dependencies
- the cuda runtime is added as a dependency (if necessary)
- The library additionally passes -DGOOGLE_CUDA=1 to the list of copts
Args:
- cuda_deps: BUILD dependencies which will be linked if and only if:
'--config=cuda' is passed to the bazel command line.
- deps: dependencies which will always be linked.
- copts: copts always passed to the cc_library.
- kwargs: Any other argument to cc_library.
"""
if not deps:
deps = []
if not cuda_deps:
cuda_deps = []
if not copts:
copts = []
native.cc_library(deps=deps + if_cuda(cuda_deps + ['@local_config_cuda//cuda:cuda_headers']), copts=copts + if_cuda(['-DGOOGLE_CUDA=1']), **kwargs)
def tf_gpu_kernel_library(srcs, copts=[], cuda_copts=[], deps=[], hdrs=[], **kwargs):
copts = copts + _cuda_copts() + if_cuda(cuda_copts) + tf_copts()
native.cc_library(srcs=srcs, hdrs=hdrs, copts=copts, deps=deps + if_cuda(['@local_config_cuda//cuda:cuda_headers']), alwayslink=1, **kwargs) |
class Solution:
def minSubArrayLen(self, s: int, nums: list) -> int:
# Time Complexity: O(n)
# Space Complexity: O(1)
# TODO Binary Search O(nlog(n))
if not nums or sum(nums) < s:
return 0
min_len = len(nums)
current_sum = 0
left = 0
for right in range(len(nums)):
current_sum += nums[right]
while current_sum >= s:
min_len = min(min_len, right - left + 1)
current_sum -= nums[left]
left += 1
return min_len
s = 7; nums = [2,3,1,2,4,3]
s = 3; nums = [1,1]
sol = Solution()
print(sol.minSubArrayLen(s, nums))
| class Solution:
def min_sub_array_len(self, s: int, nums: list) -> int:
if not nums or sum(nums) < s:
return 0
min_len = len(nums)
current_sum = 0
left = 0
for right in range(len(nums)):
current_sum += nums[right]
while current_sum >= s:
min_len = min(min_len, right - left + 1)
current_sum -= nums[left]
left += 1
return min_len
s = 7
nums = [2, 3, 1, 2, 4, 3]
s = 3
nums = [1, 1]
sol = solution()
print(sol.minSubArrayLen(s, nums)) |
# Adding an if statement so that the print statements aren't so wrong!
# This was not part of the exercise
animals = ['Dog', 'Cat', 'Dolphin', 'Wolf', 'Polar bear', 'Penguin']
for animal in animals:
if animal == 'Dog' or animal == 'Cat':
print(f"A {animal.lower()} would make a great pet!")
else:
print(f"A {animal.lower()} would NOT make a great pet.")
print("You should be careful about what sort of animal you pick as a pet!")
| animals = ['Dog', 'Cat', 'Dolphin', 'Wolf', 'Polar bear', 'Penguin']
for animal in animals:
if animal == 'Dog' or animal == 'Cat':
print(f'A {animal.lower()} would make a great pet!')
else:
print(f'A {animal.lower()} would NOT make a great pet.')
print('You should be careful about what sort of animal you pick as a pet!') |
# Fibonacci series
class FibonacciSeriesDemo:
Instances = 0
def __init__(self):
FibonacciSeriesDemo.Instances += 1
def displayFibonacci(self, title, value):
first, second = 0, 1
print(f"----- {title}till {value} -----")
print(f'FibonacciSeriesDemo.Instances: {self.Instances}')
while first < value:
print(first)
# print(f'----- {first} {second} -----')
first, second = second, first+second
title = "Fibonacci Series Demo"
fibonacci = FibonacciSeriesDemo()
fibonacci.displayFibonacci(title, 10)
fibonacci.displayFibonacci(title, 20)
# first, second = 0, 1
# while first < 10:
# print(first)
# print(f'----- {first} {second} -----')
# first, second = second, first+second
| class Fibonacciseriesdemo:
instances = 0
def __init__(self):
FibonacciSeriesDemo.Instances += 1
def display_fibonacci(self, title, value):
(first, second) = (0, 1)
print(f'----- {title}till {value} -----')
print(f'FibonacciSeriesDemo.Instances: {self.Instances}')
while first < value:
print(first)
(first, second) = (second, first + second)
title = 'Fibonacci Series Demo'
fibonacci = fibonacci_series_demo()
fibonacci.displayFibonacci(title, 10)
fibonacci.displayFibonacci(title, 20) |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: lines.py
#
# Tests: mesh - 2D lines (unstructured), 3D lines (unstructured)
# plots - mesh
#
# Programmer: Alister Maguire
# Date: Tue Mar 17 08:50:32 PDT 2020
#
# Modifications:
#
# Mark C. Miller, Mon Jan 11 10:32:17 PST 2021
# Replace AssertEqual() with TestValueEQ()
# ----------------------------------------------------------------------------
def TestMeshPlot():
#
# First, let's make sure that 3d lines are read appropriately.
#
v = GetView3D()
v.viewNormal = (0.9, 0.35, -0.88)
SetView3D(v)
OpenDatabase(data_path("lines_test_data/spring.lines"))
AddPlot("Mesh", "Lines", 1, 1)
DrawPlots()
Query("SpatialExtents")
# Check dimensionality.
ext_len = len(GetQueryOutputValue())
TestValueEQ("Verifying 3D lines", ext_len, 6)
# Check the rendering.
Test("mesh_plot_00")
DeleteAllPlots()
CloseDatabase(data_path("lines_test_data/spring.lines"))
#
# Next, let's check 2d lines.
#
OpenDatabase(data_path("lines_test_data/2d.lines"))
AddPlot("Mesh", "Lines", 1, 1)
DrawPlots()
Query("SpatialExtents")
# Check dimensionality.
ext_len = len(GetQueryOutputValue())
TestValueEQ("Verifying 2D lines", ext_len, 4)
# Check the rendering.
Test("mesh_plot_01")
DeleteAllPlots()
CloseDatabase(data_path("lines_test_data/2d.lines"))
#
# This test makes sure that consecutive points are only
# removed from one line at a time.
#
OpenDatabase(data_path("lines_test_data/consecutive.lines"))
AddPlot("Mesh", "Lines", 1, 1)
DrawPlots()
# Check the rendering.
Test("mesh_plot_02")
DeleteAllPlots()
CloseDatabase(data_path("lines_test_data/consecutive.lines"))
def main():
TestMeshPlot()
Exit()
main()
| def test_mesh_plot():
v = get_view3_d()
v.viewNormal = (0.9, 0.35, -0.88)
set_view3_d(v)
open_database(data_path('lines_test_data/spring.lines'))
add_plot('Mesh', 'Lines', 1, 1)
draw_plots()
query('SpatialExtents')
ext_len = len(get_query_output_value())
test_value_eq('Verifying 3D lines', ext_len, 6)
test('mesh_plot_00')
delete_all_plots()
close_database(data_path('lines_test_data/spring.lines'))
open_database(data_path('lines_test_data/2d.lines'))
add_plot('Mesh', 'Lines', 1, 1)
draw_plots()
query('SpatialExtents')
ext_len = len(get_query_output_value())
test_value_eq('Verifying 2D lines', ext_len, 4)
test('mesh_plot_01')
delete_all_plots()
close_database(data_path('lines_test_data/2d.lines'))
open_database(data_path('lines_test_data/consecutive.lines'))
add_plot('Mesh', 'Lines', 1, 1)
draw_plots()
test('mesh_plot_02')
delete_all_plots()
close_database(data_path('lines_test_data/consecutive.lines'))
def main():
test_mesh_plot()
exit()
main() |
# author : @akash
n=int(input())
a=[]
for i in range(n):
s=str(input())
a.append(s)
b=sorted(a)
#print(b)
for i in range(n-1):
aa=b[i]
bb=b[i+1]
nn=len(aa)
mm=len(bb)
if(mm>nn and aa==bb[:nn]):
t=b[i]
b[i]=b[i+1]
b[i+1]=t
for i in b:
print(i)
| n = int(input())
a = []
for i in range(n):
s = str(input())
a.append(s)
b = sorted(a)
for i in range(n - 1):
aa = b[i]
bb = b[i + 1]
nn = len(aa)
mm = len(bb)
if mm > nn and aa == bb[:nn]:
t = b[i]
b[i] = b[i + 1]
b[i + 1] = t
for i in b:
print(i) |
# https://adventofcode.com/2021/day/8
# load file
infile = open('08/input.txt', 'r')
lines = infile.readlines()
infile.close()
# parse input
answer = 0
unique_number_of_segments_lengths = [2, 4, 3, 7]
for line in lines:
line = line.strip()
print("line: {}".format(line))
line_parts = line.split(' | ')
unique_signal_patterns = line_parts[0].split(' ')
four_digit_output_value = line_parts[1].split(' ')
for value in four_digit_output_value:
output_value_length = len(value)
if output_value_length in unique_number_of_segments_lengths:
answer += 1
print(answer) # 365
print("OK")
| infile = open('08/input.txt', 'r')
lines = infile.readlines()
infile.close()
answer = 0
unique_number_of_segments_lengths = [2, 4, 3, 7]
for line in lines:
line = line.strip()
print('line: {}'.format(line))
line_parts = line.split(' | ')
unique_signal_patterns = line_parts[0].split(' ')
four_digit_output_value = line_parts[1].split(' ')
for value in four_digit_output_value:
output_value_length = len(value)
if output_value_length in unique_number_of_segments_lengths:
answer += 1
print(answer)
print('OK') |
a=int(input())
b=int(input())
sum=a+b
dif=a-b
mul=a*b
if b==0:
print('Error')
return
div=a//b
Exp=a**b
print('sum of a and b is:',sum)
print('dif of a and b is:',dif)
print('mul of a and b is:',mul)
print('div of a and b is:',div)
print('Exp of a and b is:',Exp)
| a = int(input())
b = int(input())
sum = a + b
dif = a - b
mul = a * b
if b == 0:
print('Error')
return
div = a // b
exp = a ** b
print('sum of a and b is:', sum)
print('dif of a and b is:', dif)
print('mul of a and b is:', mul)
print('div of a and b is:', div)
print('Exp of a and b is:', Exp) |
#! /usr/bin/env python3
with open('../inputs/input14.txt') as fp:
lines = [line.strip() for line in fp.readlines()]
polymer, rules = lines[0], lines[2:]
# build mappings
chr_mappings = {} # character mappings: NN -> H
ins_mappings = {} # insertion mappings: NN -> [NH, HN]
for rule in rules:
[key, val] = rule.split(' -> ')
chr_mappings[key] = val
ins_mappings[key] = [key[0]+val, val+key[1]]
# track individual char counts
char_counts = {}
for i in range(len(polymer)):
char = polymer[i]
if not char in char_counts:
char_counts[char] = 1
else:
char_counts[char] += 1
# track char-pair counts
pair_counts = {}
for i in range(len(polymer) - 1):
pair = polymer[i:i+2]
if not pair in pair_counts:
pair_counts[pair] = 1
else:
pair_counts[pair] += 1
# Iterate one round of insertions, producing new pair_counts & updating char_counts in place
def insertion_step(pair_counts):
new_pair_counts = pair_counts.copy()
for (k1, v1) in pair_counts.items():
# lose all of 1 broken-up pair
new_pair_counts[k1] -= v1
# gain 2 new pairs (v1 times)
for k2 in ins_mappings[k1]:
if not k2 in new_pair_counts:
new_pair_counts[k2] = v1
else:
new_pair_counts[k2] += v1
# count inserted char (v1 times)
char = chr_mappings[k1]
if not char in char_counts:
char_counts[char] = v1
else:
char_counts[char] += v1
return new_pair_counts
# Calculate (most frequent minus least frequent) in freqs dict
def calc_freq_diff(freqs):
freq_vals_order = sorted([v for (k,v) in freqs.items()])
return freq_vals_order[-1] - freq_vals_order[0]
# part 1
for n in range(10):
pair_counts = insertion_step(pair_counts)
print("Part 1:", calc_freq_diff(char_counts)) # 4244
# part 2
for n in range(30):
pair_counts = insertion_step(pair_counts)
print("Part 2:", calc_freq_diff(char_counts)) # 4807056953866
| with open('../inputs/input14.txt') as fp:
lines = [line.strip() for line in fp.readlines()]
(polymer, rules) = (lines[0], lines[2:])
chr_mappings = {}
ins_mappings = {}
for rule in rules:
[key, val] = rule.split(' -> ')
chr_mappings[key] = val
ins_mappings[key] = [key[0] + val, val + key[1]]
char_counts = {}
for i in range(len(polymer)):
char = polymer[i]
if not char in char_counts:
char_counts[char] = 1
else:
char_counts[char] += 1
pair_counts = {}
for i in range(len(polymer) - 1):
pair = polymer[i:i + 2]
if not pair in pair_counts:
pair_counts[pair] = 1
else:
pair_counts[pair] += 1
def insertion_step(pair_counts):
new_pair_counts = pair_counts.copy()
for (k1, v1) in pair_counts.items():
new_pair_counts[k1] -= v1
for k2 in ins_mappings[k1]:
if not k2 in new_pair_counts:
new_pair_counts[k2] = v1
else:
new_pair_counts[k2] += v1
char = chr_mappings[k1]
if not char in char_counts:
char_counts[char] = v1
else:
char_counts[char] += v1
return new_pair_counts
def calc_freq_diff(freqs):
freq_vals_order = sorted([v for (k, v) in freqs.items()])
return freq_vals_order[-1] - freq_vals_order[0]
for n in range(10):
pair_counts = insertion_step(pair_counts)
print('Part 1:', calc_freq_diff(char_counts))
for n in range(30):
pair_counts = insertion_step(pair_counts)
print('Part 2:', calc_freq_diff(char_counts)) |
def inverno():
dias = list(map(int, input().split()))
dia1 = dias[0]
dia2 = dias[1]
dia3 = dias[2]
# 1 - ok
if dia1 > dia2 and (dia2 < dia3 or dia2 == dia3):
print(':)')
# 2 - ok
elif dia1 < dia2 and (dia2 > dia3 or dia2 == dia3):
print(':(')
# 3 - ok
elif dia1 < dia2 < dia3 and (dia3-dia2) < (dia2-dia1):
print(':(')
# 4 - ok
elif dia1 < dia2 < dia3 and (dia3-dia2) >= (dia2-dia1):
print(':)')
# 5 - ok
elif dia1 > dia2 > dia3 and (dia1-dia2) > (dia2-dia3):
print(':)')
# 6 - ok
elif dia1 > dia2 > dia3 and (dia2-dia3) >= (dia2-dia1):
print(':(')
# 7 - ok
elif dia1 == dia2:
if dia2 < dia3:
print(':)')
else:
print(':(')
inverno()
| def inverno():
dias = list(map(int, input().split()))
dia1 = dias[0]
dia2 = dias[1]
dia3 = dias[2]
if dia1 > dia2 and (dia2 < dia3 or dia2 == dia3):
print(':)')
elif dia1 < dia2 and (dia2 > dia3 or dia2 == dia3):
print(':(')
elif dia1 < dia2 < dia3 and dia3 - dia2 < dia2 - dia1:
print(':(')
elif dia1 < dia2 < dia3 and dia3 - dia2 >= dia2 - dia1:
print(':)')
elif dia1 > dia2 > dia3 and dia1 - dia2 > dia2 - dia3:
print(':)')
elif dia1 > dia2 > dia3 and dia2 - dia3 >= dia2 - dia1:
print(':(')
elif dia1 == dia2:
if dia2 < dia3:
print(':)')
else:
print(':(')
inverno() |
RED = '\033[1;91m'
GREEN = '\033[1;92m'
YELLOW = '\033[1;93m'
BLUE = '\033[1;94m'
BROWN = '\033[1;95m'
CYAN = '\033[1;96m'
WHITE = '\033[1;97m'
COL_END = '\033[0m'
| red = '\x1b[1;91m'
green = '\x1b[1;92m'
yellow = '\x1b[1;93m'
blue = '\x1b[1;94m'
brown = '\x1b[1;95m'
cyan = '\x1b[1;96m'
white = '\x1b[1;97m'
col_end = '\x1b[0m' |
class Node(object):
def __init__(self, Node1 = None, Node2 = None):
"""
A binary tree is either a leaf or a node with two subtrees.
INPUT:
- children, either None (for a leaf), or a list of size excatly 2
of either two binary trees or 2 objects that can be made into binary trees
"""
self._isleaf = Node1 is None and Node2 is None
if not self._isleaf:
if Node1 is None or Node2 is None != 2:
raise ValueError("A binary tree needs exactly two children")
self._children = tuple(c if isinstance(c,Node) else Node(c) for c in [Node1, Node2])
self._size = None
def __repr__(self):
if self.is_leaf():
return "Leaf"
else:
return "Node" + str(self._children)
def __eq__(self, other):
"""
Return true if other represents the same binary tree as self
"""
if not isinstance(other, Node):
return False
if self.is_leaf():
return other.is_leaf()
if other.is_leaf():
return False
return self.left() == other.left() and self.right() == other.right()
def left(self):
"""
Return the left subtree of self
"""
return self._children[0]
def right(self):
"""
Return the right subtree of self
"""
return self._children[1]
def is_leaf(self):
"""
Return true is self is a leaf
"""
return self._isleaf
def _compute_size(self):
"""
Recursively computes the size of self
"""
if self.is_leaf():
self._size = 0
else:
self._size = self.left().size() + self.right().size() + 1
def size(self):
"""
Return the number of non leaf nodes in the binary tree
"""
if self._size is None:
self._compute_size()
return self._size
def height(self):
if self._isleaf:
return 0
else:
aux_left = self.left()
height_left = aux_left.height()
aux_right = self.right()
height_right = aux_right.height()
return 1+max(height_left, height_right)
Leaf = Node() | class Node(object):
def __init__(self, Node1=None, Node2=None):
"""
A binary tree is either a leaf or a node with two subtrees.
INPUT:
- children, either None (for a leaf), or a list of size excatly 2
of either two binary trees or 2 objects that can be made into binary trees
"""
self._isleaf = Node1 is None and Node2 is None
if not self._isleaf:
if Node1 is None or Node2 is None != 2:
raise value_error('A binary tree needs exactly two children')
self._children = tuple((c if isinstance(c, Node) else node(c) for c in [Node1, Node2]))
self._size = None
def __repr__(self):
if self.is_leaf():
return 'Leaf'
else:
return 'Node' + str(self._children)
def __eq__(self, other):
"""
Return true if other represents the same binary tree as self
"""
if not isinstance(other, Node):
return False
if self.is_leaf():
return other.is_leaf()
if other.is_leaf():
return False
return self.left() == other.left() and self.right() == other.right()
def left(self):
"""
Return the left subtree of self
"""
return self._children[0]
def right(self):
"""
Return the right subtree of self
"""
return self._children[1]
def is_leaf(self):
"""
Return true is self is a leaf
"""
return self._isleaf
def _compute_size(self):
"""
Recursively computes the size of self
"""
if self.is_leaf():
self._size = 0
else:
self._size = self.left().size() + self.right().size() + 1
def size(self):
"""
Return the number of non leaf nodes in the binary tree
"""
if self._size is None:
self._compute_size()
return self._size
def height(self):
if self._isleaf:
return 0
else:
aux_left = self.left()
height_left = aux_left.height()
aux_right = self.right()
height_right = aux_right.height()
return 1 + max(height_left, height_right)
leaf = node() |
# Time: O(n)
# space: O(1)
class Solution(object):
def mincostTickets(self, days, costs):
"""
:type days: List[int]
:type costs: List[int]
:rtype: int
"""
durations = [1, 7, 30]
W = durations[-1]
dp = [float("inf") for i in range(W)]
dp[0] = 0
last_buy_days = [0, 0, 0]
for i in range(1,len(days)+1):
dp[i%W] = float("inf")
for j in range(len(durations)):
while i-1 < len(days) and \
days[i-1] > days[last_buy_days[j]]+durations[j]-1:
last_buy_days[j] += 1 # Time: O(n)
dp[i%W] = min(dp[i%W], dp[last_buy_days[j]%W]+costs[j])
return dp[len(days)%W]
| class Solution(object):
def mincost_tickets(self, days, costs):
"""
:type days: List[int]
:type costs: List[int]
:rtype: int
"""
durations = [1, 7, 30]
w = durations[-1]
dp = [float('inf') for i in range(W)]
dp[0] = 0
last_buy_days = [0, 0, 0]
for i in range(1, len(days) + 1):
dp[i % W] = float('inf')
for j in range(len(durations)):
while i - 1 < len(days) and days[i - 1] > days[last_buy_days[j]] + durations[j] - 1:
last_buy_days[j] += 1
dp[i % W] = min(dp[i % W], dp[last_buy_days[j] % W] + costs[j])
return dp[len(days) % W] |
int_float_err = "%i + %f" % ("1", "2.00")
#Output
"""
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int_float_err = "%i + %f" % ("1", "2.00")
TypeError: %i format: a number is required, not str
"""
int_float_err = "%i + %f" % (1, "2.00")
#Output
"""
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
int_float_err = "%i + %f" % (1, "2.00")
TypeError: must be real number, not str
"""
| int_float_err = '%i + %f' % ('1', '2.00')
'\nTraceback (most recent call last):\n File "<pyshell#1>", line 1, in <module>\n int_float_err = "%i + %f" % ("1", "2.00")\nTypeError: %i format: a number is required, not str\n'
int_float_err = '%i + %f' % (1, '2.00')
'\nTraceback (most recent call last):\n File "<pyshell#2>", line 1, in <module>\n int_float_err = "%i + %f" % (1, "2.00")\nTypeError: must be real number, not str\n' |
'''
6 kyu Your order, please
https://www.codewars.com/kata/55c45be3b2079eccff00010f/train/python
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
Examples
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
'''
def order(sentence):
return ' '.join([i[1] for i in sorted(zip(filter(str.isdigit, sentence), sentence.split()))]) | """
6 kyu Your order, please
https://www.codewars.com/kata/55c45be3b2079eccff00010f/train/python
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
Examples
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"""
def order(sentence):
return ' '.join([i[1] for i in sorted(zip(filter(str.isdigit, sentence), sentence.split()))]) |
def armstrong(num):
for x in range(1, num):
if x>10:
order = len(str(x))
sum = 0
temp = x
while temp > 0:
digit = temp % 10
sum += digit**order
temp //= 10
if x == sum:
yield print("T he First Armstrong Nubmer is : ", x)
lst=list(armstrong(1000)) | def armstrong(num):
for x in range(1, num):
if x > 10:
order = len(str(x))
sum = 0
temp = x
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if x == sum:
yield print('T he First Armstrong Nubmer is : ', x)
lst = list(armstrong(1000)) |
'''PROGRAM TO CALCULATE WHEN THE USER WILL TURN 100 YEARS OLD'''
#Current Year
Year = 2020
#Input for name and age
Name = input('\nWhat is your name?: ')
Age = int(input('How old are you?: '))
#Calculating year of birth
YOB = Year-Age
#Displaying the output
print('\n'+Name,'will be 100 years in the year',YOB + 100,"\n") | """PROGRAM TO CALCULATE WHEN THE USER WILL TURN 100 YEARS OLD"""
year = 2020
name = input('\nWhat is your name?: ')
age = int(input('How old are you?: '))
yob = Year - Age
print('\n' + Name, 'will be 100 years in the year', YOB + 100, '\n') |
"""ClipTools clipboard manager and text processing tools
with a lines based GUI interface
Test
Controller part, driving the GUI and the Data
"""
# Placeholder for future tests
pass
| """ClipTools clipboard manager and text processing tools
with a lines based GUI interface
Test
Controller part, driving the GUI and the Data
"""
pass |
"""
Module for preprocessing tools.
Class List (in order):
DataFrameSelector
"""
#Column Selectors
#=================
class DataFrameSelector(BaseEstimator, TransformerMixin):
"""
Description:
A selection tranformer that will select columns of specific datatypes,
e.g. numeric, categoric etc..
Authors:
Chris Schon
Eden Trainor
TODO:
Allow for choice to return numpy array or pandas Dataframe
"""
def __init__(self, attribute_names, returning = 'DataFrame'):
"""
Description
-----------
Initialise the transformer object.
Args
----
attribute_names: string
"""
self.attribute_names = attribute_names
def fit(self, X, y=None):
"""
Description
-----------
No fitting required for this transformer.
Simply checks that input is a pandas dataframe.
Args
----
X: DataFrame, (examples, features)
Pandas DataFrame containing training example features
y: array/DataFrame, (examples,)
(Optional) Training example labels
Returns
-------
self: sklearn.transfromer object
Returns the fitted transformer object.
"""
assert isinstance(X, pd.DataFrame)
return self
def transform(self, X):
"""
Description
-----------
Args
----
X: DataFrame, (examples, features)
Pandas DataFrame containing training or example features
Returns
-------
self: sklearn.transfromer object
Returns the fitted transformer object.
"""
return X[self.attribute_names].values
#=======
#Scalers
#=======
| """
Module for preprocessing tools.
Class List (in order):
DataFrameSelector
"""
class Dataframeselector(BaseEstimator, TransformerMixin):
"""
Description:
A selection tranformer that will select columns of specific datatypes,
e.g. numeric, categoric etc..
Authors:
Chris Schon
Eden Trainor
TODO:
Allow for choice to return numpy array or pandas Dataframe
"""
def __init__(self, attribute_names, returning='DataFrame'):
"""
Description
-----------
Initialise the transformer object.
Args
----
attribute_names: string
"""
self.attribute_names = attribute_names
def fit(self, X, y=None):
"""
Description
-----------
No fitting required for this transformer.
Simply checks that input is a pandas dataframe.
Args
----
X: DataFrame, (examples, features)
Pandas DataFrame containing training example features
y: array/DataFrame, (examples,)
(Optional) Training example labels
Returns
-------
self: sklearn.transfromer object
Returns the fitted transformer object.
"""
assert isinstance(X, pd.DataFrame)
return self
def transform(self, X):
"""
Description
-----------
Args
----
X: DataFrame, (examples, features)
Pandas DataFrame containing training or example features
Returns
-------
self: sklearn.transfromer object
Returns the fitted transformer object.
"""
return X[self.attribute_names].values |
'''
Config file for CNN model
'''
# -- CHANGE PATHS --#
# Jamendo
JAMENDO_DIR = '../jamendo/' # path to jamendo dataset
MEL_JAMENDO_DIR = '../data/schluter_mel_dir/' # path to save computed melgrams of jamendo
JAMENDO_LABEL_DIR = '../data/labels/' # path to jamendo dataset label
# MedleyDB
MDB_VOC_DIR = '/media/bach1/dataset/MedleyDB/' # path to medleyDB vocal containing songs
MDB_LABEL_DIR = '../mdb_voc_label/'
# vibrato
SAW_DIR = '../sawtooth_200/songs/'
MEL_SAW_DIR = '../sawtooth_200/schluter_mel_dir/'
# -- Audio processing parameters --#
SR = 22050
FRAME_LEN = 1024
HOP_LENGTH = 315
CNN_INPUT_SIZE = 115 # 1.6 sec
CNN_OVERLAP = 5 # Hopsize of 5 for training, 1 for inference
N_MELS = 80
CUTOFF = 8000 # fmax = 8kHz | """
Config file for CNN model
"""
jamendo_dir = '../jamendo/'
mel_jamendo_dir = '../data/schluter_mel_dir/'
jamendo_label_dir = '../data/labels/'
mdb_voc_dir = '/media/bach1/dataset/MedleyDB/'
mdb_label_dir = '../mdb_voc_label/'
saw_dir = '../sawtooth_200/songs/'
mel_saw_dir = '../sawtooth_200/schluter_mel_dir/'
sr = 22050
frame_len = 1024
hop_length = 315
cnn_input_size = 115
cnn_overlap = 5
n_mels = 80
cutoff = 8000 |
'''
Created on Jul 1, 2015
@author: egodolja
'''
'''
import unittest
from mock import MagicMock
from authorizenet import apicontractsv1
#from controller.ARBCancelSubscriptionController import ARBCancelSubscriptionController
from tests import apitestbase
from authorizenet.apicontrollers import *
import test
'''
'''
class ARBCancelSubscriptionControllerTest(apitestbase.ApiTestBase):
def test_ARBCancelSubscriptionController(self):
cancelSubscriptionRequest = apicontractsv1.ARBCancelSubscriptionRequest()
cancelSubscriptionRequest.merchantAuthentication = self.merchantAuthentication
cancelSubscriptionRequest.refId = 'Sample'
cancelSubscriptionRequest.subscriptionId = '2680891'
ctrl = ARBCancelSubscriptionController()
ctrl.execute = MagicMock(return_value=None)
ctrl.execute(cancelSubscriptionRequest, apicontractsv1.ARBCancelSubscriptionResponse)
ctrl.execute.assert_called_with(cancelSubscriptionRequest, apicontractsv1.ARBCancelSubscriptionResponse)
ctrl.execute.assert_any_call(cancelSubscriptionRequest, apicontractsv1.ARBCancelSubscriptionResponse)
'''
'''
class ARBCreateSubscriptionTest(apitestbase.ApiTestBase):
def testCreateSubscriptionController(self):
createSubscriptionRequest = apicontractsv1.ARBCreateSubscriptionRequest()
createSubscriptionRequest.merchantAuthentication = self.merchantAuthentication
createSubscriptionRequest.refId = 'Sample'
createSubscriptionRequest.subscription = self.subscriptionOne
ctrl = ARBCreateSubscriptionController()
ctrl.execute = MagicMock(return_value=None)
createRequest = ctrl.ARBCreateSubscriptionController(createSubscriptionRequest)
ctrl.execute(createRequest, apicontractsv1.ARBCreateSubscriptionResponse)
ctrl.execute.assert_called_with(createRequest, apicontractsv1.ARBCreateSubscriptionResponse )
ctrl.execute.assert_any_call(createRequest, apicontractsv1.ARBCreateSubscriptionResponse)
class ARBGetSubscriptionStatusTest(object):
def testGetSubscriptionStatusController(self):
getSubscriptionStatusRequest = apicontractsv1.ARBGetSubscriptionStatusRequest()
getSubscriptionStatusRequest.merchantAuthentication = self.merchantAuthentication
getSubscriptionStatusRequest.refId = 'Sample'
getSubscriptionStatusRequest.subscriptionId = '2680891'
ctrl = ARBGetSubscriptionStatusController()
ctrl.execute = MagicMock(return_value=None)
statusRequest = ctrl.ARBGetSubscriptionStatusController(getSubscriptionStatusRequest)
ctrl.execute(statusRequest, apicontractsv1.ARBGetSubscriptionStatusResponse)
ctrl.execute.assert_called_with(statusRequest, apicontractsv1.ARBGetSubscriptionStatusResponse)
ctrl.execute.assert_any_call(statusRequest, apicontractsv1.ARBGetSubscriptionStatusResponse)
'''
| """
Created on Jul 1, 2015
@author: egodolja
"""
'\nimport unittest\n\nfrom mock import MagicMock\nfrom authorizenet import apicontractsv1\n#from controller.ARBCancelSubscriptionController import ARBCancelSubscriptionController\nfrom tests import apitestbase\nfrom authorizenet.apicontrollers import *\nimport test\n'
"\nclass ARBCancelSubscriptionControllerTest(apitestbase.ApiTestBase):\n\n def test_ARBCancelSubscriptionController(self):\n cancelSubscriptionRequest = apicontractsv1.ARBCancelSubscriptionRequest()\n cancelSubscriptionRequest.merchantAuthentication = self.merchantAuthentication\n cancelSubscriptionRequest.refId = 'Sample'\n cancelSubscriptionRequest.subscriptionId = '2680891'\n \n ctrl = ARBCancelSubscriptionController()\n\n ctrl.execute = MagicMock(return_value=None)\n\n ctrl.execute(cancelSubscriptionRequest, apicontractsv1.ARBCancelSubscriptionResponse)\n \n ctrl.execute.assert_called_with(cancelSubscriptionRequest, apicontractsv1.ARBCancelSubscriptionResponse)\n ctrl.execute.assert_any_call(cancelSubscriptionRequest, apicontractsv1.ARBCancelSubscriptionResponse)\n\n"
" \nclass ARBCreateSubscriptionTest(apitestbase.ApiTestBase):\n\n def testCreateSubscriptionController(self):\n createSubscriptionRequest = apicontractsv1.ARBCreateSubscriptionRequest()\n createSubscriptionRequest.merchantAuthentication = self.merchantAuthentication\n createSubscriptionRequest.refId = 'Sample'\n createSubscriptionRequest.subscription = self.subscriptionOne\n \n ctrl = ARBCreateSubscriptionController()\n \n ctrl.execute = MagicMock(return_value=None)\n \n createRequest = ctrl.ARBCreateSubscriptionController(createSubscriptionRequest)\n ctrl.execute(createRequest, apicontractsv1.ARBCreateSubscriptionResponse)\n \n ctrl.execute.assert_called_with(createRequest, apicontractsv1.ARBCreateSubscriptionResponse )\n ctrl.execute.assert_any_call(createRequest, apicontractsv1.ARBCreateSubscriptionResponse)\n\nclass ARBGetSubscriptionStatusTest(object):\n \n \n def testGetSubscriptionStatusController(self):\n getSubscriptionStatusRequest = apicontractsv1.ARBGetSubscriptionStatusRequest()\n getSubscriptionStatusRequest.merchantAuthentication = self.merchantAuthentication\n getSubscriptionStatusRequest.refId = 'Sample'\n getSubscriptionStatusRequest.subscriptionId = '2680891'\n \n ctrl = ARBGetSubscriptionStatusController()\n \n ctrl.execute = MagicMock(return_value=None)\n \n statusRequest = ctrl.ARBGetSubscriptionStatusController(getSubscriptionStatusRequest)\n ctrl.execute(statusRequest, apicontractsv1.ARBGetSubscriptionStatusResponse)\n \n ctrl.execute.assert_called_with(statusRequest, apicontractsv1.ARBGetSubscriptionStatusResponse)\n ctrl.execute.assert_any_call(statusRequest, apicontractsv1.ARBGetSubscriptionStatusResponse) \n" |
# coding : utf8
# version : 0.0
class Object:
"""
Main class
"""
def size():
return self.size
| class Object:
"""
Main class
"""
def size():
return self.size |
def translate(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
words = {"mother": "madre", "father": "padre",
"grandmother": "abuela", "grandfather": "abuelo"}
translate(**words) | def translate(**kwargs):
for (key, value) in kwargs.items():
print(key, ':', value)
words = {'mother': 'madre', 'father': 'padre', 'grandmother': 'abuela', 'grandfather': 'abuelo'}
translate(**words) |
# O(n) time | O(1) space
class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
oddCount = 0
evenCount = 0
for p in position:
if p & 1:
oddCount += 1
else:
evenCount += 1
return min(oddCount, evenCount) | class Solution:
def min_cost_to_move_chips(self, position: List[int]) -> int:
odd_count = 0
even_count = 0
for p in position:
if p & 1:
odd_count += 1
else:
even_count += 1
return min(oddCount, evenCount) |
class GroupHelper:
def __init__(self, app):
self.app = app
def return_to_groups_page(self):
wd = self.app.wd
wd.find_element_by_link_text("group page").click()
def go_to_home(self):
wd = self.app.wd
wd.find_element_by_link_text("home page").click()
def create(self, group):
wd = self.app.wd
self.open_groups_page()
# init group creation
wd.find_element_by_name("new").click()
# fill form
wd.find_element_by_name("group_name").click()
wd.find_element_by_name("group_name").clear()
wd.find_element_by_name("group_name").send_keys(group.name)
wd.find_element_by_name("group_header").click()
wd.find_element_by_name("group_header").clear()
wd.find_element_by_name("group_header").send_keys(group.header)
wd.find_element_by_name("group_footer").click()
wd.find_element_by_name("group_footer").clear()
wd.find_element_by_name("group_footer").send_keys(group.footer)
# submit group creation
wd.find_element_by_xpath("//div[@id='content']/form").click()
wd.find_element_by_name("submit").click()
self.return_to_groups_page()
def add_osoba(self, person):
wd = self.app.wd
wd.find_element_by_link_text("nowy wpis").click()
# add_1st_name
wd.find_element_by_name("firstname").click()
wd.find_element_by_name("firstname").clear()
wd.find_element_by_name("firstname").send_keys(person.first_name)
# add_middle_name
wd.find_element_by_name("middlename").click()
wd.find_element_by_name("middlename").clear()
wd.find_element_by_name("middlename").send_keys(person.middle)
# add_2nd_name
wd.find_element_by_name("lastname").click()
wd.find_element_by_name("lastname").clear()
wd.find_element_by_name("lastname").send_keys(person.last)
# add_nick
wd.find_element_by_name("nickname").click()
wd.find_element_by_name("nickname").clear()
wd.find_element_by_name("nickname").send_keys(person.nick)
# add_title
wd.find_element_by_name("title").click()
wd.find_element_by_name("title").clear()
wd.find_element_by_name("title").send_keys(person.title)
# add_company
wd.find_element_by_name("company").click()
wd.find_element_by_name("company").clear()
wd.find_element_by_name("company").send_keys(person.company)
# add_company_address
wd.find_element_by_name("address").click()
wd.find_element_by_name("address").clear()
wd.find_element_by_name("address").send_keys(person.comaddr)
# add_private_tel
wd.find_element_by_name("home").click()
wd.find_element_by_name("home").clear()
wd.find_element_by_name("home").send_keys(person.homenr)
# add_mobile
wd.find_element_by_name("mobile").click()
wd.find_element_by_name("mobile").clear()
wd.find_element_by_name("mobile").send_keys(person.mobile)
# add_work_tel
wd.find_element_by_name("work").click()
wd.find_element_by_name("work").clear()
wd.find_element_by_name("work").send_keys(person.worknr)
# add_fax_no
wd.find_element_by_name("fax").click()
wd.find_element_by_name("fax").clear()
wd.find_element_by_name("fax").send_keys(person.faxnr)
# add_email1
wd.find_element_by_name("email").click()
wd.find_element_by_name("email").clear()
wd.find_element_by_name("email").send_keys(person.email_1)
# add_email2
wd.find_element_by_name("email2").click()
wd.find_element_by_name("email2").clear()
wd.find_element_by_name("email2").send_keys(person.email_2)
# add_email3
wd.find_element_by_name("email3").click()
wd.find_element_by_name("email3").clear()
wd.find_element_by_name("email3").send_keys(person.email_3)
# add_homepage
wd.find_element_by_name("homepage").click()
wd.find_element_by_name("homepage").clear()
wd.find_element_by_name("homepage").send_keys(person.home_page)
# add_birth
wd.find_element_by_css_selector("body").click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[19]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[19]").click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[13]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[13]").click()
wd.find_element_by_name("byear").click()
wd.find_element_by_name("byear").clear()
wd.find_element_by_name("byear").send_keys(person.year_b)
# add_anniver=
wd.find_element_by_name("theform").click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[20]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[20]").click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[13]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[13]").click()
wd.find_element_by_name("ayear").click()
wd.find_element_by_name("ayear").clear()
wd.find_element_by_name("ayear").send_keys(person.year_a)
wd.find_element_by_name("theform").click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[5]//option[3]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[5]//option[3]").click()
# add_home_add
wd.find_element_by_name("address2").click()
wd.find_element_by_name("address2").clear()
wd.find_element_by_name("address2").send_keys(person.home_add)
# add_home_tel
wd.find_element_by_name("phone2").click()
wd.find_element_by_name("phone2").clear()
wd.find_element_by_name("phone2").send_keys(person.home_phone)
# add_notes
wd.find_element_by_name("notes").click()
wd.find_element_by_name("notes").clear()
wd.find_element_by_name("notes").send_keys(person.note)
# submit_accept
wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click()
def open_groups_page(self):
wd = self.app.wd
# open groups page
wd.find_element_by_link_text("grupy").click() | class Grouphelper:
def __init__(self, app):
self.app = app
def return_to_groups_page(self):
wd = self.app.wd
wd.find_element_by_link_text('group page').click()
def go_to_home(self):
wd = self.app.wd
wd.find_element_by_link_text('home page').click()
def create(self, group):
wd = self.app.wd
self.open_groups_page()
wd.find_element_by_name('new').click()
wd.find_element_by_name('group_name').click()
wd.find_element_by_name('group_name').clear()
wd.find_element_by_name('group_name').send_keys(group.name)
wd.find_element_by_name('group_header').click()
wd.find_element_by_name('group_header').clear()
wd.find_element_by_name('group_header').send_keys(group.header)
wd.find_element_by_name('group_footer').click()
wd.find_element_by_name('group_footer').clear()
wd.find_element_by_name('group_footer').send_keys(group.footer)
wd.find_element_by_xpath("//div[@id='content']/form").click()
wd.find_element_by_name('submit').click()
self.return_to_groups_page()
def add_osoba(self, person):
wd = self.app.wd
wd.find_element_by_link_text('nowy wpis').click()
wd.find_element_by_name('firstname').click()
wd.find_element_by_name('firstname').clear()
wd.find_element_by_name('firstname').send_keys(person.first_name)
wd.find_element_by_name('middlename').click()
wd.find_element_by_name('middlename').clear()
wd.find_element_by_name('middlename').send_keys(person.middle)
wd.find_element_by_name('lastname').click()
wd.find_element_by_name('lastname').clear()
wd.find_element_by_name('lastname').send_keys(person.last)
wd.find_element_by_name('nickname').click()
wd.find_element_by_name('nickname').clear()
wd.find_element_by_name('nickname').send_keys(person.nick)
wd.find_element_by_name('title').click()
wd.find_element_by_name('title').clear()
wd.find_element_by_name('title').send_keys(person.title)
wd.find_element_by_name('company').click()
wd.find_element_by_name('company').clear()
wd.find_element_by_name('company').send_keys(person.company)
wd.find_element_by_name('address').click()
wd.find_element_by_name('address').clear()
wd.find_element_by_name('address').send_keys(person.comaddr)
wd.find_element_by_name('home').click()
wd.find_element_by_name('home').clear()
wd.find_element_by_name('home').send_keys(person.homenr)
wd.find_element_by_name('mobile').click()
wd.find_element_by_name('mobile').clear()
wd.find_element_by_name('mobile').send_keys(person.mobile)
wd.find_element_by_name('work').click()
wd.find_element_by_name('work').clear()
wd.find_element_by_name('work').send_keys(person.worknr)
wd.find_element_by_name('fax').click()
wd.find_element_by_name('fax').clear()
wd.find_element_by_name('fax').send_keys(person.faxnr)
wd.find_element_by_name('email').click()
wd.find_element_by_name('email').clear()
wd.find_element_by_name('email').send_keys(person.email_1)
wd.find_element_by_name('email2').click()
wd.find_element_by_name('email2').clear()
wd.find_element_by_name('email2').send_keys(person.email_2)
wd.find_element_by_name('email3').click()
wd.find_element_by_name('email3').clear()
wd.find_element_by_name('email3').send_keys(person.email_3)
wd.find_element_by_name('homepage').click()
wd.find_element_by_name('homepage').clear()
wd.find_element_by_name('homepage').send_keys(person.home_page)
wd.find_element_by_css_selector('body').click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[19]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[19]").click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[13]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[13]").click()
wd.find_element_by_name('byear').click()
wd.find_element_by_name('byear').clear()
wd.find_element_by_name('byear').send_keys(person.year_b)
wd.find_element_by_name('theform').click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[20]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[20]").click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[13]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[13]").click()
wd.find_element_by_name('ayear').click()
wd.find_element_by_name('ayear').clear()
wd.find_element_by_name('ayear').send_keys(person.year_a)
wd.find_element_by_name('theform').click()
if not wd.find_element_by_xpath("//div[@id='content']/form/select[5]//option[3]").is_selected():
wd.find_element_by_xpath("//div[@id='content']/form/select[5]//option[3]").click()
wd.find_element_by_name('address2').click()
wd.find_element_by_name('address2').clear()
wd.find_element_by_name('address2').send_keys(person.home_add)
wd.find_element_by_name('phone2').click()
wd.find_element_by_name('phone2').clear()
wd.find_element_by_name('phone2').send_keys(person.home_phone)
wd.find_element_by_name('notes').click()
wd.find_element_by_name('notes').clear()
wd.find_element_by_name('notes').send_keys(person.note)
wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click()
def open_groups_page(self):
wd = self.app.wd
wd.find_element_by_link_text('grupy').click() |
welcome_message = "Hey there!"
speech = "I became a developer because it's fascinates me how one can develop a thing and it can we use by many people around the world."
art = """
____/, _____)
\ // / /
_\/_ \ (
/ \ ___\_|_
____/ \_\/ \\
(\___/\\ \\
| \_______/
| // \\
/ | \_______/
___\ | _// \\
\__| //\______/
|__\______/ ____
_____|____|____|____|
/ __________o\\
/ / \\
\_________/_____________/
"""
print(welcome_message)
print(art)
print(speech)
| welcome_message = 'Hey there!'
speech = "I became a developer because it's fascinates me how one can develop a thing and it can we use by many people around the world."
art = '\n ____/, _____)\n \\ // / /\n _\\/_ \\ (\n / \\ ___\\_|_\n____/ \\_\\/ \\\n (\\___/\\ \\\n | \\_______/\n | // \\\n / | \\_______/\n___\\ | _// \\\n \\__| //\\______/\n |__\\______/ ____\n _____|____|____|____|\n / __________o\\\n / / \\\n \\_________/_____________/\n'
print(welcome_message)
print(art)
print(speech) |
scanners = []
with open('day19/input.txt') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if line == "":
continue
if line.startswith("---"):
scanner = []
scanners.append(scanner)
continue
scanner.append(list(map(lambda s: int(s), line.split(","))))
def add(p, q):
result = p.copy()
for i in range(3):
result[i] += q[i]
return result
def sub(p, q):
result = p.copy()
for i in range(3):
result[i] -= q[i]
return result
def rot(p):
x, y, z = p
return [
[ x, y, z], [ x, z, y], [ y, x, z], [ y, z, x], [ z, x, y], [ z, y, x],
[ x, -y, z], [ x, -z, y], [ y, -x, z], [ y, -z, x], [ z, -x, y], [ z, -y, x],
[-x, y, -z], [-x, z, -y], [-y, x, -z], [-y, z, -x], [-z, x, -y], [-z, y, -x],
[-x, -y, -z], [-x, -z, -y], [-y, -x, -z], [-y, -z, -x], [-z, -x, -y], [-z, -y, -x]
]
def trans(s, r, v):
result = []
for p in s:
pr = rot(p)[r]
result.append(add(pr, v))
return result
def count_matches(s1, s2) -> int:
n = 0
for p in s1:
if p in s2:
n += 1
#if n > 1: print(n)
return n
def match(s1, s2):
for p1 in s1:
for p2 in s2:
p2rotations = rot(p2)
for r in range(len(p2rotations)):
p2r = p2rotations[r]
v = sub(p1, p2r)
s2x = trans(s2, r, v)
if count_matches(s1, s2x) >= 12:
return (r, v)
# test
# for i in range(len(scanners)-1):
# print(i+1, match(scanners[0], scanners[i+1]))
beacons = scanners[0].copy()
L1 = [0]
L2 = list(range(1, len(scanners)))
while len(L2) > 0:
#for s1 in L1:
for s2 in L2:
print(s2)
# m = match(scanners[s1], scanners[s2])
m = match(beacons, scanners[s2])
if m:
print(s2, "*")
r, v = m
s2x = trans(scanners[s2], r, v)
scanners[s2] = s2x
for b in s2x:
if not b in beacons:
beacons.append(b)
L1.append(s2)
L2.remove(s2)
break
#if m: break
print(len(beacons))
| scanners = []
with open('day19/input.txt') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if line == '':
continue
if line.startswith('---'):
scanner = []
scanners.append(scanner)
continue
scanner.append(list(map(lambda s: int(s), line.split(','))))
def add(p, q):
result = p.copy()
for i in range(3):
result[i] += q[i]
return result
def sub(p, q):
result = p.copy()
for i in range(3):
result[i] -= q[i]
return result
def rot(p):
(x, y, z) = p
return [[x, y, z], [x, z, y], [y, x, z], [y, z, x], [z, x, y], [z, y, x], [x, -y, z], [x, -z, y], [y, -x, z], [y, -z, x], [z, -x, y], [z, -y, x], [-x, y, -z], [-x, z, -y], [-y, x, -z], [-y, z, -x], [-z, x, -y], [-z, y, -x], [-x, -y, -z], [-x, -z, -y], [-y, -x, -z], [-y, -z, -x], [-z, -x, -y], [-z, -y, -x]]
def trans(s, r, v):
result = []
for p in s:
pr = rot(p)[r]
result.append(add(pr, v))
return result
def count_matches(s1, s2) -> int:
n = 0
for p in s1:
if p in s2:
n += 1
return n
def match(s1, s2):
for p1 in s1:
for p2 in s2:
p2rotations = rot(p2)
for r in range(len(p2rotations)):
p2r = p2rotations[r]
v = sub(p1, p2r)
s2x = trans(s2, r, v)
if count_matches(s1, s2x) >= 12:
return (r, v)
beacons = scanners[0].copy()
l1 = [0]
l2 = list(range(1, len(scanners)))
while len(L2) > 0:
for s2 in L2:
print(s2)
m = match(beacons, scanners[s2])
if m:
print(s2, '*')
(r, v) = m
s2x = trans(scanners[s2], r, v)
scanners[s2] = s2x
for b in s2x:
if not b in beacons:
beacons.append(b)
L1.append(s2)
L2.remove(s2)
break
print(len(beacons)) |
db.session.execute('''
alter table "user"
add column created timestamp
''')
db.session.execute('''
update "user" set created = '1979-07-07'
''')
db.session.execute('''
alter table "user" alter column created set not null
''')
db.session.commit()
| db.session.execute('\n alter table "user"\n add column created timestamp\n')
db.session.execute('\n update "user" set created = \'1979-07-07\'\n')
db.session.execute('\n alter table "user" alter column created set not null\n')
db.session.commit() |
"""Generic gridworld environments
A generic grid-world environment consists of:
* An agent, which occupies a location on the grid
* A rectangular 2D grid
* A set of objects, which occupy (possibly overlapping) locations on the grid.
* A set of actions, which allow the agent to interact with the grid and
the objects contained within
The agent, cells and objects expose behaviors, which query and potentially
modify the environment. Examples of behaviors include the agent's MOVE_EAST
behavior (which moves the agent one square east) and a cell's GET behavior
(which reacts to an actor attempting to pick up a portable object contained
in the cell). The agent's behaviors define the environment's actions and (at
least in the current iteration of the generic gridworld) do not take arguments.
The agent's behaviors invoke the behaviors of cells and objects as part of
their implementation. For example, the MOVE_EAST behavior invokes the
EXIT behavior of the cell the agent occupies and the ENTER behavior of the
cell to the agent's east. Unlike agent behaviors, the behaviors of cells
and objects may take arguments. The cell and object behaviors will
implement certains parts of the overall action (for example, a cell's
EXIT behavior will remove the agent from the cell's contents) and may block
or alter aspects of the agent's behavior (for example, an object may prevent
the agent from exiting the cell in a certain direction until it is removed).
All behaviors return a reward and an optional exception token. The exception
token indicates something unusual occured that prevented the normal completion
of the behavior. The invoking behavior should take note of this condition
and behave accordingly. Behaviors that complete normally do not return an
exception token.
In the baseline generic gridworld, behaviors provided by the agent map
one-to-one to the actions the agent may take in the environment, so these
behaviors will not have arguments. However, extensions to the generic
gridworld may add arguments to the agent's actions, resulting in a
parameterized action space. This no-argument limitation imposes some
constraints on the generic gridworld's modeling capabilities:
* The agent may only carry one object at a time, eliminating any ambiguity
about the target of the agent's DROP or USE behaviors. Objects the agent
may carry are called "portable objects."
* Each cell may only contain one portable object at a time, eliminating
any ambiguity in the target of the agent's GET behavior.
* Objects the agent may push from cell to cell but not pick up are called
"movable" objects. Each cell may contain only one movable object,
eliminating any ambiguity in the target of the PUSH behavior.
In contrast, The behaviors of grid cells and objects are parameterized, to
allow the agent behavior to specify the target of the behavior, if a target
is needed.
The agent in the generic gridworld provides the following behaviors:
* MOVE_{NORTH,EAST,SOUTH,WEST}
* Move one step along the grid in the given direction.
* GET
* Transfer the portable object in the agent's cell to the agent's
inventory by invoking the cell's GET behavior to transfer the cell's
portable object stack, and then popping that object into the agent's
inventory. Fails if the agent is already carrying an object or
if the cell's GET behavior fails. Reward is equal to the reward
returned by the cell's GET behavior.
* DROP
* Invokes the DROP behavior of the cell the agent occupies on the
object the agent is carrying to transfer the object from the agent's
inventory to that cell. Fails if the agent is not carrying an object
or if the cell's DROP behavior fails. Reward is equal to the reward
returned by the cell's DROP behavior.
* USE
* Invokes the USE behavior of the object the agent is carrying and
returns the result of that behavior. Fails if the agent is not
carrying an object.
* PUSH_{NORTH,EAST,SOUTH,WEST}
* Push the object in the adjoining cell in the given direction, causing
both the agent and the object to move one cell in that direction. The
adjoining cell must contain a movable object, the agent must be able
to exit its current cell in the given direction and enter the next
cell from the opposite direction (as if it executed the appropriate
move action) and the object must be able to leave its cell and enter
its neighboring cell along the same direction. If any of these
conditions fails, the PUSH behavior fails.
The cells in the generic gridworld provide the following behaviors:
* EXIT actor direction
* Called when an actor (e.g. the agent) leaves the cell headed in the
given direction. Calls the EXIT behavior of every object in the
cell and fails if any of them fail. Removes the actor from the
cell's contents.
* ENTER actor direction
* Called when an actor enters the cell from the given direction to allow
the cell to react to the entry of that actor. The default implementation
calls the ENTER behavior of every object in the cell, fails if any
of them fail and adds the actor to the cell's contents if they
all return CONTINUE.
* GET actor object
* Called to remove the given object from the cell and push it onto the
object stack, invoking the GET behavior on each object contained in
the cell first. The GET behavior is invoked on every object except
the target object first, followed by the GET behavior of the target
object. eails if the object is not contained in the cell or if any
of the GET behaviors fail.
* DROP actor object
* Called to place the given object into the cell. Prior to placing the
object in the cell, this behavior invokes the DROP behavior on each
object in the cell, followed by the object's own DROP behavior
Objects provide the following behaviors
* ENTER thing direction
* Called when an actor (typically the agent) or an object attempts to
enter the cell occupied by this object from the given direction (in
the object's case, this means the object is being pushed). The default
implementation of this behavior does nothing, but individual objects
may use this behavior to prevent the entry of actors or objects or
to intercept actors or objects and send them elsewhere.
* EXIT thing direction
* Same as ENTER, but called when an actor or an object (because it is
being pushed) leaves the cell this object occupies.
* GET actor object
* Called when an actor (typically the agent) attempts to pick up an
object in a cell. The default implementation of this behavior does
nothing, but objects can provide implementations that permit themselves
to be picked up only under certain circumstances or prevent other
objects from being picked up and so on.
* DROP actor object
* Same as GET but called when an actor attempts to place a portable
object inside the cell occupied by this object.
* USE actor
* Invoked when an actor attempts to use this object. The default
implementation always fails, but individual objects can override
this behavior to make themselves usable.
"""
| """Generic gridworld environments
A generic grid-world environment consists of:
* An agent, which occupies a location on the grid
* A rectangular 2D grid
* A set of objects, which occupy (possibly overlapping) locations on the grid.
* A set of actions, which allow the agent to interact with the grid and
the objects contained within
The agent, cells and objects expose behaviors, which query and potentially
modify the environment. Examples of behaviors include the agent's MOVE_EAST
behavior (which moves the agent one square east) and a cell's GET behavior
(which reacts to an actor attempting to pick up a portable object contained
in the cell). The agent's behaviors define the environment's actions and (at
least in the current iteration of the generic gridworld) do not take arguments.
The agent's behaviors invoke the behaviors of cells and objects as part of
their implementation. For example, the MOVE_EAST behavior invokes the
EXIT behavior of the cell the agent occupies and the ENTER behavior of the
cell to the agent's east. Unlike agent behaviors, the behaviors of cells
and objects may take arguments. The cell and object behaviors will
implement certains parts of the overall action (for example, a cell's
EXIT behavior will remove the agent from the cell's contents) and may block
or alter aspects of the agent's behavior (for example, an object may prevent
the agent from exiting the cell in a certain direction until it is removed).
All behaviors return a reward and an optional exception token. The exception
token indicates something unusual occured that prevented the normal completion
of the behavior. The invoking behavior should take note of this condition
and behave accordingly. Behaviors that complete normally do not return an
exception token.
In the baseline generic gridworld, behaviors provided by the agent map
one-to-one to the actions the agent may take in the environment, so these
behaviors will not have arguments. However, extensions to the generic
gridworld may add arguments to the agent's actions, resulting in a
parameterized action space. This no-argument limitation imposes some
constraints on the generic gridworld's modeling capabilities:
* The agent may only carry one object at a time, eliminating any ambiguity
about the target of the agent's DROP or USE behaviors. Objects the agent
may carry are called "portable objects."
* Each cell may only contain one portable object at a time, eliminating
any ambiguity in the target of the agent's GET behavior.
* Objects the agent may push from cell to cell but not pick up are called
"movable" objects. Each cell may contain only one movable object,
eliminating any ambiguity in the target of the PUSH behavior.
In contrast, The behaviors of grid cells and objects are parameterized, to
allow the agent behavior to specify the target of the behavior, if a target
is needed.
The agent in the generic gridworld provides the following behaviors:
* MOVE_{NORTH,EAST,SOUTH,WEST}
* Move one step along the grid in the given direction.
* GET
* Transfer the portable object in the agent's cell to the agent's
inventory by invoking the cell's GET behavior to transfer the cell's
portable object stack, and then popping that object into the agent's
inventory. Fails if the agent is already carrying an object or
if the cell's GET behavior fails. Reward is equal to the reward
returned by the cell's GET behavior.
* DROP
* Invokes the DROP behavior of the cell the agent occupies on the
object the agent is carrying to transfer the object from the agent's
inventory to that cell. Fails if the agent is not carrying an object
or if the cell's DROP behavior fails. Reward is equal to the reward
returned by the cell's DROP behavior.
* USE
* Invokes the USE behavior of the object the agent is carrying and
returns the result of that behavior. Fails if the agent is not
carrying an object.
* PUSH_{NORTH,EAST,SOUTH,WEST}
* Push the object in the adjoining cell in the given direction, causing
both the agent and the object to move one cell in that direction. The
adjoining cell must contain a movable object, the agent must be able
to exit its current cell in the given direction and enter the next
cell from the opposite direction (as if it executed the appropriate
move action) and the object must be able to leave its cell and enter
its neighboring cell along the same direction. If any of these
conditions fails, the PUSH behavior fails.
The cells in the generic gridworld provide the following behaviors:
* EXIT actor direction
* Called when an actor (e.g. the agent) leaves the cell headed in the
given direction. Calls the EXIT behavior of every object in the
cell and fails if any of them fail. Removes the actor from the
cell's contents.
* ENTER actor direction
* Called when an actor enters the cell from the given direction to allow
the cell to react to the entry of that actor. The default implementation
calls the ENTER behavior of every object in the cell, fails if any
of them fail and adds the actor to the cell's contents if they
all return CONTINUE.
* GET actor object
* Called to remove the given object from the cell and push it onto the
object stack, invoking the GET behavior on each object contained in
the cell first. The GET behavior is invoked on every object except
the target object first, followed by the GET behavior of the target
object. eails if the object is not contained in the cell or if any
of the GET behaviors fail.
* DROP actor object
* Called to place the given object into the cell. Prior to placing the
object in the cell, this behavior invokes the DROP behavior on each
object in the cell, followed by the object's own DROP behavior
Objects provide the following behaviors
* ENTER thing direction
* Called when an actor (typically the agent) or an object attempts to
enter the cell occupied by this object from the given direction (in
the object's case, this means the object is being pushed). The default
implementation of this behavior does nothing, but individual objects
may use this behavior to prevent the entry of actors or objects or
to intercept actors or objects and send them elsewhere.
* EXIT thing direction
* Same as ENTER, but called when an actor or an object (because it is
being pushed) leaves the cell this object occupies.
* GET actor object
* Called when an actor (typically the agent) attempts to pick up an
object in a cell. The default implementation of this behavior does
nothing, but objects can provide implementations that permit themselves
to be picked up only under certain circumstances or prevent other
objects from being picked up and so on.
* DROP actor object
* Same as GET but called when an actor attempts to place a portable
object inside the cell occupied by this object.
* USE actor
* Invoked when an actor attempts to use this object. The default
implementation always fails, but individual objects can override
this behavior to make themselves usable.
""" |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class PolicyInterruptInput(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'action': 'str',
'policyScope': 'str',
'scopeWirelessSegment': 'str'
}
self.attributeMap = {
'action': 'action',
'policyScope': 'policyScope',
'scopeWirelessSegment': 'scopeWirelessSegment'
}
#One of {ABORT, ABORT-RESTORE-TO-ORIGINAL}
self.action = None # str
#Policy scope
self.policyScope = None # str
#Scope wireless segment
self.scopeWirelessSegment = None # str
| class Policyinterruptinput(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'action': 'str', 'policyScope': 'str', 'scopeWirelessSegment': 'str'}
self.attributeMap = {'action': 'action', 'policyScope': 'policyScope', 'scopeWirelessSegment': 'scopeWirelessSegment'}
self.action = None
self.policyScope = None
self.scopeWirelessSegment = None |
"""Write a program to swap two numbers"""
a = int (input("Enter first number \n"))
b = int (input("Enter second number \n"))
def swapper(af, bf):
return bf, af
a, b = swapper(a, b)
print(F"The first number is {a}")
print(F"The second number is {b}") | """Write a program to swap two numbers"""
a = int(input('Enter first number \n'))
b = int(input('Enter second number \n'))
def swapper(af, bf):
return (bf, af)
(a, b) = swapper(a, b)
print(f'The first number is {a}')
print(f'The second number is {b}') |
{
"targets": [
{
"target_name": "civetkern",
"sources": [
"src/lmdb/mdb.c",
"src/lmdb/midl.c",
"src/util/util.cpp",
"src/util/pinyin.cpp",
"src/interface.cpp",
"src/database.cpp",
"src/db_manager.cpp",
"src/log.cpp",
"src/DBThread.cpp",
"src/table/TableTag.cpp",
"src/table/TableMeta.cpp",
"src/table/TableClass.cpp",
"src/RPN.cpp",
"src/Condition.cpp",
"src/Table.cpp",
"src/Expression.cpp",
"src/StorageProxy.cpp",
"src/upgrader.cpp",
"src/civetkern.cpp" ],
"include_dirs": [
"include",
"src",
# "<!(node -e \"require('nan')\")",
'<!@(node -p "require(\'node-addon-api\').include")',
],
'cflags_c': [],
'cflags_cc': [
'-std=c++17',
'-frtti',
'-Wno-pessimizing-move'
],
"cflags!": [
'-fno-exceptions'
],
"cflags_cc!": [
'-fno-exceptions',
'-std=gnu++1y',
'-std=gnu++0x'
],
'xcode_settings': {
'CLANG_CXX_LANGUAGE_STANDARD': 'c++17',
'MACOSX_DEPLOYMENT_TARGET': '10.9',
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'YES',
'OTHER_CPLUSPLUSFLAGS': [
'-fexceptions',
'-Wall',
'-mmacosx-version-min=10.15',
'-O3'
]
},
'conditions':[
['OS=="win"', {
'configurations':{
'Release': {
'msvs_settings': {
'VCCLCompilerTool': {
"ExceptionHandling": 1,
'AdditionalOptions': [ '-std:c++17' ],
'RuntimeTypeInfo': 'true'
}
}
},
'Debug': {
'msvs_settings': {
'VCCLCompilerTool': {
"ExceptionHandling": 1,
'AdditionalOptions': [ '-std:c++17' ],
'RuntimeTypeInfo': 'true'
}
}
}
}
}],
['OS=="linux"', {
}]
]
}
]
} | {'targets': [{'target_name': 'civetkern', 'sources': ['src/lmdb/mdb.c', 'src/lmdb/midl.c', 'src/util/util.cpp', 'src/util/pinyin.cpp', 'src/interface.cpp', 'src/database.cpp', 'src/db_manager.cpp', 'src/log.cpp', 'src/DBThread.cpp', 'src/table/TableTag.cpp', 'src/table/TableMeta.cpp', 'src/table/TableClass.cpp', 'src/RPN.cpp', 'src/Condition.cpp', 'src/Table.cpp', 'src/Expression.cpp', 'src/StorageProxy.cpp', 'src/upgrader.cpp', 'src/civetkern.cpp'], 'include_dirs': ['include', 'src', '<!@(node -p "require(\'node-addon-api\').include")'], 'cflags_c': [], 'cflags_cc': ['-std=c++17', '-frtti', '-Wno-pessimizing-move'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions', '-std=gnu++1y', '-std=gnu++0x'], 'xcode_settings': {'CLANG_CXX_LANGUAGE_STANDARD': 'c++17', 'MACOSX_DEPLOYMENT_TARGET': '10.9', 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'GCC_ENABLE_CPP_RTTI': 'YES', 'OTHER_CPLUSPLUSFLAGS': ['-fexceptions', '-Wall', '-mmacosx-version-min=10.15', '-O3']}, 'conditions': [['OS=="win"', {'configurations': {'Release': {'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1, 'AdditionalOptions': ['-std:c++17'], 'RuntimeTypeInfo': 'true'}}}, 'Debug': {'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1, 'AdditionalOptions': ['-std:c++17'], 'RuntimeTypeInfo': 'true'}}}}}], ['OS=="linux"', {}]]}]} |
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
edgeOne= edges[0][0]
edgeTwo = edges[0][1]
edgeOneCouner = 0
for i in range(len(edges)):
if edgeOne == edges[i][0] or edgeOne == edges[i][1]:
edgeOneCouner+=1
return edgeOne if edgeOneCouner == len(edges) else edgeTwo | class Solution:
def find_center(self, edges: List[List[int]]) -> int:
edge_one = edges[0][0]
edge_two = edges[0][1]
edge_one_couner = 0
for i in range(len(edges)):
if edgeOne == edges[i][0] or edgeOne == edges[i][1]:
edge_one_couner += 1
return edgeOne if edgeOneCouner == len(edges) else edgeTwo |
d=int(input("Enter d -> "))
e=int(input("Enter e -> "))
b=1
a=0
s=0
k=0
for i in range(max(d,e)):
if (((d==0) and (e==1))) or (((d==1) and (e==0))):
k=1
print("True")
break
else:
if (((d==a) and (e==b))) or (((d==b) and (e==a))):
k=1
print("True")
break
s=a+b
a=b
b=s
if k==0:
print("False")
| d = int(input('Enter d -> '))
e = int(input('Enter e -> '))
b = 1
a = 0
s = 0
k = 0
for i in range(max(d, e)):
if d == 0 and e == 1 or (d == 1 and e == 0):
k = 1
print('True')
break
else:
if d == a and e == b or (d == b and e == a):
k = 1
print('True')
break
s = a + b
a = b
b = s
if k == 0:
print('False') |
'''
Builds a calculator that reads a string and addition and subtraction.
Example:
Input: '1+3-5+7'
Output: 6
'''
def calculator(math_string):
return sum([int(item) for item in math_string.replace('-', '+-').split('+')])
def test_calculator():
assert calculator('1+3-5+7') == 6, calculator('1+3-5+7')
if __name__ == '__main__':
test_calculator()
| """
Builds a calculator that reads a string and addition and subtraction.
Example:
Input: '1+3-5+7'
Output: 6
"""
def calculator(math_string):
return sum([int(item) for item in math_string.replace('-', '+-').split('+')])
def test_calculator():
assert calculator('1+3-5+7') == 6, calculator('1+3-5+7')
if __name__ == '__main__':
test_calculator() |
#Faca um programa que mostre a tabuada de varios numeros, um de cada vez, para cada valor
#digitado pelo usuario. O programa sera interrompido quando o numero solicitado for negativo
#minha resposta
while True:
num = int(input('Quer ver a tabuada de qual valor? '))
if num < 0:
break
print('-'*30)
print(f'''{num} x 1 = {num*1}
{num} x 2 = {num*2}
{num} x 3 = {num*3}
{num} x 4 = {num*4}
{num} x 5 = {num*5}
{num} x 6 = {num*6}
{num} x 7 = {num*7}
{num} x 8 = {num*8}
{num} x 9 = {num*9}
{num} x 10 = {num*10}''')
print('-'*30)
print('PROGRAMA TABUADA ENCERRADO. Volte sempre!')
#resposta do Gustavo
while True:
n = int(input('Quer ver a tabuada de qual valor? '))
print('-'*30)
if n < 0:
break
for c in range(1, 11):
print(f'{n} x {c} = {n*c}')
print('-'*30)
print('PROGRAMA TABUADA ENCERRADO. Volte sempre!') | while True:
num = int(input('Quer ver a tabuada de qual valor? '))
if num < 0:
break
print('-' * 30)
print(f'{num} x 1 = {num * 1}\n{num} x 2 = {num * 2}\n{num} x 3 = {num * 3}\n{num} x 4 = {num * 4}\n{num} x 5 = {num * 5}\n{num} x 6 = {num * 6}\n{num} x 7 = {num * 7}\n{num} x 8 = {num * 8}\n{num} x 9 = {num * 9}\n{num} x 10 = {num * 10}')
print('-' * 30)
print('PROGRAMA TABUADA ENCERRADO. Volte sempre!')
while True:
n = int(input('Quer ver a tabuada de qual valor? '))
print('-' * 30)
if n < 0:
break
for c in range(1, 11):
print(f'{n} x {c} = {n * c}')
print('-' * 30)
print('PROGRAMA TABUADA ENCERRADO. Volte sempre!') |
NUMBER_WORKER = 5
ITEM_DURATION = 60
INPUT_FILE_NAME = 'input.txt'
class WorkItem:
def __init__(self, name):
self.name = name
self.dependencies = []
self.completed = False
self.completed_at = None
def addDependency(self, item):
self.dependencies.append(item)
def isWorkable(self):
if self.completed: return False
for p in self.dependencies:
if not p.completed: return False
return True
def startWorking(self, current_time):
self.completed_at = current_time + ITEM_DURATION + (ord(self.name) - ord('A')) + 1
def getWorkableItems(work_item_map):
result = []
for item in work_item_map.values():
if item.isWorkable(): result.append(item)
return result
def workOnItemsSequential(work_item_map):
instruction = ''
while True:
work_items = getWorkableItems(work_item_map)
if len(work_items) == 0: break
item = min(work_items, key = lambda item: item.name)
instruction += item.name
item.completed = True
return instruction
def initWorkItemMap(file_name):
result = {}
with open(file_name) as input_file:
for dep_str in input_file:
tmp = dep_str.rstrip().split(' ')
dep_work_item = result.get(tmp[1], WorkItem(tmp[1]))
result[tmp[1]] = dep_work_item
work_item = result.get(tmp[7], WorkItem(tmp[7]))
result[tmp[7]] = work_item
work_item.addDependency(dep_work_item)
return result
work_item_map = initWorkItemMap(INPUT_FILE_NAME)
instruction = workOnItemsSequential(work_item_map)
print('Solution to part 1: %s' % (instruction,))
# -------------
def workOnItemsParallel(workers, work_item_map):
current_time = 0
in_progress_items = {}
while True:
# First check if some tasks has been completed
remove_items = []
for w, item in in_progress_items.values():
if item.completed_at == current_time:
item.completed = True
w['busy'] = False
remove_items.append(item)
for item in remove_items:
del in_progress_items[item.name]
# Check if we've completed everything
work_items = getWorkableItems(work_item_map)
if len(work_items) == 0 and len(in_progress_items) == 0: break
# If not, assign available tasks to workers
for w in workers:
if not w['busy'] and len(work_items) > 0:
item = min(work_items, key = lambda item: item.name)
item.startWorking(current_time)
w['busy'] = True
in_progress_items[item.name] = (w, item)
del work_item_map[item.name]
work_items = getWorkableItems(work_item_map)
current_time += 1
return current_time
work_item_map = initWorkItemMap(INPUT_FILE_NAME)
workers = [{'name': i, 'busy': False} for i in range(NUMBER_WORKER)]
duration = workOnItemsParallel(workers, work_item_map)
print('Solution to part 2: %i' % (duration,)) | number_worker = 5
item_duration = 60
input_file_name = 'input.txt'
class Workitem:
def __init__(self, name):
self.name = name
self.dependencies = []
self.completed = False
self.completed_at = None
def add_dependency(self, item):
self.dependencies.append(item)
def is_workable(self):
if self.completed:
return False
for p in self.dependencies:
if not p.completed:
return False
return True
def start_working(self, current_time):
self.completed_at = current_time + ITEM_DURATION + (ord(self.name) - ord('A')) + 1
def get_workable_items(work_item_map):
result = []
for item in work_item_map.values():
if item.isWorkable():
result.append(item)
return result
def work_on_items_sequential(work_item_map):
instruction = ''
while True:
work_items = get_workable_items(work_item_map)
if len(work_items) == 0:
break
item = min(work_items, key=lambda item: item.name)
instruction += item.name
item.completed = True
return instruction
def init_work_item_map(file_name):
result = {}
with open(file_name) as input_file:
for dep_str in input_file:
tmp = dep_str.rstrip().split(' ')
dep_work_item = result.get(tmp[1], work_item(tmp[1]))
result[tmp[1]] = dep_work_item
work_item = result.get(tmp[7], work_item(tmp[7]))
result[tmp[7]] = work_item
work_item.addDependency(dep_work_item)
return result
work_item_map = init_work_item_map(INPUT_FILE_NAME)
instruction = work_on_items_sequential(work_item_map)
print('Solution to part 1: %s' % (instruction,))
def work_on_items_parallel(workers, work_item_map):
current_time = 0
in_progress_items = {}
while True:
remove_items = []
for (w, item) in in_progress_items.values():
if item.completed_at == current_time:
item.completed = True
w['busy'] = False
remove_items.append(item)
for item in remove_items:
del in_progress_items[item.name]
work_items = get_workable_items(work_item_map)
if len(work_items) == 0 and len(in_progress_items) == 0:
break
for w in workers:
if not w['busy'] and len(work_items) > 0:
item = min(work_items, key=lambda item: item.name)
item.startWorking(current_time)
w['busy'] = True
in_progress_items[item.name] = (w, item)
del work_item_map[item.name]
work_items = get_workable_items(work_item_map)
current_time += 1
return current_time
work_item_map = init_work_item_map(INPUT_FILE_NAME)
workers = [{'name': i, 'busy': False} for i in range(NUMBER_WORKER)]
duration = work_on_items_parallel(workers, work_item_map)
print('Solution to part 2: %i' % (duration,)) |
class IrisError(Exception):
pass
class IrisDataError(IrisError):
pass
class IrisStorageError(IrisError):
pass
| class Iriserror(Exception):
pass
class Irisdataerror(IrisError):
pass
class Irisstorageerror(IrisError):
pass |
def fab(n):
if n == 1 or n == 2:
return 1
else:
return fab(n - 1) + fab(n - 2)
if __name__ == '__main__':
print(fab(10))
| def fab(n):
if n == 1 or n == 2:
return 1
else:
return fab(n - 1) + fab(n - 2)
if __name__ == '__main__':
print(fab(10)) |
# -*- coding: utf-8 -*-
"""
Spyder Editor
@auther: syenpark
Python Version: 3.6
"""
def bubble_sort(L):
"""
inputs : A list
outputs: The list in a reverse order
"""
swap = False
while not swap:
swap = True
for i in range(1, len(L)):
if L[i-1] < L[i]:
swap = False
L[i-1], L[i] = L[i], L[i-1]
test = [1, 5, 3, 8, 4, 2, 9, 6]
bubble_sort(test)
| """
Spyder Editor
@auther: syenpark
Python Version: 3.6
"""
def bubble_sort(L):
"""
inputs : A list
outputs: The list in a reverse order
"""
swap = False
while not swap:
swap = True
for i in range(1, len(L)):
if L[i - 1] < L[i]:
swap = False
(L[i - 1], L[i]) = (L[i], L[i - 1])
test = [1, 5, 3, 8, 4, 2, 9, 6]
bubble_sort(test) |
def f1():
x = 42
def f2():
x = 0
f2()
print(x)
f1()
| def f1():
x = 42
def f2():
x = 0
f2()
print(x)
f1() |
""" Parent class: User
holds deatils about an user
has a function to show user details
Child class: Bank
stores detials about the account balance, amount deposits withdraw and view_balance
"""
# Class Parent: User. Login and Details about user
class login(object):
"""docstring for login"""
def __init__(self, user, password):
self.user = user
self.password = password
if self.user == '123' and self.password == '123':
print('Logged Successfully!')
self.personal_details()
else:
print('Logged Out.')
self.delete()
def personal_details(self):
# i needed to a database...
self.name = 'Ingrid Cards'
self.age = '27 Years Old'
self.gender = 'Female'
settings = input('Hello! {}. Confirm these info? {} and {}? Press 1 - Yes and 2 - No '.format(self.name, self.age, self.gender))
if settings == '1':
print('Confirmed.')
else:
print('Logged Out.')
self.delete()
def delete(self):
def __del__(self):
print('Failed Try.')
class Bank(object):
"""docstring for Bank"""
def __init__(self):
option = input('1- balance / 2- withdraw ')
if option == '1':
self.balance()
else:
self.withdraw()
def balance(self):
print('balance')
def withdraw(self):
print('withdraw')
# Log in system
User = input('User: ')
Pass = input('Password: ')
# pass to classes
you = login(User, Pass)
# enter in the bank system
banks = Bank()
| """ Parent class: User
holds deatils about an user
has a function to show user details
Child class: Bank
stores detials about the account balance, amount deposits withdraw and view_balance
"""
class Login(object):
"""docstring for login"""
def __init__(self, user, password):
self.user = user
self.password = password
if self.user == '123' and self.password == '123':
print('Logged Successfully!')
self.personal_details()
else:
print('Logged Out.')
self.delete()
def personal_details(self):
self.name = 'Ingrid Cards'
self.age = '27 Years Old'
self.gender = 'Female'
settings = input('Hello! {}. Confirm these info? {} and {}? Press 1 - Yes and 2 - No '.format(self.name, self.age, self.gender))
if settings == '1':
print('Confirmed.')
else:
print('Logged Out.')
self.delete()
def delete(self):
def __del__(self):
print('Failed Try.')
class Bank(object):
"""docstring for Bank"""
def __init__(self):
option = input('1- balance / 2- withdraw ')
if option == '1':
self.balance()
else:
self.withdraw()
def balance(self):
print('balance')
def withdraw(self):
print('withdraw')
user = input('User: ')
pass = input('Password: ')
you = login(User, Pass)
banks = bank() |
ACTION_ACK = 'ack'
ACTION_UNACK = 'unack'
ACTION_SHELVE = 'shelve'
ACTION_UNSHELVE = 'unshelve'
ACTION_OPEN = 'open'
ACTION_CLOSE = 'close'
| action_ack = 'ack'
action_unack = 'unack'
action_shelve = 'shelve'
action_unshelve = 'unshelve'
action_open = 'open'
action_close = 'close' |
class Course():
"""Documents the class. Useful for understanding what it's for."""
def __init__(self, id, name):
self.id = id
self.name = name
def __repr__(self):
return f"Course with {self.id} called {self.name}."
def append_to_name(self, text_to_append):
self.name += text_to_append
course_1 = Course(id=123, name="Jazz")
course_2 = Course(id=456, name="Classical")
course_2.append_to_name(" with Jazz")
print(course_2)
| class Course:
"""Documents the class. Useful for understanding what it's for."""
def __init__(self, id, name):
self.id = id
self.name = name
def __repr__(self):
return f'Course with {self.id} called {self.name}.'
def append_to_name(self, text_to_append):
self.name += text_to_append
course_1 = course(id=123, name='Jazz')
course_2 = course(id=456, name='Classical')
course_2.append_to_name(' with Jazz')
print(course_2) |
# https://codility.com/programmers/lessons/2-arrays/cyclic_rotation/
def solution(A, K):
''' Rotate an array A to the right by a given number of steps K.
'''
N = len(A)
if N == 0:
return A
# After K rotations, the -Kth element becomes first element of list
return A[-K:] + A[:N-K]
if __name__ == "__main__":
cases = [(([3, 8, 9, 7, 6], 3), [9, 7, 6, 3, 8]),
(([], 0), []),
(([5, -1000], 1), [-1000, 5])
]
for case, expt in cases:
res = solution(*case)
assert expt == res, (expt, res)
| def solution(A, K):
""" Rotate an array A to the right by a given number of steps K.
"""
n = len(A)
if N == 0:
return A
return A[-K:] + A[:N - K]
if __name__ == '__main__':
cases = [(([3, 8, 9, 7, 6], 3), [9, 7, 6, 3, 8]), (([], 0), []), (([5, -1000], 1), [-1000, 5])]
for (case, expt) in cases:
res = solution(*case)
assert expt == res, (expt, res) |
"""
LC 128
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
"""
class Solution:
def longestConsecutive(self, nums) -> int:
nums = set(nums)
res = 0
while nums:
n = nums.pop()
cnt = 1
num = n + 1
while num in nums:
nums.remove(num)
cnt += 1
num += 1
num = n - 1
while num in nums:
nums.remove(num)
cnt += 1
num -= 1
res = max(res, cnt)
return res
"""
Time/Space O(N)
"""
| """
LC 128
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
"""
class Solution:
def longest_consecutive(self, nums) -> int:
nums = set(nums)
res = 0
while nums:
n = nums.pop()
cnt = 1
num = n + 1
while num in nums:
nums.remove(num)
cnt += 1
num += 1
num = n - 1
while num in nums:
nums.remove(num)
cnt += 1
num -= 1
res = max(res, cnt)
return res
'\nTime/Space O(N)\n' |
#============================================================================#
# subsets
#============================================================================#
def subsets(array):
"""iterative solution"""
n = len(array)
subsets_ = []
for i in range(1<<n):
subsets_.append([array[j] for j in range(n) if i & (1<<j)])
return subsets_
#print(subsets([1,2,3,4,5,6,7,8,9]))
def subsets(array, curr=0, subset=[]):
"""tail recursion"""
if curr == len(array):
subsets_.append(subset)
return
subsets(array, curr+1, subset)
subsets(array, curr+1, subset.append(array[start]))
def gcd(n, k):
while k:
n, k = k, n%k
return n
def palin_substrings(string):
""""""
count = 0
for center in range(2*len(string)-1):
left, right = center//2, (center+1)//2
while left >= 0 and right < len(string) and string[left] == string[right]:
count += 1
left -= 1
right += 1
return count
def sum_unique(array):
""""""
prev, sum = array[0], array[0]
for i in range(len(array)):
if array[i] <= prev:
prev += 1
else:
prev = array[i]
sum += prev
return sum
def mindiff(array):
""""""
array.sort()
return min([array[i] - array[i-1] for i in range(1, len(array))])
def power(x, n):
""""""
if x == 0: return 0
if n < 0:
x, n = 1/x, -n
temp = power(x, n//2)
if n % 2:
return temp * temp * x
else:
return temp * temp
def zig_sort(arr):
""""""
aux = sorted(arr)
lo, hi = 0, len(arr) - 1
while lo <= hi:
arr | def subsets(array):
"""iterative solution"""
n = len(array)
subsets_ = []
for i in range(1 << n):
subsets_.append([array[j] for j in range(n) if i & 1 << j])
return subsets_
def subsets(array, curr=0, subset=[]):
"""tail recursion"""
if curr == len(array):
subsets_.append(subset)
return
subsets(array, curr + 1, subset)
subsets(array, curr + 1, subset.append(array[start]))
def gcd(n, k):
while k:
(n, k) = (k, n % k)
return n
def palin_substrings(string):
""""""
count = 0
for center in range(2 * len(string) - 1):
(left, right) = (center // 2, (center + 1) // 2)
while left >= 0 and right < len(string) and (string[left] == string[right]):
count += 1
left -= 1
right += 1
return count
def sum_unique(array):
""""""
(prev, sum) = (array[0], array[0])
for i in range(len(array)):
if array[i] <= prev:
prev += 1
else:
prev = array[i]
sum += prev
return sum
def mindiff(array):
""""""
array.sort()
return min([array[i] - array[i - 1] for i in range(1, len(array))])
def power(x, n):
""""""
if x == 0:
return 0
if n < 0:
(x, n) = (1 / x, -n)
temp = power(x, n // 2)
if n % 2:
return temp * temp * x
else:
return temp * temp
def zig_sort(arr):
""""""
aux = sorted(arr)
(lo, hi) = (0, len(arr) - 1)
while lo <= hi:
arr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.