content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Timer:
def __init__(self, duration, ticks):
self.duration = duration
self.ticks = ticks
self.thread = None
def start(self):
pass
# start Thread here
| class Timer:
def __init__(self, duration, ticks):
self.duration = duration
self.ticks = ticks
self.thread = None
def start(self):
pass |
#MAIN PROGRAM STARTS HERE:
num = int(input('Enter the number of rows and columns for the square: '))
for x in range(1, num + 1):
for y in range(1, num - 2 + 1):
print ('{} {} '.format(x, y), end='')
print() | num = int(input('Enter the number of rows and columns for the square: '))
for x in range(1, num + 1):
for y in range(1, num - 2 + 1):
print('{} {} '.format(x, y), end='')
print() |
def segmented_sieve(n):
# Create an boolean array with all values True
primes = [True]*n
for p in range(2,n):
#If prime[p] is True,it is a prime and its multiples are not prime
if primes[p]:
for i in range(2*p,n,p):
# Mark every multiple of a prime as not prim... | def segmented_sieve(n):
primes = [True] * n
for p in range(2, n):
if primes[p]:
for i in range(2 * p, n, p):
primes[i] = False
for l in range(2, n):
if primes[l]:
print(f'{l} ')
while True:
try:
input_value = int(input('Please a number: '))... |
class AuxPowMixin(object):
AUXPOW_START_HEIGHT = 0
AUXPOW_CHAIN_ID = 0x0001
BLOCK_VERSION_AUXPOW_BIT = 0
@classmethod
def is_auxpow_active(cls, header) -> bool:
height_allows_auxpow = header['block_height'] >= cls.AUXPOW_START_HEIGHT
version_allows_auxpow = header['version'] & cls.B... | class Auxpowmixin(object):
auxpow_start_height = 0
auxpow_chain_id = 1
block_version_auxpow_bit = 0
@classmethod
def is_auxpow_active(cls, header) -> bool:
height_allows_auxpow = header['block_height'] >= cls.AUXPOW_START_HEIGHT
version_allows_auxpow = header['version'] & cls.BLOCK_... |
#!/usr/bin/env python3
#filter sensitive words in user's input
def replace_sensitive_words(input_word):
s_words = []
with open('filtered_words','r') as f:
line = f.readline()
while line != '':
s_words.append(line.strip())
line = f.readline()
for word in s_words:
... | def replace_sensitive_words(input_word):
s_words = []
with open('filtered_words', 'r') as f:
line = f.readline()
while line != '':
s_words.append(line.strip())
line = f.readline()
for word in s_words:
if word in input_word:
input_word = input_word.... |
#Calcular el salario neto de un tnrabajador en fucion del numero de horas trabajadas, el precio de la hora
#y el descuento fijo al sueldo base por concepto de impuestos del 20%
horas = float(input("Ingrese el numero de horas trabajadas: "))
precio_hora = float(input("Ingrese el precio por hora trabajada: "))
sueldo_ba... | horas = float(input('Ingrese el numero de horas trabajadas: '))
precio_hora = float(input('Ingrese el precio por hora trabajada: '))
sueldo_base = float(input('Ingrese el valor del sueldo base: '))
pago_hora = horas * precio_hora
impuesto = 0.2
salario_neto = pago_hora + sueldo_base * 0.8
print(f'Si el trabajador tiene... |
class Runtime:
@staticmethod
def v3(major: str, feature: str, ml_type: str = None, scala_version: str = "2.12"):
if ml_type and ml_type.lower() not in ["cpu", "gpu"]:
raise ValueError('"ml_type" can only be "cpu" or "gpu"!')
return "".join(
[
f"{major}.",
... | class Runtime:
@staticmethod
def v3(major: str, feature: str, ml_type: str=None, scala_version: str='2.12'):
if ml_type and ml_type.lower() not in ['cpu', 'gpu']:
raise value_error('"ml_type" can only be "cpu" or "gpu"!')
return ''.join([f'{major}.', f'{feature}.x', '' if not ml_typ... |
s = 'abc'; print(s.isupper(), s)
s = 'Abc'; print(s.isupper(), s)
s = 'aBc'; print(s.isupper(), s)
s = 'abC'; print(s.isupper(), s)
s = 'abc'; print(s.isupper(), s)
s = 'ABC'; print(s.isupper(), s)
s = 'abc'; print(s.capitalize().isupper(), s.capitalize())
| s = 'abc'
print(s.isupper(), s)
s = 'Abc'
print(s.isupper(), s)
s = 'aBc'
print(s.isupper(), s)
s = 'abC'
print(s.isupper(), s)
s = 'abc'
print(s.isupper(), s)
s = 'ABC'
print(s.isupper(), s)
s = 'abc'
print(s.capitalize().isupper(), s.capitalize()) |
#!/usr/bin/env python
'''
Global Variables convention:
* start with UpperCase
* have no _ character
* may have mid UpperCase words
'''
Debug = True
Silent = True
Verbose = False
CustomerName = 'customer_name'
AuthHeader = {'Content-Type': 'application/json'}
BaseURL = "https://firewall-api.d-zone.ca"
... | """
Global Variables convention:
* start with UpperCase
* have no _ character
* may have mid UpperCase words
"""
debug = True
silent = True
verbose = False
customer_name = 'customer_name'
auth_header = {'Content-Type': 'application/json'}
base_url = 'https://firewall-api.d-zone.ca'
auth_url = 'https://fir... |
#
# PySNMP MIB module FUNI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FUNI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:03:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, constraints_intersection, value_size_constraint) ... |
x = 5
x |= 3
print(x)
| x = 5
x |= 3
print(x) |
## CUDA blocks are initialized here!
## Created by: Aditya Atluri
## Date: Mar 03 2014
def bx(blocks_dec, kernel):
if blocks_dec == False:
string = "int bx = blockIdx.x;\n"
kernel = kernel + string
blocks_dec = True
return kernel, blocks_dec
def by(blocks_dec, kernel):
if blocks_dec == False:
string = "int... | def bx(blocks_dec, kernel):
if blocks_dec == False:
string = 'int bx = blockIdx.x;\n'
kernel = kernel + string
blocks_dec = True
return (kernel, blocks_dec)
def by(blocks_dec, kernel):
if blocks_dec == False:
string = 'int by = blockIdx.y;\n'
kernel = kernel + string... |
def sample(name, custom_package):
native.android_binary(
name = name,
deps = [":sdk"],
srcs = native.glob(["samples/" + name + "/src/**/*.java"]),
custom_package = custom_package,
manifest = "samples/" + name + "/AndroidManifest.xml",
resource_files = native.glob(["sa... | def sample(name, custom_package):
native.android_binary(name=name, deps=[':sdk'], srcs=native.glob(['samples/' + name + '/src/**/*.java']), custom_package=custom_package, manifest='samples/' + name + '/AndroidManifest.xml', resource_files=native.glob(['samples/' + name + '/res/**/*'])) |
# generated from catkin/cmake/template/order_packages.context.py.in
source_root_dir = '/home/sim2real/ep_ws/src'
whitelisted_packages = ''.split(';') if '' != '' else []
blacklisted_packages = ''.split(';') if '' != '' else []
underlay_workspaces = '/home/sim2real/carto_ws/devel_isolated/cartographer_rviz;/home/sim2rea... | source_root_dir = '/home/sim2real/ep_ws/src'
whitelisted_packages = ''.split(';') if '' != '' else []
blacklisted_packages = ''.split(';') if '' != '' else []
underlay_workspaces = '/home/sim2real/carto_ws/devel_isolated/cartographer_rviz;/home/sim2real/carto_ws/install_isolated;/home/sim2real/ep_ws/devel;/opt/ros/noet... |
#
# PySNMP MIB module CISCOSB-RMON (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-RMON
# Produced by pysmi-0.3.4 at Wed May 1 12:23:18 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,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
class Stats:
writes: int
reads: int
accesses: int
def __init__(self) -> None:
self.reset()
def reset(self) -> None:
self.writes = 0
self.reads = 0
self.accesses = 0
def add_reads(self, count: int = 1) -> None:
self.reads += count
self.accesses +... | class Stats:
writes: int
reads: int
accesses: int
def __init__(self) -> None:
self.reset()
def reset(self) -> None:
self.writes = 0
self.reads = 0
self.accesses = 0
def add_reads(self, count: int=1) -> None:
self.reads += count
self.accesses += ... |
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = [
(color, size)
for color in colors
for size in sizes
]
print(f"Cartesian products from {colors} and {sizes}: {tshirts}")
| colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for color in colors for size in sizes]
print(f'Cartesian products from {colors} and {sizes}: {tshirts}') |
MAX_SENTENCE = 30
MAX_ALL = 50
MAX_SENT_LENGTH=MAX_SENTENCE
MAX_SENTS=MAX_ALL
max_entity_num = 10
num = 100
num1 = 200
num2 = 100
npratio=4
| max_sentence = 30
max_all = 50
max_sent_length = MAX_SENTENCE
max_sents = MAX_ALL
max_entity_num = 10
num = 100
num1 = 200
num2 = 100
npratio = 4 |
n=1
def f(x):
print(n)
f(0) | n = 1
def f(x):
print(n)
f(0) |
# creates a list and prints it
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
# traversing without an index
for day in days:
print(day)
# traversing with an index
for i in range(len(days)):
print(f"Day {i} is {days[i]}")
days[1] = "Lunes"
print("Day[1] is now ... | days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for day in days:
print(day)
for i in range(len(days)):
print(f'Day {i} is {days[i]}')
days[1] = 'Lunes'
print('Day[1] is now ', days[1])
for day in days:
print(day) |
# -*- coding: utf-8 -*-
# Memory addresses
ADDRESS_R15 = 0x400f
ADDRESS_ADC_POWER = 0x4062
ADDRESS_ADC_BATTERY = 0x4063
ADDRESS_LEVELA = 0x4064
ADDRESS_LEVELB = 0x4065
ADDRESS_PUSH_BUTTON = 0x4068
ADDRESS_COMMAND_1 = 0x4070
ADDRESS_COMMAND_2 = 0x4071
ADDRESS_MA_MIN_VALUE = 0x4086
ADDRESS_MA_MAX_VALUE = 0x4087
ADDRESS_... | address_r15 = 16399
address_adc_power = 16482
address_adc_battery = 16483
address_levela = 16484
address_levelb = 16485
address_push_button = 16488
address_command_1 = 16496
address_command_2 = 16497
address_ma_min_value = 16518
address_ma_max_value = 16519
address_current_mode = 16507
address_lcd_write_parameter_1 = 1... |
# http://www.codewars.com/kata/55f73f66d160f1f1db000059/
def combine_names(first_name, last_name):
return "{0} {1}".format(first_name, last_name)
| def combine_names(first_name, last_name):
return '{0} {1}'.format(first_name, last_name) |
# ------------------------------------------
#
# Program created by Maksim Kumundzhiev
#
#
# email: kumundzhievmaxim@gmail.com
# github: https://github.com/KumundzhievMaxim
# -------------------------------------------
BATCH_SIZE = 10
IMG_SIZE = (160, 160)
MODEL_PATH = 'checkpoints/model'
| batch_size = 10
img_size = (160, 160)
model_path = 'checkpoints/model' |
#1
num = int(input("Enter a number : "))
largest_divisor = 0
#2
for i in range(2, num):
#3
if num % i == 0:
#4
largest_divisor = i
#5
print("Largest divisor of {} is {}".format(num,largest_divisor))
| num = int(input('Enter a number : '))
largest_divisor = 0
for i in range(2, num):
if num % i == 0:
largest_divisor = i
print('Largest divisor of {} is {}'.format(num, largest_divisor)) |
class ObjectProperties:
def __init__(self, object_id, extra_data=None, ticket_type=None, quantity=None):
if extra_data:
self.extraData = extra_data
self.objectId = object_id
if ticket_type:
self.ticketType = ticket_type
if quantity:
self.quantity =... | class Objectproperties:
def __init__(self, object_id, extra_data=None, ticket_type=None, quantity=None):
if extra_data:
self.extraData = extra_data
self.objectId = object_id
if ticket_type:
self.ticketType = ticket_type
if quantity:
self.quantity ... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0:
return 0
m = 1
for _ in range(len(s)):
i = 0
S = set()
for x in range(_, len(s)):
if s[x] not in S:
S.add(s... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
if len(s) == 0:
return 0
m = 1
for _ in range(len(s)):
i = 0
s = set()
for x in range(_, len(s)):
if s[x] not in S:
S.add(s[x])
... |
class Stack:
def __init__(self):
self.items = []
def is_empty(self): # test to see whether the stack is empty.
return self.items == []
def push(self, item): # adds a new item to the top of the stack.
self.items.append(item)
def pop(self): # removes the top item from the sta... | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
... |
class Book:
def __init__(self, title, author, location):
self.title = title
self.author = author
self.location = location
self.page = 0
def turn_page(self, page):
self.page = page
| class Book:
def __init__(self, title, author, location):
self.title = title
self.author = author
self.location = location
self.page = 0
def turn_page(self, page):
self.page = page |
class Entity(object):
'''
An entity has:
- energy
- position(x,y)
- size(length, width)
An entity may have a parent entity
An entity may have child entities
'''
def __init__(
self,
p,
parent=None,
children=None):
... | class Entity(object):
"""
An entity has:
- energy
- position(x,y)
- size(length, width)
An entity may have a parent entity
An entity may have child entities
"""
def __init__(self, p, parent=None, children=None):
self.p = p
self.energy = p.getfloat('ENTITY', 'en... |
N = int(input())
A = list(map(int, input().split()))
d = {}
for i in range(N - 1):
if A[i] in d:
d[A[i]].append(i + 2)
else:
d[A[i]] = [i + 2]
for i in range(1, N + 1):
if i in d:
print(len(d[i]))
else:
print(0)
| n = int(input())
a = list(map(int, input().split()))
d = {}
for i in range(N - 1):
if A[i] in d:
d[A[i]].append(i + 2)
else:
d[A[i]] = [i + 2]
for i in range(1, N + 1):
if i in d:
print(len(d[i]))
else:
print(0) |
GENERIC = [
'Half of US adults have had family jailed',
'Judge stopped me winning election',
'Stock markets stabilise after earlier sell-off'
]
NON_GENERIC = [
'Leicester helicopter rotor controls failed',
'Pizza Express founder Peter Boizot dies aged 89',
'Senior Tory suggests vote could be d... | generic = ['Half of US adults have had family jailed', 'Judge stopped me winning election', 'Stock markets stabilise after earlier sell-off']
non_generic = ['Leicester helicopter rotor controls failed', 'Pizza Express founder Peter Boizot dies aged 89', 'Senior Tory suggests vote could be delayed'] |
class Solution:
def uniqueLetterString(self, S: str) -> int:
idxes = {ch : (-1, -1) for ch in string.ascii_uppercase}
ans = 0
for idx, ch in enumerate(S):
i, j = idxes[ch]
ans += (j - i) * (idx - j)
idxes[ch] = j, idx
for i, j in idxes.values():
... | class Solution:
def unique_letter_string(self, S: str) -> int:
idxes = {ch: (-1, -1) for ch in string.ascii_uppercase}
ans = 0
for (idx, ch) in enumerate(S):
(i, j) = idxes[ch]
ans += (j - i) * (idx - j)
idxes[ch] = (j, idx)
for (i, j) in idxes.va... |
class Image_Anotation:
def __init__(self, id, image, path_image):
self.id = id
self.FOV = [0.30,0.60]
self.image = image
self.list_roi=[]
self.list_compose_ROI=[]
self.id_roi=0
self.path_image = path_image
def set_image(self, image):
self.imag... | class Image_Anotation:
def __init__(self, id, image, path_image):
self.id = id
self.FOV = [0.3, 0.6]
self.image = image
self.list_roi = []
self.list_compose_ROI = []
self.id_roi = 0
self.path_image = path_image
def set_image(self, image):
self.im... |
NEO_HOST = "seed3.neo.org"
MAINNET_HTTP_RPC_PORT = 10332
MAINNET_HTTPS_RPC_PORT = 10331
TESTNET_HTTP_RPC_PORT = 20332
TESTNET_HTTPS_RPC_PORT = 20331
| neo_host = 'seed3.neo.org'
mainnet_http_rpc_port = 10332
mainnet_https_rpc_port = 10331
testnet_http_rpc_port = 20332
testnet_https_rpc_port = 20331 |
# first.n.squares.manual.method.py
def get_squares_gen(n):
for x in range(n):
yield x ** 2
squares = get_squares_gen(3)
print(squares.__next__()) # prints: 0
print(squares.__next__()) # prints: 1
print(squares.__next__()) # prints: 4
# the following raises StopIteration, the generator is exhausted,
# a... | def get_squares_gen(n):
for x in range(n):
yield (x ** 2)
squares = get_squares_gen(3)
print(squares.__next__())
print(squares.__next__())
print(squares.__next__())
print(squares.__next__()) |
class binary_tree:
def __init__(self):
pass
class Node(binary_tree):
__field_0 : int
__field_1 : binary_tree
__field_2 : binary_tree
def __init__(self, arg_0 : int , arg_1 : binary_tree , arg_2 : binary_tree ):
self.__field_0 = arg_0
self.__field_1 = arg_1
self.__fi... | class Binary_Tree:
def __init__(self):
pass
class Node(binary_tree):
__field_0: int
__field_1: binary_tree
__field_2: binary_tree
def __init__(self, arg_0: int, arg_1: binary_tree, arg_2: binary_tree):
self.__field_0 = arg_0
self.__field_1 = arg_1
self.__field_2 = ... |
def main():
_ = input()
string = input()
if _ == 0 or _ == 1:
return 0
if _ == 2:
if string[0] == string[1]:
return 1
return 0
last = string[0]
cnt = 0
for i in range(1, len(string)):
if string[i] == last:
cnt += 1
last = str... | def main():
_ = input()
string = input()
if _ == 0 or _ == 1:
return 0
if _ == 2:
if string[0] == string[1]:
return 1
return 0
last = string[0]
cnt = 0
for i in range(1, len(string)):
if string[i] == last:
cnt += 1
last = string... |
num = int(input("Enter a number: "))
sum = 0; size = 0; temp = num; temp2 = num
while(temp2!=0):
size += 1
temp2 = int(temp2/10)
while(temp!=0):
remainder = temp%10
sum += remainder**size
temp = int(temp/10)
if(sum == num):
print("It's an armstrong number")
else:
print("It's not an arms... | num = int(input('Enter a number: '))
sum = 0
size = 0
temp = num
temp2 = num
while temp2 != 0:
size += 1
temp2 = int(temp2 / 10)
while temp != 0:
remainder = temp % 10
sum += remainder ** size
temp = int(temp / 10)
if sum == num:
print("It's an armstrong number")
else:
print("It's not an arm... |
data_size_plus_header = 1000001
train_dir = 'train'
subset_train_dir = 'sub_train.txt'
fullfile = open(train_dir, 'r')
subfile = open(subset_train_dir,'w')
for i in range(data_size_plus_header):
subfile.write(fullfile.readline())
fullfile.close()
subfile.close()
| data_size_plus_header = 1000001
train_dir = 'train'
subset_train_dir = 'sub_train.txt'
fullfile = open(train_dir, 'r')
subfile = open(subset_train_dir, 'w')
for i in range(data_size_plus_header):
subfile.write(fullfile.readline())
fullfile.close()
subfile.close() |
long_number = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428280644448664523874930358... | long_number = '73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428280644448664523874930358... |
class Game:
def __init__(self,span=[0,100],sub_fun="Square"):
self.span=span
self.func_dict = {
"Square":lambda x: pow(x,2),
"Odd":lambda x: 1 + (x-1)*2,
"Even":lambda x: x*2,
"Identity":lambda x: x,
"Logarithm":lambda x: pow(10,x-1)
... | class Game:
def __init__(self, span=[0, 100], sub_fun='Square'):
self.span = span
self.func_dict = {'Square': lambda x: pow(x, 2), 'Odd': lambda x: 1 + (x - 1) * 2, 'Even': lambda x: x * 2, 'Identity': lambda x: x, 'Logarithm': lambda x: pow(10, x - 1)}
self.sub_fun = self.func_dict[sub_fun... |
# -*- coding: utf-8 -*-
# @Time : 2021/01/05 22:53:23
# @Author : ddvv
# @Site : https://ddvvmmzz.github.io
# @File : about.py
# @Software: Visual Studio Code
__all__ = [
"__author__",
"__copyright__",
"__email__",
"__license__",
"__summary__",
"__title__",
"__uri__",
"__ver... | __all__ = ['__author__', '__copyright__', '__email__', '__license__', '__summary__', '__title__', '__uri__', '__version__']
__title__ = 'python_mmdt'
__summary__ = 'Python wrapper for the mmdt library'
__uri__ = 'https://github.com/a232319779/python_mmdt'
__version__ = '0.2.3'
__author__ = 'ddvv'
__email__ = 'dadavivi5... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
A,B,M = map(int,input().split())
A_prise = list(map(int,input().split()))
B_prise = list(map(int,input().split()))
Most_low_prise = min(A_prise)+min(B_prise)
for i in range(M):
x,y,c = map(int,input().split())
Post_coupon_ori... | def main():
(a, b, m) = map(int, input().split())
a_prise = list(map(int, input().split()))
b_prise = list(map(int, input().split()))
most_low_prise = min(A_prise) + min(B_prise)
for i in range(M):
(x, y, c) = map(int, input().split())
post_coupon_orientation_prise = A_prise[x - 1] +... |
#!/usr/bin/env python3
# 2018-10-13 (cc) <paul4hough@gmail.com>
'''
pips:
- testinfra
- molecule
- tox
'''
class test_role_ans_dev (object):
''' test_role_ans_dev useless class
'''
assert packages.installed(
yaml.array( pkgs[common],
pkgs[os][common],
... | """
pips:
- testinfra
- molecule
- tox
"""
class Test_Role_Ans_Dev(object):
""" test_role_ans_dev useless class
"""
assert packages.installed(yaml.array(pkgs[common], pkgs[os][common], pkgs[os][major]))
assert pips.installed()
assert validate.python('https://github.com/python/stuff') |
#
# @lc app=leetcode id=657 lang=python3
#
# [657] Robot Return to Origin
#
# https://leetcode.com/problems/robot-return-to-origin/description/
#
# algorithms
# Easy (73.67%)
# Likes: 1228
# Dislikes: 692
# Total Accepted: 274.1K
# Total Submissions: 371K
# Testcase Example: '"UD"'
#
# There is a robot starting ... | class Solution:
def judge_circle(self, moves: str) -> bool:
start = [0, 0]
for move in moves:
if move == 'U':
(start[0], start[1]) = (start[0] + 0, start[1] + 1)
elif move == 'R':
(start[0], start[1]) = (start[0] + 1, start[1] + 0)
... |
def test_open_home_page(driver, request):
url = 'opencart/'
return driver.get("".join([request.config.getoption("--address"), url]))
element = driver.find_elements_by_xpath("//base[contains(@href, 'http://192.168.56.103/opencart/]")
assert element == 'http://192.168.56.103/opencart/'
assert driver.f... | def test_open_home_page(driver, request):
url = 'opencart/'
return driver.get(''.join([request.config.getoption('--address'), url]))
element = driver.find_elements_by_xpath("//base[contains(@href, 'http://192.168.56.103/opencart/]")
assert element == 'http://192.168.56.103/opencart/'
assert driver.f... |
TOMASULO_DEFAULT_PARAMETERS = {
"num_register": 32,
"num_rob": 128,
"num_cdb": 1,
"cdb_buffer_size": 0,
"nop_latency": 1,
"nop_unit_pipelined": 1,
"integer_adder_latency": 1,
"integer_adder_rs": 5,
"integer_adder_pipelined": 0,
"float_adder_latency": 3,
"float_adder_rs": 3... | tomasulo_default_parameters = {'num_register': 32, 'num_rob': 128, 'num_cdb': 1, 'cdb_buffer_size': 0, 'nop_latency': 1, 'nop_unit_pipelined': 1, 'integer_adder_latency': 1, 'integer_adder_rs': 5, 'integer_adder_pipelined': 0, 'float_adder_latency': 3, 'float_adder_rs': 3, 'float_adder_pipelined': 1, 'float_multiplier_... |
# answer = 5
# print("please guess number between 1 and 10: ")
# guess = int(input())
#
# if guess < answer:
# print("Please guess higher")
# elif guess > answer:
# print ( "Please guess lower")
# else:
# print("You got it first time")
answer = 5
print ("Please guess number between 1 and 10: ")
guess = in... | answer = 5
print('Please guess number between 1 and 10: ')
guess = int(input())
if guess != answer:
if guess < answer:
print('Please guess higher')
guess = int(input())
if guess == answer:
print('Well done, you guessed it')
else:
print('Sorry, you have not guessed correctly')
els... |
print("linear search")
si=int(input("\nEnter the size:"))
data=list()
for i in range(0,si):
n=int(input())
data.append(n)
cot=0
print("\nEnter the number you want to search:")
val=int(input())
for i in range(0,len(data)):
if(data[i]==val):
break;
else:
cot=co... | print('linear search')
si = int(input('\nEnter the size:'))
data = list()
for i in range(0, si):
n = int(input())
data.append(n)
cot = 0
print('\nEnter the number you want to search:')
val = int(input())
for i in range(0, len(data)):
if data[i] == val:
break
else:
cot = cot + 1
print(cot... |
#Pio_prefs
prefsdict = {
###modify or add preferences below
#below are the database preferences.
"sqluser" : "user",
"sqldb" : "database",
"sqlhost" : "127.0.0.1",
#authorization must come from same address - extra security
#valid values yes/no
"staticip" : "no",
#below is to do logging of qrystmts.... | prefsdict = {'sqluser': 'user', 'sqldb': 'database', 'sqlhost': '127.0.0.1', 'staticip': 'no', 'piolog': 'yes', 'showpobj': 'no', 'showpinp': 'no', 'showppref': 'no', 'pobjerror': 'bottom', 'pobjautherrorfile': 'Pio_login.html', 'pobjautherror': 'top', 'piosiderrorfile': 'none', 'piosiderror': 'bottom', 'loginerror': '... |
'''
Module for basic averaging of system states across multiple trials.
Used in plotting.
@author: Joe Schaul <joe.schaul@gmail.com>
'''
class TrialState(object):
def __init__(self, trial_id, times, systemStates, uniqueStates, stateCounterForStateX):
self.trial_id = trial_id
self.times... | """
Module for basic averaging of system states across multiple trials.
Used in plotting.
@author: Joe Schaul <joe.schaul@gmail.com>
"""
class Trialstate(object):
def __init__(self, trial_id, times, systemStates, uniqueStates, stateCounterForStateX):
self.trial_id = trial_id
self.times = times
... |
trees = []
with open("input.txt", "r") as f:
for line in f.readlines():
trees.append(line[:-1])
# curr pos
x, y = 0, 0
count = 0
while True:
x += 3
y += 1
if y >= len(trees):
break
if trees[y][x % len(trees[y])] == '#':
count += 1
print(count) | trees = []
with open('input.txt', 'r') as f:
for line in f.readlines():
trees.append(line[:-1])
(x, y) = (0, 0)
count = 0
while True:
x += 3
y += 1
if y >= len(trees):
break
if trees[y][x % len(trees[y])] == '#':
count += 1
print(count) |
#35011
#a3_p10.py
#Miruthula Ramesh
#mramesh@jacobs-university.de
n = int(input("Enter the width"))
w = int(input("Enter the length"))
c = input("Enter a character")
space=" "
def print_frame(n, w):
for i in range(n):
if i == 0 or i == n-1:
print(w*c)
else:
pr... | n = int(input('Enter the width'))
w = int(input('Enter the length'))
c = input('Enter a character')
space = ' '
def print_frame(n, w):
for i in range(n):
if i == 0 or i == n - 1:
print(w * c)
else:
print(c + space * (w - 2) + c)
print_frame(n, w) |
a = int(input())
sum = 0
while True:
if ( a == 0):
print (int(sum))
break
if ( a <= 2):
print (-1)
break
if (a%5 != 0):
a = a - 3
sum = sum + 1
else:
sum = sum + int(a/5)
a = 0
| a = int(input())
sum = 0
while True:
if a == 0:
print(int(sum))
break
if a <= 2:
print(-1)
break
if a % 5 != 0:
a = a - 3
sum = sum + 1
else:
sum = sum + int(a / 5)
a = 0 |
def add_num(x, y):
return x + y
def sub_num(x, y):
return x - y
class MathFunctions(object):
pass
| def add_num(x, y):
return x + y
def sub_num(x, y):
return x - y
class Mathfunctions(object):
pass |
if __name__ == '__main__':
N = int(input())
main_list=[]
for iterate in range(N):
entered_string=input().split()
if entered_string[0] == 'insert':
main_list.insert(int(entered_string[1]),int(entered_string[2]))
elif entered_string[0] == 'print':
print(main_lis... | if __name__ == '__main__':
n = int(input())
main_list = []
for iterate in range(N):
entered_string = input().split()
if entered_string[0] == 'insert':
main_list.insert(int(entered_string[1]), int(entered_string[2]))
elif entered_string[0] == 'print':
print(mai... |
with open('input.txt', 'r') as file:
input = file.readlines()
input = [ step.split() for step in input ]
input = [ {step[0]: int(step[1])} for step in input ]
def part1():
x = 0
y = 0
for step in input:
x += step.get('forward', 0)
y += step.get('down', 0)
y -= step.get('up', 0)... | with open('input.txt', 'r') as file:
input = file.readlines()
input = [step.split() for step in input]
input = [{step[0]: int(step[1])} for step in input]
def part1():
x = 0
y = 0
for step in input:
x += step.get('forward', 0)
y += step.get('down', 0)
y -= step.get('up', 0)
... |
def f(x):
if x:
x = 1
else:
x = 'zero'
y = x
return y
f(1)
| def f(x):
if x:
x = 1
else:
x = 'zero'
y = x
return y
f(1) |
class Pattern_Twenty_Six:
'''Pattern twenty_six
***
* *
*
* ***
* *
* *
***
'''
def __init__(self, strings='*'):
if not isinstance(strings, str):
strings = str(strings)
for i in range(7):
if i i... | class Pattern_Twenty_Six:
"""Pattern twenty_six
***
* *
*
* ***
* *
* *
***
"""
def __init__(self, strings='*'):
if not isinstance(strings, str):
strings = str(strings)
for i in range(7):
if i in... |
def debug_transformer(func):
def wrapper():
print(f'Function `{func.__name__}` called')
func()
print(f'Function `{func.__name__}` finished')
return wrapper
@debug_transformer
def walkout():
print('Bye Felicia')
walkout() | def debug_transformer(func):
def wrapper():
print(f'Function `{func.__name__}` called')
func()
print(f'Function `{func.__name__}` finished')
return wrapper
@debug_transformer
def walkout():
print('Bye Felicia')
walkout() |
def preprocess(text):
text=text.replace('\n', '\n\r')
return text
def getLetter():
return open("./input/letter.txt", "r").read()
| def preprocess(text):
text = text.replace('\n', '\n\r')
return text
def get_letter():
return open('./input/letter.txt', 'r').read() |
MainWindow.clearData()
MainWindow.openPreWindow()
box = CAD.Box()
box.setName('Box_1')
box.setLocation(0,0,0)
box.setPara(10,10,10)
box.create()
cylinder = CAD.Cylinder()
cylinder.setName('Cylinder_2')
cylinder.setLocation(0,0,0)
cylinder.setRadius(5)
cylinder.setLength(10)
cylinder.setAxis(0,0,1)
cylinder... | MainWindow.clearData()
MainWindow.openPreWindow()
box = CAD.Box()
box.setName('Box_1')
box.setLocation(0, 0, 0)
box.setPara(10, 10, 10)
box.create()
cylinder = CAD.Cylinder()
cylinder.setName('Cylinder_2')
cylinder.setLocation(0, 0, 0)
cylinder.setRadius(5)
cylinder.setLength(10)
cylinder.setAxis(0, 0, 1)
cylinder.crea... |
class Parrot():
def __init__(self, squawk, is_alive=True):
self.squawk = squawk
self.is_alive = is_alive
african_grey = Parrot('Polly want a Cracker?')
norwegian_blue = Parrot('', is_alive=False)
def squawk(self):
if self.is_alive:
return self.squawk
else:
... | class Parrot:
def __init__(self, squawk, is_alive=True):
self.squawk = squawk
self.is_alive = is_alive
african_grey = parrot('Polly want a Cracker?')
norwegian_blue = parrot('', is_alive=False)
def squawk(self):
if self.is_alive:
return self.squawk
else:
return None
african... |
def solution(S, K):
# write your code in Python 3.6
day_dict = {0:'Mon', 1:'Tue', 2:'Wed', 3:'Thu', 4:'Fri', 5:'Sat', 6:'Sun'}
return day_dict[list(day_dict.values()).index(S)+K]
S='Wed'
K=2
print(solution(S,K))
| def solution(S, K):
day_dict = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
return day_dict[list(day_dict.values()).index(S) + K]
s = 'Wed'
k = 2
print(solution(S, K)) |
produtos = {1: 4.0, 2: 4.5, 3: 5.0, 4: 2.0, 5: 1.5}
produto, quantidade = [int(num) for num in input().split()]
total = produtos[produto] * quantidade
print('Total: R$ {:.2f}'.format(total))
| produtos = {1: 4.0, 2: 4.5, 3: 5.0, 4: 2.0, 5: 1.5}
(produto, quantidade) = [int(num) for num in input().split()]
total = produtos[produto] * quantidade
print('Total: R$ {:.2f}'.format(total)) |
arr=[int(x) for x in input().split()]
sum=0
for i in range(1,(arr[2]+1)):
sum+=arr[0]*i
if sum<=arr[1]:
print(0)
else:
print(sum-arr[1])
| arr = [int(x) for x in input().split()]
sum = 0
for i in range(1, arr[2] + 1):
sum += arr[0] * i
if sum <= arr[1]:
print(0)
else:
print(sum - arr[1]) |
# Binary search of an item in a (sorted) list
def binary_search(alist, item):
first = 0
last = len(alist) - 1
found = False
while first <= last and not found:
middle = (first + last) // 2
if alist[middle] == item:
found = True
else:
if item < alist[midd... | def binary_search(alist, item):
first = 0
last = len(alist) - 1
found = False
while first <= last and (not found):
middle = (first + last) // 2
if alist[middle] == item:
found = True
elif item < alist[middle]:
last = middle - 1
else:
fi... |
def resolve():
'''
code here
'''
N = int(input())
A_list = [int(item) for item in input().split()]
hp = sum(A_list) #leaf
is_slove = True
res = 1 # root
prev = 1
prev_add_num = 0
delete_cnt = 0
if hp > 2**N:
is_slove = False
elif A_list[0] == 1:
i... | def resolve():
"""
code here
"""
n = int(input())
a_list = [int(item) for item in input().split()]
hp = sum(A_list)
is_slove = True
res = 1
prev = 1
prev_add_num = 0
delete_cnt = 0
if hp > 2 ** N:
is_slove = False
elif A_list[0] == 1:
if len(A_list) >=... |
class Solution:
def reverseWords(self, s: str) -> str:
s = s.split(" ")
s = [i for i in s if i != ""]
return " ".join(s[::-1]) | class Solution:
def reverse_words(self, s: str) -> str:
s = s.split(' ')
s = [i for i in s if i != '']
return ' '.join(s[::-1]) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# if root.left and root.right:
# if v <= root.left.val or v >= root.right.val: return False
# elif ... | class Solution:
def is_valid_bst(self, root: TreeNode) -> bool:
self.prev = None
return self.recur(root)
def recur(self, root):
if not root:
return True
left = self.recur(root.left)
if self.prev and self.prev.val >= root.val:
return False
... |
class hparams:
sample_rate = 16000
n_fft = 1024
#fft_bins = n_fft // 2 + 1
num_mels = 80
hop_length = 256
win_length = 1024
fmin = 90
fmax = 7600
min_level_db = -100
ref_level_db = 20
seq_len_factor = 64
bits = 12
seq_len = seq_len_factor * hop_length
d... | class Hparams:
sample_rate = 16000
n_fft = 1024
num_mels = 80
hop_length = 256
win_length = 1024
fmin = 90
fmax = 7600
min_level_db = -100
ref_level_db = 20
seq_len_factor = 64
bits = 12
seq_len = seq_len_factor * hop_length
dim_neck = 32
dim_emb = 256
dim_pre... |
# Material
buttonType = ['Arrow button', 'Radio button', 'Switch button', 'Option']
requestLUT = [
{
'name' : 'Radio',
'on' : 'OSD_ImgFolder/radio_on.png',
'off' : 'OSD_ImgFolder/radio_off.png',
'default' : 'off',
'hint_path' : 'OSD_ImgFolder/L4 off.png',
'hint': 0
},
{
'nam... | button_type = ['Arrow button', 'Radio button', 'Switch button', 'Option']
request_lut = [{'name': 'Radio', 'on': 'OSD_ImgFolder/radio_on.png', 'off': 'OSD_ImgFolder/radio_off.png', 'default': 'off', 'hint_path': 'OSD_ImgFolder/L4 off.png', 'hint': 0}, {'name': 'Switch', 'on': 'OSD_ImgFolder/switch_on.png', 'off': 'OSD_... |
database = "database"
user = "postgres"
password = "password"
host = "localhost"
port = "5432"
| database = 'database'
user = 'postgres'
password = 'password'
host = 'localhost'
port = '5432' |
def mul(a, b):
return a * b
mul(3, 4)
#12
def mul5(a):
return mul(5,a)
mul5(2)
#10
def mul(a):
def helper(b):
return a * b
return helper
mul(5)(2)
#10
def fun1(a):
x = a * 3
def fun2(b):
nonlocal x
return b + x
return fun2
test_fun = fun1(4)
test_fun(7)
#19
| def mul(a, b):
return a * b
mul(3, 4)
def mul5(a):
return mul(5, a)
mul5(2)
def mul(a):
def helper(b):
return a * b
return helper
mul(5)(2)
def fun1(a):
x = a * 3
def fun2(b):
nonlocal x
return b + x
return fun2
test_fun = fun1(4)
test_fun(7) |
seagate_sense_codes = {0: {0: {0: {0: 'No error.', 'L1': 'No Sense', 'L2': 'No Sense'},
31: {0: 'No Specific FRU code.',
'L1': 'No Sense',
'L2': 'Logical unit transitioning to another power condition'}},
... | seagate_sense_codes = {0: {0: {0: {0: 'No error.', 'L1': 'No Sense', 'L2': 'No Sense'}, 31: {0: 'No Specific FRU code.', 'L1': 'No Sense', 'L2': 'Logical unit transitioning to another power condition'}}, 94: {0: {0: 'No Specific FRU code.', 'L1': 'No Sense', 'L2': 'Drive is in power save mode for unknown reasons'}, 1: ... |
frase = str(input('Digite a frase: ')).strip().upper()
palavras = frase.split()
juntarPalavras = ''.join(palavras)
trocar = juntarPalavras[::-1]
print(trocar) | frase = str(input('Digite a frase: ')).strip().upper()
palavras = frase.split()
juntar_palavras = ''.join(palavras)
trocar = juntarPalavras[::-1]
print(trocar) |
def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2. * np.pi)
return tf.reduce_sum(
-.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi),
axis=raxis)
def compute_loss(model, x):
mean, logvar = model.encode(x)
z = model.reparameterize(mean, logvar)
x_logit = mod... | def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2.0 * np.pi)
return tf.reduce_sum(-0.5 * ((sample - mean) ** 2.0 * tf.exp(-logvar) + logvar + log2pi), axis=raxis)
def compute_loss(model, x):
(mean, logvar) = model.encode(x)
z = model.reparameterize(mean, logvar)
x_logit = mo... |
my_name = "Jan"
my_age = 23
print(f"Age: { my_age }, Name: { my_name }")
| my_name = 'Jan'
my_age = 23
print(f'Age: {my_age}, Name: {my_name}') |
# Yunfan Ye 10423172
def Fibonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
# arr = [1,2,3,4,5,6,7,8,9,10]
# for i in arr:
# print(Fibonacci(i))
| def fibonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) |
class UrlPath:
@staticmethod
def combine(*args):
result = ''
for path in args:
result += path if path.endswith('/') else '{}/'.format(path)
#result = result[:-1]
return result | class Urlpath:
@staticmethod
def combine(*args):
result = ''
for path in args:
result += path if path.endswith('/') else '{}/'.format(path)
return result |
class Error():
def __init__(self):
print("An error has occured !")
class TypeError(Error):
def __init__(self):
print("This is Type Error\nThere is a type mismatch.. ! Please fix it.") | class Error:
def __init__(self):
print('An error has occured !')
class Typeerror(Error):
def __init__(self):
print('This is Type Error\nThere is a type mismatch.. ! Please fix it.') |
class Node(object):
def __init__(self, value, next=None, prev=None):
self.value = value
self.next = next
self.prev = prev
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def push(self, value):
new_node... | class Node(object):
def __init__(self, value, next=None, prev=None):
self.value = value
self.next = next
self.prev = prev
class Linkedlist(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def push(self, value):
new_nod... |
# Check if the value is in the list?
words = ['apple', 'banana', 'peach', '42']
if 'apple' in words:
print('found apple')
if 'a' in words:
print('found a')
else:
print('NOT found a')
if 42 in words:
print('found 42')
else:
print('NOT found 42')
# found apple
# NOT found a
# NOT found 42 | words = ['apple', 'banana', 'peach', '42']
if 'apple' in words:
print('found apple')
if 'a' in words:
print('found a')
else:
print('NOT found a')
if 42 in words:
print('found 42')
else:
print('NOT found 42') |
__author__ = 'renderle'
class OpenWeatherParser:
def __init__(self, data):
self.data = data
def getValueFor(self, idx):
return self.data['list'][idx]
def getTemperature(self):
earlymorningValue = self.getValueFor(0)['main']['temp_max']
morningValue = self.getValueFor(1)['... | __author__ = 'renderle'
class Openweatherparser:
def __init__(self, data):
self.data = data
def get_value_for(self, idx):
return self.data['list'][idx]
def get_temperature(self):
earlymorning_value = self.getValueFor(0)['main']['temp_max']
morning_value = self.getValueFor... |
X = []
Y = []
cont = 0
n = True
while n:
a,b = input().split(" ")
a = int(a)
b = int(b)
if a == b:
n = False
cont-=1
else:
X.append(a)
Y.append(b)
cont+=1
i = 0
while i < cont:
if X[i] > Y[i]:
print('Decrescente')
elif X[i] < ... | x = []
y = []
cont = 0
n = True
while n:
(a, b) = input().split(' ')
a = int(a)
b = int(b)
if a == b:
n = False
cont -= 1
else:
X.append(a)
Y.append(b)
cont += 1
i = 0
while i < cont:
if X[i] > Y[i]:
print('Decrescente')
elif X[i] < Y[i]:
p... |
def test_example():
num1 = 1
num2 = 3
if num2 > num1:
print("Working")
| def test_example():
num1 = 1
num2 = 3
if num2 > num1:
print('Working') |
class Node:
def __init__(self,v):
self.next=None
self.prev=None
self.value=v
class Deque:
def __init__(self):
self.front=None
self.tail=None
def addFront(self, item):
node=Node(item)
if self.front is None: #case of none items
se... | class Node:
def __init__(self, v):
self.next = None
self.prev = None
self.value = v
class Deque:
def __init__(self):
self.front = None
self.tail = None
def add_front(self, item):
node = node(item)
if self.front is None:
self.front = nod... |
'''
A package to manipulate and display some random structures,
including meander systems, planar triangulations, and ribbon tilings
Created on May 8, 2021
@author: vladislavkargin
'''
'''
#I prefer blank __init__.py
from . import mndrpy
from . import pmaps
from . import ribbons
''' | """
A package to manipulate and display some random structures,
including meander systems, planar triangulations, and ribbon tilings
Created on May 8, 2021
@author: vladislavkargin
"""
'\n#I prefer blank __init__.py\n\nfrom . import mndrpy\nfrom . import pmaps\nfrom . import ribbons\n' |
name = input('Please enter your name:\n')
age = int(input("Please enter your age:\n"))
color = input('Enter your favorite color:\n')
animal = input('Enter your favorite animal:\n')
print('Hello my name is' , name , '.')
print('I am' , age , 'years old.')
print('My favorite color is' , color ,'.')
print('My favorite... | name = input('Please enter your name:\n')
age = int(input('Please enter your age:\n'))
color = input('Enter your favorite color:\n')
animal = input('Enter your favorite animal:\n')
print('Hello my name is', name, '.')
print('I am', age, 'years old.')
print('My favorite color is', color, '.')
print('My favorite animal i... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/vis-02-curtailment.ipynb (unless otherwise specified).
__all__ = ['get_wf_ids', 'flatten_list', 'get_curtailed_wfs_df', 'load_curtailed_wfs',
'add_next_week_of_data_to_curtailed_wfs']
# Cell
flatten_list = lambda list_: [item for sublist in list_ for item in ... | __all__ = ['get_wf_ids', 'flatten_list', 'get_curtailed_wfs_df', 'load_curtailed_wfs', 'add_next_week_of_data_to_curtailed_wfs']
flatten_list = lambda list_: [item for sublist in list_ for item in sublist]
def get_wf_ids(dictionary_url='https://raw.githubusercontent.com/OSUKED/Power-Station-Dictionary/main/data/output... |
'''
No 2. Buatlah fungsi tanpa pengembalian nilai, yaitu fungsi segitigabintang.
Misal, jika dipanggil dg segitigabintang(4), keluarannya :
*
**
***
****
'''
def segitigabintang(baris):
for i in range(baris):
print('*' * (i+1))
| """
No 2. Buatlah fungsi tanpa pengembalian nilai, yaitu fungsi segitigabintang.
Misal, jika dipanggil dg segitigabintang(4), keluarannya :
*
**
***
****
"""
def segitigabintang(baris):
for i in range(baris):
print('*' * (i + 1)) |
#!/usr/bin/python3
m1 = int(input("Enter no. of rows : \t"))
n1 = int(input("Enter no. of columns : \t"))
a = []
print("Enter Matrix 1:\n")
for i in range(n1):
row = list(map(int, input().split()))
a.append(row)
print(a)
m2 = int(n1)
print("\n Your Matrix 2 must have",n1,"rows and",m1,"columns \n")
n2 ... | m1 = int(input('Enter no. of rows : \t'))
n1 = int(input('Enter no. of columns : \t'))
a = []
print('Enter Matrix 1:\n')
for i in range(n1):
row = list(map(int, input().split()))
a.append(row)
print(a)
m2 = int(n1)
print('\n Your Matrix 2 must have', n1, 'rows and', m1, 'columns \n')
n2 = int(m1)
b = []
for i i... |
# =============================================================================
# TexGen: Geometric textile modeller.
# Copyright (C) 2015 Louise Brown
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Found... | textile = c_textile()
section = c_section_lenticular(0.3, 0.14)
Section.AssignSectionMesh(c_section_mesh_triangulate(30))
yarns = (c_yarn(), c_yarn(), c_yarn(), c_yarn())
Yarns[0].AddNode(c_node(xyz(0, 0, 0)))
Yarns[0].AddNode(c_node(xyz(0.35, 0, 0.15)))
Yarns[0].AddNode(c_node(xyz(0.7, 0, 0)))
Yarns[1].AddNode(c_node(... |
# -*- coding: UTF-8 -*-
logger.info("Loading 1 objects to table invoicing_plan...")
# fields: id, user, today, journal, max_date, partner, course
loader.save(create_invoicing_plan(1,6,date(2015,3,1),1,None,None,None))
loader.flush_deferred_objects()
| logger.info('Loading 1 objects to table invoicing_plan...')
loader.save(create_invoicing_plan(1, 6, date(2015, 3, 1), 1, None, None, None))
loader.flush_deferred_objects() |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
# Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
#
# For example, given the following Node class:
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
... | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def serialize(root, string=''):
string += root.val
string += '('
if root.left != None:
string = serialize(root.left, string)
string += '|'
if root.righ... |
store.set_global_value('hotkey', '<meta>+r')
if re.match('.*(Hyper)', window.get_active_class()):
logging.debug('terminal refresh buffer')
engine.set_return_value('<ctrl>+<shift>+r')
else:
logging.debug('normal')
engine.set_return_value('<ctrl>+r')
engine.run_script('combo') | store.set_global_value('hotkey', '<meta>+r')
if re.match('.*(Hyper)', window.get_active_class()):
logging.debug('terminal refresh buffer')
engine.set_return_value('<ctrl>+<shift>+r')
else:
logging.debug('normal')
engine.set_return_value('<ctrl>+r')
engine.run_script('combo') |
# Defining the left function
def left(i):
return 2*i+1
# Defining the right function
def right(i):
return 2*i+2
# Defining the parent node function
def parent(i):
return (i-1)//2
# Max_Heapify
def max_heapify(arr,n,i):
l=left(i)
r=right(i)
largest=i
if n>l and arr[largest]<arr[l] :
... | def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
def parent(i):
return (i - 1) // 2
def max_heapify(arr, n, i):
l = left(i)
r = right(i)
largest = i
if n > l and arr[largest] < arr[l]:
largest = l
if n > r and arr[largest] < arr[r]:
largest = r
if large... |
#num1=int(raw_input("Enter num #1:"))
#num2=int(raw_input("Enter num #2:"))
#total= num1 + num2
#print("The sum is: "+ str(total))
# need to be a string so computer can read it
# all strings can be integers but not all integers can be strings
# num = int(raw_input("Enter a number:"))
# if num>0:
# print("That's a p... | word = 'computerz'
print(word[:5])
print(word[:-1])
print(word[4:])
print(word[-3:]) |
class SinavroObject: pass
def init(self, val): self.value = val
gencls = lambda n: type(f'Sinavro{n.title()}', (SinavroObject,), {'__init__': init, 'type': n})
SinavroInt = gencls('int')
SinavroFloat = gencls('float')
SinavroString = gencls('string')
SinavroBool = gencls('bool')
SinavroArray = gencls('array'... | class Sinavroobject:
pass
def init(self, val):
self.value = val
gencls = lambda n: type(f'Sinavro{n.title()}', (SinavroObject,), {'__init__': init, 'type': n})
sinavro_int = gencls('int')
sinavro_float = gencls('float')
sinavro_string = gencls('string')
sinavro_bool = gencls('bool')
sinavro_array = gencls('arr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.