content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
print(gcd(24, 32))
| def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
print(gcd(24, 32)) |
def remove_lead_and_trail_slash(val):
if val.startswith('/'):
val = val[1:]
if val.endswith('/'):
val = val[:-1]
return val
| def remove_lead_and_trail_slash(val):
if val.startswith('/'):
val = val[1:]
if val.endswith('/'):
val = val[:-1]
return val |
#!/usr/bin/python3
"""
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208... | """
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Fi... |
def countItems(a: list) -> int:
if len(a) == 0:
return 0
else:
return 1 + countItems(a[1:])
| def count_items(a: list) -> int:
if len(a) == 0:
return 0
else:
return 1 + count_items(a[1:]) |
def factorial(n):
return 1 if n < 2 else n * factorial(n-1)
if __name__=='__main__':
for i in range(1, 26):
print('%s! = %s' % (i, factorial(i)))
"""
output:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
1... | def factorial(n):
return 1 if n < 2 else n * factorial(n - 1)
if __name__ == '__main__':
for i in range(1, 26):
print('%s! = %s' % (i, factorial(i)))
'\noutput:\n\n1! = 1\n2! = 2\n3! = 6\n4! = 24\n5! = 120\n6! = 720\n7! = 5040\n8! = 40320\n9! = 362880\n10! = 3628800\n11! = 39916800\n12! = 479001600\n13!... |
'''
# > File Name : P1655.py
# > Author : Tony_Wong
# > Created Time : 2019/12/07 12:05:15
# > Algorithm : Stirling II
'''
S = [[0] * 110 for i in range(110)]
for i in range(1, 110):
S[i][i] = S[i][1] = 1
for j in range(2, i):
S[i][j] = S[i - 1][j - 1] + S[i - 1][j] ... | """
# > File Name : P1655.py
# > Author : Tony_Wong
# > Created Time : 2019/12/07 12:05:15
# > Algorithm : Stirling II
"""
s = [[0] * 110 for i in range(110)]
for i in range(1, 110):
S[i][i] = S[i][1] = 1
for j in range(2, i):
S[i][j] = S[i - 1][j - 1] + S[i - 1][j] *... |
target_steps = 10000
steps_done = 0
while True:
line = input()
if line == "Going home":
home_steps = int(input())
steps_done = steps_done + home_steps
if steps_done >= target_steps:
print("Goal reached! Good job!")
print(f"{steps_done - target_steps} steps over ... | target_steps = 10000
steps_done = 0
while True:
line = input()
if line == 'Going home':
home_steps = int(input())
steps_done = steps_done + home_steps
if steps_done >= target_steps:
print('Goal reached! Good job!')
print(f'{steps_done - target_steps} steps over th... |
def axisAlignedBoundingBox(x, y):
minX = x[0]
maxX = x[0]
minY = y[0]
maxY = y[0]
for i in range(1, len(x)):
minX = min(x[i], minX)
maxX = max(x[i], maxX)
minY = min(y[i], minY)
maxY = max(y[i], maxY)
return (maxX - minX) * (maxY - minY) | def axis_aligned_bounding_box(x, y):
min_x = x[0]
max_x = x[0]
min_y = y[0]
max_y = y[0]
for i in range(1, len(x)):
min_x = min(x[i], minX)
max_x = max(x[i], maxX)
min_y = min(y[i], minY)
max_y = max(y[i], maxY)
return (maxX - minX) * (maxY - minY) |
def integrate(a, b, f, N=2000):
dx = (b-a)/N
s=0.0
for i in range(N):
s += f(a+i*dx)
return s * dx
| def integrate(a, b, f, N=2000):
dx = (b - a) / N
s = 0.0
for i in range(N):
s += f(a + i * dx)
return s * dx |
#!/usr/bin/env python3
#coding: utf-8
### 1st line allows to execute this script by typing only its name in terminal, with no need to precede it with the python command
### 2nd line declaring source code charset should be not necessary but for exemple pydoc request it
__doc__ = "INI File Reading and Writing."#inform... | __doc__ = 'INI File Reading and Writing.'
__status__ = 'Development'
__version__ = '1.0.0'
__license__ = 'public domain'
__date__ = '2021'
__author__ = 'N-zo syslog@laposte.net'
__maintainer__ = 'Nzo'
__credits__ = []
__contact__ = 'syslog@laposte.net'
class Parser:
def __init__(self, pathname):
self.pars... |
while True:
try:
code = input("Enter customer code: ")
if code == 'r' or code=='R' or code =='c' or code=='C' or code =='i' or code == 'I':
tcode = 'ok'
else:
break
iread = float(input("Enter init read: "))
fread = float(input('Enter final reading: '))... | while True:
try:
code = input('Enter customer code: ')
if code == 'r' or code == 'R' or code == 'c' or (code == 'C') or (code == 'i') or (code == 'I'):
tcode = 'ok'
else:
break
iread = float(input('Enter init read: '))
fread = float(input('Enter final ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 22:38:14 2019
@author: Pooyan
"""
######################################
class ID:
def __init__(hh,name,age):
hh.name=name
hh.age=age
def callback(hh):
print("Name: "+hh.name +"Age: "+hh.age)
del hh.n... | """
Created on Sat Mar 2 22:38:14 2019
@author: Pooyan
"""
class Id:
def __init__(hh, name, age):
hh.name = name
hh.age = age
def callback(hh):
print('Name: ' + hh.name + 'Age: ' + hh.age)
del hh.name
name_p = input('Enter your name:')
age_p = input('Enter your age:')
new_... |
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# TODO: Do with good solutions
class Solution:
def convertToDoubly(self, root):
head = TreeNode(0)
pre = [head]
def doublyUtil(root, pre)... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convert_to_doubly(self, root):
head = tree_node(0)
pre = [head]
def doubly_util(root, pre):
if not root:
return
d... |
def find_count(numbers, target, expression=''):
if not numbers:
print(expression)
if target == 0:
return 1
else:
return 0
result = 0
result += find_count(numbers[1:], target - numbers[0], expression + f'+{numbers[0]}')
result += find_count(numbers[1:], ta... | def find_count(numbers, target, expression=''):
if not numbers:
print(expression)
if target == 0:
return 1
else:
return 0
result = 0
result += find_count(numbers[1:], target - numbers[0], expression + f'+{numbers[0]}')
result += find_count(numbers[1:], tar... |
#1 Interation through lists
L1 = [3,4,5]
L2 = [1,2,3]
L3 = []
for i in range(len(L1)):
L3.append(L1[i] + L2[i])
print(L3)
#2
L1 = [3,4,5]
L2 = [1,2,3]
L4 = list(zip(L1,L2)) #The zip fuction takes two or more sequences and it makes a list of tuples
print(L4)
#3
L1 = [3,4,5]
L2 = [1,2,3]
L3 = []
L4 = list(zip(L1... | l1 = [3, 4, 5]
l2 = [1, 2, 3]
l3 = []
for i in range(len(L1)):
L3.append(L1[i] + L2[i])
print(L3)
l1 = [3, 4, 5]
l2 = [1, 2, 3]
l4 = list(zip(L1, L2))
print(L4)
l1 = [3, 4, 5]
l2 = [1, 2, 3]
l3 = []
l4 = list(zip(L1, L2))
for (x1, x2) in L4:
L3.append(x1 + x2)
print(L3)
l1 = [3, 4, 5]
l2 = [1, 2, 3]
l3 = [x1 + ... |
class TeamConfig:
def __init__(self,
n_agents=2,
initial_epsilon=1.0,
final_epsilon=0.1,
epsilon_decay=0.999,
replay_buffer_size=250000,
replay_start_size=200000,
batch_size=32,
tr... | class Teamconfig:
def __init__(self, n_agents=2, initial_epsilon=1.0, final_epsilon=0.1, epsilon_decay=0.999, replay_buffer_size=250000, replay_start_size=200000, batch_size=32, train_interval=4, target_update_interval=5000):
"""
:param n_agents: number of agents in the team
:param initial_... |
def solution(st: str, limit: int) -> str:
if len(st) <= limit:
return st
for i in range(len(st)):
return st[i:limit]+'...' | def solution(st: str, limit: int) -> str:
if len(st) <= limit:
return st
for i in range(len(st)):
return st[i:limit] + '...' |
def MergeSort(m):
"""
If the length is less than or equal to 1, just return
since we don't even need to run SelectionSort
"""
if len(m) <= 1:
return m
#Calculate the midpoint and cast to int so there is no decimal
middle = int(len(m) / 2)
#Init some empty arrays. ls/rs a... | def merge_sort(m):
"""
If the length is less than or equal to 1, just return
since we don't even need to run SelectionSort
"""
if len(m) <= 1:
return m
middle = int(len(m) / 2)
l = []
r = []
ls = []
rs = []
l = m[0:middle]
r = m[middle:]
'\n If the length i... |
# zdebeer 2021-08-14
# Collection of cuntions that can be used in a template for assiting in transforming values to the required text.
def list_format(items, fmt):
"""format each item in a list"""
out = []
for i in items:
out.append(fmt.format(i))
return out
| def list_format(items, fmt):
"""format each item in a list"""
out = []
for i in items:
out.append(fmt.format(i))
return out |
class DetectLangsRequest:
def __init__(self, text, multi, count):
self.text = text
self.multi = multi
self.count = count | class Detectlangsrequest:
def __init__(self, text, multi, count):
self.text = text
self.multi = multi
self.count = count |
print('hi\nmy name is : abdullah')
print("in this code we will do ")
#if elif else
print("if elif else")
print("\n\n")
#________________________#
age = int(input("enter your age "))
print(age)
if (age > 30 and age<60) :
print("wow")
elif (age > 60 ):
print("old")
else :
print("almost") | print('hi\nmy name is : abdullah')
print('in this code we will do ')
print('if elif else')
print('\n\n')
age = int(input('enter your age '))
print(age)
if age > 30 and age < 60:
print('wow')
elif age > 60:
print('old')
else:
print('almost') |
# Exercise 5
#
# We will define a new object, SoccerPlayer
# 1) Think about what data attributes define a soccer player in real life
# Examples include: name, age, position, goals scored
# Feel free to be creative!
# 2) Write the __init__ method for SoccerPlayer
# 3) Write the getters and setters fo... | class Soccerplayer:
pass |
"""
Provide help messages for command line interface's batch commands.
"""
BATCH_IDENTIFIER_ARGUMENT_HELP_MESSAGE = 'Identifier to get a batch by.'
BATCH_STATUS_IDENTIFIER_ARGUMENT_HELP_MESSAGE = 'Identifier to get a batch status by.'
BATCHES_IDENTIFIERS_ARGUMENT_HELP_MESSAGE = 'Identifiers to get a list of batches by.... | """
Provide help messages for command line interface's batch commands.
"""
batch_identifier_argument_help_message = 'Identifier to get a batch by.'
batch_status_identifier_argument_help_message = 'Identifier to get a batch status by.'
batches_identifiers_argument_help_message = 'Identifiers to get a list of batches by.... |
g = 9.81
l1 = 1
l2 = 1
m1 = 1
m2 = 1
| g = 9.81
l1 = 1
l2 = 1
m1 = 1
m2 = 1 |
"""
The Jumping Cloud challenge is about a girl, Emma, that has to jump
through the clouds to reach the end point. In order to arrive safe, she
has to avoid the thunder clouds.
The path is given as an array (c) containing binary integers.
0 means that a cloud is safe and 1 means it must be avoided.
The objective is t... | """
The Jumping Cloud challenge is about a girl, Emma, that has to jump
through the clouds to reach the end point. In order to arrive safe, she
has to avoid the thunder clouds.
The path is given as an array (c) containing binary integers.
0 means that a cloud is safe and 1 means it must be avoided.
The objective is t... |
rand_map = [47, 20, 77, 91, 7, 18, 55, 46, 17, 60, 27, 40, 85, 15, 11, 12, 92, 9, 76, 62, 16, 80, 44, 13, 10, 67, 86, 65, 89, 81, 68, 26, 6, 64, 54, 57, 25, 45, 1, 83, 38, 71, 36, 75, 33, 79, 29, 63, 50, 70, 90, 56, 51, 37, 61, 42, 39, 93, 66, 43, 0, 2, 53, 74, 5, 22, 69, 82, 3, 28, 30, 34, 23, 19, 31, 84, 24, 41, 59, ... | rand_map = [47, 20, 77, 91, 7, 18, 55, 46, 17, 60, 27, 40, 85, 15, 11, 12, 92, 9, 76, 62, 16, 80, 44, 13, 10, 67, 86, 65, 89, 81, 68, 26, 6, 64, 54, 57, 25, 45, 1, 83, 38, 71, 36, 75, 33, 79, 29, 63, 50, 70, 90, 56, 51, 37, 61, 42, 39, 93, 66, 43, 0, 2, 53, 74, 5, 22, 69, 82, 3, 28, 30, 34, 23, 19, 31, 84, 24, 41, 59, ... |
course = "Python 101"
name = ("Carl Richard Matson")
print(course) # Python 101
print(name) | course = 'Python 101'
name = 'Carl Richard Matson'
print(course)
print(name) |
def label_modes(trip_list, silent=True):
"""Labels trip segments by likely mode of travel.
Labels are "chilling" if traveler is stationary, "walking" if slow,
"driving" if fast, and "bogus" if too fast to be real.
trip_list [list]: a list of dicts in JSON format.
silent [bool]: if True, does n... | def label_modes(trip_list, silent=True):
"""Labels trip segments by likely mode of travel.
Labels are "chilling" if traveler is stationary, "walking" if slow,
"driving" if fast, and "bogus" if too fast to be real.
trip_list [list]: a list of dicts in JSON format.
silent [bool]: if True, does n... |
def binary(a, tv):
minimum = 0
maximum = len(a) - 1
while minimum < maximum:
guess = round((minimum + maximum)/2)
if a[guess] == tv:
return guess
elif a[guess] < tv:
minimum = guess + 1
else:
maximum = guess - 1
return -1
arr = []
in... | def binary(a, tv):
minimum = 0
maximum = len(a) - 1
while minimum < maximum:
guess = round((minimum + maximum) / 2)
if a[guess] == tv:
return guess
elif a[guess] < tv:
minimum = guess + 1
else:
maximum = guess - 1
return -1
arr = []
ind... |
#
# PySNMP MIB module MERU-CONFIG-ICR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MERU-CONFIG-ICR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:01:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ... |
N = int(input())
_hour = str(N // 3600)
N = N % 3600
_min = str(N // 60)
_sec = str(N % 60)
print(_hour + ':', _min + ':', _sec, sep='')
| n = int(input())
_hour = str(N // 3600)
n = N % 3600
_min = str(N // 60)
_sec = str(N % 60)
print(_hour + ':', _min + ':', _sec, sep='') |
__all__ = ['Subcommand']
# placeholder class for subcommand classes to derive from
class Subcommand(object):
pass
# placeholder class for internal subcommand classes
class InternalSubcommand(object):
pass
| __all__ = ['Subcommand']
class Subcommand(object):
pass
class Internalsubcommand(object):
pass |
class DataStructureError(ValueError):
"""
Exception signalling that there is something wrong in the data saved to the database
- might be missing data, conflict with existing data, etc.
"""
class SourceFileMissingError(Exception):
"""
Used in re-importing code if is finds that the file to read... | class Datastructureerror(ValueError):
"""
Exception signalling that there is something wrong in the data saved to the database
- might be missing data, conflict with existing data, etc.
"""
class Sourcefilemissingerror(Exception):
"""
Used in re-importing code if is finds that the file to read ... |
# -*- coding: utf-8 -*-
class School(object):
"""Data class for schools."""
def __init__(
self,
code,
name,
city,
state,
from_m,
from_y,
to_m,
to_y,
grad_m,
grad_y,
):
"""Intitalization method."""
self... | class School(object):
"""Data class for schools."""
def __init__(self, code, name, city, state, from_m, from_y, to_m, to_y, grad_m, grad_y):
"""Intitalization method."""
self.school_code = code
self.school_name = name
self.school_city = city
self.school_state = state
... |
def Alchemy(C, N):
return 'N' if abs(C.count('A') - C.count('B')) > 1 else 'Y'
if __name__ == "__main__":
T = int(input())
for i in range(T):
N = int(input())
C = input()
print("Case #{}:".format(i+1), end=" ")
print(Alchemy(list(C), N))
# s = "ABBBBABAAABAABBBAABAAAAAABBB... | def alchemy(C, N):
return 'N' if abs(C.count('A') - C.count('B')) > 1 else 'Y'
if __name__ == '__main__':
t = int(input())
for i in range(T):
n = int(input())
c = input()
print('Case #{}:'.format(i + 1), end=' ')
print(alchemy(list(C), N)) |
'''
Lab2
'''
#3.1
my_name = 'Tom'
print(my_name.upper())
#3.2
my_id = 123
print(my_id)
#3.3
# 123=my_id
my_id=your_id=123
print(my_id)
print(your_id)
#3.4
my_id_str = '123'
print(my_id_str)
#3.5
#print(my_name+my_id)
#3.6
print(my_name+my_id_str)
#3.7
print(my_name*3)
#3.8
print('hello, world. This is my fi... | """
Lab2
"""
my_name = 'Tom'
print(my_name.upper())
my_id = 123
print(my_id)
my_id = your_id = 123
print(my_id)
print(your_id)
my_id_str = '123'
print(my_id_str)
print(my_name + my_id_str)
print(my_name * 3)
print('hello, world. This is my first python string.'.split('.')) |
syscalls = [
"fork",
"exit",
"wait",
"pipe",
"read",
"write",
"close",
"kill",
"exec",
"open",
"mknod",
"unlink",
"fstat",
"link",
"mkdir",
"chdir",
"dup",
"getpid",
"sbrk",
"sleep",
"uptime"
]
| syscalls = ['fork', 'exit', 'wait', 'pipe', 'read', 'write', 'close', 'kill', 'exec', 'open', 'mknod', 'unlink', 'fstat', 'link', 'mkdir', 'chdir', 'dup', 'getpid', 'sbrk', 'sleep', 'uptime'] |
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: binary tree
@return: N-ary tree
"""
def decode(... | class Undirectedgraphnode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Treenode:
def __init__(self, val):
self.val = val
(self.left, self.right) = (None, None)
class Solution:
"""
@param root: binary tree
@return: N-ary tree
"""
def de... |
class TranslationException(Exception):
"""
Error raised when a translation file can't be found.
"""
pass
class MediaNotSetUp(Exception):
"""
Error raised when a media file can't be found or set up.
"""
pass
class DataRetrievingError(Exception):
"""
Error raised when some raw ... | class Translationexception(Exception):
"""
Error raised when a translation file can't be found.
"""
pass
class Medianotsetup(Exception):
"""
Error raised when a media file can't be found or set up.
"""
pass
class Dataretrievingerror(Exception):
"""
Error raised when some raw co... |
class Config():
# simulation
T = 2200
sim_t = 2000 + 1
current_time = 0
# Job
process_t_lower = 1
process_t_upper = 5
job_resource_lower = 5
job_resource_upper = 15
# Server
server_r = 40
server_count = 6
server_heat_constant = 200
server_pos_x = [0, 1, -2, -2,... | class Config:
t = 2200
sim_t = 2000 + 1
current_time = 0
process_t_lower = 1
process_t_upper = 5
job_resource_lower = 5
job_resource_upper = 15
server_r = 40
server_count = 6
server_heat_constant = 200
server_pos_x = [0, 1, -2, -2, 3, 3]
server_pos_y = [0, 0, 0, 2, 1, 3]
... |
"""A module defining custom exceptions for the package.
Each subpackage has a base exception class.
"""
class OdkFormError(Exception):
"""The base exception class for the odkform subpackage."""
class MismatchedGroupOrRepeatError(OdkFormError):
"""An exception for parsing group or repeats."""
class LabelN... | """A module defining custom exceptions for the package.
Each subpackage has a base exception class.
"""
class Odkformerror(Exception):
"""The base exception class for the odkform subpackage."""
class Mismatchedgrouporrepeaterror(OdkFormError):
"""An exception for parsing group or repeats."""
class Labelnotf... |
class maze_control():
def __init__(self, map, solution):
self.solution = solution
self.dmap = []
for x in map:
temp = []
for y in x:
temp.append(y)
self.dmap.append(temp)
def get_car(self):
if self.solution[0] !=... | class Maze_Control:
def __init__(self, map, solution):
self.solution = solution
self.dmap = []
for x in map:
temp = []
for y in x:
temp.append(y)
self.dmap.append(temp)
def get_car(self):
if self.solution[0] != '':
... |
def print_hello(name=''):
print('Hello,'+name)
name = 'Ann'
name2 = 'Bob'
print_hello(name2) | def print_hello(name=''):
print('Hello,' + name)
name = 'Ann'
name2 = 'Bob'
print_hello(name2) |
if __name__ == '__main__':
input = open('input', 'r').readlines()
inverse = {
'(': ')',
'[': ']',
'{': '}',
'<': '>'
}
points = {
')': 1,
']': 2,
'}': 3,
'>': 4
}
score = lambda x: points[x[0]] if len(x) == 1 else 5*score(x[1:]) ... | if __name__ == '__main__':
input = open('input', 'r').readlines()
inverse = {'(': ')', '[': ']', '{': '}', '<': '>'}
points = {')': 1, ']': 2, '}': 3, '>': 4}
score = lambda x: points[x[0]] if len(x) == 1 else 5 * score(x[1:]) + points[x[0]]
scores = list()
for line in input:
stack = lis... |
"""
Space : O(n)
Time : O(n)
"""
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
if len(matrix) == 0:
return True
if len(matrix[0]) == 0:
return True
ly = len(matrix)
lx = len(matrix[0])
for y in range(ly-1):
... | """
Space : O(n)
Time : O(n)
"""
class Solution:
def is_toeplitz_matrix(self, matrix: List[List[int]]) -> bool:
if len(matrix) == 0:
return True
if len(matrix[0]) == 0:
return True
ly = len(matrix)
lx = len(matrix[0])
for y in range(ly - 1):
... |
class Queue:
def __init__(self):
self.items = []
def push(self, e):
self.items.append(e)
def pop(self):
head = self.items[0]
self.items = self.items[1:]
return head
q = Queue()
q.push(5) # [5]
q.push(7) # [5, 7]
q.push(11) # [5, 7, 11]
print(q.pop()) # ... | class Queue:
def __init__(self):
self.items = []
def push(self, e):
self.items.append(e)
def pop(self):
head = self.items[0]
self.items = self.items[1:]
return head
q = queue()
q.push(5)
q.push(7)
q.push(11)
print(q.pop())
print(q.pop()) |
def check(attempt, context):
if attempt.answer == flags[attempt.participant.id % len(flags)]:
return Checked(True)
if attempt.answer in flags:
return CheckedPlagiarist(False, flags.index(attempt.answer))
return Checked(False)
flags = ['LKL{s0_uSB_PXwlrPxA}', 'LKL{s0_uSB_z7dg8Y9I}... | def check(attempt, context):
if attempt.answer == flags[attempt.participant.id % len(flags)]:
return checked(True)
if attempt.answer in flags:
return checked_plagiarist(False, flags.index(attempt.answer))
return checked(False)
flags = ['LKL{s0_uSB_PXwlrPxA}', 'LKL{s0_uSB_z7dg8Y9I}', 'LKL{s0_... |
# Settings example file
# Edit as needed and save to local_settings.py
HOST = "imap.gmail.com"
USERNAME = "you@gmail.com"
PASSWORD = "IMAPappPassWord"
SEARCH_EMAIL = "tom@myspace.com"
DOWNLOAD_FOLDER = "."
POLLING_INTERVAL = 10000
DATABASE="/home/user/myfinances.gnucash"
| host = 'imap.gmail.com'
username = 'you@gmail.com'
password = 'IMAPappPassWord'
search_email = 'tom@myspace.com'
download_folder = '.'
polling_interval = 10000
database = '/home/user/myfinances.gnucash' |
# Whether to run the call graph tracer with debugging enabled. Turning off
# `if DEBUG: LOGGER.debug()` code completely yielded massive performance improvements.
DEBUG = False
FAIL_ON_UNKNOWN_BYTECODE = False
| debug = False
fail_on_unknown_bytecode = False |
# --------------
# Code starts here
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2=['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1+class_2
print(new_class)
new_class.append("Peter Warden")
print(new_class)
new_class.remove("Carla Gentry")
print(new_class)
# Code... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English... |
x = int(input())
if(x % 2 == 0 or x % 5 == 0):
print(x)
else:
print("Not a multiple of 2 or 5")
| x = int(input())
if x % 2 == 0 or x % 5 == 0:
print(x)
else:
print('Not a multiple of 2 or 5') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 25 06:28:00 2018
@author: tuheenahmmed
"""
def integerDivision(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the integer division of x divided by a.
"""
while x >= a:
... | """
Created on Mon Jun 25 06:28:00 2018
@author: tuheenahmmed
"""
def integer_division(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the integer division of x divided by a.
"""
while x >= a:
count += 1
x = x - a
return count... |
age = int(input("How old are you? "))
# if age >= 16 and age <=65:
# if 16 <= age <=65:
if age in range(16, 66):
print("Have a good day at work")
else:
print("Enjoy your free time!")
print("-" * 80)
if age <16 or age > 65:
print("Enjoy your free time!")
else:
print("Have a good day at work!") | age = int(input('How old are you? '))
if age in range(16, 66):
print('Have a good day at work')
else:
print('Enjoy your free time!')
print('-' * 80)
if age < 16 or age > 65:
print('Enjoy your free time!')
else:
print('Have a good day at work!') |
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return len(nums)
nums.sort()
length = 0
curLen = 1
for i in range(1, len(nums)):
if nums[i] == nums[i-1]+1:... | class Solution:
def longest_consecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return len(nums)
nums.sort()
length = 0
cur_len = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - ... |
"""Jest helper tools."""
load("@npm//@bazel/typescript:index.bzl", "ts_project")
load("@npm//jest-cli:index.bzl", _jest_test = "jest_test")
def ts_jest_test(name, srcs, deps = [], **kwargs):
"""Run a Jest test suite for a TS project.
Args:
name: name of the resulting test rule
srcs: typescrip... | """Jest helper tools."""
load('@npm//@bazel/typescript:index.bzl', 'ts_project')
load('@npm//jest-cli:index.bzl', _jest_test='jest_test')
def ts_jest_test(name, srcs, deps=[], **kwargs):
"""Run a Jest test suite for a TS project.
Args:
name: name of the resulting test rule
srcs: typescript sou... |
class Solution:
def addBinary(self, a: str, b: str) -> str:
ai,bi,carry = len(a)-1,len(b)-1,0
res = ''
while ai >= 0 or bi >= 0 or carry:
av = int(a[ai]) if ai >= 0 else 0
bv = int(b[bi]) if bi >= 0 else 0
sum3 = av+bv+carry
res = str(sum3%2)+r... | class Solution:
def add_binary(self, a: str, b: str) -> str:
(ai, bi, carry) = (len(a) - 1, len(b) - 1, 0)
res = ''
while ai >= 0 or bi >= 0 or carry:
av = int(a[ai]) if ai >= 0 else 0
bv = int(b[bi]) if bi >= 0 else 0
sum3 = av + bv + carry
r... |
sprinklers = [[False for j in range(1000)] for i in range(1000)]
def checkAndSwap(x1, x2):
if (x1 > x2):
return (x2, x1)
else:
return (x1, x2)
with open("D:\\Work\\Repositories\\programmingContest\\contest1\\programmingContest1Input2.txt") as file:
for line in file:
lin... | sprinklers = [[False for j in range(1000)] for i in range(1000)]
def check_and_swap(x1, x2):
if x1 > x2:
return (x2, x1)
else:
return (x1, x2)
with open('D:\\Work\\Repositories\\programmingContest\\contest1\\programmingContest1Input2.txt') as file:
for line in file:
line = line.lowe... |
politician_mapping = {
"properties": {
"name": {"type": "text", "analyzer": "indexing_analyzer", "search_analyzer":"search_analyzer"},
"occupation": {"type": "text", "analyzer": "indexing_analyzer", "search_analyzer":"search_analyzer"},
"party": {"type": "text", "analyzer": "indexing_analyze... | politician_mapping = {'properties': {'name': {'type': 'text', 'analyzer': 'indexing_analyzer', 'search_analyzer': 'search_analyzer'}, 'occupation': {'type': 'text', 'analyzer': 'indexing_analyzer', 'search_analyzer': 'search_analyzer'}, 'party': {'type': 'text', 'analyzer': 'indexing_analyzer', 'search_analyzer': 'sear... |
class Project:
def __init__(self, id, name, country, altitude, currency):
self.id = id
self.name = name
self.country = country
self.altitude = altitude
self.currency = currency
def __str__(self):
return "ID: {} \nName: {} \nCountry: {} \nAltitude: {} \nCurrency: ... | class Project:
def __init__(self, id, name, country, altitude, currency):
self.id = id
self.name = name
self.country = country
self.altitude = altitude
self.currency = currency
def __str__(self):
return 'ID: {} \nName: {} \nCountry: {} \nAltitude: {} \nCurrency:... |
#!/usr/bin/env python3
# Thinking process:
# This doesn't work
# We need 3 DP tables:
# TD: at day i, if we have a 1-day pass, the [min cost, days left]
# TW: at day i, if we have a 1-week pass, the [min cost, days left]
# TM: at day i, if we have a 1-month pass, the [min cost, days left]
# Recurrence relation
# TD[... | class Solution:
def mincost_tickets(self, days, costs):
(cd, cw, cm) = costs
(ld, lw, lm) = (1, 7, 30)
for d in range(days[0] + 1, days[-1] + 1):
(ld, lw, lm) = (ld - 1, lw - 1, lm - 1)
if d in days:
m = min(cd, cw, cm)
(cd, ld) = (m +... |
class Matrix(object):
"""
The Matrix represents a matrix containing a list of rows.
:param matrix_string: The string representing the matrix.
:type matrix_string: str
:ivar rows: Contains the rows of the matrix
:vartype rows: list(list(int))
"""
def __init__(self, matrix_string):
... | class Matrix(object):
"""
The Matrix represents a matrix containing a list of rows.
:param matrix_string: The string representing the matrix.
:type matrix_string: str
:ivar rows: Contains the rows of the matrix
:vartype rows: list(list(int))
"""
def __init__(self, matrix_string):
... |
"""
[8/10/2014] Challenge #174 [Extra] Functional Thinking
https://www.reddit.com/r/dailyprogrammer/comments/2d52d8/8102014_challenge_174_extra_functional_thinking/
# *(Extra)*: Functional Thinking
I'm trying a new bonus challenge today with any theme I can think of, such as rewriting an existing solution using a
dif... | """
[8/10/2014] Challenge #174 [Extra] Functional Thinking
https://www.reddit.com/r/dailyprogrammer/comments/2d52d8/8102014_challenge_174_extra_functional_thinking/
# *(Extra)*: Functional Thinking
I'm trying a new bonus challenge today with any theme I can think of, such as rewriting an existing solution using a
dif... |
def to_list(string):
list_str = []
for tok in string:
list_str.append(tok)
return list_str
def to_string(list):
string_list = ""
for item in list:
string_list += item
return string_list
def fst_op(program):
raw = ""
for item in program:
if item == "(":
... | def to_list(string):
list_str = []
for tok in string:
list_str.append(tok)
return list_str
def to_string(list):
string_list = ''
for item in list:
string_list += item
return string_list
def fst_op(program):
raw = ''
for item in program:
if item == '(':
... |
"""
Routine to perform color printing of text, wrapping standard pyton print function.
"""
# ANSI terminal colors - just put in as part of the string to get color terminal output
colors = {'red': '\x1b[31m', 'r': '\x1b[31m',
'orange': '\x1b[48:5:208:0m', 'o': '\x1b[48:5:208:0m',
'yellow': '\x1b[3... | """
Routine to perform color printing of text, wrapping standard pyton print function.
"""
colors = {'red': '\x1b[31m', 'r': '\x1b[31m', 'orange': '\x1b[48:5:208:0m', 'o': '\x1b[48:5:208:0m', 'yellow': '\x1b[33m', 'y': '\x1b[33m', 'green': '\x1b[32m', 'g': '\x1b[32m', 'magenta': '\x1b[35m', 'm': '\x1b[35m', 'blue': '\... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: aghast_generated
class InterpretedBuffer(object):
NONE = 0
InterpretedInlineBuffer = 1
InterpretedInlineInt64Buffer = 2
InterpretedInlineFloat64Buffer = 3
InterpretedExternalBuffer = 4
| class Interpretedbuffer(object):
none = 0
interpreted_inline_buffer = 1
interpreted_inline_int64_buffer = 2
interpreted_inline_float64_buffer = 3
interpreted_external_buffer = 4 |
# https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules
crLog = None
environment_config = None
magic_value_config = None
message_config = None
| cr_log = None
environment_config = None
magic_value_config = None
message_config = None |
class Menu:
def __init__(self, position=(0, 0)):
"""
Make all menu mechanics
:param position: start position for drawing
"""
self.index = 0
self.x = position[0]
self.y = position[1]
self.menu = list()
def down(self):
"""
Move menu ... | class Menu:
def __init__(self, position=(0, 0)):
"""
Make all menu mechanics
:param position: start position for drawing
"""
self.index = 0
self.x = position[0]
self.y = position[1]
self.menu = list()
def down(self):
"""
Move menu... |
"""
Session: 8
Topic: Set vs List
"""
# my_set = {1, 2, 3, 1, 2}
my_set = {"apple", "apple", "orange", "orange", "orange"}
print(my_set)
print ("\n\n")
# my_list = [1, 2, 3, 1, 2]
my_list = ["apple", "apple", "orange", "orange", "orange"]
print(my_list) | """
Session: 8
Topic: Set vs List
"""
my_set = {'apple', 'apple', 'orange', 'orange', 'orange'}
print(my_set)
print('\n\n')
my_list = ['apple', 'apple', 'orange', 'orange', 'orange']
print(my_list) |
def check(i):
for j in range(m):
if need[i][j] > available[j]:
return False
return True
n = int(input("Enter the number of Processes: "))
m = int(input("Enter the number of Resources: "))
allocation = []
for i in range(n):
allocation.append(list(map(int, input('\nEnter the number of in... | def check(i):
for j in range(m):
if need[i][j] > available[j]:
return False
return True
n = int(input('Enter the number of Processes: '))
m = int(input('Enter the number of Resources: '))
allocation = []
for i in range(n):
allocation.append(list(map(int, input('\nEnter the number of inst... |
#web scraping - open the html file
#then find the appropriate chunk of code like <table> where your data is
#then extract what you want from there
"""
For APIs, they'll help you scrape the webpage more easily
based on the documentation provided by the webpage, if any.
So you can look for APIs from various web... | """
For APIs, they'll help you scrape the webpage more easily
based on the documentation provided by the webpage, if any.
So you can look for APIs from various websites, so you don't
have to manually go into the html webpage to find the correct
class etc
""" |
RESOLVER_STORE = {"pulumi.json": {"Any": {"type": "any"}, "Asset": {"type": "string"}}}
PULUMI_ID = "id"
PULUMI_NS = "pulumi"
PULUMI_HOME_ENV = "PULUMI_HOME"
| resolver_store = {'pulumi.json': {'Any': {'type': 'any'}, 'Asset': {'type': 'string'}}}
pulumi_id = 'id'
pulumi_ns = 'pulumi'
pulumi_home_env = 'PULUMI_HOME' |
def is_in_range(digits, r_max):
number = 0
for i, d in enumerate(digits):
number += d * 10**i
if number > r_max:
return False
# print(number)
return True
def is_valid(digits):
distinct_digits = list(set(digits))
for dd in distinct_digits:
if digits.count(dd) == 2:
return True
return False
def solve(... | def is_in_range(digits, r_max):
number = 0
for (i, d) in enumerate(digits):
number += d * 10 ** i
if number > r_max:
return False
return True
def is_valid(digits):
distinct_digits = list(set(digits))
for dd in distinct_digits:
if digits.count(dd) == 2:
return... |
def analysis(filename):
file = open(filename)
total = []
for entry in file:
info = entry.split(' ')
total.append(info)
total.sort(key = lambda x: int(x[1][:-1]),reverse=True)
# print(total[:1000])
final_analysis = open('final_analysis.txt','w')
for entry in total:
fin... | def analysis(filename):
file = open(filename)
total = []
for entry in file:
info = entry.split(' ')
total.append(info)
total.sort(key=lambda x: int(x[1][:-1]), reverse=True)
final_analysis = open('final_analysis.txt', 'w')
for entry in total:
final_analysis.write(' '.join... |
def sudoku(grid):
match = [i for i in range(1, 10)]
for row in grid:
if sorted(row) != match:
return False
for column_index in range(9):
column = [grid[row_index][column_index] for row_index in range(9)]
if sorted(column) != match:
return False
for row in ... | def sudoku(grid):
match = [i for i in range(1, 10)]
for row in grid:
if sorted(row) != match:
return False
for column_index in range(9):
column = [grid[row_index][column_index] for row_index in range(9)]
if sorted(column) != match:
return False
for row in ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 21 18:38:37 2019
@author: NOTEBOOK
"""
#This program displays the total earnings of a worker over a number of days in dollars
# starting from 1 penny and doubling each day
def main():
#Get number of days
days = int(input('Enter number of days: ' ))
#Print Head... | """
Created on Sat Dec 21 18:38:37 2019
@author: NOTEBOOK
"""
def main():
days = int(input('Enter number of days: '))
print('Days\tEarnings')
print('---------------------')
starter = 1.0
total = 0.0
for num in range(days):
earnings = starter * 2 ** num
print('Day', num + 1, '\t... |
## Verifica Palavra no Nome
nome = str(input('Qual seu nome completo? ')).strip()
print('Seu nome tem Silva? {}'.format('SILVA' in nome.upper()))
## Concatenando Strings
print('-='*30)
print('CONCATENANDO STRINGS')
print('-='*30)
a = 'Wollacy'
b = 'Lilian'
c = 'Augusto'
print(a)
print(b)
print(c)
d = a + ' + ' + ... | nome = str(input('Qual seu nome completo? ')).strip()
print('Seu nome tem Silva? {}'.format('SILVA' in nome.upper()))
print('-=' * 30)
print('CONCATENANDO STRINGS')
print('-=' * 30)
a = 'Wollacy'
b = 'Lilian'
c = 'Augusto'
print(a)
print(b)
print(c)
d = a + ' + ' + b + ' = ' + c
print(d) |
syntax = r'^\+(?:tel|port|teleport)(?P<quiet>/quiet)? (?P<target>.+)$'
def teleport(caller, target, quiet=False, force=False):
target = search(caller, target).all()
if not target:
commands.pemit(caller, caller, "\c(red)!!! Unable to find target.")
return
target = target[0]
... | syntax = '^\\+(?:tel|port|teleport)(?P<quiet>/quiet)? (?P<target>.+)$'
def teleport(caller, target, quiet=False, force=False):
target = search(caller, target).all()
if not target:
commands.pemit(caller, caller, '\\c(red)!!! Unable to find target.')
return
target = target[0]
if target is... |
load("@rules_maven_third_party//:import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "org_codehaus_plexus_plexus_archiver",
artifact = "org.codehaus.plexus:plexus-archiver:3.4",
artifact_sha256 = "3c6611c98547dbf3f5125848c273ba719bc10df44e3... | load('@rules_maven_third_party//:import_external.bzl', import_external='import_external')
def dependencies():
import_external(name='org_codehaus_plexus_plexus_archiver', artifact='org.codehaus.plexus:plexus-archiver:3.4', artifact_sha256='3c6611c98547dbf3f5125848c273ba719bc10df44e3f492fa2e302d6135a6ea5', srcjar_sh... |
# 1. Decoration
def deco(param):
def wrapper(func):
def inner_wrapper(*arg, **kwargs):
print(param, arg, kwargs)
inner_res = func(*arg, **kwargs)
return inner_res
return inner_wrapper
return wrapper
@deco(param="do what you want to do")
def origin(times, add... | def deco(param):
def wrapper(func):
def inner_wrapper(*arg, **kwargs):
print(param, arg, kwargs)
inner_res = func(*arg, **kwargs)
return inner_res
return inner_wrapper
return wrapper
@deco(param='do what you want to do')
def origin(times, add, sub, num=1):
... |
"""
Analyze the grades of the students.
Here's an example of the data
.. code-block::
111111004 5.0 5.0 6.0
111111005 3.75 3.0 4.0
111111006 4.5 2.25 4.0
Every line represents a grading of a student. It starts with her matriculation number,
followed by space-delimited grades (between 1.0 and 6.0,... | """
Analyze the grades of the students.
Here's an example of the data
.. code-block::
111111004 5.0 5.0 6.0
111111005 3.75 3.0 4.0
111111006 4.5 2.25 4.0
Every line represents a grading of a student. It starts with her matriculation number,
followed by space-delimited grades (between 1.0 and 6.0,... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Recurring Documents',
'category': 'Extra Tools',
'description': """
Create recurring documents.
===========================
This module allows to create new documents and add subscriptions on tha... | {'name': 'Recurring Documents', 'category': 'Extra Tools', 'description': '\nCreate recurring documents.\n===========================\n\nThis module allows to create new documents and add subscriptions on that document.\n\ne.g. To have an invoice generated automatically periodically:\n----------------------------------... |
# __INIT__.PY
__version__='v1.0.0'
| __version__ = 'v1.0.0' |
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
dp = [[0] * (len(first) + 1) for _ in range(len(second) + 1)]
n1 = len(first) + 1
n2 = len(second) + 1
for i in range(1, n1):
dp[0][i] = dp[0][i - 1] + 1
for i in range(1, n2):
dp[... | class Solution:
def one_edit_away(self, first: str, second: str) -> bool:
dp = [[0] * (len(first) + 1) for _ in range(len(second) + 1)]
n1 = len(first) + 1
n2 = len(second) + 1
for i in range(1, n1):
dp[0][i] = dp[0][i - 1] + 1
for i in range(1, n2):
... |
class Fraction:
def __repr__(self):
return '%s/%s' % (self.num, self.den)
def __add__(self, other):
num = self.num * other.den + self.den * other.num
den = self.den * other.den
return Fraction(num, den)
def __sub__(self, other):
num = self.num * other.den - self.den... | class Fraction:
def __repr__(self):
return '%s/%s' % (self.num, self.den)
def __add__(self, other):
num = self.num * other.den + self.den * other.num
den = self.den * other.den
return fraction(num, den)
def __sub__(self, other):
num = self.num * other.den - self.de... |
"""
This module is used to represent a ROI object from the DICOMROI table in the database.
"""
class ROI:
"""
This class stores all information about a region of interest from the DICOMROI table in the database.
"""
def __init__(self, name: str, identity: int = -1, priority: int = -1) -> None:
... | """
This module is used to represent a ROI object from the DICOMROI table in the database.
"""
class Roi:
"""
This class stores all information about a region of interest from the DICOMROI table in the database.
"""
def __init__(self, name: str, identity: int=-1, priority: int=-1) -> None:
"""... |
# To import:
# from twoscomplement import *
def lars_reverse_twos_complement(j, bits=1):
return (1<<j.bit_length()+bits) - j
def lars_twos_complement(j):
return (1<<(j.bit_length()))-j
def build_twos_complement_down(j):
origj=j
prevj=0
while prevj != j:
print(f'{j:10d}, {prevj^j:10d}')
prevj... | def lars_reverse_twos_complement(j, bits=1):
return (1 << j.bit_length() + bits) - j
def lars_twos_complement(j):
return (1 << j.bit_length()) - j
def build_twos_complement_down(j):
origj = j
prevj = 0
while prevj != j:
print(f'{j:10d}, {prevj ^ j:10d}')
prevj = j
j = lars_... |
class State:
def __init__(self):
pass
def update(self):
pass | class State:
def __init__(self):
pass
def update(self):
pass |
LEVELS = [
("echo 'bang'", "echo 'bang!';"),
("swap two files in your homedir", """files=(~/*);
f1="${files[RANDOM % ${#files[@]}]}"
f2="${files[RANDOM % ${#files[@]}]}"
mv "$f1" /tmp/russianroulette
mv "$f2" "$f1"
mv /tmp/russianroulette "$f2"
echo 'bang! two files got their names mixed up. now, which ones wer... | levels = [("echo 'bang'", "echo 'bang!';"), ('swap two files in your homedir', 'files=(~/*);\nf1="${files[RANDOM % ${#files[@]}]}"\nf2="${files[RANDOM % ${#files[@]}]}"\nmv "$f1" /tmp/russianroulette\nmv "$f2" "$f1"\nmv /tmp/russianroulette "$f2"\necho \'bang! two files got their names mixed up. now, which ones were th... |
class EventPropertyError(Exception):
pass
class ValidationError(Exception):
def __init__(self, message: str):
self.message = message
class RetrievalError(Exception):
def __init__(self, message: str):
self.message = message
| class Eventpropertyerror(Exception):
pass
class Validationerror(Exception):
def __init__(self, message: str):
self.message = message
class Retrievalerror(Exception):
def __init__(self, message: str):
self.message = message |
# www.census.gov/geo/www/us_regdiv.pdf
CensusDivisions = (
('PACIFIC', 'AK HI WA OR CA'.split()),
('MOUNTAIN', 'MT ID WY NV UT CO AZ NM'.split()),
('WN_CENTRAL', 'ND SD MN NE IA KS MO'.split()),
('EN_CENTRAL', 'WI MI IL IN OH'.split()),
('WS_CENTRAL', 'OK AR TX LA'.split()),
('ES_CENTRAL', 'KY TN MS AL'.split()),
('S_... | census_divisions = (('PACIFIC', 'AK HI WA OR CA'.split()), ('MOUNTAIN', 'MT ID WY NV UT CO AZ NM'.split()), ('WN_CENTRAL', 'ND SD MN NE IA KS MO'.split()), ('EN_CENTRAL', 'WI MI IL IN OH'.split()), ('WS_CENTRAL', 'OK AR TX LA'.split()), ('ES_CENTRAL', 'KY TN MS AL'.split()), ('S_ATLANTIC', 'FL GA SC NC VA WV DC MD DE'... |
class Enemy:
#state
player_seen_at_tower = None # tower coordinates (x, y, z)
player_seen = None # world coordinates vec3
# constants
speed = 1
jump_speed = 5
jump_angle = 30
maxhp = 100
disappear_on_sight = False
use_ranged_weapons = True
use_grenades = False
... | class Enemy:
player_seen_at_tower = None
player_seen = None
speed = 1
jump_speed = 5
jump_angle = 30
maxhp = 100
disappear_on_sight = False
use_ranged_weapons = True
use_grenades = False
melee_weapon = None
inventory_choices = [] |
def flatten_chebi_api_attr(ch: dict, attr, _mapping: dict):
val = ch.pop(attr)
if isinstance(val, list):
if isinstance(val[0], dict):
if 'data' in val[0]:
# list of dicts
val = [el['data'] for el in val]
else:
# todo: ... | def flatten_chebi_api_attr(ch: dict, attr, _mapping: dict):
val = ch.pop(attr)
if isinstance(val, list):
if isinstance(val[0], dict):
if 'data' in val[0]:
val = [el['data'] for el in val]
else:
pass
else:
pass
elif isinstanc... |
# Path to images we are extracting content and style from
CONTENT_IMAGE_PATH = './coastal_scene.jpg'
STYLE_IMAGE_PATH = './starry_night.jpg'
# Seed for initializing numpy and tf
NP_SEED = 0
TF_SEED = 0
# Path to vgg19 checkpoint, must be downloaded separately
CHECKPOINT_PATH = './vgg_19.ckpt'
# Location of tensorboa... | content_image_path = './coastal_scene.jpg'
style_image_path = './starry_night.jpg'
np_seed = 0
tf_seed = 0
checkpoint_path = './vgg_19.ckpt'
tensorboard_dir = './train/'
debug_dir = './debug/'
height = 224
width = 224
channels = 3
content_layer = 'vgg_19/conv2/conv2_2'
style_list = ['vgg_19/conv1/conv1_1', 'vgg_19/conv... |
path = "input.txt"
file = open(path)
input = file.readlines()
file.close()
horizontal = 0
depth = 0
for item in input:
dir, speed = item.split(" ")
if dir == "forward":
horizontal += int(speed)
elif dir == "down":
depth += int(speed)
elif dir == "up":
depth -= int(speed)
... | path = 'input.txt'
file = open(path)
input = file.readlines()
file.close()
horizontal = 0
depth = 0
for item in input:
(dir, speed) = item.split(' ')
if dir == 'forward':
horizontal += int(speed)
elif dir == 'down':
depth += int(speed)
elif dir == 'up':
depth -= int(speed)
el... |
# Implementantion of all PetriNet class
# 1st class to be implemented is Petri Net Basic (or classic Petri Net)
class PetriNet(object):
"""
This class contains all major object necessary to describe a complete Petri Net
"""
pass
class Place(object):
"""
Class Place implements the behavior of ... | class Petrinet(object):
"""
This class contains all major object necessary to describe a complete Petri Net
"""
pass
class Place(object):
"""
Class Place implements the behavior of the similar structure within a Petri Net
"""
pass
class Transition(object):
"""
Class Transition... |
def str_bin(s_str):
st = s_str
print(' '.join(format(ord(x), "b") for x in st))
def main():
str_bin("lol")
if __name__ == "__main__":
main()
print("done") | def str_bin(s_str):
st = s_str
print(' '.join((format(ord(x), 'b') for x in st)))
def main():
str_bin('lol')
if __name__ == '__main__':
main()
print('done') |
x = list(input("Input String: "))
x = x [::-1]
j = 0
def reverseword(x):
i = 0
print(int)
while i !=int(len(x)/2):
temp = x[i]
x[i] = x[len(x)-1-i]
x[len(x)-1-i] = temp
i+=1
return str(x)
print(reverseword(x))
| x = list(input('Input String: '))
x = x[::-1]
j = 0
def reverseword(x):
i = 0
print(int)
while i != int(len(x) / 2):
temp = x[i]
x[i] = x[len(x) - 1 - i]
x[len(x) - 1 - i] = temp
i += 1
return str(x)
print(reverseword(x)) |
platforms = {
"UA": "usaco.org",
"CC": "codechef.com",
"EOL":"e-olimp.com",
"CH24": "ch24.org",
"HR": "hackerrank.com",
"HE": "hackerearth.com",
"ICPC": "icfpcontest.org",
"GCJ": "google.com/codejam",
"DE24": "deadline24.pl",
"IOI": "stats.ioinformatics.org",
"PE": "projecteuler.net",
"SN... | platforms = {'UA': 'usaco.org', 'CC': 'codechef.com', 'EOL': 'e-olimp.com', 'CH24': 'ch24.org', 'HR': 'hackerrank.com', 'HE': 'hackerearth.com', 'ICPC': 'icfpcontest.org', 'GCJ': 'google.com/codejam', 'DE24': 'deadline24.pl', 'IOI': 'stats.ioinformatics.org', 'PE': 'projecteuler.net', 'SN': 'contests.snarknews.info', '... |
"""EasyEngine exception classes."""
class EEError(Exception):
"""Generic errors."""
def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
def __str__(self):
return self.msg
class EEConfigError(EEError):
"""Config related errors."""
pass
class EERuntimeError(... | """EasyEngine exception classes."""
class Eeerror(Exception):
"""Generic errors."""
def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
def __str__(self):
return self.msg
class Eeconfigerror(EEError):
"""Config related errors."""
pass
class Eeruntimeerror(EE... |
class SimpleGroupProvider(object):
def __init__(self, *group_names):
self.group_names = group_names
def get_group_names(self):
return self.group_names | class Simplegroupprovider(object):
def __init__(self, *group_names):
self.group_names = group_names
def get_group_names(self):
return self.group_names |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.