content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def add_same_site(response):
for idx, header in enumerate(response.raw_headers):
if header[0].decode("utf-8") == "set-cookie":
cookie = header[1].decode("utf-8")
if "SameSite=None" not in cookie:
cookie = cookie + "; SameSite=None"
response.raw_headers... | def add_same_site(response):
for (idx, header) in enumerate(response.raw_headers):
if header[0].decode('utf-8') == 'set-cookie':
cookie = header[1].decode('utf-8')
if 'SameSite=None' not in cookie:
cookie = cookie + '; SameSite=None'
response.raw_heade... |
print("counting Sort")
print("Range of input")
n=int(input())
l=[]
print("Total elements:")
t=int(input())
print("input elements:")
for j in range(0,t):
p=int(input())
if p>n:
print("out of bounds")
else:
l.append(p)
print("Unsorted list is:")
print(l)
print("Sorted list is:")
l.s... | print('counting Sort')
print('Range of input')
n = int(input())
l = []
print('Total elements:')
t = int(input())
print('input elements:')
for j in range(0, t):
p = int(input())
if p > n:
print('out of bounds')
else:
l.append(p)
print('Unsorted list is:')
print(l)
print('Sorted list is:')
l.s... |
class query:
def __init__(self, name, url):
self.name = name
self.url = url
class change:
def __init__(self, car, summary, reason):
self.car = car
self.summary = summary
self.reason = reason
def __str__(self):
return self.reason + "\n" + str(... | class Query:
def __init__(self, name, url):
self.name = name
self.url = url
class Change:
def __init__(self, car, summary, reason):
self.car = car
self.summary = summary
self.reason = reason
def __str__(self):
return self.reason + '\n' + str(self.car)
... |
a = int(input())
b = 0
while True:
if a == 1:
break
if a % 2 == 0:
a /= 2
else:
a = (a * 3) + 1
b += 1
print(b) | a = int(input())
b = 0
while True:
if a == 1:
break
if a % 2 == 0:
a /= 2
else:
a = a * 3 + 1
b += 1
print(b) |
# player_amp
### written in Phyton 3.8.1 by Strolch
# setserver.setserver()
# debug.debug()
print("Unfortunately, there was an problem.")
print("Please try it again with player_amp.debug to see the errors!")
print("amp.debug uses no exception handling and prints more information")
| print('Unfortunately, there was an problem.')
print('Please try it again with player_amp.debug to see the errors!')
print('amp.debug uses no exception handling and prints more information') |
number = int(input(" Enter the number : "))
if((number % 5 == 0) and (number % 3 == 0)):
print("Given Number is Divisible by 5 and 3",number)
else:
print("Given Number is Not Divisible by 5 and 3",number) | number = int(input(' Enter the number : '))
if number % 5 == 0 and number % 3 == 0:
print('Given Number is Divisible by 5 and 3', number)
else:
print('Given Number is Not Divisible by 5 and 3', number) |
num1 = 1
mun2 = 2
num3 = 3
num4 = 40
num4 = 4
num5 = 5
num6 = 6
| num1 = 1
mun2 = 2
num3 = 3
num4 = 40
num4 = 4
num5 = 5
num6 = 6 |
__all__ = ["<caret>"]
m3 = 1
m4 = 1 | __all__ = ['<caret>']
m3 = 1
m4 = 1 |
'''
As a final exercise in hypothesis testing before we put everything together in our case study in the next chapter, you will investigate the effects of neonicotinoid insecticides on bee reproduction. These insecticides are very widely used in the United States to combat aphids and other pests that damage plants.
In... | """
As a final exercise in hypothesis testing before we put everything together in our case study in the next chapter, you will investigate the effects of neonicotinoid insecticides on bee reproduction. These insecticides are very widely used in the United States to combat aphids and other pests that damage plants.
In... |
def prepare_data(self, data):
inp = []
out = []
for imgs, labels in data:
inp.append(imgs)
out.append(labels)
return inp, out
def partition_data(self):
# Randomize training set
random.shuffle(self.training_data)
X_train, y_train = self.prepare_data(self.training_data)
... | def prepare_data(self, data):
inp = []
out = []
for (imgs, labels) in data:
inp.append(imgs)
out.append(labels)
return (inp, out)
def partition_data(self):
random.shuffle(self.training_data)
(x_train, y_train) = self.prepare_data(self.training_data)
val_set_size = int(len(se... |
'''
An implementation of the Language Server Protocol for the YARA pattern matching language
https://microsoft.github.io/language-server-protocol/
'''
| """
An implementation of the Language Server Protocol for the YARA pattern matching language
https://microsoft.github.io/language-server-protocol/
""" |
#
# PySNMP MIB module JUNIPER-UTIL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-UTIL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:01:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
VISIBILITY = (
("public", "public"),
("private", "private"),
("forked", "forked"),
)
| visibility = (('public', 'public'), ('private', 'private'), ('forked', 'forked')) |
class DataConfig(object):
data_path = "./models/rambo/data"
data_name = "hsv_gray_diff_ch4"
img_height = 160
img_width = 320
num_channels = 2
class TrainConfig(DataConfig):
model_name = "comma_prelu"
batch_size = 32
num_epoch = 10
val_part = 33
X_train_mean_path = "./data/X_tra... | class Dataconfig(object):
data_path = './models/rambo/data'
data_name = 'hsv_gray_diff_ch4'
img_height = 160
img_width = 320
num_channels = 2
class Trainconfig(DataConfig):
model_name = 'comma_prelu'
batch_size = 32
num_epoch = 10
val_part = 33
x_train_mean_path = './data/X_trai... |
# Camera maker and system
# For exemple: for a 'Canon EOS Rebel T5i' the
# maker is 'Canon' and the system is 'EOS'.
camera = {
'maker' : 'Canon',
'system' : 'EOS'
}
# Lenses to be compared to define the best one, based in the history
# of photos taken in the focal length covered by the lenses in the list.
... | camera = {'maker': 'Canon', 'system': 'EOS'}
lenses = [['Canon EF-S 10-18mm f/4.5-5.6 IS STM', 10, 18, 0], ['Canon EF-S 18-55mm f/3.5-5.6 IS STM', 18, 55, 0], ['Canon EF-S 55-250mm f/4-5.6 IS STM', 55, 250, 0], ['Canon EF-S 24mm f/2.8 STM', 24, 24, 0], ['Canon EF 50mm f/1.8 STM', 50, 50, 0]] |
CONST_RESPONSE_CODES_FOR_QUEUE = (10000, # Connection refused
421,
450,
451,
452,
455,
553
... | const_response_codes_for_queue = (10000, 421, 450, 451, 452, 455, 553) |
'''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Ex... | """
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Ex... |
self.description = "Scriptlet test (pre/post install)"
p1 = pmpkg("dummy")
p1.files = ['etc/dummy.conf']
p1.install['pre_install'] = "echo foobar > pre_install"
p1.install['post_install'] = "echo foobar > post_install"
self.addpkg(p1)
self.args = "-U %s" % p1.filename()
self.addrule("PACMAN_RETCODE=0")
self.addrule(... | self.description = 'Scriptlet test (pre/post install)'
p1 = pmpkg('dummy')
p1.files = ['etc/dummy.conf']
p1.install['pre_install'] = 'echo foobar > pre_install'
p1.install['post_install'] = 'echo foobar > post_install'
self.addpkg(p1)
self.args = '-U %s' % p1.filename()
self.addrule('PACMAN_RETCODE=0')
self.addrule('FI... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == "__main__":
mi_objeto_a = "Un texto"
mi_objeto_b = "Un texto"
if mi_objeto_a == mi_objeto_b:
print("El contenido de mi_objeto_a es igual que el de mi_objeto_b")
else:
print("El contenido de mi_objeto_a NO es igual que el de ... | if __name__ == '__main__':
mi_objeto_a = 'Un texto'
mi_objeto_b = 'Un texto'
if mi_objeto_a == mi_objeto_b:
print('El contenido de mi_objeto_a es igual que el de mi_objeto_b')
else:
print('El contenido de mi_objeto_a NO es igual que el de mi_objeto_b') |
def isValid(s):
frequencies = []
freq_frequencies = []
for letter in set(s):
frequencies.append(s.count(letter))
for freq in set(frequencies):
freq_frequencies.append(frequencies.count(freq))
if (len(freq_frequencies) > 2):
return "NO"
if (sum(frequencies) % len(frequenci... | def is_valid(s):
frequencies = []
freq_frequencies = []
for letter in set(s):
frequencies.append(s.count(letter))
for freq in set(frequencies):
freq_frequencies.append(frequencies.count(freq))
if len(freq_frequencies) > 2:
return 'NO'
if sum(frequencies) % len(frequencies... |
# md5 : 29cbdb71b0558448282df4aaeb79105d
# sha1 : 7fa902f178f8c267cdeaa4b2c32f34ceda504979
# sha256 : 97c3eb810120c22e16de716c104d0d99abbc0e73832b9abda6da70515a29a213
ord_names = {
248: b'OleIconToCursor',
249: b'OleCreatePropertyFrameIndirect',
250: b'OleCreatePropertyFrame',
251: b'OleLoadPicture',
... | ord_names = {248: b'OleIconToCursor', 249: b'OleCreatePropertyFrameIndirect', 250: b'OleCreatePropertyFrame', 251: b'OleLoadPicture', 252: b'OleCreatePictureIndirect', 253: b'OleCreateFontIndirect', 254: b'OleTranslateColor', 255: b'DllCanUnloadNow', 256: b'DllGetClassObject', 257: b'DllRegisterServer', 258: b'DllUnreg... |
#
# PySNMP MIB module CTRON-IPX-ROUTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-IPX-ROUTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
class DefaultConfig(object):
pass
class DevConfig(DefaultConfig):
DEBUG = True
class ProductionConfig(DefaultConfig):
DEBUG = False
class TestConfig(DefaultConfig):
TESTING = True
| class Defaultconfig(object):
pass
class Devconfig(DefaultConfig):
debug = True
class Productionconfig(DefaultConfig):
debug = False
class Testconfig(DefaultConfig):
testing = True |
#!/usr/bin/env python3
# p3_190819_1215.py
# CodeWars: Persistent Bugger
# Details: Write a function, persistence, that takes in a positive
# parameter num and returns its multiplicative persistence, which is the
# number of times you must multiply the digits in num until you reach a
# single digit.
def convert_to_int... | def convert_to_int_list(number: int):
return [int(nlist) for nlist in str(number)]
def persistence(n: int):
steps = 0
while not len(str(n)) < 2:
j = 1
for i in convert_to_int_list(n):
j = j * i
steps += 1
n = j
return steps
if __name__ == '__main__':
prin... |
def get_sum(a,b):
if a > b:
a, b = b, a
if a == b:
print(a)
x = 0
for i in range(a, b + 1):
if a == b:
continue
else: x = x + i
print(x)
a = -1
b = 2
if __name__ == '__main__':
get_sum(a, b) | def get_sum(a, b):
if a > b:
(a, b) = (b, a)
if a == b:
print(a)
x = 0
for i in range(a, b + 1):
if a == b:
continue
else:
x = x + i
print(x)
a = -1
b = 2
if __name__ == '__main__':
get_sum(a, b) |
score_counter = 0
iter = 1
with open('clean_output_newnn.txt') as clean_file:
with open('reward_output_newnn.txt', 'w') as reward_file:
line = clean_file.readline()
while line != "":
reward = float(line.split(",")[3].split(": ")[1])
#print(reward)
if reward == 1:... | score_counter = 0
iter = 1
with open('clean_output_newnn.txt') as clean_file:
with open('reward_output_newnn.txt', 'w') as reward_file:
line = clean_file.readline()
while line != '':
reward = float(line.split(',')[3].split(': ')[1])
if reward == 1:
score_count... |
#APIC="sandboxapic.cisco.com:9443"
APIC="sandboxapic.cisco.com"
APIC_USER="devnetuser"
APIC_PASSWORD="Cisco123!"
| apic = 'sandboxapic.cisco.com'
apic_user = 'devnetuser'
apic_password = 'Cisco123!' |
def test_betting_stategy(predictions, test_features, test_labels, bet_difference=0.05):
result = {
'spend': 0,
'return': 0,
}
for i in range(0, len(predictions)):
probabilities = predictions[i]['probabilities']
if probabilities[1] > (1 / test_features['odds-draw'][i]) + bet... | def test_betting_stategy(predictions, test_features, test_labels, bet_difference=0.05):
result = {'spend': 0, 'return': 0}
for i in range(0, len(predictions)):
probabilities = predictions[i]['probabilities']
if probabilities[1] > 1 / test_features['odds-draw'][i] + bet_difference:
re... |
def text2time(timestamp):
timestamp = timestamp[:-1]
time_split = timestamp.split('m ')
time_converted = float(time_split[0]) + (float(time_split[-1]) / 60)
return round(time_converted, 2)
def categorize_kda(x):
if 0 <= x < 1:
x = 0
elif 1 <= x < 2:
x = 1
elif 2 <= x < 3:
... | def text2time(timestamp):
timestamp = timestamp[:-1]
time_split = timestamp.split('m ')
time_converted = float(time_split[0]) + float(time_split[-1]) / 60
return round(time_converted, 2)
def categorize_kda(x):
if 0 <= x < 1:
x = 0
elif 1 <= x < 2:
x = 1
elif 2 <= x < 3:
... |
#
# PySNMP MIB module Wellfleet-IPSEC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-IPSEC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:40:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
def before_after(func):
def wrapper(*args, **kwargs):
print('Before function call')
res = func(*args, **kwargs)
print(res)
print('After function call')
return res
return wrapper
@before_after
def get_text():
return 'Inside the function'
get_text()
| def before_after(func):
def wrapper(*args, **kwargs):
print('Before function call')
res = func(*args, **kwargs)
print(res)
print('After function call')
return res
return wrapper
@before_after
def get_text():
return 'Inside the function'
get_text() |
l="MONIKA"
r=len(l)
for i in range(-1,-r -1,-1, ):
print(l[i],end="")
| l = 'MONIKA'
r = len(l)
for i in range(-1, -r - 1, -1):
print(l[i], end='') |
with open('E_coli.txt', 'r') as file:
TEXT = file.read().replace('\n', '')
K=9
L=500
T=3
def get_close_occrs(occrs, k, l, t):
if len(occrs) < t:
return 0
count = 0
for i in range(len(occrs) - t + 1):
if occrs[i + t-1] + k - occrs[i] + 1 <= l:
count = count + 1
return cou... | with open('E_coli.txt', 'r') as file:
text = file.read().replace('\n', '')
k = 9
l = 500
t = 3
def get_close_occrs(occrs, k, l, t):
if len(occrs) < t:
return 0
count = 0
for i in range(len(occrs) - t + 1):
if occrs[i + t - 1] + k - occrs[i] + 1 <= l:
count = count + 1
re... |
class Foo:
def test():
pass
Foo.test2
Foo.test3
Bar() | class Foo:
def test():
pass
Foo.test2
Foo.test3
bar() |
def isIn(char,aStr):
'''
use the idea of bisection search to determine if a character is in a string,
so long as the string is sorted in alphabetical order.
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if... | def is_in(char, aStr):
"""
use the idea of bisection search to determine if a character is in a string,
so long as the string is sorted in alphabetical order.
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
"""
if len(aSt... |
class Node:
def __init__(self):
self.parent = -1
def dfs(v, d=0):
G[v].depth = d
for child in G[v].children:
dfs(child, d+1)
N = int(input())
G = [Node() for _ in range(N)]
for _ in range(N):
idx, k, *children = [int(x) for x in input().split()]
G[idx].children = children
if ... | class Node:
def __init__(self):
self.parent = -1
def dfs(v, d=0):
G[v].depth = d
for child in G[v].children:
dfs(child, d + 1)
n = int(input())
g = [node() for _ in range(N)]
for _ in range(N):
(idx, k, *children) = [int(x) for x in input().split()]
G[idx].children = children
i... |
'''
Assignment No: 0202 - Stem and Leaf plot
Name: Umaima Khurshid Ahmad
Youtube Link: https://youtu.be/-gUXrM5HVrE
Date: 04/14/2020
I have not given or received any unauthorized assistance on this assignment
'''
def computeStemLeafMain():
'''main function that shows users greetings passing entered file... | """
Assignment No: 0202 - Stem and Leaf plot
Name: Umaima Khurshid Ahmad
Youtube Link: https://youtu.be/-gUXrM5HVrE
Date: 04/14/2020
I have not given or received any unauthorized assistance on this assignment
"""
def compute_stem_leaf_main():
"""main function that shows users greetings passing entered file name fo... |
def fbx_template_def_light(scene, settings, override_defaults=None, nbr_users=0):
gscale = settings.global_scale
props = OrderedDict((
(b"LightType", (0, "p_enum", False)), # Point light.
(b"CastLight", (True, "p_bool", False)),
(b"Color", ((1.0, 1.0, 1.0), "p_color", True)),
(b... | def fbx_template_def_light(scene, settings, override_defaults=None, nbr_users=0):
gscale = settings.global_scale
props = ordered_dict(((b'LightType', (0, 'p_enum', False)), (b'CastLight', (True, 'p_bool', False)), (b'Color', ((1.0, 1.0, 1.0), 'p_color', True)), (b'Intensity', (100.0, 'p_number', True)), (b'Deca... |
# question about current age
age = int(input("What is your age currently?"))
# years left
years_remaining = 90-age
# days left
daysLeft = years_remaining * 365
# weeks left
weeksLeft = years_remaining * 52
# months left
monthsLeft = years_remaining * 12
# message var
message = "You have {daysLeft} days, {weeksLeft... | age = int(input('What is your age currently?'))
years_remaining = 90 - age
days_left = years_remaining * 365
weeks_left = years_remaining * 52
months_left = years_remaining * 12
message = 'You have {daysLeft} days, {weeksLeft} weeks, or {monthsLeft} months left to live.'
print(message) |
class CharAI:
def __init__(self, retreat_hp_threshold: int, retreat_mp_threshold: int,
max_attack_instead_spell: int, health_potion_gold_percent: int,
mana_potion_gold_percent: int, max_hp_percent_to_heal: int):
self.retreat_hp_threshold = retreat_hp_threshold
self.... | class Charai:
def __init__(self, retreat_hp_threshold: int, retreat_mp_threshold: int, max_attack_instead_spell: int, health_potion_gold_percent: int, mana_potion_gold_percent: int, max_hp_percent_to_heal: int):
self.retreat_hp_threshold = retreat_hp_threshold
self.retreat_mp_threshold = retreat_mp... |
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
# BFS
# key
# 1. use a dictionary mapping original n... | class Solution:
def clone_graph(self, node):
if not node:
return
node_copy = undirected_graph_node(node.label)
dic = {node: nodeCopy}
queue = [node]
while queue:
node = queue.pop(0)
for neighbor in node.neighbors:
if neighb... |
#!/usr/bin/python3
'''program to do shit'''
# func to push commands
def commandpush(devicecmd): #devicecmd==list
'''func to do something'''
for coffeetime in devicecmd.keys():
print('\nHandshake. .. ... connecting with ' + coffeetime)
for mycmds in devicecmd[coffeetime]: #we'll lear... | """program to do shit"""
def commandpush(devicecmd):
"""func to do something"""
for coffeetime in devicecmd.keys():
print('\nHandshake. .. ... connecting with ' + coffeetime)
for mycmds in devicecmd[coffeetime]:
print('Attempting to send command --> ' + mycmds)
def devicereboot(ips... |
class ProcessUtils:
# return dict list with tasks description per Lane
# {'editor': ['aprova materia', 'publica materia'] }
@staticmethod #pytest this!
def get_tasks_by_lane(elements):
if 'Activity' not in elements and len(elements['Activity']) == 0:
return {}
if len(elem... | class Processutils:
@staticmethod
def get_tasks_by_lane(elements):
if 'Activity' not in elements and len(elements['Activity']) == 0:
return {}
if len(elements['Lane']) == 0:
return {}
tasks_by_lanes = init_lanes(elements['Lane'])
(distance, author) = (999... |
VERSION = '1.0a'
# -------------DB------------- #
USERS = 'db/users.json'
# ---------------------------- #
# -----------SERVER----------- #
PORT = 8956
IP = '0.0.0.0'
GZIP = False
DEBUG = False
# ---------------------------- #
| version = '1.0a'
users = 'db/users.json'
port = 8956
ip = '0.0.0.0'
gzip = False
debug = False |
#
# PySNMP MIB module MICOM-WAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MICOM-WAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
# Aula 18 (Listas (Parte2))
alunos = []
dados = []
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Nota 1: ')))
dados.append(float(input('Nota 2: ')))
media = (dados[1] + dados[2]) / 2
dados.append(media)
alunos.append(dados[:])
dados.clear()
opcao = str(input... | alunos = []
dados = []
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Nota 1: ')))
dados.append(float(input('Nota 2: ')))
media = (dados[1] + dados[2]) / 2
dados.append(media)
alunos.append(dados[:])
dados.clear()
opcao = str(input('Seguir cadastrando? (S/N): ')... |
def main():
ar = []
i1 = input('input an array: ')
ar.append(i1)
l = len(i1)
if l < 3:
print('insert more than 3numbers.pls try again')
main()
elif l >= 1:
p = i1[0]
f = i1[3]
print('the first number = ',p)
print('the last number = ',f)
sum... | def main():
ar = []
i1 = input('input an array: ')
ar.append(i1)
l = len(i1)
if l < 3:
print('insert more than 3numbers.pls try again')
main()
elif l >= 1:
p = i1[0]
f = i1[3]
print('the first number = ', p)
print('the last number = ', f)
s... |
def main(j, args, params, tags, tasklet):
page = args.page
if len(args.doc.htmlBodiesCustom) < 1:
raise RuntimeError("Could not find custom html body on doc %s" % args.doc.name)
page.addMessage(args.doc.htmlBodiesCustom[0])
params.result = page
return params
def match(j, args, params, ... | def main(j, args, params, tags, tasklet):
page = args.page
if len(args.doc.htmlBodiesCustom) < 1:
raise runtime_error('Could not find custom html body on doc %s' % args.doc.name)
page.addMessage(args.doc.htmlBodiesCustom[0])
params.result = page
return params
def match(j, args, params, tags... |
expected_output = {
"interfaces": {
"GigabitEthernet1/0/15": {
"tx": "enabled",
"rx": "enabled",
"tx_state": "idle",
"rx_state": "wait for frame",
},
"GigabitEthernet1/0/16": {
"tx": "enabled",
"rx": "enabled",
... | expected_output = {'interfaces': {'GigabitEthernet1/0/15': {'tx': 'enabled', 'rx': 'enabled', 'tx_state': 'idle', 'rx_state': 'wait for frame'}, 'GigabitEthernet1/0/16': {'tx': 'enabled', 'rx': 'enabled', 'tx_state': 'idle', 'rx_state': 'wait for frame'}, 'GigabitEthernet1/0/17': {'tx': 'enabled', 'rx': 'enabled', 'tx_... |
'''
Template untuk solusi Lab 09 kelas C.
'''
class Pegawai():
'''
Seorang pegawai.
'''
def __init__(self, nama, rate_gaji):
# Ganti None dan assign nilai dari objek Pegawai
self.nama = nama
self.rate_gaji = rate_gaji
self.jam_kerja = 0
def __str__(self, divisi=Non... | """
Template untuk solusi Lab 09 kelas C.
"""
class Pegawai:
"""
Seorang pegawai.
"""
def __init__(self, nama, rate_gaji):
self.nama = nama
self.rate_gaji = rate_gaji
self.jam_kerja = 0
def __str__(self, divisi=None):
return
def tambah_jam_kerja(self, jam_kerj... |
R = float(input())
if R <= 2000.00:
i = 0
print('Isento')
if 2000.00 < R <= 3000.00:
R8 = R - 2000.00
i = R8 * (8 / 100)
if 3000.00 < R <= 4500.00:
i8 = (8 / 100) * 1000.00
R18 = R - 3000.00
i = R18 * (18 / 100) + i8
if R > 4500.00:
i8 = (8 / 100) * 1000.00
i18 = (18 / 100) * 150... | r = float(input())
if R <= 2000.0:
i = 0
print('Isento')
if 2000.0 < R <= 3000.0:
r8 = R - 2000.0
i = R8 * (8 / 100)
if 3000.0 < R <= 4500.0:
i8 = 8 / 100 * 1000.0
r18 = R - 3000.0
i = R18 * (18 / 100) + i8
if R > 4500.0:
i8 = 8 / 100 * 1000.0
i18 = 18 / 100 * 1500.0
r28 = R - 45... |
#!/usr/bin/env python3
def extract_context(msa, mut_pos, mut_base):
context = set()
context_frq = dict()
bad_positions = 0
seq_errors = 0
mut_pos = str(mut_pos)
only_mut_msa = msa[msa[mut_pos] == mut_base] #Filter the msa to keep only the mutant reads
for pos in only_mut_msa.columns:
... | def extract_context(msa, mut_pos, mut_base):
context = set()
context_frq = dict()
bad_positions = 0
seq_errors = 0
mut_pos = str(mut_pos)
only_mut_msa = msa[msa[mut_pos] == mut_base]
for pos in only_mut_msa.columns:
if pos == mut_pos:
continue
for variant in set(o... |
pobierz = lambda : map(int, input().split())
def main():
n, m, k = pobierz()
ans = pobierz()
operations = list(map(lambda lrd : (lrd[0]-1, lrd[1], lrd[2]), [list(pobierz()) for i in range(m)]))
queries = list(map(lambda xy : (xy[0]-1, xy[1]), [list(pobierz()) for i in range(k)]))
ileKazdejOperacji... | pobierz = lambda : map(int, input().split())
def main():
(n, m, k) = pobierz()
ans = pobierz()
operations = list(map(lambda lrd: (lrd[0] - 1, lrd[1], lrd[2]), [list(pobierz()) for i in range(m)]))
queries = list(map(lambda xy: (xy[0] - 1, xy[1]), [list(pobierz()) for i in range(k)]))
ile_kazdej_ope... |
def swap(l, a, b):
temp = l[a]
l[a] = l[b]
l[b] = temp
def is_sorted(lst):
for i in range(len(l)-1):
if l[i] > l[i+1]:
return False
return True
def bubblesort(lst):
l = []
for i in range(len(lst)):
l.append(lst[i])
for j in range(len(l)-1):
for i in range(len(l)-1):
if l[i] > l[i+1]:
... | def swap(l, a, b):
temp = l[a]
l[a] = l[b]
l[b] = temp
def is_sorted(lst):
for i in range(len(l) - 1):
if l[i] > l[i + 1]:
return False
return True
def bubblesort(lst):
l = []
for i in range(len(lst)):
l.append(lst[i])
for j in range(len(l) - 1):
for... |
#%%
# always check the input carefully after opening and splitting
# split r and c indices for simplicity (instead of combining them into a tuple)
# when using re, be sure to thing if greedy or nongreedy parsing is necessary
# don't use re when split() suffices, whitespaces can be casted to int
# make sure to experimen... | def nextstate(inp):
b = inp[::-1]
c = ''.join(['0' if bb == '1' else '1' for bb in b])
return inp + '0' + c
assert nextstate('111100001010') == '1111000010100101011110000'
def checksum(inp):
res = ['1' if x == y else '0' for (x, y) in zip(inp[::2], inp[1::2])]
if len(res) % 2 == 0:
return c... |
height = 1.6
width = 4.3
depth = 2.7
mass = 1600
ixx = 1/12.0*mass*(height**2+depth**2)
iyy = 1/12.0*mass*(height**2+width**2)
izz = 1/12.0*mass*(width**2+depth**2)
print(ixx)
print(iyy)
print(izz) | height = 1.6
width = 4.3
depth = 2.7
mass = 1600
ixx = 1 / 12.0 * mass * (height ** 2 + depth ** 2)
iyy = 1 / 12.0 * mass * (height ** 2 + width ** 2)
izz = 1 / 12.0 * mass * (width ** 2 + depth ** 2)
print(ixx)
print(iyy)
print(izz) |
a = 10
b = 11
print(a, b, a + b)
b = '11'
print(a, b,str(a) + b)
| a = 10
b = 11
print(a, b, a + b)
b = '11'
print(a, b, str(a) + b) |
TO = ['FIRST.LAST@inria.fr', 'TEAM@inria.fr']
SUBJECT = 'COATI seminar'
TEMPLATE = '''
Hi,
The next seminar will take place %(DELTA)s (%(DATE)s),
in %(LOCATION)s at %(TIME)s.
%(AUTHOR)s (%(AFFILIATION)s) will present:
%(SUMMARY)s
Abstract:
%(ABSTRACT)s
The list of past and future seminars is available at:
https://... | to = ['FIRST.LAST@inria.fr', 'TEAM@inria.fr']
subject = 'COATI seminar'
template = "\nHi,\n\nThe next seminar will take place %(DELTA)s (%(DATE)s),\nin %(LOCATION)s at %(TIME)s.\n%(AUTHOR)s (%(AFFILIATION)s) will present:\n\n%(SUMMARY)s\n\nAbstract:\n\n%(ABSTRACT)s\n\nThe list of past and future seminars is available a... |
class BertForEntityClassification:
@classmethod
def from_pretrained(cls,model_path:str):
pass | class Bertforentityclassification:
@classmethod
def from_pretrained(cls, model_path: str):
pass |
# run flags
make_dirs = True
make_scp = True
do_sptk_pitch_analysis = False
do_reaper_pitch_analysis = True
do_glott_vocoder_analysis = True
make_dnn_train_data = False
make_dnn_infofile = False
do_dnn_training = False
do_glott_vocoder_synthesis = False
# directories
prjdir = '/Users/ljuvela/CODE/GlottDNN' # add your ... | make_dirs = True
make_scp = True
do_sptk_pitch_analysis = False
do_reaper_pitch_analysis = True
do_glott_vocoder_analysis = True
make_dnn_train_data = False
make_dnn_infofile = False
do_dnn_training = False
do_glott_vocoder_synthesis = False
prjdir = '/Users/ljuvela/CODE/GlottDNN'
datadir = prjdir + '/data/slt48'
sampl... |
## Play with two Strings
## 5 kyu
## https://www.codewars.com//kata/56c30ad8585d9ab99b000c54
def work_on_strings(a,b):
a_answer = ''
b_answer = ''
for x in b:
if (a.casefold().count(x.casefold()) == 0) or (a.casefold().count(x.casefold()) % 2 == 0):
b_answer += x
... | def work_on_strings(a, b):
a_answer = ''
b_answer = ''
for x in b:
if a.casefold().count(x.casefold()) == 0 or a.casefold().count(x.casefold()) % 2 == 0:
b_answer += x
elif a.casefold().count(x.casefold()) % 2 == 1:
b_answer += x.swapcase()
for y in a:
if ... |
GET = 'get'
POST = 'post'
PUT = 'put'
PATCH = 'patch'
DELETE = 'delete'
| get = 'get'
post = 'post'
put = 'put'
patch = 'patch'
delete = 'delete' |
# FCFS Algorithm in Python
# This is the function: It takes input parameter process, and number of process
def FCFS(process, n):
wait, time = 0,0 # Initailzing some variables that will be used in function
waitSum, turnSum = 0,0 # Initializing Sum of Waiting-Time
... | def fcfs(process, n):
(wait, time) = (0, 0)
(wait_sum, turn_sum) = (0, 0)
print('Process\t Burst-Time\tWaiting-Time\tTurnaround-Time')
for i in range(n):
turn = wait + process[i][1]
print('P' + str(process[i][0]) + '\t\t' + str(process[i][1]) + '\t\t' + str(wait) + '\t\t' + str(turn))... |
print('===== DESAFIO 063 =====')
n = int(input('digite um valor: '))
t1 = 0
t2 = 1
print(f'{t1} -> {t2}', end='')
count = 3
while count <= n:
t3 = t1 + t2
print(f' -> {t3}', end='')
t1 = t2
t2 = t3
count+=1
print('-> fim')
| print('===== DESAFIO 063 =====')
n = int(input('digite um valor: '))
t1 = 0
t2 = 1
print(f'{t1} -> {t2}', end='')
count = 3
while count <= n:
t3 = t1 + t2
print(f' -> {t3}', end='')
t1 = t2
t2 = t3
count += 1
print('-> fim') |
def generate_permutations(array):
# see https://en.wikipedia.org/wiki/Heap%27s_algorithm
stack = [0 for _ in range(len(array))]
permutations = [array.copy()]
i = 0
while i < len(array):
if stack[i] < i:
if i % 2 == 0:
array[0], array[i] = array[i], array[0]
... | def generate_permutations(array):
stack = [0 for _ in range(len(array))]
permutations = [array.copy()]
i = 0
while i < len(array):
if stack[i] < i:
if i % 2 == 0:
(array[0], array[i]) = (array[i], array[0])
else:
(array[stack[i]], array[i])... |
#
# PySNMP MIB module CISCO-ATM-SWITCH-FR-IWF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SWITCH-FR-IWF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, constraints_union, single_value_constraint) ... |
x = 9
y = 3
# Arithmetic Operators
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
print(x % y) # Modulus
print(x ** y) # Exponentiation
x = 9.191823
print("Floor divide: ", x // y) # Floor Division
print("Modulo: ", x % y)
# Assignment operators
x =... | x = 9
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x ** y)
x = 9.191823
print('Floor divide: ', x // y)
print('Modulo: ', x % y)
x = 9
x += 3
print(x)
x = 9
x -= 3
print(x)
x *= 3
print(x)
x /= 3
print(x)
x **= 3
print(x)
x = 9
y = 3
print('Is x equal to y? ', x == y)
print('Is x equal t... |
'''
https://leetcode.com/explore/featured/card/september-leetcoding-challenge/556/week-3-september-15th-september-21st/3465/
'''
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
s="123456789"
nums=[]
for i in range(0,9):
for j in range(0,9-i):
... | """
https://leetcode.com/explore/featured/card/september-leetcoding-challenge/556/week-3-september-15th-september-21st/3465/
"""
class Solution:
def sequential_digits(self, low: int, high: int) -> List[int]:
s = '123456789'
nums = []
for i in range(0, 9):
for j in range(0, 9 - ... |
STORAGE_ACCOUNT_NAME = "sparkonbatch"
STORAGE_ACCOUNT_KEY = ""
BATCH_ACCOUNT_NAME = "sparkonbatch"
BATCH_ACCOUNT_KEY = ""
BATCH_ACCOUNT_URL = ""
ACR_LOGINSERVER = "sparkonbatch.azurecr.io"
ACR_USERNAME = ""
ACR_PASSWORD = ""
| storage_account_name = 'sparkonbatch'
storage_account_key = ''
batch_account_name = 'sparkonbatch'
batch_account_key = ''
batch_account_url = ''
acr_loginserver = 'sparkonbatch.azurecr.io'
acr_username = ''
acr_password = '' |
class RangeDictError(Exception):
pass
class InvalidMappingError(RangeDictError):
def __init__(self):
super().__init__(
"argument for RangeDict must be a dictionary with iterables of length 2 as keys"
)
class KeyNotFoundError(RangeDictError):
def __init__(self, key):
s... | class Rangedicterror(Exception):
pass
class Invalidmappingerror(RangeDictError):
def __init__(self):
super().__init__('argument for RangeDict must be a dictionary with iterables of length 2 as keys')
class Keynotfounderror(RangeDictError):
def __init__(self, key):
super().__init__(f'key ... |
#
# PySNMP MIB module ISO3201-OPT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ISO3201-OPT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:57:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, constraints_intersection, single_value_constraint) ... |
# https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxLevelSum(self, root):
self.ans = [0] * 10001
... | class Solution:
def max_level_sum(self, root):
self.ans = [0] * 10001
self.ans[0] = -float('inf')
def traverse(node, level):
self.ans[level] += node.val
if not node.left and (not node.right):
return
if node.left:
traverse(... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-AtmBaseMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-AtmBaseMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:29:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) ... |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... | class Apiobject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.clie... |
a = 50
print('\033[32m_\033[m'*a)
print('\033[1;32m{:=^{}}\033[m'.format('SISTEMA ORDENADOR DE PARES E IMPARES', a))
print('\033[32m-\033[m'*a)
lista = []
par = []
impar = []
cont = 's'
while True:
if 's' in cont:
lista.append(int(input('\033[36mDigite um numero inteiro: \033[m')))
if lista[-1] % ... | a = 50
print('\x1b[32m_\x1b[m' * a)
print('\x1b[1;32m{:=^{}}\x1b[m'.format('SISTEMA ORDENADOR DE PARES E IMPARES', a))
print('\x1b[32m-\x1b[m' * a)
lista = []
par = []
impar = []
cont = 's'
while True:
if 's' in cont:
lista.append(int(input('\x1b[36mDigite um numero inteiro: \x1b[m')))
if lista[-1] ... |
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
s1 = set()
for i in range(k, len(s)):
s1.add(s[i-k:i])
s1.add(s[-k:])
#print(s1)
return len(s1) == 2**k
| class Solution:
def has_all_codes(self, s: str, k: int) -> bool:
s1 = set()
for i in range(k, len(s)):
s1.add(s[i - k:i])
s1.add(s[-k:])
return len(s1) == 2 ** k |
p = "Python_is_fun!"
print("p[0:6] = ", p[0:6])
print("p[-1] = ", p[-1])
print("p[7:9] = ", p[7:9])
| p = 'Python_is_fun!'
print('p[0:6] = ', p[0:6])
print('p[-1] = ', p[-1])
print('p[7:9] = ', p[7:9]) |
class _Result(object):
def __init__(self, reason="", details=""):
self.reason = reason
self.details = details
@property
def type(self):
return type(self)
@property
def name(self):
return type(self).__name__.upper()
class Pass(_Result):
pass
class Skip(_Resul... | class _Result(object):
def __init__(self, reason='', details=''):
self.reason = reason
self.details = details
@property
def type(self):
return type(self)
@property
def name(self):
return type(self).__name__.upper()
class Pass(_Result):
pass
class Skip(_Result... |
class Dog:
# Class object attributes
# Same for any instance of a class
species = 'mammal'
def __init__(self, breed, name):
# Attributes
# We take in the argument
# Assign it using self.attribute_name
self.breed = breed
self.name = name
# Operations/Actions ... | class Dog:
species = 'mammal'
def __init__(self, breed, name):
self.breed = breed
self.name = name
def bark(self, number):
print('WOOF! My name is {} and the number is {}'.format(self.name, number))
my_dog = dog('Lab', 'Frankie')
print(type(my_dog))
print(my_dog.breed)
print(my_dog... |
# https://leetcode.com/problems/two-sum/
# 1. Two Sum
# Easy
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# You can return th... | class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
d = {}
for (index, value) in enumerate(nums):
if target - value in d:
return (d[target - value], index)
else:
d[value] = index |
class Job:
def __init__(self, callback, *args, **kwargs):
self.callback = callback
self.args = args
self.kwargs = kwargs
def run(self):
self.callback(*self.args, **self.kwargs)
def __str__(self):
return f"job:{self.__class__.__name__}, args: {self.args}, kwargs... | class Job:
def __init__(self, callback, *args, **kwargs):
self.callback = callback
self.args = args
self.kwargs = kwargs
def run(self):
self.callback(*self.args, **self.kwargs)
def __str__(self):
return f'job:{self.__class__.__name__}, args: {self.args}, kwargs: {s... |
# CONFIGURATION
# --------------------------------------------------------------------------------------------
y_min = 48.14430 # minimum value displayed on y axis (min latitude)
y_max = 48.15026 # maximum value displayed on y axis (max latitude)
x_min = 11.55723 ... | y_min = 48.1443
y_max = 48.15026
x_min = 11.55723
x_max = 11.57143
inputs = 'input1'
output = 'output'
chart_color = '#DC143C'
chart_height = 652
chart_width = 975
graph_name = 'Map - Munich'
map_url = 'https://raw.githubusercontent.com/stuparmihailo/blogs/master/data-hub-visualization/examples/ex-5/ex-5-map.png'
backg... |
# print("ENTER YOUR NUMBER")
# adi = input()
# print("ENTER YOUR SECOUND NUMBER")
# adi2 = input()
# print("THE ANSWER IS ", int(adi) + int(adi2))
adi = "helloaditya how are you."
# print(adi)
# print(len(adi))
# print(adi[10])
# print(adi[0:5])
print(adi.endswith("."))
# print(adi.endswith("you"))
print(adi.count("... | adi = 'helloaditya how are you.'
print(adi.endswith('.'))
print(adi.count('l'))
print(adi.replace('l', 'a')) |
# UMass Robotics Team
# Challenge01 Main Project File
#
# Constants.py
#
# Created by Samuel DuBois and Andrew Tran
# Created on April 11, 2020
# MARK: Challenge Constants and Variables
# H-Bridge / Motor Controller
IN1 = 4
IN2 = 17
IN3 = 27
IN4 = 22
# HC-SR04 Ultrasonic Sensor
TRIG = 23
ECHO = 24
# Status LED
LED ... | in1 = 4
in2 = 17
in3 = 27
in4 = 22
trig = 23
echo = 24
led = 25 |
# ASSUMPTIONS::
# Anyone can buy or search for cars
#
#
#=======================================================================================
# CLASSES & Variables
#=======================================================================================
#to store the details of each... | class Vehicle:
def __init__(self, model, city, year, seller, price, details, company):
self.seller = seller
self.company = company
self.city = city
self.year = year
self.model = model
self.price = price
self.details = details
self.comments = []
... |
#
# PySNMP MIB module CISCO-CONFIG-COPY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CONFIG-COPY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:53:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, single_value_constraint, value_size_constraint) ... |
class Solution:
# @param A a list of integers
# @return nothing, sort in place
def sortColors(self, A):
n0 = A.count(0)
n1 = A.count(1)
n2 = A.count(2)
for i in range(n0):
A[i] = 0
for i in range(n0, n0+n1):
A[i] = 1
for i in range(n0+n... | class Solution:
def sort_colors(self, A):
n0 = A.count(0)
n1 = A.count(1)
n2 = A.count(2)
for i in range(n0):
A[i] = 0
for i in range(n0, n0 + n1):
A[i] = 1
for i in range(n0 + n1, n0 + n1 + n2):
A[i] = 2 |
# cook your dish here
def radixSort(arr):
rad= 10
maxlen = False
tmp=-1
placement=1
while not maxlen:
maxlen = True
buckets = [list() for _ in range(rad)]
for i in arr:
tmp = i // placement
buckets[tmp % rad].append(i)
if maxlen ... | def radix_sort(arr):
rad = 10
maxlen = False
tmp = -1
placement = 1
while not maxlen:
maxlen = True
buckets = [list() for _ in range(rad)]
for i in arr:
tmp = i // placement
buckets[tmp % rad].append(i)
if maxlen and tmp > 0:
... |
class Player:
def __init__(self, id, firstname, lastname):
self.id = id
self.firstname = firstname
self.lastname = lastname
def serialize(self):
return {
'id': self.id,
'firstname': self.firstname,
'lastname': self.lastname
}
| class Player:
def __init__(self, id, firstname, lastname):
self.id = id
self.firstname = firstname
self.lastname = lastname
def serialize(self):
return {'id': self.id, 'firstname': self.firstname, 'lastname': self.lastname} |
def circular_prime(n, sieve):
s = str(n)
l = len(s)
for _ in range(l - 1):
s = s[1:] + s[0]
if sieve[int(s)] == 0:
return False
return True
def solve(n):
sieve = [0, 1] + [i for i in range(2, n + 1)]
for i in range(2, n + 1):
for j in range(i + i, n + 1, i):... | def circular_prime(n, sieve):
s = str(n)
l = len(s)
for _ in range(l - 1):
s = s[1:] + s[0]
if sieve[int(s)] == 0:
return False
return True
def solve(n):
sieve = [0, 1] + [i for i in range(2, n + 1)]
for i in range(2, n + 1):
for j in range(i + i, n + 1, i):
... |
#
# PySNMP MIB module EQUIPE-SONET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQUIPE-SONET-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:51:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
#!/usr/bin/python
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | class Dataset:
def __init__(self):
pass
class Criteodataset(Dataset):
def __init__(self, feature_names):
self.feature_names = feature_names
self.feature_dict = {}
for (idx, name) in enumerate(self.feature_names):
self.feature_dict[name] = idx
def _reader_creat... |
RECAPTCHA_PRIVATE = None #replace private key text here
DOMAIN = None #Replace with domain to override email domain lookup, otherwise system hostname is used
EMAILFROM = None #Is set to None, use noreply@domain
SMTPUSER = None #If your smtp server requires authentication define it here
SMTPPASS = None #If your... | recaptcha_private = None
domain = None
emailfrom = None
smtpuser = None
smtppass = None
smtpdomain = 'localhost'
smtpport = 25
smtpstarttls = False
welcomecid = None
localdevbypassdb = 0
server_secret = 'SoSecret!'
session_secret = 'SuperSecretSessionStuff'
websocket_secret = 'SocketSecret!'
aeskey = 'use a 16 char pas... |
a0 = '376782365465497859'
a0 = '87489543528930998385608359876385765806784785670487869469874896789457064'
b0 = '87567948756746869874'
b0 = '8578493780570495789469548699569346098358063345873895380949288945445403584'
a = list(a0)
b = list(b0)
if(len(a)!=len(b)):
padding = len(a)-len(b)
if(padding > 0):
#a... | a0 = '376782365465497859'
a0 = '87489543528930998385608359876385765806784785670487869469874896789457064'
b0 = '87567948756746869874'
b0 = '8578493780570495789469548699569346098358063345873895380949288945445403584'
a = list(a0)
b = list(b0)
if len(a) != len(b):
padding = len(a) - len(b)
if padding > 0:
p... |
class Fault():
def __init__(self, faulted_obs, faulted_value):
self.faulted_obs = faulted_obs
self.faulted_value = faulted_value
| class Fault:
def __init__(self, faulted_obs, faulted_value):
self.faulted_obs = faulted_obs
self.faulted_value = faulted_value |
class MyTaskExtension(object):
def __init__(self, outfolder=None):
self._outfolder = outfolder
@property
def outfolder(self):
return self._outfolder
@outfolder.setter
def outfolder(self, outfolder):
self._outfolder = outfolder
| class Mytaskextension(object):
def __init__(self, outfolder=None):
self._outfolder = outfolder
@property
def outfolder(self):
return self._outfolder
@outfolder.setter
def outfolder(self, outfolder):
self._outfolder = outfolder |
# Helper library with simple matrix functions
class Matrix:
def __init__(self, values, dimensions):
''' values is a list of numbers, dimensions is a tuple of ints '''
self.values = values
self.dimensions = dimensions
size = 1
for i in dimensions:
size *= i
... | class Matrix:
def __init__(self, values, dimensions):
""" values is a list of numbers, dimensions is a tuple of ints """
self.values = values
self.dimensions = dimensions
size = 1
for i in dimensions:
size *= i
if size != len(values):
raise va... |
# coding: utf-8
__version__ = '4.5.0'
| __version__ = '4.5.0' |
# GENERATED VERSION FILE
# TIME: Fri Mar 12 13:50:43 2021
__version__ = '0.3.0+30773fd'
short_version = '0.3.0'
| __version__ = '0.3.0+30773fd'
short_version = '0.3.0' |
class ShellSort(object):
def sort(self, obj):
longitud = len(arr)
gap = 2
for i in range(longitud-gap):
if arr[i] > arr[i + gap]:
tmp = arr[i]
arr[i] = arr[i + gap]
arr[i + gap] = tmp
return arr
def __init__(self, arg=None):
s... | class Shellsort(object):
def sort(self, obj):
longitud = len(arr)
gap = 2
for i in range(longitud - gap):
if arr[i] > arr[i + gap]:
tmp = arr[i]
arr[i] = arr[i + gap]
arr[i + gap] = tmp
return arr
def __init__(self, ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.