content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class FixtureException(Exception):
pass
class FixtureUploadError(FixtureException):
pass
class DuplicateFixtureTagException(FixtureUploadError):
pass
class ExcelMalformatException(FixtureUploadError):
pass
class FixtureAPIException(Exception):
pass
class FixtureTypeCheckError(Exception):
... | class Fixtureexception(Exception):
pass
class Fixtureuploaderror(FixtureException):
pass
class Duplicatefixturetagexception(FixtureUploadError):
pass
class Excelmalformatexception(FixtureUploadError):
pass
class Fixtureapiexception(Exception):
pass
class Fixturetypecheckerror(Exception):
pa... |
#!/usr/bin/env python3
# tuples is a type of list.
# tuples is immutable.
# the structure of a tuple: (1, "nice work", 2.3, [1,2,"hey"])
my_tuple = ("hey", 1, 2, "hey ho!", "hey", "hey")
print("My tuple:", my_tuple)
# to get a tuple value use it's index
print("Second item in my_tuple:", my_tuple[1])
# to count how ... | my_tuple = ('hey', 1, 2, 'hey ho!', 'hey', 'hey')
print('My tuple:', my_tuple)
print('Second item in my_tuple:', my_tuple[1])
print("How many 'hey' in my_tuple:", my_tuple.count('hey'))
print("Index position of 'hey ho!' in my_tuple:", my_tuple.index('hey ho!')) |
def possibleHeights(parent):
edges = [[] for i in range(len(parent))]
height = [0 for i in range(len(parent))]
isPossibleHeight = [False for i in range(len(parent))]
def initGraph(parent):
for i in range(1, len(parent)):
edges[parent[i]].append(i)
def calcHeight(v):
fo... | def possible_heights(parent):
edges = [[] for i in range(len(parent))]
height = [0 for i in range(len(parent))]
is_possible_height = [False for i in range(len(parent))]
def init_graph(parent):
for i in range(1, len(parent)):
edges[parent[i]].append(i)
def calc_height(v):
... |
expected_output = {
'instance': {
'isp': {
'address_family': {
'IPv4 Unicast': {
'spf_log': {
1: {
'type': 'FSPF',
'time_ms': 1,
'level': 1,
... | expected_output = {'instance': {'isp': {'address_family': {'IPv4 Unicast': {'spf_log': {1: {'type': 'FSPF', 'time_ms': 1, 'level': 1, 'total_nodes': 1, 'trigger_count': 1, 'first_trigger_lsp': '12a5.00-00', 'triggers': 'NEWLSP0', 'start_timestamp': 'Mon Aug 16 2004 19:25:35.140', 'delay': {'since_first_trigger_ms': 51}... |
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ")
def newBoard():
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ")
def display(): #white side view
c , k= 1 ... | b = 'r n b q k b n r p p p p p p p p'.split(' ') + ['.'] * 32 + 'p p p p p p p p r n b q k b n r'.upper().split(' ')
def new_board():
b = 'r n b q k b n r p p p p p p p p'.split(' ') + ['.'] * 32 + 'p p p p p p p p r n b q k b n r'.upper().split(' ')
def display():
(c, k) = (1, 0)
ap = range(1, 9)[::-1]
... |
#!/usr/bin/env python3
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
| print('Usage: thingy [OPTIONS]\n -h Display this usage message\n -H hostname Hostname to connect to\n') |
tree_count, tree_hinput, tree_chosen = int(input()), input().split(), 0
tree_height = [int(x) for x in tree_hinput]
for each_tree in range(tree_count):
if each_tree==0 and tree_height[0]>tree_height[1]:tree_chosen+=1
elif each_tree==tree_count-1 and tree_height[each_tree]>tree_height[each_tree-1]:tree_chose... | (tree_count, tree_hinput, tree_chosen) = (int(input()), input().split(), 0)
tree_height = [int(x) for x in tree_hinput]
for each_tree in range(tree_count):
if each_tree == 0 and tree_height[0] > tree_height[1]:
tree_chosen += 1
elif each_tree == tree_count - 1 and tree_height[each_tree] > tree_height[ea... |
# Create the DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(data=X, label=y)
# Create the parameter dictionary: params
params = {'objective':'reg:linear', 'max_depth':4}
# Train the model: xg_reg
xg_reg = xgb.train(dtrain=housing_dmatrix, params=params, num_boost_round=10)
# Plot the feature importances
xgb.... | housing_dmatrix = xgb.DMatrix(data=X, label=y)
params = {'objective': 'reg:linear', 'max_depth': 4}
xg_reg = xgb.train(dtrain=housing_dmatrix, params=params, num_boost_round=10)
xgb.plot_importance(xg_reg)
plt.show() |
# -*- encoding:utf-8 -*-
impar = lambda n : 2 * n - 1
header = """
Demostrar que es cierto:
1 + 3 + 5 + ... + (2*n)-1 = n ^ 2
Luego con este programa se busca probar dicha afirmacion.
"""
def suma_impares(n):
suma = 0
for i in range(1, n+1):
suma += impar(i)
return suma
def main():
print(header)
num ... | impar = lambda n: 2 * n - 1
header = '\n\tDemostrar que es cierto:\n\n\t1 + 3 + 5 + ... + (2*n)-1 = n ^ 2\n\t\n\tLuego con este programa se busca probar dicha afirmacion.\n'
def suma_impares(n):
suma = 0
for i in range(1, n + 1):
suma += impar(i)
return suma
def main():
print(header)
num =... |
#!/usr/bin/env python
def bubble_search_func(data_list):
cnt_num_all = len(data_list)
for i in range(cnt_num_all-1):
for j in range(1,cnt_num_all-i):
if(data_list[j-1]>data_list[j]):
data_list[j-1],data_list[j]=data_list[j],data_list[j-1]
data_list = [54, 25, 93, 17, 77... | def bubble_search_func(data_list):
cnt_num_all = len(data_list)
for i in range(cnt_num_all - 1):
for j in range(1, cnt_num_all - i):
if data_list[j - 1] > data_list[j]:
(data_list[j - 1], data_list[j]) = (data_list[j], data_list[j - 1])
data_list = [54, 25, 93, 17, 77, 31, 44... |
entries = [
{
'env-title': 'atari-enduro',
'score': 207.47,
},
{
'env-title': 'atari-space-invaders',
'score': 459.89,
},
{
'env-title': 'atari-qbert',
'score': 7184.73,
},
{
'env-title': 'atari-seaquest',
'score': 1383.38,
... | entries = [{'env-title': 'atari-enduro', 'score': 207.47}, {'env-title': 'atari-space-invaders', 'score': 459.89}, {'env-title': 'atari-qbert', 'score': 7184.73}, {'env-title': 'atari-seaquest', 'score': 1383.38}, {'env-title': 'atari-pong', 'score': 13.9}, {'env-title': 'atari-beam-rider', 'score': 594.45}, {'env-titl... |
class Solution:
def diStringMatch(self, S):
low,high=0,len(S)
ans=[]
for i in S:
if i=="I":
ans.append(low)
low+=1
else:
ans.append(high)
high-=1
return ans +[low]
| class Solution:
def di_string_match(self, S):
(low, high) = (0, len(S))
ans = []
for i in S:
if i == 'I':
ans.append(low)
low += 1
else:
ans.append(high)
high -= 1
return ans + [low] |
def main() -> None:
s = input()
print(s * (6 // len(s)))
if __name__ == "__main__":
main()
| def main() -> None:
s = input()
print(s * (6 // len(s)))
if __name__ == '__main__':
main() |
def get_next_target(page):
start_link = page.find('<a href=')
if start_link == -1:
return None,0
else:
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote]
return url, end_quote
| def get_next_target(page):
start_link = page.find('<a href=')
if start_link == -1:
return (None, 0)
else:
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote]
return (url, end_quote) |
def test_socfaker_application_status(socfaker_fixture):
assert socfaker_fixture.application.status in ['Active', 'Inactive', 'Legacy']
def test_socfaker_application_account_status(socfaker_fixture):
assert socfaker_fixture.application.account_status in ['Enabled', 'Disabled']
def test_socfaker_name(socfaker_f... | def test_socfaker_application_status(socfaker_fixture):
assert socfaker_fixture.application.status in ['Active', 'Inactive', 'Legacy']
def test_socfaker_application_account_status(socfaker_fixture):
assert socfaker_fixture.application.account_status in ['Enabled', 'Disabled']
def test_socfaker_name(socfaker_f... |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/bdd100k_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
# model
model = dict(
bbox_head=dict(
num_c... | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/bdd100k_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
model = dict(bbox_head=dict(num_classes=10))
data = dict(samples_per_gpu=4, workers... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rt... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def build_tree(self, inorder, postorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
... |
class InterfaceWriter(object):
def __init__(self, output_path):
self._output_path_template = output_path + '/_{key}_{subsystem}.i'
self._fp = {
'pre': {},
'post': {},
}
def _write(self, key, subsystem, text):
subsystem = subsystem.lower()
fp = se... | class Interfacewriter(object):
def __init__(self, output_path):
self._output_path_template = output_path + '/_{key}_{subsystem}.i'
self._fp = {'pre': {}, 'post': {}}
def _write(self, key, subsystem, text):
subsystem = subsystem.lower()
fp = self._fp[key].get(subsystem)
... |
# Format of training prompt
defaultPrompt = """I am a Cardiologist. My patient asked me what this means:
Input: Normal left ventricular size and systolic function. EF > 55 %. Normal right ventricular size and systolic function. Normal valve structure and function
Output: Normal pumping function of the left and right ... | default_prompt = 'I am a Cardiologist. My patient asked me what this means:\n\nInput: Normal left ventricular size and systolic function. EF > 55 %. Normal right ventricular size and systolic function. Normal valve structure and function\n\nOutput: Normal pumping function of the left and right side of the heart. Heart ... |
abilities = {1: 'Stench', 2: 'Drizzle', 3: 'Speed Boost', 4: 'Battle Armor', 5: 'Sturdy', 6: 'Damp', 7: 'Limber',
8: 'Sand Veil', 9: 'Static', 10: 'Volt Absorb', 11: 'Water Absorb', 12: 'Oblivious', 13: 'Cloud Nine',
14: 'Compound Eyes', 15: 'Insomnia', 16: 'Color Change', 17: 'Immunity', 18: ... | abilities = {1: 'Stench', 2: 'Drizzle', 3: 'Speed Boost', 4: 'Battle Armor', 5: 'Sturdy', 6: 'Damp', 7: 'Limber', 8: 'Sand Veil', 9: 'Static', 10: 'Volt Absorb', 11: 'Water Absorb', 12: 'Oblivious', 13: 'Cloud Nine', 14: 'Compound Eyes', 15: 'Insomnia', 16: 'Color Change', 17: 'Immunity', 18: 'Flash Fire', 19: 'Shield ... |
STRICTDOC_GRAMMAR = r"""
Document[noskipws]:
'[DOCUMENT]' '\n'
// NAME: is deprecated. Both documents and sections now have TITLE:.
(('NAME: ' name = /.*$/ '\n') | ('TITLE: ' title = /.*$/ '\n')?)
(config = DocumentConfig)?
('\n' grammar = DocumentGrammar)?
free_texts *= SpaceThenFreeText
section_contents... | strictdoc_grammar = "\nDocument[noskipws]:\n '[DOCUMENT]' '\\n'\n // NAME: is deprecated. Both documents and sections now have TITLE:.\n (('NAME: ' name = /.*$/ '\\n') | ('TITLE: ' title = /.*$/ '\\n')?)\n (config = DocumentConfig)?\n ('\\n' grammar = DocumentGrammar)?\n free_texts *= SpaceThenFreeText\n section... |
li=["a","b","d"]
print(li)
str="".join(li)#adding the lists value together
print(str)
str=" ".join(li)#adding the lists value together along with a space
print(str)
str=",".join(li)#adding the lists value together along with a comma
print(str)
str="&".join(li)#adding the lists value together along with a &
print(st... | li = ['a', 'b', 'd']
print(li)
str = ''.join(li)
print(str)
str = ' '.join(li)
print(str)
str = ','.join(li)
print(str)
str = '&'.join(li)
print(str) |
def limpar(*args):
telaPrincipal = args[0]
cursor = args[1]
banco10 = args[2]
sql_limpa_tableWidget = args[3]
telaPrincipal.valorTotal.setText("Valor Total:")
telaPrincipal.tableWidget_cadastro.clear()
telaPrincipal.desconto.clear()
telaPrincipal.acrescimo.clear()
sql_limpa_tableW... | def limpar(*args):
tela_principal = args[0]
cursor = args[1]
banco10 = args[2]
sql_limpa_table_widget = args[3]
telaPrincipal.valorTotal.setText('Valor Total:')
telaPrincipal.tableWidget_cadastro.clear()
telaPrincipal.desconto.clear()
telaPrincipal.acrescimo.clear()
sql_limpa_tableWi... |
consonents = ['sch', 'squ', 'thr', 'qu', 'th', 'sc', 'sh', 'ch', 'st', 'rh']
consonents.extend('bcdfghjklmnpqrstvwxyz')
def prefix(word):
if word[:2] not in ['xr', 'yt']:
for x in consonents:
if word.startswith(x):
return (x, word[len(x):])
return ('', word)
d... | consonents = ['sch', 'squ', 'thr', 'qu', 'th', 'sc', 'sh', 'ch', 'st', 'rh']
consonents.extend('bcdfghjklmnpqrstvwxyz')
def prefix(word):
if word[:2] not in ['xr', 'yt']:
for x in consonents:
if word.startswith(x):
return (x, word[len(x):])
return ('', word)
def translate(p... |
[
[float("NaN"), float("NaN"), 73.55631426, 76.45173763],
[float("NaN"), float("NaN"), 71.11031587, 73.6557548],
[float("NaN"), float("NaN"), 11.32891221, 9.80444014],
[float("NaN"), float("NaN"), 10.27812002, 8.15602626],
[float("NaN"), float("NaN"), 21.60703222, 17.9604664],
[float("NaN"), flo... | [[float('NaN'), float('NaN'), 73.55631426, 76.45173763], [float('NaN'), float('NaN'), 71.11031587, 73.6557548], [float('NaN'), float('NaN'), 11.32891221, 9.80444014], [float('NaN'), float('NaN'), 10.27812002, 8.15602626], [float('NaN'), float('NaN'), 21.60703222, 17.9604664], [float('NaN'), float('NaN'), 2.44599839, 2.... |
numbers = [float(num) for num in input().split()]
nums_dict = {}
for el in numbers:
if el not in nums_dict:
nums_dict[el] = 0
nums_dict[el] += 1
[print(f"{el:.1f} - {occurence} times") for el, occurence in nums_dict.items()] | numbers = [float(num) for num in input().split()]
nums_dict = {}
for el in numbers:
if el not in nums_dict:
nums_dict[el] = 0
nums_dict[el] += 1
[print(f'{el:.1f} - {occurence} times') for (el, occurence) in nums_dict.items()] |
modules_rules = {
"graphlib": (None, (3, 9)),
"test.support.socket_helper": (None, (3, 9)),
"zoneinfo": (None, (3, 9)),
}
classes_rules = {
"asyncio.BufferedProtocol": (None, (3, 7)),
"asyncio.PidfdChildWatcher": (None, (3, 9)),
"importlib.abc.Traversable": (None, (3, 9)),
"importlib.abc.Tr... | modules_rules = {'graphlib': (None, (3, 9)), 'test.support.socket_helper': (None, (3, 9)), 'zoneinfo': (None, (3, 9))}
classes_rules = {'asyncio.BufferedProtocol': (None, (3, 7)), 'asyncio.PidfdChildWatcher': (None, (3, 9)), 'importlib.abc.Traversable': (None, (3, 9)), 'importlib.abc.TraversableReader': (None, (3, 9)),... |
def bolha_curta(self, lista):
fim = len(lista)
for i in range(fim-1, 0, -1):
trocou = False
for j in range(i):
if lista[j] > lista[j+1]:
lista[j], lista[j+1] = lista[j+1], lista[j]
trocou = True
if trocou== Fal... | def bolha_curta(self, lista):
fim = len(lista)
for i in range(fim - 1, 0, -1):
trocou = False
for j in range(i):
if lista[j] > lista[j + 1]:
(lista[j], lista[j + 1]) = (lista[j + 1], lista[j])
trocou = True
if trocou == False:
retur... |
a = float(input('digite um numero:'))
b = float(input('digite um numero:'))
c = float(input('digite um numero:'))
if a > b:
if a > c:
ma = a
if b > c:
mi = c
if c > b:
mi = b
if b > a:
if b > c:
ma = b
if a > c:
mi = c
if c > ... | a = float(input('digite um numero:'))
b = float(input('digite um numero:'))
c = float(input('digite um numero:'))
if a > b:
if a > c:
ma = a
if b > c:
mi = c
if c > b:
mi = b
if b > a:
if b > c:
ma = b
if a > c:
mi = c
if c > a:... |
"""
Common constants for Pipeline.
"""
AD_FIELD_NAME = 'asof_date'
ANNOUNCEMENT_FIELD_NAME = 'announcement_date'
CASH_FIELD_NAME = 'cash'
CASH_AMOUNT_FIELD_NAME = 'cash_amount'
BUYBACK_ANNOUNCEMENT_FIELD_NAME = 'buyback_date'
DAYS_SINCE_PREV = 'days_since_prev'
DAYS_SINCE_PREV_DIVIDEND_ANNOUNCEMENT = 'days_since_prev_d... | """
Common constants for Pipeline.
"""
ad_field_name = 'asof_date'
announcement_field_name = 'announcement_date'
cash_field_name = 'cash'
cash_amount_field_name = 'cash_amount'
buyback_announcement_field_name = 'buyback_date'
days_since_prev = 'days_since_prev'
days_since_prev_dividend_announcement = 'days_since_prev_d... |
# Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string.
# Return the n copies of the whole string if the length is less than 2
s = input("Enter a string: ")
def copies(string, number):
copy = ""
for i in range(number):
copy += string[0] + strin... | s = input('Enter a string: ')
def copies(string, number):
copy = ''
for i in range(number):
copy += string[0] + string[1]
return copy
if len(s) > 2:
n = int(input('Enter the number of copies: '))
print(copies(s, n))
else:
print(s + s) |
# model settings
model = dict(
type='Recognizer3D',
backbone=dict(type='X3D', frozen_stages = -1, gamma_w=1, gamma_b=2.25, gamma_d=2.2),
cls_head=dict(
type='X3DHead',
in_channels=432,
num_classes=400,
multi_class=False,
spatial_type='avg',
dropout_ratio=0.7,
... | model = dict(type='Recognizer3D', backbone=dict(type='X3D', frozen_stages=-1, gamma_w=1, gamma_b=2.25, gamma_d=2.2), cls_head=dict(type='X3DHead', in_channels=432, num_classes=400, multi_class=False, spatial_type='avg', dropout_ratio=0.7, fc1_bias=False), train_cfg=None, test_cfg=dict(average_clips='prob')) |
channels1 = { "#test1": ("@user1", "user2", "user3"),
"#test2": ("@user4", "user5", "user6"),
"#test3": ("@user7", "user8", "user9")
}
channels2 = { "#test1": ("@user1", "user2", "user3"),
"#test2": ("@user4", "user5", "user6"),
"#test3": ("@user7", "... | channels1 = {'#test1': ('@user1', 'user2', 'user3'), '#test2': ('@user4', 'user5', 'user6'), '#test3': ('@user7', 'user8', 'user9')}
channels2 = {'#test1': ('@user1', 'user2', 'user3'), '#test2': ('@user4', 'user5', 'user6'), '#test3': ('@user7', 'user8', 'user9'), None: ('user10', 'user11')}
channels3 = {'#test1': ('@... |
class BaseAnsiblerException(Exception):
message = "Error"
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args)
self.__class__.message = kwargs.get("message", self.message)
def __str__(self) -> str:
return self.__class__.message
class CommandNotFound(BaseAnsiblerEx... | class Baseansiblerexception(Exception):
message = 'Error'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args)
self.__class__.message = kwargs.get('message', self.message)
def __str__(self) -> str:
return self.__class__.message
class Commandnotfound(BaseAnsiblerExc... |
"""
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
"""
__author__ = 'Danyang'
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:... | """
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
"""
__author__ = 'Danyang'
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def build_t... |
def make_list(element, keep_none=False):
""" Turns element into a list of itself
if it is not of type list or tuple. """
if element is None and not keep_none:
element = [] # Convert none to empty list
if not isinstance(element, (list, tuple, set)):
element = [element]
elif isinstan... | def make_list(element, keep_none=False):
""" Turns element into a list of itself
if it is not of type list or tuple. """
if element is None and (not keep_none):
element = []
if not isinstance(element, (list, tuple, set)):
element = [element]
elif isinstance(element, (tuple, set)):
... |
#Evaludador de numero primo
#Created by @neriphy
numero = input("Ingrese el numero a evaluar: ")
divisor = numero - 1
residuo = True
while divisor > 1 and residuo == True:
if numero%divisor != 0:
divisor = divisor - 1
print("Evaluando")
residuo = True
elif numero%divisor == 0:
residuo = False
if residu... | numero = input('Ingrese el numero a evaluar: ')
divisor = numero - 1
residuo = True
while divisor > 1 and residuo == True:
if numero % divisor != 0:
divisor = divisor - 1
print('Evaluando')
residuo = True
elif numero % divisor == 0:
residuo = False
if residuo == True:
print(n... |
# Python programming that returns the weight of the maximum weight path in a triangle
def triangle_max_weight(arrs, level=0, index=0):
if level == len(arrs) - 1:
return arrs[level][index]
else:
return arrs[level][index] + max(
triangle_max_weight(arrs, level + 1, index), triangle_ma... | def triangle_max_weight(arrs, level=0, index=0):
if level == len(arrs) - 1:
return arrs[level][index]
else:
return arrs[level][index] + max(triangle_max_weight(arrs, level + 1, index), triangle_max_weight(arrs, level + 1, index + 1))
if __name__ == '__main__':
arrs1 = [[1], [2, 3], [1, 5, 1]... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
## By passing the case if empty linked list
if not he... | class Solution:
def reverse_list(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
else:
(prev, curr) = (None, head)
while curr:
rest_ll = curr.next
curr.next = prev
prev = curr
... |
def get_span_and_trace(headers):
try:
trace, span = headers.get("X-Cloud-Trace-Context").split("/")
except (ValueError, AttributeError):
return None, None
span = span.split(";")[0]
return span, trace
| def get_span_and_trace(headers):
try:
(trace, span) = headers.get('X-Cloud-Trace-Context').split('/')
except (ValueError, AttributeError):
return (None, None)
span = span.split(';')[0]
return (span, trace) |
def trigger():
return """
CREATE OR REPLACE FUNCTION trg_ticket_prioridade()
RETURNS TRIGGER AS $$
DECLARE
prioridade_grupo smallint;
prioridade_subgrupo smallint;
BEGIN
prioridade_grupo = COALESCE((SELECT prioridade FR... | def trigger():
return '\n CREATE OR REPLACE FUNCTION trg_ticket_prioridade()\n RETURNS TRIGGER AS $$\n DECLARE\n prioridade_grupo smallint;\n prioridade_subgrupo smallint;\n \n BEGIN\n prioridade_grupo = COALESCE((SELECT priorid... |
# CPU: 0.18 s
n_rows, _ = map(int, input().split())
common_items = set(input().split())
for _ in range(n_rows - 1):
common_items = common_items.intersection(set(input().split()))
print(len(common_items))
print(*sorted(common_items), sep="\n")
| (n_rows, _) = map(int, input().split())
common_items = set(input().split())
for _ in range(n_rows - 1):
common_items = common_items.intersection(set(input().split()))
print(len(common_items))
print(*sorted(common_items), sep='\n') |
class APIException(Exception):
def __init__(self, message, code=None):
self.context = {}
if code:
self.context['errorCode'] = code
super().__init__(message)
| class Apiexception(Exception):
def __init__(self, message, code=None):
self.context = {}
if code:
self.context['errorCode'] = code
super().__init__(message) |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_len = 0
l, r = 0, 0
count = dict()
while r < len(s):
count[s[r]] = count.get(s[r], 0) + 1
while count[s[r]] > 1:
count[s[l]] = count[s[l]] - 1
l += 1
... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
max_len = 0
(l, r) = (0, 0)
count = dict()
while r < len(s):
count[s[r]] = count.get(s[r], 0) + 1
while count[s[r]] > 1:
count[s[l]] = count[s[l]] - 1
l += 1... |
class DeviceInterface:
# This operation is used to initialize the device instance. Accepts a dictionary that is read in from the device's yaml definition.
# This device_config_yaml may contain any number of parameters/fields necessary to initialize/setup the instance for data collection.
def initialize(self... | class Deviceinterface:
def initialize(self, device_config_dict):
pass
def get_device_data(self):
pass |
'''
mro stands for Method Resolution Order.
It returns a list of types the class is
derived from, in the order they are searched
for methods'''
print(__doc__)
print('\n'+'-'*35+ 'Method Resolution Order'+'-'*35)
class A(object):
def dothis(self):
print('From A class')
class B1(A):
de... | """
mro stands for Method Resolution Order.
It returns a list of types the class is
derived from, in the order they are searched
for methods"""
print(__doc__)
print('\n' + '-' * 35 + 'Method Resolution Order' + '-' * 35)
class A(object):
def dothis(self):
print('From A class')
class B1(A):
def do... |
def solution(s1, s2):
'''
EXPLANATION
-------------------------------------------------------------------
I approached this problem by creating two dictionaries, one for
each string. These dictionaries are formatted with characters as
keys, and counts as values. I then iterate over each string,
... | def solution(s1, s2):
"""
EXPLANATION
-------------------------------------------------------------------
I approached this problem by creating two dictionaries, one for
each string. These dictionaries are formatted with characters as
keys, and counts as values. I then iterate over each string,
... |
class Node:
def __init__(self, data=None, left=None, right=None):
self._left = left
self._data = data
self._right = right
@property
def left(self):
return self._left
@left.setter
def left(self, left):
self._left = left
@property
def right(self):
return self._right
@right.setter
def right(self, ... | class Node:
def __init__(self, data=None, left=None, right=None):
self._left = left
self._data = data
self._right = right
@property
def left(self):
return self._left
@left.setter
def left(self, left):
self._left = left
@property
def right(self):
... |
# A resizable list of integers
class Vector(object):
# Attributes
items: [int] = None
size: int = 0
# Constructor
def __init__(self:"Vector"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector") -> int:
return len(self.items)
# Increases capacity of... | class Vector(object):
items: [int] = None
size: int = 0
def __init__(self: 'Vector'):
self.items = [0]
def capacity(self: 'Vector') -> int:
return len(self.items)
def increase_capacity(self: 'Vector') -> int:
self.items = self.items + [0]
return self.capacity()
... |
#!/usr/bin/python3
# File: fizz_buzz.py
# Author: Jonathan Belden
# Description: Fizz-Buzz Coding Challenge
# Reference: https://edabit.com/challenge/WXqH9qvvGkmx4dMvp
def evaluate(inputValue):
result = None
if inputValue % 3 == 0 and inputValue % 5 == 0:
result = "FizzBuzz"
elif inputValue % 3 ... | def evaluate(inputValue):
result = None
if inputValue % 3 == 0 and inputValue % 5 == 0:
result = 'FizzBuzz'
elif inputValue % 3 == 0:
result = 'Fizz'
elif inputValue % 5 == 0:
result = 'Buzz'
else:
result = str(inputValue)
return result |
class Solution:
"""
@param A:
@return: nothing
"""
def numFactoredBinaryTrees(self, A):
A.sort()
MOD = 10 ** 9 + 7
dp = {}
for j in range(len(A)):
dp[A[j]] = 1
for i in range(j):
if A[j] % A[i] == 0:
num = A... | class Solution:
"""
@param A:
@return: nothing
"""
def num_factored_binary_trees(self, A):
A.sort()
mod = 10 ** 9 + 7
dp = {}
for j in range(len(A)):
dp[A[j]] = 1
for i in range(j):
if A[j] % A[i] == 0:
num... |
def multiplo(a, b):
if a % b == 0:
return True
else:
return False
print(multiplo(2, 1))
print(multiplo(9, 5))
print(multiplo(81, 9))
| def multiplo(a, b):
if a % b == 0:
return True
else:
return False
print(multiplo(2, 1))
print(multiplo(9, 5))
print(multiplo(81, 9)) |
valores = []
quant = int(input())
for c in range(0, quant):
x, y = input().split(' ')
x = int(x)
y = int(y)
maior = menor = soma = 0
if x > y:
maior = x
menor = y
else:
maior = y
menor = x
if maior == menor+1 or maior == menor:
valores.append(0)
e... | valores = []
quant = int(input())
for c in range(0, quant):
(x, y) = input().split(' ')
x = int(x)
y = int(y)
maior = menor = soma = 0
if x > y:
maior = x
menor = y
else:
maior = y
menor = x
if maior == menor + 1 or maior == menor:
valores.append(0)
... |
def binary_search(collection, lhs, rhs, value):
if rhs > lhs:
mid = lhs + (rhs - lhs) // 2
if collection[mid] == value:
return mid
if collection[mid] > value:
return binary_search(collection, lhs, mid-1, value)
return binary_search(collection, mid+1, rhs, v... | def binary_search(collection, lhs, rhs, value):
if rhs > lhs:
mid = lhs + (rhs - lhs) // 2
if collection[mid] == value:
return mid
if collection[mid] > value:
return binary_search(collection, lhs, mid - 1, value)
return binary_search(collection, mid + 1, rhs, ... |
click(Pattern("Bameumbrace.png").similar(0.80))
sleep(1)
click("3abnb.png")
exit(0)
| click(pattern('Bameumbrace.png').similar(0.8))
sleep(1)
click('3abnb.png')
exit(0) |
class Rover:
def __init__(self,photo,name,date):
self.photo = photo
self.name = name
self.date = date
class Articles:
def __init__(self,author,title,description,url,poster,time):
self.author = author
self.title = title
self.description = description
... | class Rover:
def __init__(self, photo, name, date):
self.photo = photo
self.name = name
self.date = date
class Articles:
def __init__(self, author, title, description, url, poster, time):
self.author = author
self.title = title
self.description = description
... |
'''https://leetcode.com/problems/max-consecutive-ones/'''
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
i, j = 0, 0
ans = 0
while j<len(nums):
if nums[j]==0:
ans = max(ans, j-i)
i = j+1
j+=1
return m... | """https://leetcode.com/problems/max-consecutive-ones/"""
class Solution:
def find_max_consecutive_ones(self, nums: List[int]) -> int:
(i, j) = (0, 0)
ans = 0
while j < len(nums):
if nums[j] == 0:
ans = max(ans, j - i)
i = j + 1
j += ... |
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
n = len(board)
q = collections.deque()
q.append(1)
visited = set()
visited.add(1)
step = 0
while q:
size = len(q)
for _ in range(size):
num = q.p... | class Solution:
def snakes_and_ladders(self, board: List[List[int]]) -> int:
n = len(board)
q = collections.deque()
q.append(1)
visited = set()
visited.add(1)
step = 0
while q:
size = len(q)
for _ in range(size):
num = ... |
def mergingLetters(s, t):
#edge cases
mergedStr = ""
firstChar = list(s)
secondChar = list(t)
for i, ele in enumerate(secondChar):
if i < len(firstChar):
mergedStr = mergedStr + firstChar[i]
print('first pointer', firstChar[i], mergedStr)
if i < len(second... | def merging_letters(s, t):
merged_str = ''
first_char = list(s)
second_char = list(t)
for (i, ele) in enumerate(secondChar):
if i < len(firstChar):
merged_str = mergedStr + firstChar[i]
print('first pointer', firstChar[i], mergedStr)
if i < len(secondChar):
... |
#
# PySNMP MIB module TIMETRA-SAS-IEEE8021-PAE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-SAS-IEEE8021-PAE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:21:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
x = 0
y = 0
aim = 0
with open('input') as f:
for line in f:
direction = line.split()[0]
magnitude = int(line.split()[1])
if direction == 'forward':
x += magnitude
y += aim * magnitude
elif direction == 'down':
aim += magnitude
elif directio... | x = 0
y = 0
aim = 0
with open('input') as f:
for line in f:
direction = line.split()[0]
magnitude = int(line.split()[1])
if direction == 'forward':
x += magnitude
y += aim * magnitude
elif direction == 'down':
aim += magnitude
elif directio... |
#
# PySNMP MIB module PRIVATE-SW0657840-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PRIVATE-SW0657840-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint) ... |
class MinDiffList:
# def __init__(self):
# self.diff = sys.maxint
def findMinDiff(self, arr):
arr.sort()
self.diff = arr[len(arr) - 1]
for iter in range(len(arr)):
adjacentDiff = abs(arr[iter + 1]) - abs(arr[iter])
if adjacentDiff < self.diff:
... | class Mindifflist:
def find_min_diff(self, arr):
arr.sort()
self.diff = arr[len(arr) - 1]
for iter in range(len(arr)):
adjacent_diff = abs(arr[iter + 1]) - abs(arr[iter])
if adjacentDiff < self.diff:
self.diff = adjacentDiff
return adjacen... |
"""
Author: CaptCorpMURICA
Project: 100DaysPython
File: module1_day06_lists.py
Creation Date: 6/2/2019, 8:55 AM
Description: Learn the basic of lists in python.
"""
list_1 = []
list_2 = list()
print("List 1 Type: {}\nList 2 Type: {}".format(type(list_1), type(list_2)))
... | """
Author: CaptCorpMURICA
Project: 100DaysPython
File: module1_day06_lists.py
Creation Date: 6/2/2019, 8:55 AM
Description: Learn the basic of lists in python.
"""
list_1 = []
list_2 = list()
print('List 1 Type: {}\nList 2 Type: {}'.format(type(list_1), type(list_2)))
t... |
class MagicDice:
def __init__(self, account, active_key):
self.account = account
self.active_key = active_key
| class Magicdice:
def __init__(self, account, active_key):
self.account = account
self.active_key = active_key |
def countWord(word):
count = 0
with open('test.txt') as file:
for line in file:
if word in line:
count += line.count(word)
return count
word = input('Enter word: ')
count = countWord(word)
print(word, '- occurence: ', count) | def count_word(word):
count = 0
with open('test.txt') as file:
for line in file:
if word in line:
count += line.count(word)
return count
word = input('Enter word: ')
count = count_word(word)
print(word, '- occurence: ', count) |
header = """/*
Icebreaker and IceSugar RSMB5 project - RV32I for Lattice iCE40
With complete open-source toolchain flow using:
-> yosys
-> icarus verilog
-> icestorm project
Tests are written in several languages
-> Systemverilog Pure Testbench (Vivado)
-> UVM testbench (Vivado)
-> PyUvm (Icarus)
-> Formal ... | header = '/*\n Icebreaker and IceSugar RSMB5 project - RV32I for Lattice iCE40\n With complete open-source toolchain flow using:\n -> yosys \n -> icarus verilog\n -> icestorm project\n\n Tests are written in several languages\n -> Systemverilog Pure Testbench (Vivado)\n -> UVM testbench (Vivado)\n -> PyUvm (Icarus)\n -... |
num = int(input())
x = 0
if num == 0:
print(1)
exit()
while num != 0:
x +=1
num = num//10
print(x)
| num = int(input())
x = 0
if num == 0:
print(1)
exit()
while num != 0:
x += 1
num = num // 10
print(x) |
class SpecValidator:
def __init__(self, type=None, default=None, choices=[], min=None,
max=None):
self.type = type
self.default = default
self.choices = choices
self.min = min
self.max = max
| class Specvalidator:
def __init__(self, type=None, default=None, choices=[], min=None, max=None):
self.type = type
self.default = default
self.choices = choices
self.min = min
self.max = max |
"""FactoryAggregate provider prototype."""
class FactoryAggregate:
"""FactoryAggregate provider prototype."""
def __init__(self, **factories):
"""Initialize instance."""
self.factories = factories
def __call__(self, factory_name, *args, **kwargs):
"""Create object."""
ret... | """FactoryAggregate provider prototype."""
class Factoryaggregate:
"""FactoryAggregate provider prototype."""
def __init__(self, **factories):
"""Initialize instance."""
self.factories = factories
def __call__(self, factory_name, *args, **kwargs):
"""Create object."""
retu... |
def f(x):
#return 1*x**3 + 5*x**2 - 2*x - 24
#return 1*x**4 - 4*x**3 - 2*x**2 + 12*x - 3
return 82*x + 6*x**2 - 0.67*x**3
print(f(2)-f(1))
#print((f(3.5) - f(0.5)) / -3)
#print(f(0.5)) | def f(x):
return 82 * x + 6 * x ** 2 - 0.67 * x ** 3
print(f(2) - f(1)) |
# Weird Algorithm
# Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one.
n = int(input())
print(n, end=" ")
while n != 1:
if n % 2 == 0:
... | n = int(input())
print(n, end=' ')
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = n * 3 + 1
print(n, end=' ') |
T = int(input())
if T > 100:
print('Steam')
elif T < 0:
print('Ice')
else:
print('Water')
| t = int(input())
if T > 100:
print('Steam')
elif T < 0:
print('Ice')
else:
print('Water') |
PSQL_CONNECTION_PARAMS = {
'dbname': 'ifcb',
'user': '******',
'password': '******',
'host': '/var/run/postgresql/'
}
DATA_DIR = '/mnt/ifcb'
| psql_connection_params = {'dbname': 'ifcb', 'user': '******', 'password': '******', 'host': '/var/run/postgresql/'}
data_dir = '/mnt/ifcb' |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
tunacell package
============
plotting/defs.py module
~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
DEFAULT_COLORS = ('red', 'blue', 'purple', 'green', 'yellowgreen', 'cyan',
'magenta',
'indigo', 'darkorange', 'pink', 'yellow')
colors = DEFAULT_... | """
tunacell package
============
plotting/defs.py module
~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
default_colors = ('red', 'blue', 'purple', 'green', 'yellowgreen', 'cyan', 'magenta', 'indigo', 'darkorange', 'pink', 'yellow')
colors = DEFAULT_COLORS
params = {'length': {'bottom': 1.0, 'top': 8.0, 'delta': 2.0, 'unit': '$\\mu$... |
class KeyBoardService():
def __init__(self):
pass
def is_key_pressed(self, *keys):
pass
def is_key_released(self, *key):
pass | class Keyboardservice:
def __init__(self):
pass
def is_key_pressed(self, *keys):
pass
def is_key_released(self, *key):
pass |
#!/usr/bin/env python3
"""Switcharoo.
Create a function that takes a string and returns a new string with its
first and last characters swapped, except under three conditions:
If the length of the string is less than two, return "Incompatible.".
If the argument is not a string, return "Incompatible.".
If the first a... | """Switcharoo.
Create a function that takes a string and returns a new string with its
first and last characters swapped, except under three conditions:
If the length of the string is less than two, return "Incompatible.".
If the argument is not a string, return "Incompatible.".
If the first and last characters are t... |
"""1/1 adventofcode"""
with open("input.txt", "r", encoding="UTF-8") as i_file:
data = list(map(int, i_file.read().splitlines()))
values = ["i" if data[i] > data[i - 1] else "d" for i in range(1, len(data))]
print(values.count("i"))
| """1/1 adventofcode"""
with open('input.txt', 'r', encoding='UTF-8') as i_file:
data = list(map(int, i_file.read().splitlines()))
values = ['i' if data[i] > data[i - 1] else 'd' for i in range(1, len(data))]
print(values.count('i')) |
def past(h, m, s):
h_ms = h * 3600000
m_ms = m * 60000
s_ms = s * 1000
return h_ms + m_ms + s_ms
# Best Practices
def past(h, m, s):
return (3600*h + 60*m + s) * 1000 | def past(h, m, s):
h_ms = h * 3600000
m_ms = m * 60000
s_ms = s * 1000
return h_ms + m_ms + s_ms
def past(h, m, s):
return (3600 * h + 60 * m + s) * 1000 |
# Iteration: Repeat the same procedure until it reaches a end point.
# Specify the data to iterate over,what to do to data at every step, and we need to specify when our loop should stop.
# Infinite Loop: Bug that may occur when ending condition speicified incorrectly or not specified.
spices = [
'salt',
'pepp... | spices = ['salt', 'pepper', 'cumin', 'turmeric']
for spice in spices:
print(spice)
print('No more boring omelettes!') |
# coding: utf-8
print(__import__('task_list_dev').tools.get_list())
| print(__import__('task_list_dev').tools.get_list()) |
#Warmup-1 > not_string
def not_string(str):
if str.startswith('not'):
return str
else:
return "not " + str | def not_string(str):
if str.startswith('not'):
return str
else:
return 'not ' + str |
'''
Docstring with single quotes instead of double quotes.
'''
my_str = "not an int"
| """
Docstring with single quotes instead of double quotes.
"""
my_str = 'not an int' |
def selection_sort(input_list):
for i in range(len(input_list)):
min_index = i
for k in range(i, len(input_list)):
if input_list[k] < input_list[min_index]:
min_index = k
input_list[i], input_list[min_index] = input_list[min_index], input_list[i]
return inpu... | def selection_sort(input_list):
for i in range(len(input_list)):
min_index = i
for k in range(i, len(input_list)):
if input_list[k] < input_list[min_index]:
min_index = k
(input_list[i], input_list[min_index]) = (input_list[min_index], input_list[i])
return in... |
username = 'user@example.com'
password = 'hunter2'
# larger = less change of delays if you skip a lot
# smaller = more responsive to ups/downs
queue_size = 2 | username = 'user@example.com'
password = 'hunter2'
queue_size = 2 |
machine_number = 43
user_number = int( raw_input("enter a number: ") )
print( type(user_number) )
if user_number == machine_number:
print("Bravo!!!")
| machine_number = 43
user_number = int(raw_input('enter a number: '))
print(type(user_number))
if user_number == machine_number:
print('Bravo!!!') |
def pedir_entero (mensaje,min,max):
numero = input(mensaje.format(min,max))
if type(numero)==int:
while numero <= min or numero>=max:
numero = input("el numero debe estar entre {:d} y {:d} ".format(min,max))
return numero
else:
return "debes introducir un entero"
valido... | def pedir_entero(mensaje, min, max):
numero = input(mensaje.format(min, max))
if type(numero) == int:
while numero <= min or numero >= max:
numero = input('el numero debe estar entre {:d} y {:d} '.format(min, max))
return numero
else:
return 'debes introducir un entero'
v... |
test_cases = int(input().strip())
def sum_sub_nums(idx, value):
global result
if value == K:
result += 1
return
if value > K or idx >= N:
return
sum_sub_nums(idx + 1, value)
sum_sub_nums(idx + 1, value + nums[idx])
for t in range(1, test_cases + 1):
N, K = map(int, i... | test_cases = int(input().strip())
def sum_sub_nums(idx, value):
global result
if value == K:
result += 1
return
if value > K or idx >= N:
return
sum_sub_nums(idx + 1, value)
sum_sub_nums(idx + 1, value + nums[idx])
for t in range(1, test_cases + 1):
(n, k) = map(int, inp... |
class VposConfigurationError(Exception):
pass
| class Vposconfigurationerror(Exception):
pass |
{
'includes': ['common.gypi'],
'conditions': [
['OS == "win"', {
'variables': {
'application_platform%': 'Win32',
'renderers%': ['Direct3D11', 'GL4'],
'audio%': 'XAudio2',
'input_devices%': ['DirectInput'],
},
}],
['OS == "mac"', {
'variables': {
... | {'includes': ['common.gypi'], 'conditions': [['OS == "win"', {'variables': {'application_platform%': 'Win32', 'renderers%': ['Direct3D11', 'GL4'], 'audio%': 'XAudio2', 'input_devices%': ['DirectInput']}}], ['OS == "mac"', {'variables': {'application_platform%': 'Cocoa', 'renderers%': ['GL4'], 'audio%': 'OpenAL', 'input... |
#coding:utf-8
'''
filename:exchange_keys_and_values.py
chap:4
subject:10
conditions:a dict
solution:exchanged keys and values
'''
origin_dict = {'book':['python','djang','data'],'author':'laoqi','publisher':'phei'}
def ishashable(obj):
try:
hash(obj)
return True
exce... | """
filename:exchange_keys_and_values.py
chap:4
subject:10
conditions:a dict
solution:exchanged keys and values
"""
origin_dict = {'book': ['python', 'djang', 'data'], 'author': 'laoqi', 'publisher': 'phei'}
def ishashable(obj):
try:
hash(obj)
return True
except:
... |
class Input_data():
def __init__(self):
self.s=''
def getString(self):
self.s = input()
def printString(self):
print(self.s.upper())
strobj=Input_data()
strobj.getString()
strobj.printString() | class Input_Data:
def __init__(self):
self.s = ''
def get_string(self):
self.s = input()
def print_string(self):
print(self.s.upper())
strobj = input_data()
strobj.getString()
strobj.printString() |
class Solution:
def minSessions(self, tasks: List[int], sessionTime: int) -> int:
n = len(tasks)
initial_state = int('0b'+'1'*n,2)
dp = {}
def find_dp(state):
if state in dp:
return dp[state]
if state == 0:
dp[state] = (1, 0)
... | class Solution:
def min_sessions(self, tasks: List[int], sessionTime: int) -> int:
n = len(tasks)
initial_state = int('0b' + '1' * n, 2)
dp = {}
def find_dp(state):
if state in dp:
return dp[state]
if state == 0:
dp[state] = (... |
"""
Given a binary tree, find the root-to-leaf path with the maximum sum.
"""
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_paths(root):
res = []
cur_path = []
find_max(root, res, cur_path, 0)
return res
max_sum = ... | """
Given a binary tree, find the root-to-leaf path with the maximum sum.
"""
class Treenode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_paths(root):
res = []
cur_path = []
find_max(root, res, cur_path, 0)
re... |
print('Grocery list:')
print('"add" to add items and "view" to view list')
grocery_list = []
while True:
command = input('Enter command: ')
if command == 'add':
to_add = input('Enter new item: ')
grocery_list.append(to_add)
# elif stands for "else if"
elif command == 'view':
for ... | print('Grocery list:')
print('"add" to add items and "view" to view list')
grocery_list = []
while True:
command = input('Enter command: ')
if command == 'add':
to_add = input('Enter new item: ')
grocery_list.append(to_add)
elif command == 'view':
for i in range(len(grocery_list)):
... |
class Solution:
# @return an integer
def uniquePaths(self, m, n):
if ((m == 0) or (n == 0)):
return 0
if (n > m):
return self.uniquePaths(n, m)
row = [1] * m
for i in range(1, n):
# print row
r2 = [1]
last = 1
... | class Solution:
def unique_paths(self, m, n):
if m == 0 or n == 0:
return 0
if n > m:
return self.uniquePaths(n, m)
row = [1] * m
for i in range(1, n):
r2 = [1]
last = 1
for j in range(1, m):
last = last + r... |
#
# Copyright (C) 2018 The Android Open Source Project
#
# 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 la... | layout = bool_scalar('layout', False)
i1 = input('op1', 'TENSOR_FLOAT32', '{1, 2, 2, 2}')
pad1 = parameter('paddings', 'TENSOR_INT32', '{2, 2}', [0, 0, 0, 0])
o1 = output('op4', 'TENSOR_FLOAT32', '{4, 1, 1, 2}')
model().Operation('SPACE_TO_BATCH_ND', i1, [2, 2], pad1, layout).To(o1)
quant8 = data_type_converter().Ident... |
class PrintDictResults:
def __init__(self, dict_of_sorted_words):
self.list_of_sorted_words = dict_of_sorted_words
def print_items(self, counter):
print(f'{counter + 1}. "{self.list_of_sorted_words[counter][1]}" : {self.list_of_sorted_words[counter][0]}')
def get_all_words(self):
f... | class Printdictresults:
def __init__(self, dict_of_sorted_words):
self.list_of_sorted_words = dict_of_sorted_words
def print_items(self, counter):
print(f'{counter + 1}. "{self.list_of_sorted_words[counter][1]}" : {self.list_of_sorted_words[counter][0]}')
def get_all_words(self):
... |
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
#Binary Tree
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def search(self, find_val):
"""Return True if the value
is in the tre... | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Binarytree(object):
def __init__(self, root):
self.root = node(root)
def search(self, find_val):
"""Return True if the value
is in the tree, return
... |
def iterative_levenshtein(string, target, costs=(1, 1, 1)):
"""
piglaker modified version :
return edits
iterative_levenshtein(s, t) -> ldist
ldist is the Levenshtein distance between the strings
s and t.
For all i and j, dist[i,j] will contain the Levenshtein... | def iterative_levenshtein(string, target, costs=(1, 1, 1)):
"""
piglaker modified version :
return edits
iterative_levenshtein(s, t) -> ldist
ldist is the Levenshtein distance between the strings
s and t.
For all i and j, dist[i,j] will contain the Levenshtein
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.