content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/python
#300 most common words according to google
#Source: https://github.com/first20hours/google-10000-english
#Some words that might refer to scientific information have been removed
boringWords=set(['the','of','and','to','a','in','for','is','on','that','by','this','with','i','you','it','not','or','be','a... | boring_words = set(['the', 'of', 'and', 'to', 'a', 'in', 'for', 'is', 'on', 'that', 'by', 'this', 'with', 'i', 'you', 'it', 'not', 'or', 'be', 'are', 'from', 'at', 'as', 'your', 'all', 'have', 'new', 'more', 'an', 'was', 'we', 'will', 'home', 'can', 'us', 'about', 'if', 'page', 'my', 'has', 'search', 'free', 'but', 'ou... |
{
'targets': [
{
'target_name': 'publish',
'type':'none',
'dependencies': [
'appjs'
],
'copies':[
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/',
'files': [
'<(module_root_dir)/README.md',
'<(module_root_... | {'targets': [{'target_name': 'publish', 'type': 'none', 'dependencies': ['appjs'], 'copies': [{'destination': '<(module_root_dir)/app/data/node_modules/appjs/', 'files': ['<(module_root_dir)/README.md', '<(module_root_dir)/package.json', '<(module_root_dir)/lib/']}, {'destination': '<(module_root_dir)/app/data/node_mod... |
n, m = map(int, input().split())
ruins = [list(map(int, input().split())) for _ in range(n)]
imos = [0] * (m+1)
sum_s = 0
for i in range(n):
l, r, s = ruins[i]
l -= 1
imos[l] += s
imos[r] -= s
sum_s += s
for i in range(m):
imos[i+1] += imos[i]
print(sum_s - min(imos[:-1]))
| (n, m) = map(int, input().split())
ruins = [list(map(int, input().split())) for _ in range(n)]
imos = [0] * (m + 1)
sum_s = 0
for i in range(n):
(l, r, s) = ruins[i]
l -= 1
imos[l] += s
imos[r] -= s
sum_s += s
for i in range(m):
imos[i + 1] += imos[i]
print(sum_s - min(imos[:-1])) |
def check(s, t):
v = 0
for i in range(len(t)):
if t[i] == s[v]:
v += 1
if v == len(s):
return "Yes"
return "No"
while True:
try:
s, t = input().split()
ans = check(s, t)
print(ans)
except:
break
| def check(s, t):
v = 0
for i in range(len(t)):
if t[i] == s[v]:
v += 1
if v == len(s):
return 'Yes'
return 'No'
while True:
try:
(s, t) = input().split()
ans = check(s, t)
print(ans)
except:
break |
class _descriptor(object):
def __get__(self, *_):
raise RuntimeError("more like funtime error")
class Methods(object):
ok_method = "ok"
err_method = _descriptor()
| class _Descriptor(object):
def __get__(self, *_):
raise runtime_error('more like funtime error')
class Methods(object):
ok_method = 'ok'
err_method = _descriptor() |
'''
+Build Your Dream Python Project Discord Team
Invite: https://dsc.gg/python_team
19 Feb 2021
@alexandros answer to @Subham
https://discord.com/channels/794684213697052712/794684213697052718/812231193213796362
Sublist Yielder
'''
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst):
for sublst in lst:
yield from s... | """
+Build Your Dream Python Project Discord Team
Invite: https://dsc.gg/python_team
19 Feb 2021
@alexandros answer to @Subham
https://discord.com/channels/794684213697052712/794684213697052718/812231193213796362
Sublist Yielder
"""
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst):
for sublst in lst:
yield from sub... |
#----------* CHALLENGE 35 *----------
#Ask the user to enter their name and then display their name three times.
name = input("Enter your name: ")
for i in range (1,4):
print(name+" ") | name = input('Enter your name: ')
for i in range(1, 4):
print(name + ' ') |
edibles = ["ham", "spam","eggs","nuts"]
for food in edibles:
if food == "spams":
print("No more spam please!")
break
print("Great, delicious " + food)
else:
print("I am so glad: No " + food +"!")
print("Finally, I finished stuffing myself") | edibles = ['ham', 'spam', 'eggs', 'nuts']
for food in edibles:
if food == 'spams':
print('No more spam please!')
break
print('Great, delicious ' + food)
else:
print('I am so glad: No ' + food + '!')
print('Finally, I finished stuffing myself') |
domain = 'mycompany.local'
user = 'automation@vsphere.local'
pwd = 'somepassword'
| domain = 'mycompany.local'
user = 'automation@vsphere.local'
pwd = 'somepassword' |
game = "Hello world"
#print(id(game))
def game_board(player=0, row=0, col=0, just_display=False):
game = "Change !"
#print(id(game))
print(game)
print(game)
game_board()
print(game)
#print(id(game))
| game = 'Hello world'
def game_board(player=0, row=0, col=0, just_display=False):
game = 'Change !'
print(game)
print(game)
game_board()
print(game) |
def groupnames(name_iterable):
name_dict = {}
for name in name_iterable:
key = _groupkeyfunc(name)
name_dict.setdefault(key, []).append(name)
for k, v in name_dict.iteritems():
aux = [(_sortkeyfunc(name), name) for name in v]
aux.sort()
name_dict[k] = tuple([ n for __... | def groupnames(name_iterable):
name_dict = {}
for name in name_iterable:
key = _groupkeyfunc(name)
name_dict.setdefault(key, []).append(name)
for (k, v) in name_dict.iteritems():
aux = [(_sortkeyfunc(name), name) for name in v]
aux.sort()
name_dict[k] = tuple([n for (... |
class reverse_iter:
def __init__(self, iterable) -> None:
self.iterable = iterable
self.start = len(iterable)
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start > 0:
self.start -= 1
return self.iterable[self.sta... | class Reverse_Iter:
def __init__(self, iterable) -> None:
self.iterable = iterable
self.start = len(iterable)
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start > 0:
self.start -= 1
return self.iterable[self.start]
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insertAtLast(self, data):
node = Node(data)
if self.head == None:
self.head = node
return
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert_at_last(self, data):
node = node(data)
if self.head == None:
self.head = node
return
curr_poin... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.incr = 0
def convertBST(self, root: TreeNode) -> TreeNode:
def dfs(node):
if not node:
... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.incr = 0
def convert_bst(self, root: TreeNode) -> TreeNode:
def dfs(node):
if not node:
return 0
... |
#import necessary data
df = pd.read_csv('~/lstm_test/input/nu_public_rep.csv', sep=';',
parse_dates={'dt' : ['Date', 'Time']}, infer_datetime_format=True,
low_memory=False, na_values=['nan','?'], index_col='dt')
#fill nan with the means of the columns to handle missing databases
dropi... | df = pd.read_csv('~/lstm_test/input/nu_public_rep.csv', sep=';', parse_dates={'dt': ['Date', 'Time']}, infer_datetime_format=True, low_memory=False, na_values=['nan', '?'], index_col='dt')
droping_list_all = []
for j in range(0, 7):
if not df.iloc[:, j].notnull().all():
droping_list_all.append(j)
droping_li... |
#!/usr/bin/env python
# coding: utf8
def writeResults(links, outfile):
fw = open(outfile, "w")
for link in links:
fw.write(link)
| def write_results(links, outfile):
fw = open(outfile, 'w')
for link in links:
fw.write(link) |
i = get_safe('id')
username = ""
if i != 0:
username = get('username')
username = escape_string(username)
query = 'some query'
it = execute(query + username)
| i = get_safe('id')
username = ''
if i != 0:
username = get('username')
username = escape_string(username)
query = 'some query'
it = execute(query + username) |
'''
file:except.py
exceptions for piclock
'''
class NoConfigError(Exception):
'''
No Config Error Exception
'''
class CharacterNotFound(Exception):
'''
Character not found exception
'''
class MatrixCharError(Exception):
'''
Matrix Character Error
'''
class NoMqttConfigSection... | """
file:except.py
exceptions for piclock
"""
class Noconfigerror(Exception):
"""
No Config Error Exception
"""
class Characternotfound(Exception):
"""
Character not found exception
"""
class Matrixcharerror(Exception):
"""
Matrix Character Error
"""
class Nomqttconfigsection(Exc... |
# Objectives
#
# In this stage, you should write a program that:
#
# Reads matrix A A A from the input.
# Reads matrix B B B from the input.
# Outputs their sum if it is possible to add them. Otherwise, it should output the ERROR message.
#
# Each matrix in the input is given in the following way: the first... | def same_dimensions(n_rows_a, n_columns_a, n_rows_b, n_columns_b):
return n_rows_a == n_rows_b and n_columns_a == n_columns_b
def addition(mat_a, mat_b, n_rows, n_columns):
return [[str(mat_a[i][j] + mat_b[i][j]) for j in range(n_columns)] for i in range(n_rows)]
def print_matrix(mat):
for row in mat:
... |
rows = 9
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')
| rows = 9
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('') |
# OpenWeatherMap API Key
weather_api_key = "ea45174aae3e4fc5de1af5d14f74cd81"
# Google API Key
g_key = "AIzaSyCiyVKYg3FYX0fAR2S2RGR1m-kUN947W9s" | weather_api_key = 'ea45174aae3e4fc5de1af5d14f74cd81'
g_key = 'AIzaSyCiyVKYg3FYX0fAR2S2RGR1m-kUN947W9s' |
def editDistance(str1, str2, m, n, ci=1,crm=1,crp=1):
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
... | def edit_distance(str1, str2, m, n, ci=1, crm=1, crp=1):
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif str1[i - 1] == str2[j -... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def funcion_generadora_print():
try:
print("GENERADOR: Se va a generar un PRIMER dato")
yield "valorGenerado1"
print("GENERADOR: Se va a generar un SEGUNDO dato")
yield "valorGenerado2"
print("GENERADOR: Se va a generar un TER... | def funcion_generadora_print():
try:
print('GENERADOR: Se va a generar un PRIMER dato')
yield 'valorGenerado1'
print('GENERADOR: Se va a generar un SEGUNDO dato')
yield 'valorGenerado2'
print('GENERADOR: Se va a generar un TERCER dato')
yield 'valorGenerado3'
fina... |
file_input="dump.seq_e10.mci.I12"
num=1
output=open('assign_cluster_num.out','w')
for i in open(file_input):
i=i.replace('\n','')
o=i.split()
for j in o:
output.write(j+'\t'+str(num)+'\n')
num+=1
output.close()
| file_input = 'dump.seq_e10.mci.I12'
num = 1
output = open('assign_cluster_num.out', 'w')
for i in open(file_input):
i = i.replace('\n', '')
o = i.split()
for j in o:
output.write(j + '\t' + str(num) + '\n')
num += 1
output.close() |
t=int(input('Tabuada do : '))
r1 = t * 1
r2 = t * 2
r3 = t * 3
r4 = t * 4
r5 = t * 5
r6 = t * 6
r7 = t * 7
r8 = t * 8
r9 = t * 9
r10 = t * 10
print("RESUlTADO\n------------------------")
print('{} x 1 = {}'.format(t,r1))
print('{} x 2 = {}'.format(t,r2))
print('{} x 3 = {}'.format(t,r3))
print('{} x 4 = {}'.format(t,... | t = int(input('Tabuada do : '))
r1 = t * 1
r2 = t * 2
r3 = t * 3
r4 = t * 4
r5 = t * 5
r6 = t * 6
r7 = t * 7
r8 = t * 8
r9 = t * 9
r10 = t * 10
print('RESUlTADO\n------------------------')
print('{} x 1 = {}'.format(t, r1))
print('{} x 2 = {}'.format(t, r2))
print('{} x 3 = {}'.format(t, r3))
print('{} x 4 = {}'.format... |
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
with plt.xkcd():
fig = plt.figure(figsize=(fig_w, fig_h))
my_plot(x, auditory, visual, posterior_pointwise)
plt.ti... | auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
with plt.xkcd():
fig = plt.figure(figsize=(fig_w, fig_h))
my_plot(x, auditory, visual, posterior_pointwise)
plt.tit... |
# Tutorial skipper snippet
def skip_tutorial():
MAPLE_ADMINISTARTOR = 2007
quests_to_complete = [
20820, # The City of Ereve
20821, # Knight's Orientation
20822, # The Path of Bravery
20823, # Question and Answer
20824, # Knight's Cavalier
20825, # Well-Behaved Student
20826, # Lesson 1 - Ereve History... | def skip_tutorial():
maple_administartor = 2007
quests_to_complete = [20820, 20821, 20822, 20823, 20824, 20825, 20826, 20827, 20828, 20829, 20830, 20831, 20832, 20833, 20834, 20835, 20836, 20837, 20838, 20839]
map_to_warp = 130000000
target_level = 10
sm.setSpeakerID(MAPLE_ADMINISTARTOR)
sm.remo... |
class ATM:
def __init__(self,balance,bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def show_withdrawals(self):
for withdrawal in self.withdrawals_list:
print("withdrawal: "+str(withdrawal))
def print_information(self):
print("Welcome to "+ self.bank_nam... | class Atm:
def __init__(self, balance, bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def show_withdrawals(self):
for withdrawal in self.withdrawals_list:
print('withdrawal: ' + str(withdrawal))
def print_information(se... |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# brute force
ar = nums1 + nums2
ar.sort()
n = len(ar)
median = ar[n//2]
if n%2 != 0:
return median
else:
return (median + ... | class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
ar = nums1 + nums2
ar.sort()
n = len(ar)
median = ar[n // 2]
if n % 2 != 0:
return median
else:
return (median + ar[n // 2 - 1]) / 2 |
defines = {}
specials = {}
defines.update(globals()["__builtins__"])
def define(fnc):
defines[fnc.__name__] = fnc
return fnc
def rename(name):
def deco(fnc):
fnc.__name__ = name
return define(fnc)
return deco
def special(fnc):
specials[fnc.__name__] = fnc
return fnc
def ... | defines = {}
specials = {}
defines.update(globals()['__builtins__'])
def define(fnc):
defines[fnc.__name__] = fnc
return fnc
def rename(name):
def deco(fnc):
fnc.__name__ = name
return define(fnc)
return deco
def special(fnc):
specials[fnc.__name__] = fnc
return fnc
def regi... |
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[i] < array[j]:
array[i], array[j] = array[j], array[i]
j -= 1
i -= 1
return array
def test_insertion_sort_simple():
assert insertion_sort([4... | def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[i] < array[j]:
(array[i], array[j]) = (array[j], array[i])
j -= 1
i -= 1
return array
def test_insertion_sort_simple():
assert insertion_sort... |
def generatorA(value, stop):
i = 0
while i < stop:
value = (value * 16807) % 2147483647
yield value
i += 1
def generatorB(value, stop):
i = 0
while i < stop:
value = (value * 48271) % 2147483647
yield value
i += 1
def generatorAPart2(value, stop):
i... | def generator_a(value, stop):
i = 0
while i < stop:
value = value * 16807 % 2147483647
yield value
i += 1
def generator_b(value, stop):
i = 0
while i < stop:
value = value * 48271 % 2147483647
yield value
i += 1
def generator_a_part2(value, stop):
i ... |
# https://www.codechef.com/ELE32018/problems/JACKJILL
t=int(input())
for _ in range(t):
n,k,d=[int(x) for x in input().strip().split()]
a=[int(x) for x in input().strip().split()]
b=[int(x) for x in input().strip().split()]
flag=0
res1=0
res2=0
for i in range(k):
res1 += a[i]
res2 += b[i]
if(re... | t = int(input())
for _ in range(t):
(n, k, d) = [int(x) for x in input().strip().split()]
a = [int(x) for x in input().strip().split()]
b = [int(x) for x in input().strip().split()]
flag = 0
res1 = 0
res2 = 0
for i in range(k):
res1 += a[i]
res2 += b[i]
if res1 + res2 >= ... |
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
ans = 0
cnt = 0
for i in range(len(nums)):
if nums[i] == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
| class Solution(object):
def find_max_consecutive_ones(self, nums):
ans = 0
cnt = 0
for i in range(len(nums)):
if nums[i] == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans |
# Accept one int and one float type value & display average
a = int(input("Enter int no.: "))
b = float(input("Enter float no.: "))
c = (a+b)/2
print(f"Average value {c}")
| a = int(input('Enter int no.: '))
b = float(input('Enter float no.: '))
c = (a + b) / 2
print(f'Average value {c}') |
class Solution:
def minimizeError(self, prices: List[str], target: int) -> str:
# A[i] := (costCeil - costFloor, costCeil, costFloor)
# the lower the costCeil - costFloor, the cheaper to ceil it
A = []
sumFloored = 0
sumCeiled = 0
for price in map(float, prices):
floored = math.floor(pr... | class Solution:
def minimize_error(self, prices: List[str], target: int) -> str:
a = []
sum_floored = 0
sum_ceiled = 0
for price in map(float, prices):
floored = math.floor(price)
ceiled = math.ceil(price)
sum_floored += floored
sum_ce... |
# GENERATED VERSION FILE
# TIME: Mon Oct 11 04:02:23 2021
__version__ = '1.2.0+f83fd55'
short_version = '1.2.0'
version_info = (1, 2, 0)
| __version__ = '1.2.0+f83fd55'
short_version = '1.2.0'
version_info = (1, 2, 0) |
values = input("Enter comma separated values: ")
list = values.split(",")
tuple = tuple(list)
#this is a forked branch
print("list: {}".format(list))
print("tuple: {}".format(tuple))
| values = input('Enter comma separated values: ')
list = values.split(',')
tuple = tuple(list)
print('list: {}'.format(list))
print('tuple: {}'.format(tuple)) |
def add_replicaset(instance, alias, roles, servers,
status='healthy', all_rw=False, weight=None):
r_uuid = '{}-uuid'.format(alias)
r_servers = []
for s in servers: # servers = ['alias-1', 'alias-2']
r_servers.append({
'alias': s,
'uuid': '{}-uuid'.format(s... | def add_replicaset(instance, alias, roles, servers, status='healthy', all_rw=False, weight=None):
r_uuid = '{}-uuid'.format(alias)
r_servers = []
for s in servers:
r_servers.append({'alias': s, 'uuid': '{}-uuid'.format(s), 'uri': '{}-uri'.format(s), 'status': 'healthy', 'replicaset': {'uuid': r_uuid... |
DEBUG = True
SECRET_KEY = "kasih-tau-gak-ya"
BUNDLE_ERRORS = True
MONGO_HOST = 'mongo'
MONGO_DBNAME = 'news-api'
MONGO_PORT = 27017
JSONIFY_PRETTYPRINT_REGULAR = False | debug = True
secret_key = 'kasih-tau-gak-ya'
bundle_errors = True
mongo_host = 'mongo'
mongo_dbname = 'news-api'
mongo_port = 27017
jsonify_prettyprint_regular = False |
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
'''
T: O(n log n), n = number of words
S: O(n)
'''
for punc in "!?',;.":
paragraph = paragraph.replace(punc, ' ')
words = paragraph.lower().strip().split()
... | class Solution:
def most_common_word(self, paragraph: str, banned: List[str]) -> str:
"""
T: O(n log n), n = number of words
S: O(n)
"""
for punc in "!?',;.":
paragraph = paragraph.replace(punc, ' ')
words = paragraph.lower().strip().split()
banne... |
# configuration file
TRAINING_FILE_ORIGINAL = '../mnist_train.csv'
TRAINING_FILE = '../input/mnist_train_folds.csv'
TESTING_FILE = '../input/mnist_test.csv'
MODEL_OUTPUT = "../models/" | training_file_original = '../mnist_train.csv'
training_file = '../input/mnist_train_folds.csv'
testing_file = '../input/mnist_test.csv'
model_output = '../models/' |
__all__ = [
"BoundHandler",
"ClassHook",
"Handler",
"Hook",
"Hookable",
"HookableMeta",
"HookDescriptor",
"InstanceHook",
"hookable",
]
| __all__ = ['BoundHandler', 'ClassHook', 'Handler', 'Hook', 'Hookable', 'HookableMeta', 'HookDescriptor', 'InstanceHook', 'hookable'] |
class gen_config(object):
vocab_size = 35000
train_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/"
data_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/"
buckets = [(5, 10), (10, 15), (20, 25), (40, 50)] | class Gen_Config(object):
vocab_size = 35000
train_dir = '/home/ssc/project/dataset/dataset/weibo/v0.0/'
data_dir = '/home/ssc/project/dataset/dataset/weibo/v0.0/'
buckets = [(5, 10), (10, 15), (20, 25), (40, 50)] |
#!/usr/bin/env python
# Assumption for the star format:
# contain one or more 'data_*' blocks, for each block,
# either
'''
data_*
loop_
item1 #1
...
itemn #n
item1_data ... itemn_data
...
item1_data ... itemn_data
'''
# or
'''
data_*
item1 item1_data
...
itemn itemn_data
'''
def star_data(star):
# return 2 d... | """
data_*
loop_
item1 #1
...
itemn #n
item1_data ... itemn_data
...
item1_data ... itemn_data
"""
'\n\ndata_*\n\nitem1 item1_data\n...\nitemn itemn_data\n\n'
def star_data(star):
data_dict = {}
with open(star) as read:
for (i, line) in enumerate(read.readlines()):
if line[:5] == 'data_'... |
#
# PySNMP MIB module TRANGOP5830S-RU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGOP5830S-RU-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:19:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, constraints_intersection, value_size_constraint) ... |
class CarrinhoCompras:
def __init__(self):
self.produtos = []
def insere_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
... | class Carrinhocompras:
def __init__(self):
self.produtos = []
def insere_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
... |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '8.3.beta3'
date = '2018-05-27'
| version = '8.3.beta3'
date = '2018-05-27' |
class Judge:
PAPER_LIMIT = 7
def __init__(
self,
judge_id,
first,
last,
email,
phone,
preferred_categories,
is_paper_reviewer,
presentation_availability,
):
self.judge_id = judge_id # int
self.first = first # str
... | class Judge:
paper_limit = 7
def __init__(self, judge_id, first, last, email, phone, preferred_categories, is_paper_reviewer, presentation_availability):
self.judge_id = judge_id
self.first = first
self.last = last
self.email = email
self.phone = phone
self.prefe... |
class dispatcher:
name = 'dispatcher'
def __init__(self, function_to_exec):
self.function = function_to_exec
return self.function
def get_name(self):
return self.name
def function_one(a,b):
return a + b
def function_two():
return 'function two' | class Dispatcher:
name = 'dispatcher'
def __init__(self, function_to_exec):
self.function = function_to_exec
return self.function
def get_name(self):
return self.name
def function_one(a, b):
return a + b
def function_two():
return 'function two' |
class UniformExchange(object):
def __init__(self, A):
if not isinstance(A, (float, int)) or A <= 0:
raise ValueError('Exchange constant must be positive float/int.')
else:
self.A = A
def get_mif(self):
# Create mif string.
mif = '# UniformExchange\n'
... | class Uniformexchange(object):
def __init__(self, A):
if not isinstance(A, (float, int)) or A <= 0:
raise value_error('Exchange constant must be positive float/int.')
else:
self.A = A
def get_mif(self):
mif = '# UniformExchange\n'
mif += 'Specify Oxs_Uni... |
# model
model = Model()
i1 = Input("op1", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}, 0.8, 5")
i2 = Output("op2", "TENSOR_QUANT8_ASYMM", "{1, 3, 3, 1}, 0.8, 5")
w = Int32Scalar("width", 3)
h = Int32Scalar("height", 3)
model = model.Operation("RESIZE_BILINEAR", i1, w, h).To(i2)
# Example 1. Input in operand 0,
input0 = {i1: ... | model = model()
i1 = input('op1', 'TENSOR_QUANT8_ASYMM', '{1, 2, 2, 1}, 0.8, 5')
i2 = output('op2', 'TENSOR_QUANT8_ASYMM', '{1, 3, 3, 1}, 0.8, 5')
w = int32_scalar('width', 3)
h = int32_scalar('height', 3)
model = model.Operation('RESIZE_BILINEAR', i1, w, h).To(i2)
input0 = {i1: [1, 1, 2, 2]}
output0 = {i2: [1, 1, 1, 2... |
def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / {b}")
return a / b
a = float(input("input a:"))
b = float(... | def add(a, b):
print(f'ADDING {a} + {b}')
return a + b
def subtract(a, b):
print(f'SUBTRACTING {a} - {b}')
return a - b
def multiply(a, b):
print(f'MULTIPLYING {a} * {b}')
return a * b
def divide(a, b):
print(f'DIVIDING {a} / {b}')
return a / b
a = float(input('input a:'))
b = float(i... |
# Description: Pass Statement in Python
# Pass statement in for loop
for var in range(5):
pass
# Pass statement in a while loop
while True:
pass # Busy-wait for keyboard interrupt (Ctrl + C)
# This is commonly used for creating minimal classes:
class MyEmptyClass:
pass
# Pass can also be ... | for var in range(5):
pass
while True:
pass
class Myemptyclass:
pass
def define_a_function():
pass |
number_dict = {
"0" : {
"color" : (187,173,160),
"font_size" : 45,
"backgroud_color" : (205,193,180),
"coordinate" : [(0,0), (0,0), (0,0), (0,0)]
},
"2" : {
"color" : (119, 110, 101),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (238, 228, 218),
"coordinate" : [(40,10), (30,3), (25,2), (22,3)]
},
"4... | number_dict = {'0': {'color': (187, 173, 160), 'font_size': 45, 'backgroud_color': (205, 193, 180), 'coordinate': [(0, 0), (0, 0), (0, 0), (0, 0)]}, '2': {'color': (119, 110, 101), 'font_size': [70, 60, 50, 40], 'backgroud_color': (238, 228, 218), 'coordinate': [(40, 10), (30, 3), (25, 2), (22, 3)]}, '4': {'color': (11... |
def eqindexMultiPass(data):
"Multi pass"
for i in range(len(data)):
suml, sumr = sum(data[:i]), sum(data[i+1:])
if suml == sumr:
yield i
| def eqindex_multi_pass(data):
"""Multi pass"""
for i in range(len(data)):
(suml, sumr) = (sum(data[:i]), sum(data[i + 1:]))
if suml == sumr:
yield i |
class languages():
def __init__(self, fDic):
self.fDic = fDic
self.scripts = set(self.fDic.scripts)
self.scripts.discard('dflt')
def languageSyntax(self, script, language):
return 'languagesystem %s %s;' %(script, language)
def syntax(self):
result = [self.language... | class Languages:
def __init__(self, fDic):
self.fDic = fDic
self.scripts = set(self.fDic.scripts)
self.scripts.discard('dflt')
def language_syntax(self, script, language):
return 'languagesystem %s %s;' % (script, language)
def syntax(self):
result = [self.language... |
n = int(input())
for i in range(1,n+1):
temp = n
for j in range(1,i):
print(temp,end="")
temp = temp -1
for j in range(1,(2*n) - (2*i) + 2):
print(n-i+1,end="")
for j in range(1,i):
temp = temp+1
print(temp,end="")
print()
for i in range(n-1,0,-1):
temp ... | n = int(input())
for i in range(1, n + 1):
temp = n
for j in range(1, i):
print(temp, end='')
temp = temp - 1
for j in range(1, 2 * n - 2 * i + 2):
print(n - i + 1, end='')
for j in range(1, i):
temp = temp + 1
print(temp, end='')
print()
for i in range(n - 1,... |
class Solution:
def shortestPalindrome(self, s: str) -> str:
temp = s + '#' + s[::-1]
i = 1
l = 0
lps = [0] * len(temp)
while i < len(temp):
if temp[i] == temp[l]:
lps[i] = l + 1
i += 1
l += 1
elif l != 0... | class Solution:
def shortest_palindrome(self, s: str) -> str:
temp = s + '#' + s[::-1]
i = 1
l = 0
lps = [0] * len(temp)
while i < len(temp):
if temp[i] == temp[l]:
lps[i] = l + 1
i += 1
l += 1
elif l !=... |
l1 = [1, 3, 5, 7, 9] # list mutable (read write)
t1 = (1, 3, 5, 7, 9) # tuple imutable (read only)
def f(x):
x.append(29)
f(l1)
print(l1)
f(t1)
print(t1)
| l1 = [1, 3, 5, 7, 9]
t1 = (1, 3, 5, 7, 9)
def f(x):
x.append(29)
f(l1)
print(l1)
f(t1)
print(t1) |
# A list contains authorized users' discord IDs.
OWNER = 184335517947658240 # foxfair
# Staff
AUTHORIZED = [
OWNER,
129405976020385792, # Auri
423991805156261889, # Kim
699053180079702098, # Gelica
266289895415218177, # Yang
294058604854509589, # Giana
107209352816914432, # Tooch
... | owner = 184335517947658240
authorized = [OWNER, 129405976020385792, 423991805156261889, 699053180079702098, 266289895415218177, 294058604854509589, 107209352816914432, 97145923691347968, 137798184721186817]
send_msg_channels = [725807955559055451] |
number = [i for i in range(1, 3001330+1)]
# number = [i for i in range(1, 10)]
number2 = number[:]
last = len(number) % 2 != 0
while len(number) > 1:
next_last = len(number) % 2 != last
number = [j for i, j in enumerate(number) if i % 2 != last]
last = next_last
print('#1', number[0])
number = number2
... | number = [i for i in range(1, 3001330 + 1)]
number2 = number[:]
last = len(number) % 2 != 0
while len(number) > 1:
next_last = len(number) % 2 != last
number = [j for (i, j) in enumerate(number) if i % 2 != last]
last = next_last
print('#1', number[0])
number = number2
while len(number) > 1:
pop = set()... |
class PagingModifier:
def __init__(self,
Id: int = None,
End: int = None,
Start: int = None,
Limit: int = None,
):
self.Id = Id
self.Start = Start
self.End = End
self.Limit = Limit
| class Pagingmodifier:
def __init__(self, Id: int=None, End: int=None, Start: int=None, Limit: int=None):
self.Id = Id
self.Start = Start
self.End = End
self.Limit = Limit |
employee_file=open("employee.txt","w") #write mode- erases previous content
employee_file.write("David - Software Developer")
print(employee_file.readable())
#print(employee_file.read())
employee_file.close()
#David - Software Developer
# previous data and content is vanished | employee_file = open('employee.txt', 'w')
employee_file.write('David - Software Developer')
print(employee_file.readable())
employee_file.close() |
__author__ = 'Lena'
class Group:
def __init__(self, name, header, footer):
self.name=name
self.header=header
self.footer=footer
| __author__ = 'Lena'
class Group:
def __init__(self, name, header, footer):
self.name = name
self.header = header
self.footer = footer |
TICKET_PRODUCTS = '''
query getTicketProducts {
tutorialProducts {
id
type
name
nameKo
nameEn
desc
descKo
descEn
warning
warningKo
warningEn
startAt
finishAt
total
remainingCount
isSoldOut
owner {
profile {
name
nameKo
n... | ticket_products = '\nquery getTicketProducts {\n tutorialProducts {\n id\n type\n name\n nameKo\n nameEn\n desc\n descKo\n descEn\n warning\n warningKo\n warningEn\n startAt\n finishAt\n total\n remainingCount\n isSoldOut\n owner {\n profile {\n name\n ... |
# This resets variables every time the Supreme While Loop is reset
# If you tried to mess around with this code, you'll find results/errors on the second time the While Loop is executed
# Messing with this code will generally not break anything on the first topic that Indra talks About
yesnorep = True
ignoreinteract =... | yesnorep = True
ignoreinteract = False
repeating = 0
cussed = False
sensitive = False
topicdone = False
nevermind = False
if ignoreinteract == False:
interactions = interactions + 1
if loveBonus == 3 and interest < 75:
print('Hey, ' + name + '.')
sleep(1.5)
print("Recently I can't help but feel that all... |
__author__ = "Lucas Grulich (grulich@uni-mainz.de)"
__version__ = "0.0.14"
# --- Globals ----------------------------------------------------------------------------------------------------------
MONOSCALE_SHADOWLEVEL = 1
OAP_FILE_EXTENSION = ".oap"
DEFAULT_TYPE = "ARRAY2D"
SLICE_SIZE = 64
# --- Markers -------------... | __author__ = 'Lucas Grulich (grulich@uni-mainz.de)'
__version__ = '0.0.14'
monoscale_shadowlevel = 1
oap_file_extension = '.oap'
default_type = 'ARRAY2D'
slice_size = 64
marker = {'poisson': 7, 'flood_fill': 8}
color = {0: 0, 1: 100, 2: 200, 3: 255, MARKER['poisson']: 50}
undefined = b'u'
indefinable = b'i'
erroneous =... |
# -*- coding: utf-8 -*-
class Java(object):
KEY = 'java'
LABEL = 'Java'
DEPENDENCIES = ['java', 'javac']
TEMP_DIR = 'java'
SUFFIX = '.java'
# javac {class_path} tmp/Estimator.java
# class_path = '-cp ./gson.jar'
CMD_COMPILE = 'javac {class_path} {src_dir}/{src_file}'
# java {cl... | class Java(object):
key = 'java'
label = 'Java'
dependencies = ['java', 'javac']
temp_dir = 'java'
suffix = '.java'
cmd_compile = 'javac {class_path} {src_dir}/{src_file}'
cmd_execute = 'java {class_path} {dest_dir}/{dest_file}' |
#Dictionaries Challenge 22: Database Admin Program
print("Welcome to the Database Admin Program")
#Create a dictionary to hold all username:password key-value pairs
log_on_information = {
'mooman74':'alskes145',
'meramo1986':'kehns010101',
'nickyD':'world1star',
'george2':'booo3oha',
'admin00':'a... | print('Welcome to the Database Admin Program')
log_on_information = {'mooman74': 'alskes145', 'meramo1986': 'kehns010101', 'nickyD': 'world1star', 'george2': 'booo3oha', 'admin00': 'admin1234'}
username = input('Enter your username: ')
if username in log_on_information.keys():
password = input('Enter your password:... |
class Inventory:
def __init__(self):
self._prisonKeys = False
self._sunflowerSeeds = False
self._guardiansMoney = False
self._guardiansSword = False
self._dragonsKey = False
@property
def prison_keys(self):
return self._prisonKeys
@prison_keys.setter
... | class Inventory:
def __init__(self):
self._prisonKeys = False
self._sunflowerSeeds = False
self._guardiansMoney = False
self._guardiansSword = False
self._dragonsKey = False
@property
def prison_keys(self):
return self._prisonKeys
@prison_keys.setter
... |
def snail(array):
temp_list = []
if array and len(array) > 1:
if isinstance(array[0], list):
temp_list.extend(array[0])
else:
temp_list.append(array[0])
array.pop(0)
for lis_index in range(len(array)):
temp_list.append(array[lis_index][-1])
... | def snail(array):
temp_list = []
if array and len(array) > 1:
if isinstance(array[0], list):
temp_list.extend(array[0])
else:
temp_list.append(array[0])
array.pop(0)
for lis_index in range(len(array)):
temp_list.append(array[lis_index][-1])
... |
def get_scale_factor(input_units, sampling_rate=None):
if input_units=='ms':
return 1e3
elif input_units=='s':
return 1
elif input_units=='samples':
if sampling_rate is None:
raise ValueError('Must provide sampling_rate if input_units=="samples"')
return sampling_... | def get_scale_factor(input_units, sampling_rate=None):
if input_units == 'ms':
return 1000.0
elif input_units == 's':
return 1
elif input_units == 'samples':
if sampling_rate is None:
raise value_error('Must provide sampling_rate if input_units=="samples"')
return... |
config = {'luna_raw':'/root/ssd_data/LUNA/',
'luna_data':'/research/dept8/jzwang/dataset/LUNA16/combined/',
'preprocess_result_path':'/research/dept8/jzwang/dataset/HKU/preprocessed/numpy/',
'luna_abbr':'./labels/shorter.csv',
'luna_label':'./labels/lunaqualified_all.csv',
... | config = {'luna_raw': '/root/ssd_data/LUNA/', 'luna_data': '/research/dept8/jzwang/dataset/LUNA16/combined/', 'preprocess_result_path': '/research/dept8/jzwang/dataset/HKU/preprocessed/numpy/', 'luna_abbr': './labels/shorter.csv', 'luna_label': './labels/lunaqualified_all.csv', 'luna_candidate_label': './labels/luna_ca... |
# https://www.codechef.com/SEPT20B/problems/TREE2
T = int(input())
for _ in range(T):
x = input()
l = list(map(int, input().split()))
s = set(l)
m = min(s)
ops = len(s)
if m: print(ops)
else: print(ops-1)
| t = int(input())
for _ in range(T):
x = input()
l = list(map(int, input().split()))
s = set(l)
m = min(s)
ops = len(s)
if m:
print(ops)
else:
print(ops - 1) |
class SessionGenerator(object):
session: "TrainingSession"
def __init__(self,
training_cycle,
fatigue_rating,
current_training_max):
load_size = self.determine_load_size(
fatigue_rating,
training_cycle.previous_large_load_train... | class Sessiongenerator(object):
session: 'TrainingSession'
def __init__(self, training_cycle, fatigue_rating, current_training_max):
load_size = self.determine_load_size(fatigue_rating, training_cycle.previous_large_load_training_max, current_training_max)
self.session = self.generate_session(t... |
filename = "CCaseScene.unity"
subA = ("<<<<<<< Updated upstream\n")
subB = ("=======\n")
subC = (">>>>>>> Stashed changes\n")
with open(filename, 'r+') as f:
data = f.read()
count = 0
# Iterate starts
while True:
# Find indexes
start, end = data.index(subA), data.index(subB)
# Slice string
... | filename = 'CCaseScene.unity'
sub_a = '<<<<<<< Updated upstream\n'
sub_b = '=======\n'
sub_c = '>>>>>>> Stashed changes\n'
with open(filename, 'r+') as f:
data = f.read()
count = 0
while True:
(start, end) = (data.index(subA), data.index(subB))
data = data[:start] + data[end:]
data =... |
# New feature in Python 3.8, assignment expressions (known as the walrus operator)
# Assignment expression are written with a new notation (:=). This operator is often
# called the walrus operator as it resembles the eyes and tusks of a walrus on its side.
#
# Video explanation: https://realpython.com/lessons/ass... | walrus = True
print(walrus)
print((walrus := True))
inputs = list()
while True:
current = input('Write something: ')
if current == 'quit':
break
inputs.append(current)
inputs = list()
while (current := input('Write something: ')) != 'quit':
inputs.append(current) |
def solve():
A = int(input())
row = (A + 2) // 3 # from (100 100) to (100+row-1, 100)
board = []
for _ in range(1000):
board.append([0]*1000)
I = J = 100 # [2, 999]
for _ in range(1000):
print('{} {}'.format(I, J))
I_, J_ = map(int, input().split())
if I_ == 0 and... | def solve():
a = int(input())
row = (A + 2) // 3
board = []
for _ in range(1000):
board.append([0] * 1000)
i = j = 100
for _ in range(1000):
print('{} {}'.format(I, J))
(i_, j_) = map(int, input().split())
if I_ == 0 and J_ == 0:
return
board[I... |
deleteObject = True
editObject = True
getObject = {'id': 1234,
'fingerprint': 'aa:bb:cc:dd',
'label': 'label',
'notes': 'notes',
'key': 'ssh-rsa AAAAB3N...pa67 user@example.com'}
createObject = getObject
getAllObjects = [getObject]
| delete_object = True
edit_object = True
get_object = {'id': 1234, 'fingerprint': 'aa:bb:cc:dd', 'label': 'label', 'notes': 'notes', 'key': 'ssh-rsa AAAAB3N...pa67 user@example.com'}
create_object = getObject
get_all_objects = [getObject] |
'''
Created on Apr 27, 2015
@author: DHawkins
'''
POSITION = [
{'abbrev': 'al', 'column': 7, 'row': 7, 'state': 'alabama'},
{'abbrev': 'ak', 'column': 1, 'row': 8, 'state': 'alaska'},
{'abbrev': 'az', 'column': 2, 'row': 6, 'state': 'arizona'},
{'abbrev': 'ar', 'column': 5, 'row': 6, 'state': 'arkansa... | """
Created on Apr 27, 2015
@author: DHawkins
"""
position = [{'abbrev': 'al', 'column': 7, 'row': 7, 'state': 'alabama'}, {'abbrev': 'ak', 'column': 1, 'row': 8, 'state': 'alaska'}, {'abbrev': 'az', 'column': 2, 'row': 6, 'state': 'arizona'}, {'abbrev': 'ar', 'column': 5, 'row': 6, 'state': 'arkansas'}, {'abbrev': 'c... |
# A ring buffer is a non-growable buffer with a fixed size. When the ring buffer is full
# and a new element is inserted, the oldest element in the ring buffer is overwritten with
# the newest element. This kind of data structure is very useful for use cases such as
# storing logs and history information, where you typ... | class Ringbuffer:
def __init__(self, capacity):
self.capacity = capacity
self.current = 0
self.storage = [None] * capacity
def append(self, item):
if self.current == self.capacity:
self.current = 0
self.storage[self.current] = item
self.current += 1
... |
HEADER_JSON_CONTENT = {
'Content-type': 'application/json', 'Accept': 'text/plain'
}
SUCCESS_MESSAGES = {
201: "Created Propertie: {title} in {provinces} province(s)",
}
ERROR_MESSAGES = {
422: {
'message': "Please, verify data for register this propertie"
},
404: {
'message': "Pr... | header_json_content = {'Content-type': 'application/json', 'Accept': 'text/plain'}
success_messages = {201: 'Created Propertie: {title} in {provinces} province(s)'}
error_messages = {422: {'message': 'Please, verify data for register this propertie'}, 404: {'message': 'Provide an valid ID to retrive the queried propert... |
jogador = {}
soma = 0
gols = []
jogador['nome'] = str(input('Nome do Jogador: '))
jogador['njogos'] = int(input(f'Quanta partidas {jogador["nome"]} Jogou?'))
for v in range(0, jogador['njogos']):
temp = int(input(f'Quantos gols na partida {v}? '))
soma += temp
gols.append(temp)
jogador['gols'] = gols[:]
p... | jogador = {}
soma = 0
gols = []
jogador['nome'] = str(input('Nome do Jogador: '))
jogador['njogos'] = int(input(f"Quanta partidas {jogador['nome']} Jogou?"))
for v in range(0, jogador['njogos']):
temp = int(input(f'Quantos gols na partida {v}? '))
soma += temp
gols.append(temp)
jogador['gols'] = gols[:]
pri... |
# -*- coding: utf-8 -*-
# This file is generated from NI-TClk API metadata version 255.0.0d0
functions = {
'ConfigureForHomogeneousTriggers': {
'documentation': {
'description': '\nConfigures the attributes commonly required for the TClk synchronization\nof device sessions with homogeneous trigg... | functions = {'ConfigureForHomogeneousTriggers': {'documentation': {'description': '\nConfigures the attributes commonly required for the TClk synchronization\nof device sessions with homogeneous triggers in a single PXI chassis or\na single PC. Use niTClk_ConfigureForHomogeneousTriggers to configure\nthe attributes for... |
print(any([True, 1, ""]))
print(all([True, 1, ""]))
print(dict(zip([1, 2, 3], "abc")))
| print(any([True, 1, '']))
print(all([True, 1, '']))
print(dict(zip([1, 2, 3], 'abc'))) |
top = [2,3,4,5,6]
# lst = [1,0,0,4,5]
lst = [1,2,3,4,5]
k = [9,9,0,0,0]
lst1 = [8,3,9,6,4,7,5,2,1]
lst2 = [10,11,12,8,3,9,6,4,7,5,2,1]
lst3 = [8,9,3,6,7,4,5,2,1]
lst4 = [8,3,9,6,4,7,5,2,1]
k = [9,0,0,0,0,0,0,0]
k = k[::-1]
def main():
subtract_1(lst1, k)
def helper1(lst, start):
new_lst = lst[start:]
ind... | top = [2, 3, 4, 5, 6]
lst = [1, 2, 3, 4, 5]
k = [9, 9, 0, 0, 0]
lst1 = [8, 3, 9, 6, 4, 7, 5, 2, 1]
lst2 = [10, 11, 12, 8, 3, 9, 6, 4, 7, 5, 2, 1]
lst3 = [8, 9, 3, 6, 7, 4, 5, 2, 1]
lst4 = [8, 3, 9, 6, 4, 7, 5, 2, 1]
k = [9, 0, 0, 0, 0, 0, 0, 0]
k = k[::-1]
def main():
subtract_1(lst1, k)
def helper1(lst, start):
... |
day = '2'
with open(f'2015/data/day_{day}.in', 'r', encoding='utf-8') as f:
content = f.read().strip().split('\n')
def make_tup(row):
i = row.index('x')
a = row[:i]
row = row[i + 1:]
i = row.index('x')
b = row[:i]
c = row[i + 1:]
return int(a), int(b), int(c)
def area(a, b, c):
re... | day = '2'
with open(f'2015/data/day_{day}.in', 'r', encoding='utf-8') as f:
content = f.read().strip().split('\n')
def make_tup(row):
i = row.index('x')
a = row[:i]
row = row[i + 1:]
i = row.index('x')
b = row[:i]
c = row[i + 1:]
return (int(a), int(b), int(c))
def area(a, b, c):
r... |
def translate():
return "jQuery(document).ready(function(){jQuery('body').translate('%s');});" % request.args(0).split('.')[0]
def changeLanguage():
session._language = request.args[0]
#T.force(request.args[0])
#T.set_current_languages(str(request.args[0]),str(request.args[0]) + '-' + str(req... | def translate():
return "jQuery(document).ready(function(){jQuery('body').translate('%s');});" % request.args(0).split('.')[0]
def change_language():
session._language = request.args[0]
if len(request.args) == 5:
redirect(url(request.args[1], request.args[2], request.args[3], args=request.args[4]))... |
def main():
square = int(input("Calculate square root of: "))
print("square root of " + str(square) + " is " +
str(binsquareroot(square)))
def binsquareroot(square):
if square < 1:
return "an imaginair number"
if square == 1:
return 1
left = 1
right = square
mid =... | def main():
square = int(input('Calculate square root of: '))
print('square root of ' + str(square) + ' is ' + str(binsquareroot(square)))
def binsquareroot(square):
if square < 1:
return 'an imaginair number'
if square == 1:
return 1
left = 1
right = square
mid = right
... |
# helpers.py
def url_join(*args, end_slash = True):
strip_args = [str(a).rstrip("/") for a in args]
url = "/".join(strip_args)
if end_slash and not url.endswith("/"):
url = url + "/"
return url
| def url_join(*args, end_slash=True):
strip_args = [str(a).rstrip('/') for a in args]
url = '/'.join(strip_args)
if end_slash and (not url.endswith('/')):
url = url + '/'
return url |
#
# Copyright (c) 2010-2016, Fabric Software Inc. All rights reserved.
#
class DirQualTypeInfo:
def __init__(self, dir_qual, type_info):
self.dir_qual = dir_qual
self.type_info = type_info
@property
def dq(self):
return self.dir_qual
@property
def ti(self):
return self.type_info
def g... | class Dirqualtypeinfo:
def __init__(self, dir_qual, type_info):
self.dir_qual = dir_qual
self.type_info = type_info
@property
def dq(self):
return self.dir_qual
@property
def ti(self):
return self.type_info
def get_desc(self):
return '%s:%s' % (self.di... |
grade = 95
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
elif grade >= 60:
print("D")
else:
print("F") | grade = 95
if grade >= 90:
print('A')
elif grade >= 80:
print('B')
elif grade >= 70:
print('C')
elif grade >= 60:
print('D')
else:
print('F') |
def gen_src(count):
for i in range(1, count):
data = "".join(["%d" % x for x in range(1, 10000)])
native.genrule(
name = "generated_class_%d" % i,
out = "Class%d.java" % i,
bash = "echo -e 'package gen;\npublic class Class%d { static String data = \"%s\"; }' > $OU... | def gen_src(count):
for i in range(1, count):
data = ''.join(['%d' % x for x in range(1, 10000)])
native.genrule(name='generated_class_%d' % i, out='Class%d.java' % i, bash='echo -e \'package gen;\npublic class Class%d { static String data = "%s"; }\' > $OUT' % (i, data))
native.android_libr... |
##Exemplo retirado do site http://code.tutsplus.com/tutorials/beginning-test-driven-development-in-python--net-30137
##//lhekheklqhlekhqkehqkehqkhelqw
##//ljkfhjdhfjkdhfkjlsdhlfkhslkjkljdflksgflsgdf
##//lkhdsklfskfgshgfsjhgfs
class Calculator(object):
def add(self, x, y):
number_types = (int, float, compl... | class Calculator(object):
def add(self, x, y):
number_types = (int, float, complex)
if instance(x, number_types) and instance(y, number_types):
return x + y
else:
raise ValueError
def sub(self, x, y):
number_types = (int, float, complex)
if insta... |
'''
Prompt:
Write a function bestSum(targetSum, numbers) that takes
in a targetSum and an array of numbers as arguments.
The function should return an array containing the
shortest combination of numbers that add up to exactly the targetSum.
If there is a tie for the shotest combination, you may return any of the sh... | """
Prompt:
Write a function bestSum(targetSum, numbers) that takes
in a targetSum and an array of numbers as arguments.
The function should return an array containing the
shortest combination of numbers that add up to exactly the targetSum.
If there is a tie for the shotest combination, you may return any of the sh... |
apps_details = [
{
"app": "Learning xc functional from experimental data",
"repo": "https://github.com/mfkasim1/xcnn", # leave blank if no repo available
# leave blank if no paper available, strongly suggested to link to open-access paper
"paper": "https://arxiv.org/abs/2102.04229",... | apps_details = [{'app': 'Learning xc functional from experimental data', 'repo': 'https://github.com/mfkasim1/xcnn', 'paper': 'https://arxiv.org/abs/2102.04229'}, {'app': 'Basis optimization', 'repo': 'https://github.com/diffqc/dqc-apps/tree/main/01-basis-opt', 'paper': ''}, {'app': 'Alchemical perturbation', 'repo': '... |
class ChainMap:
def __init__(self, *maps):
if maps:
self.maps = list(maps)
else:
self.maps = [{}]
def __getitem__(self, k):
for m in self.maps:
if k in m:
return m[k]
raise KeyError(k)
def __setitem__(self, k, v):
... | class Chainmap:
def __init__(self, *maps):
if maps:
self.maps = list(maps)
else:
self.maps = [{}]
def __getitem__(self, k):
for m in self.maps:
if k in m:
return m[k]
raise key_error(k)
def __setitem__(self, k, v):
... |
#
# PySNMP MIB module BDCOM-FLASH (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BDCOM-FLASH
# Produced by pysmi-0.3.4 at Wed May 1 11:36:39 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, 0... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) ... |
# https://www.codewars.com/kata/human-readable-duration-format
def format_duration(seconds):
if not seconds:
return "now"
units = [
("year", 365 * 24 * 60 * 60),
("day", 24 * 60 * 60),
("hour", 60 * 60),
("minute", 60),
("second", 1)
]
parts = []
... | def format_duration(seconds):
if not seconds:
return 'now'
units = [('year', 365 * 24 * 60 * 60), ('day', 24 * 60 * 60), ('hour', 60 * 60), ('minute', 60), ('second', 1)]
parts = []
for (unit, divisor) in units:
(quantity, seconds) = divmod(seconds, divisor)
if quantity:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.