content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#Receber as temperaturas e dizer qual a maior e qual a menor
def maior(lista):
maior = lista[0]
for i in lista:
if maior < i:
maior = i
return maior
def menor(lista):
menor = lista[0]
for i in lista:
if menor > i:
menor = i
return menor
#Func pr... | def maior(lista):
maior = lista[0]
for i in lista:
if maior < i:
maior = i
return maior
def menor(lista):
menor = lista[0]
for i in lista:
if menor > i:
menor = i
return menor
temperaturas = []
counter = 0
leitor_temp = 0
while counter != 30:
leitor_t... |
class FreshStartHousing():
def __init__(self, inputs):
self.relationship = inputs.relationship.data
self.age = inputs.age.data
self.employment = inputs.employment.data
self.avgIncome = inputs.avgIncome.data
def checkEligibility(self):
name = "Fresh Start Housing Sche... | class Freshstarthousing:
def __init__(self, inputs):
self.relationship = inputs.relationship.data
self.age = inputs.age.data
self.employment = inputs.employment.data
self.avgIncome = inputs.avgIncome.data
def check_eligibility(self):
name = 'Fresh Start Housing Scheme'
... |
class MyCircularQueue:
def __init__(self, k: int):
self.queue = list()
self.max_size = k
def enQueue(self, value: int) -> bool:
if not self.isFull():
self.queue.append(value)
return True
return False
def deQueue(self) -> bool:
if... | class Mycircularqueue:
def __init__(self, k: int):
self.queue = list()
self.max_size = k
def en_queue(self, value: int) -> bool:
if not self.isFull():
self.queue.append(value)
return True
return False
def de_queue(self) -> bool:
if not self.... |
# NOTE: This isn't fully baked. Will probably redo this and
# create a BatchClient like in neo4jserver/batch.py
class RexsterTransaction(object):
def __init__(self):
self.actions = []
def create_edge(self,outV,label,inV,data={}):
edge_data = dict(_outV=outV,_label=label,_inV=inV)
da... | class Rexstertransaction(object):
def __init__(self):
self.actions = []
def create_edge(self, outV, label, inV, data={}):
edge_data = dict(_outV=outV, _label=label, _inV=inV)
data.update(edge_data)
action = build_action('create', 'edge', data)
self.actions.append(action... |
#maze 2020 data storage module
direction = 0
wanted_rotation = 0
tile_counter = 0
last_checkpoint_x = 0
last_checkpoint_y = 0
last_checkpoint_z = 0
def get_direction():
global direction
with open('data.txt', 'r') as content_file:
content = content_file.read()
here = 'direction = '
index = con... | direction = 0
wanted_rotation = 0
tile_counter = 0
last_checkpoint_x = 0
last_checkpoint_y = 0
last_checkpoint_z = 0
def get_direction():
global direction
with open('data.txt', 'r') as content_file:
content = content_file.read()
here = 'direction = '
index = content.find(here)
direction = i... |
def save_bibtex(bibtexes):
with open("bibtex.bib", "a") as myfile:
for item in bibtexes:
myfile.write(
getBibtex(item) + '\n')
def getBibtex(item):
bib = f'@author{{{item.pk},\n author =\t"{item.authors}", \
\n title =\t"{item.title}",\n'
bib = bib[0:len(bib)-... | def save_bibtex(bibtexes):
with open('bibtex.bib', 'a') as myfile:
for item in bibtexes:
myfile.write(get_bibtex(item) + '\n')
def get_bibtex(item):
bib = f'@author{{{item.pk},\n author =\t"{item.authors}", \n title =\t"{item.title}",\n'
bib = bib[0:len(bib) - 1] + '\n}\n'
... |
class PubSubManager:
def __init__(self, clazz):
self.manages = clazz
self.subscribers = set()
def add_subscriber(self, suber):
self.subscribers.add(suber)
def broadcast_data(self, data, sender):
for sub in self.subscribers:
if sender is sub:
i... | class Pubsubmanager:
def __init__(self, clazz):
self.manages = clazz
self.subscribers = set()
def add_subscriber(self, suber):
self.subscribers.add(suber)
def broadcast_data(self, data, sender):
for sub in self.subscribers:
if sender is sub:
if ... |
fig, ax = plt.subplots(figsize=(12,12), nrows=4)
hf.visualize_probabilities(p=0.05,loc=mu,scale=sigma, tails='lower', ax=ax[0])
hf.visualize_probabilities(p=0.05,loc=mu,scale=sigma, tails='upper', ax=ax[1])
hf.visualize_probabilities(p=0.1,loc=mu,scale=sigma, tails='both', ax=ax[2])
hf.visualize_probabilities(p=0.50,lo... | (fig, ax) = plt.subplots(figsize=(12, 12), nrows=4)
hf.visualize_probabilities(p=0.05, loc=mu, scale=sigma, tails='lower', ax=ax[0])
hf.visualize_probabilities(p=0.05, loc=mu, scale=sigma, tails='upper', ax=ax[1])
hf.visualize_probabilities(p=0.1, loc=mu, scale=sigma, tails='both', ax=ax[2])
hf.visualize_probabilities(... |
#!/usr/bin/env python
# List of choices
codes = [
"501 San Antonio (SAT)",
"503 Austin (ATX)",
"504 Dallas (DFW)",
"507 Virginia (IAD)",
"508 London (LON)",
"509 Hong Kong (HKG)",
"515 Sydney (SYD)",
"700 US Hunt Group",
"720 International Hunt Group"
]
# Create function
def prefix... | codes = ['501 San Antonio (SAT)', '503 Austin (ATX)', '504 Dallas (DFW)', '507 Virginia (IAD)', '508 London (LON)', '509 Hong Kong (HKG)', '515 Sydney (SYD)', '700 US Hunt Group', '720 International Hunt Group']
def prefixes():
return 'Office Prefixes:\n' + '\n'.join(('{}'.format(k) for (i, k) in enumerate(codes))... |
# Copyright (c) 2011, Manfred Moitzi
# License: MIT License
class SubscriptAttributes:
def __getitem__(self, item):
if hasattr(self, item):
return getattr(self, item)
else:
raise KeyError(item)
def __setitem__(self, key, value):
if hasattr(self, key):
... | class Subscriptattributes:
def __getitem__(self, item):
if hasattr(self, item):
return getattr(self, item)
else:
raise key_error(item)
def __setitem__(self, key, value):
if hasattr(self, key):
setattr(self, key, value)
else:
raise... |
#string
s = "I am a string."
print(type(s)) #will say str
#Boolean
yes = True #Boolean True
print(type(yes))
no = False #Boolean False
print(type(no))
#List -- ordered and changeable
alpha_list = ["a", "b" , "c"] #list initialization
print(type(alpha_list)) #will say tuple
print(type(alpha_list[0])) #will s... | s = 'I am a string.'
print(type(s))
yes = True
print(type(yes))
no = False
print(type(no))
alpha_list = ['a', 'b', 'c']
print(type(alpha_list))
print(type(alpha_list[0]))
alpha_list.append('d')
print(alpha_list)
alpha_tuple = ('a', 'b', 'c')
print(type(alpha_tuple))
try:
alpha_tuple[2] = 'd'
except TypeError:
p... |
def makeArrayConsecutive2(statues):
'''
Ratiorg got statues of different sizes as a present from CodeMaster for his birthday,
each statue having an non-negative integer size.
Since he likes to make things perfect, he wants to arrange them from smallest to
largest so that each statue will be bigge... | def make_array_consecutive2(statues):
"""
Ratiorg got statues of different sizes as a present from CodeMaster for his birthday,
each statue having an non-negative integer size.
Since he likes to make things perfect, he wants to arrange them from smallest to
largest so that each statue will be big... |
#
# PySNMP MIB module ONEACCESS-ATM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-ATM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:24:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, constraints_union, single_value_constraint) ... |
# You are given the root of a binary search tree (BST) and an integer val.
# Find the node in the BST that the node's value equals val and return the subtree rooted with that node.
# If such a node does not exist, return null.
# Constraints:
## The number of nodes in the tree is in the range [1, 5000].
## 1 <= Node.v... | class Solution:
"""
Function Description:
Input: root of a BST and an integer
Output: subtree of a node whose value is equal to the given integer
"""
def search_bst(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return None
if root.val ... |
# ----------------------------------
class DataTypesDemo:
Instances = 0
def __init__(self, tupleObject):
self.tupleObject = tupleObject
DataTypesDemo.Instances += 1
def displayDetails(self):
print("----- DataTypesDemo Details -----")
print('DataTypesDemo.Instances: ', sel... | class Datatypesdemo:
instances = 0
def __init__(self, tupleObject):
self.tupleObject = tupleObject
DataTypesDemo.Instances += 1
def display_details(self):
print('----- DataTypesDemo Details -----')
print('DataTypesDemo.Instances: ', self.Instances)
print('Tuple Data... |
#!/usr/bin/env python2
class Notification(object):
_MSG_DEAD_NODE = "Lost contact with host"
_MSG_RESURRECTED_NODE = "Found node that resurrected from dead"
def __init__(self, category='', severity='', file_name='', file_path='',
metric_type='', time='', hostname='', ip_address_public=''... | class Notification(object):
_msg_dead_node = 'Lost contact with host'
_msg_resurrected_node = 'Found node that resurrected from dead'
def __init__(self, category='', severity='', file_name='', file_path='', metric_type='', time='', hostname='', ip_address_public='', machine_id='', plugin='', plugin_instanc... |
class InventoryItem(object):
def __init__(self, title, description, price, store_id):
self.title = title
self.description = description
self.price = price
self.store_id = store_id
def __str__(self):
return self.title
def __eq__(self, other):
if self.store_id... | class Inventoryitem(object):
def __init__(self, title, description, price, store_id):
self.title = title
self.description = description
self.price = price
self.store_id = store_id
def __str__(self):
return self.title
def __eq__(self, other):
if self.store_i... |
n,m = [int(x) for x in input().split()]
count = 0
for a in range(n+1):
b = n - a*a
if b < 0:
break
if a + b*b == m:
count += 1
print(count) | (n, m) = [int(x) for x in input().split()]
count = 0
for a in range(n + 1):
b = n - a * a
if b < 0:
break
if a + b * b == m:
count += 1
print(count) |
shopping = [5.99, 7.99, 4, 9, 10, 5.50, 7.50, 2, 9.99, 15]
totalCost = 0
for item in shopping:
totalCost += item
print(totalCost) | shopping = [5.99, 7.99, 4, 9, 10, 5.5, 7.5, 2, 9.99, 15]
total_cost = 0
for item in shopping:
total_cost += item
print(totalCost) |
Scale.default = "chromatic"
Root.default = 2
Clock.bpm = 120
drp = [0, 7, 12, 17, 21, 26]
std = [0, 5, 10, 15, 19, 24]
d1 >> play("<X x n [--]>")
d2 >> play("( [II]) I ")
d3 >> play(
"funky",
dur = 1/2,
sample = PRand(5),
pan = (-1, 1),
amp = 0.5,
rate = PRand([0.25, 0.5, 1])
)
a1 >> amb... | Scale.default = 'chromatic'
Root.default = 2
Clock.bpm = 120
drp = [0, 7, 12, 17, 21, 26]
std = [0, 5, 10, 15, 19, 24]
d1 >> play('<X x n [--]>')
d2 >> play('( [II]) I ')
d3 >> play('funky', dur=1 / 2, sample=p_rand(5), pan=(-1, 1), amp=0.5, rate=p_rand([0.25, 0.5, 1]))
a1 >> ambi(var([drp[0], drp[0] + 5, drp[0] + 3... |
class SecretsProvider(object):
'''
Interface to be implemented by a secrets provider.
'''
def initialize(self, tk):
raise NotImplementedError('subclasses should override this')
def close(self):
raise NotImplementedError('subclasses should override this')
def get... | class Secretsprovider(object):
"""
Interface to be implemented by a secrets provider.
"""
def initialize(self, tk):
raise not_implemented_error('subclasses should override this')
def close(self):
raise not_implemented_error('subclasses should override this')
def get_v3_api_key... |
# multiply method, given a and b will calculate a*b
def multiply(a: int, b: int) -> int:
# 0 is a absorbing element in multiplication so the result is always 0
# whenever there's a 0, be it the first operand, second operand or both.
if a == 0 or b == 0:
return 0
# Since a multiplication ... | def multiply(a: int, b: int) -> int:
if a == 0 or b == 0:
return 0
result = 0
i = 0
while i < b:
result += a
i += 1
return result
def power(base: int, exponent: int) -> int:
if exponent == 0:
return 1
result = 1
i = 0
while i < exponent:
resul... |
correct = 0
num_wrong = 0
correct = [] # Stores the
all_problem = {} # Python dictionaries (key: value pairs)
wrong_attempts = {}
while True:
line = input()
if line == '-1':
break
n, m, rw = line.split()
n = int(n)
# Check to see if the answer is right/wrong
if rw == 'right':
... | correct = 0
num_wrong = 0
correct = []
all_problem = {}
wrong_attempts = {}
while True:
line = input()
if line == '-1':
break
(n, m, rw) = line.split()
n = int(n)
if rw == 'right':
all_problem[m] = n
if m not in correct:
correct.append(m)
elif rw == 'wrong':
... |
#
# PySNMP MIB module HPN-ICF-FC-FLOGIN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-FC-FLOGIN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:26:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
def get_argparser_log_part(parser):
parser.add_argument(
"--log",
dest="LOG",
help="To apply a log2 transformation log2(x + C) " +
"(see -c) ).",
action='store_true'
)
parser.add_argument(
"-c",
dest="C",
help="Constant value used during... | def get_argparser_log_part(parser):
parser.add_argument('--log', dest='LOG', help='To apply a log2 transformation log2(x + C) ' + '(see -c) ).', action='store_true')
parser.add_argument('-c', dest='C', help='Constant value used during log ' + 'transformation and to compute l2fc (log2(x+C), Default: C=1).', type... |
flagg = "27F;VPbAs>clu}={9ln=_o1{0n5tp~"
flag_length = len(flagg)
def factorial(n):
f = 1
for i in range(2, n+1):
f *= i
return f
def series(A, X, n):
val = []
nFact = factorial(n)
for i in range(0, n + 1):
niFact = factorial(n - i)
iFact = factorial(i)
... | flagg = '27F;VPbAs>clu}={9ln=_o1{0n5tp~'
flag_length = len(flagg)
def factorial(n):
f = 1
for i in range(2, n + 1):
f *= i
return f
def series(A, X, n):
val = []
n_fact = factorial(n)
for i in range(0, n + 1):
ni_fact = factorial(n - i)
i_fact = factorial(i)
a_p... |
def read_data():
with open ('input.txt') as f:
data = f.readlines()
return [d.strip() for d in data]
def write_data(data):
with open('output.txt','w') as f:
for d in data:
f.write(str(d)+'\n')
###
def row(txt):
txt = txt.replace('F','0')
txt = txt.replace('B','1')
a = int(txt,2)
return a
def col(txt... | def read_data():
with open('input.txt') as f:
data = f.readlines()
return [d.strip() for d in data]
def write_data(data):
with open('output.txt', 'w') as f:
for d in data:
f.write(str(d) + '\n')
def row(txt):
txt = txt.replace('F', '0')
txt = txt.replace('B', '1')
a... |
def bubblesort(arr):
l = len(arr)
for i in range(l-1):
for j in range(l-1-i):
if arr[j]>arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
n = int(input())
arr = list(int(x) for x in input().strip().split())
bubblesort(arr)
for number in arr:
pr... | def bubblesort(arr):
l = len(arr)
for i in range(l - 1):
for j in range(l - 1 - i):
if arr[j] > arr[j + 1]:
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j])
n = int(input())
arr = list((int(x) for x in input().strip().split()))
bubblesort(arr)
for number in arr:
print(number, ... |
# In grams
dry_weight_per_liter = 0.1
carbon_ratio_of_dry_algae = 0.7
cubic_meters_of_water = 1
batch_time_days = 1
# Calculate
liters_of_water = cubic_meters_of_water * 1000
carbon_removed = liters_of_water * dry_weight_per_liter * carbon_ratio_of_dry_algae
removed_daily = carbon_removed / batch_time_days
print(... | dry_weight_per_liter = 0.1
carbon_ratio_of_dry_algae = 0.7
cubic_meters_of_water = 1
batch_time_days = 1
liters_of_water = cubic_meters_of_water * 1000
carbon_removed = liters_of_water * dry_weight_per_liter * carbon_ratio_of_dry_algae
removed_daily = carbon_removed / batch_time_days
print('grams of carbon removed per ... |
limit=int(input('Enter the size:'))
list1=[]
for i in range(1,limit+1):
n=int(input("Enter the value:"))
list1.append(n)
if(n in list1):
print(n)
| limit = int(input('Enter the size:'))
list1 = []
for i in range(1, limit + 1):
n = int(input('Enter the value:'))
list1.append(n)
if n in list1:
print(n) |
class Typed(object):
_expected_type = type(None)
def __set_name__(self, owner, name):
self.name = name
# def __init__(self, name=None):
# self.name = name
def __set__(self, instance, value):
if not isinstance(value, self._expected_type):
raise TypeError('Expected' +... | class Typed(object):
_expected_type = type(None)
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, self._expected_type):
raise type_error('Expected' + str(self._expected_type))
instance.__dict__[self.name]... |
class IOLiteError(Exception):
pass
class UnsupportedDeviceError(IOLiteError):
def __init__(self, type_name: str, identifier: str, payload: dict):
self.type_name = type_name
self.identifier = identifier
self.payload = payload
super().__init__(f"Unsupported device with type_name ... | class Ioliteerror(Exception):
pass
class Unsupporteddeviceerror(IOLiteError):
def __init__(self, type_name: str, identifier: str, payload: dict):
self.type_name = type_name
self.identifier = identifier
self.payload = payload
super().__init__(f'Unsupported device with type_name ... |
diagram = input()
mpos = diagram.find('$')
tpos = diagram.find('T')
#sawp if mpos > pos
if tpos >= mpos:
tpos +=1
else:
mpos += 1
tmp = mpos
mpos = tpos
tpos = tmp
#get substring between $ and T
action = "quiet" if 'G' in diagram[mpos:tpos] else "ALARM"
print(diagram[mpos:tpos],end="")
| diagram = input()
mpos = diagram.find('$')
tpos = diagram.find('T')
if tpos >= mpos:
tpos += 1
else:
mpos += 1
tmp = mpos
mpos = tpos
tpos = tmp
action = 'quiet' if 'G' in diagram[mpos:tpos] else 'ALARM'
print(diagram[mpos:tpos], end='') |
n = int(input())
for i in range(int(n**2)):
a = input()
for i in range(n):
print(*[j+1 for j in range(n-1,-1,-1)])
| n = int(input())
for i in range(int(n ** 2)):
a = input()
for i in range(n):
print(*[j + 1 for j in range(n - 1, -1, -1)]) |
def dimensoes(minha_matriz):
print( str(len(minha_matriz))+'X'+str(len((minha_matriz[0]))))
if __name__=='__main__':
minha_matriz = [[1], [2], [3]]
dimensoes(minha_matriz)
minha_matriz = [[1, 2, 3], [4, 5, 6]]
dimensoes(minha_matriz)
| def dimensoes(minha_matriz):
print(str(len(minha_matriz)) + 'X' + str(len(minha_matriz[0])))
if __name__ == '__main__':
minha_matriz = [[1], [2], [3]]
dimensoes(minha_matriz)
minha_matriz = [[1, 2, 3], [4, 5, 6]]
dimensoes(minha_matriz) |
def validate_required_field(field_value, field_name, action):
assert field_value, f'{field_name} is required to {action}'
def validate_required_fields(action, **kwargs):
for item in kwargs.items():
validate_required_field(item[1], item[0], action=action)
def validate_names(action, **kwargs):
fo... | def validate_required_field(field_value, field_name, action):
assert field_value, f'{field_name} is required to {action}'
def validate_required_fields(action, **kwargs):
for item in kwargs.items():
validate_required_field(item[1], item[0], action=action)
def validate_names(action, **kwargs):
for i... |
#
# PySNMP MIB module RFC1229-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1229-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:48:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
def Sort_in_range(lst, start, end):
temp = []
for i in range(start,end+1):
temp.append(lst[i])
temp.sort()
k = 0
for i in range(start, end+1):
lst[i] = temp[k]
k += 1
return lst
lst_0 = [5, 21, 2, 67, 12, 7, 66, 3, 5]
lst_0 = Sort_in_range(lst_0, 1,6)
print(lst_0)
| def sort_in_range(lst, start, end):
temp = []
for i in range(start, end + 1):
temp.append(lst[i])
temp.sort()
k = 0
for i in range(start, end + 1):
lst[i] = temp[k]
k += 1
return lst
lst_0 = [5, 21, 2, 67, 12, 7, 66, 3, 5]
lst_0 = sort_in_range(lst_0, 1, 6)
print(lst_0) |
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Moun... | class Easydict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
del self[name]
data_dir = 'datasets'
result_... |
'''
Created on Nov 21, 2016
@author: matth
'''
class WebSocketServerd(object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
| """
Created on Nov 21, 2016
@author: matth
"""
class Websocketserverd(object):
"""
classdocs
"""
def __init__(self):
"""
Constructor
""" |
class Solution:
# @param A : tuple of strings
# @return a list of list of integers
def anagrams(self, A):
hmp = dict()
pairs = []
for i in range(len(A)):
vec = self.vectorize(A[i]) # get the vector string
if vec not in hmp:
hmp[vec] = [i+1]
else:
# ... | class Solution:
def anagrams(self, A):
hmp = dict()
pairs = []
for i in range(len(A)):
vec = self.vectorize(A[i])
if vec not in hmp:
hmp[vec] = [i + 1]
else:
hmp[vec].append(i + 1)
return list(hmp.values())
def... |
# ========================
# MAIN SETTINGS
# make this something secret in your overriding app.cfg
SECRET_KEY = "default-key"
# contact info
ADMIN_NAME = "Cottage Labs"
ADMIN_EMAIL = "sysadmin@openaccessbutton.org"
# service info
SERVICE_NAME = "Trust OA"
SERVICE_TAGLINE = ""
HOST = "0.0.0.0"
DEBUG = True
PORT = 511... | secret_key = 'default-key'
admin_name = 'Cottage Labs'
admin_email = 'sysadmin@openaccessbutton.org'
service_name = 'Trust OA'
service_tagline = ''
host = '0.0.0.0'
debug = True
port = 5111
elastic_search_host = 'http://127.0.0.1:9200'
elastic_search_db = 'trustoa'
index_version = 0
initialise_index = True
super_user =... |
class Solution:
def kidCandies(self, candies:list[int], extraCandies: int):
k=[]
for i in candies:
i+extraCandies
if i+extraCandies>=max(candies):
k.append(True)
if i+extraCandies<max(candies):
k.append(False)
return k
| class Solution:
def kid_candies(self, candies: list[int], extraCandies: int):
k = []
for i in candies:
i + extraCandies
if i + extraCandies >= max(candies):
k.append(True)
if i + extraCandies < max(candies):
k.append(False)
... |
#!/usr/bin/python
listA = []
with open("F:\Research\Python\data.txt", "r") as P:
listA = [line.strip() for line in P]
listA = sorted(listA, key=len)
for line in listA:
print(line,'\n' , end="" )
| list_a = []
with open('F:\\Research\\Python\\data.txt', 'r') as p:
list_a = [line.strip() for line in P]
list_a = sorted(listA, key=len)
for line in listA:
print(line, '\n', end='') |
class ProcessException(Exception):
def __init__(self, message: str, exit_code: int) -> None:
super().__init__(message)
self.exit_code = exit_code
| class Processexception(Exception):
def __init__(self, message: str, exit_code: int) -> None:
super().__init__(message)
self.exit_code = exit_code |
dist = int(input())
if dist<=5 and dist>0:
print(int(dist/dist))
elif dist>5:
if dist%5!=0:
num = (dist//5)+1
print(num)
else:
num = dist//5
print(num) | dist = int(input())
if dist <= 5 and dist > 0:
print(int(dist / dist))
elif dist > 5:
if dist % 5 != 0:
num = dist // 5 + 1
print(num)
else:
num = dist // 5
print(num) |
# jumlah keramik
JumKeramik = 533
# jumlah 1 box keramik adalah 5
box = 5
#hitung total box keramik yang dibutuhkan
totalbox = JumKeramik / box
print("jumlah box yang diperlukan = ", totalbox)
| jum_keramik = 533
box = 5
totalbox = JumKeramik / box
print('jumlah box yang diperlukan = ', totalbox) |
# zwei 06/28/2014
# yield expression in generator functions
def generator(n):
for i in range(n):
x = len([]) + (yield i * 2)
print(x)
gen = generator(5)
it = 0
gen.__next__()
try:
while True:
gen.send(it)
it += 1
except StopIteration:
pass | def generator(n):
for i in range(n):
x = len([]) + (yield (i * 2))
print(x)
gen = generator(5)
it = 0
gen.__next__()
try:
while True:
gen.send(it)
it += 1
except StopIteration:
pass |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"DeepZoomBucket": "20_uploading-your-own-deep-zoom-images.ipynb",
"PREFIX": "20_uploading-your-own-deep-zoom-images.ipynb",
"ROOTDIR": "20_uploading-your-own-deep-zoom-images.ipynb",
... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'DeepZoomBucket': '20_uploading-your-own-deep-zoom-images.ipynb', 'PREFIX': '20_uploading-your-own-deep-zoom-images.ipynb', 'ROOTDIR': '20_uploading-your-own-deep-zoom-images.ipynb', 'VIEWERSDIR': '20_uploading-your-own-deep-zoom-images.ipynb'}
modu... |
a=int(input("Enter the first number of the series "))
b=int(input("Enter the second number of the series "))
n=int(input("Enter the number of terms needed "))
print(a,b,end=" ")
while(n-2):
c=a+b
a=b
b=c
print(c,end=" ")
n=n-1 | a = int(input('Enter the first number of the series '))
b = int(input('Enter the second number of the series '))
n = int(input('Enter the number of terms needed '))
print(a, b, end=' ')
while n - 2:
c = a + b
a = b
b = c
print(c, end=' ')
n = n - 1 |
def create_package_test(myclass_type,h_group,name,**kwargs):
return h_group,()
def load_package_test(h_node,base_type,py_obj_type):
return {12:12}
class_register = [
( dict,b'dict',create_package_test,load_package_test )
]
exclude_register = [b'please_kindly_ignore_me']
| def create_package_test(myclass_type, h_group, name, **kwargs):
return (h_group, ())
def load_package_test(h_node, base_type, py_obj_type):
return {12: 12}
class_register = [(dict, b'dict', create_package_test, load_package_test)]
exclude_register = [b'please_kindly_ignore_me'] |
selected_fields = ['MSZoning', 'LotArea', 'Street', 'LotShape', 'LandContour', 'Utilities', 'Neighborhood',
'Condition1', 'Condition2', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd',
'YrSold', 'SaleType', 'SaleCondition']
encoding_fields = ['MSZoning', 'Street', 'LotSh... | selected_fields = ['MSZoning', 'LotArea', 'Street', 'LotShape', 'LandContour', 'Utilities', 'Neighborhood', 'Condition1', 'Condition2', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd', 'YrSold', 'SaleType', 'SaleCondition']
encoding_fields = ['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities', 'Neig... |
# O(nlgn) solution
# class Solution:
# def minMeetingRooms(self, intervals: List[List[int]]) -> int:
# # pre-process
# processedIntervals = []
# for interval in intervals:
# processedIntervals.append((interval[0], 0))
# processedIntervals.append((interval[1], 1))
# ... | class Solution:
def min_meeting_rooms(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
free_rooms = []
intervals.sort(key=lambda x: x[0])
heapq.heappush(freeRooms, intervals[0][1])
for interval in intervals[1:]:
if freeRooms[0] <= ... |
class DobotCamera:
def __init__(self, xDobRefPoint, yDobRefPoint, xCamRefPoint,
yCamRefPoint, xScaleFactor, yScaleFactor):
self.X_DOB_REF_POINT = xDobRefPoint
self.Y_DOB_REF_POINT = yDobRefPoint
self.X_CAM_REF_POINT = xCamRefPoint
self.Y_CAM_REF_POINT = yCamRefPo... | class Dobotcamera:
def __init__(self, xDobRefPoint, yDobRefPoint, xCamRefPoint, yCamRefPoint, xScaleFactor, yScaleFactor):
self.X_DOB_REF_POINT = xDobRefPoint
self.Y_DOB_REF_POINT = yDobRefPoint
self.X_CAM_REF_POINT = xCamRefPoint
self.Y_CAM_REF_POINT = yCamRefPoint
self.X_S... |
__author__ = 'PAY.ON'
# following module represents the configuration of the OPP library
# all configuration values apply both for opp.core and opp.facade modules
#constants
TEST_INTERNAL = 0
TEST_EXTERNAL = 1
LIVE = 3
#configuration values for OPP
TEST_URL = "https://test.oppwa.com/v1" # url used for TEST_INTERNAL ... | __author__ = 'PAY.ON'
test_internal = 0
test_external = 1
live = 3
test_url = 'https://test.oppwa.com/v1'
live_url = 'https://oppwa.com/v1'
mode = TEST_INTERNAL
request_timeout = 60
validate_ssl = True
http_debug_mode = False
class Config(object):
def __init__(self, test_url=TEST_URL, live_url=LIVE_URL, mode=TEST... |
STRING_LIST = '''
aids
airlines
billionaires
broadway
business_dynamics
cancer
cars
classics
construction_permits
construction_spending
county_crime
county_demographics
drugs
drug_bank
earthquakes
education
election
energy
finance
food
food_access
global_development
graduates
health
hospitals
hydropower
immigration
inj... | string_list = '\naids\nairlines\nbillionaires\nbroadway\nbusiness_dynamics\ncancer\ncars\nclassics\nconstruction_permits\nconstruction_spending\ncounty_crime\ncounty_demographics\ndrugs\ndrug_bank\nearthquakes\neducation\nelection\nenergy\nfinance\nfood\nfood_access\nglobal_development\ngraduates\nhealth\nhospitals\nhy... |
#
# PySNMP MIB module Juniper-ERX-System-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-ERX-System-CONF
# Produced by pysmi-0.3.4 at Mon Apr 29 19:51:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, constraints_union, value_size_constraint) ... |
#
# @lc app=leetcode id=85 lang=python3
#
# [85] Maximal Rectangle
#
# @lc code=start
class Solution:
def largestRecInHist(self, heights: List[int]) -> int:
if not heights:
return 0
total_num = len(heights)
if total_num == 1:
return heights[0]
less_from_left... | class Solution:
def largest_rec_in_hist(self, heights: List[int]) -> int:
if not heights:
return 0
total_num = len(heights)
if total_num == 1:
return heights[0]
less_from_left = [None] * total_num
less_from_left[0] = -1
for i in range(1, total... |
def myGauss(m):
for col in range(len(m[0])):
for row in range(col+1, len(m)):
r = [(rowValue * (-(m[row][col] / m[col][col]))) for rowValue in m[col]]
m[row] = [sum(pair) for pair in zip(m[row], r)]
ans = []
m.reverse()
for sol in range(len(m)):
if ... | def my_gauss(m):
for col in range(len(m[0])):
for row in range(col + 1, len(m)):
r = [rowValue * -(m[row][col] / m[col][col]) for row_value in m[col]]
m[row] = [sum(pair) for pair in zip(m[row], r)]
ans = []
m.reverse()
for sol in range(len(m)):
if sol == 0:
... |
#!/usr/bin/env python
# encoding: utf-8
class OsfStorageError(Exception):
pass
class PathLockedError(OsfStorageError):
pass
class SignatureConsumedError(OsfStorageError):
pass
class VersionNotFoundError(OsfStorageError):
pass
class SignatureMismatchError(OsfStorageError):
pass
class VersionSta... | class Osfstorageerror(Exception):
pass
class Pathlockederror(OsfStorageError):
pass
class Signatureconsumederror(OsfStorageError):
pass
class Versionnotfounderror(OsfStorageError):
pass
class Signaturemismatcherror(OsfStorageError):
pass
class Versionstatuserror(OsfStorageError):
pass
clas... |
class Postgres:
def __init__(self, db):
self.__db = db
def load(self, checks):
for check in checks:
check_exists = len(self.__db.query('SELECT id FROM pingdom_check WHERE id = :id', id=check['id']).all()) == 1
if (check_exists):
self.__db.query(
... | class Postgres:
def __init__(self, db):
self.__db = db
def load(self, checks):
for check in checks:
check_exists = len(self.__db.query('SELECT id FROM pingdom_check WHERE id = :id', id=check['id']).all()) == 1
if check_exists:
self.__db.query('UPDATE pin... |
class Demo:
a1 = 1
def __init__(self):
del Demo.a1
print("Before object creation static variable a1 is present")
print(Demo.__dict__)
print("---------------------------")
myobj = Demo()
print("After object creation static variable a1 is absent")
print(Demo.__dict__)
| class Demo:
a1 = 1
def __init__(self):
del Demo.a1
print('Before object creation static variable a1 is present')
print(Demo.__dict__)
print('---------------------------')
myobj = demo()
print('After object creation static variable a1 is absent')
print(Demo.__dict__) |
def to_hexcol(kivycol):
return "#" + "".join(f"{round(c * 255):02x}" for c in kivycol[:3])
DEFAULT_FONT = "fonts/NotoSans-Regular.ttf"
# basic color definitions
WHITE = [0.95, 0.95, 0.95, 1]
BLACK = [0.05, 0.05, 0.05, 1]
LIGHTGREY = [0.7, 0.7, 0.7, 1]
RED = [0.8, 0.1, 0.1, 1]
GREEN = [0.1, 0.8, 0.1, 1]
YELLOW =... | def to_hexcol(kivycol):
return '#' + ''.join((f'{round(c * 255):02x}' for c in kivycol[:3]))
default_font = 'fonts/NotoSans-Regular.ttf'
white = [0.95, 0.95, 0.95, 1]
black = [0.05, 0.05, 0.05, 1]
lightgrey = [0.7, 0.7, 0.7, 1]
red = [0.8, 0.1, 0.1, 1]
green = [0.1, 0.8, 0.1, 1]
yellow = [0.8, 0.8, 0.1, 1]
darkred ... |
'''
Author: Shuailin Chen
Created Date: 2021-09-30
Last Modified: 2021-10-22
content: resnet with stochastic path
'''
_base_=['./r18-d8.py']
model = dict(
backbone=dict(
type='ResNetDropPathV1c',
drop_path_rate=0.3
),
) | """
Author: Shuailin Chen
Created Date: 2021-09-30
Last Modified: 2021-10-22
content: resnet with stochastic path
"""
_base_ = ['./r18-d8.py']
model = dict(backbone=dict(type='ResNetDropPathV1c', drop_path_rate=0.3)) |
#!/usr/bin/env python3
num = int(input('Enter an integer: '))
if num % 2 == 0:
print(f'The number {num} is even.')
else:
print(f'The number {num} is odd.')
| num = int(input('Enter an integer: '))
if num % 2 == 0:
print(f'The number {num} is even.')
else:
print(f'The number {num} is odd.') |
#zzw 20180714 support str encode
gFlagDic = {'strEncode' : 'utf8'}
gVerbose = False
| g_flag_dic = {'strEncode': 'utf8'}
g_verbose = False |
# -*- coding: utf-8 -*-
x = 1
y = 1
while x!= 0 or y!=0:
x, y = map(int, input().split())
if x!=0 or y!=0:
if y>0 and x>0:
print('primeiro')
if y<0 and x>0:
print('quarto')
if y<0 and x<0:
print('terceiro')
if y>0 and x<0:
print('s... | x = 1
y = 1
while x != 0 or y != 0:
(x, y) = map(int, input().split())
if x != 0 or y != 0:
if y > 0 and x > 0:
print('primeiro')
if y < 0 and x > 0:
print('quarto')
if y < 0 and x < 0:
print('terceiro')
if y > 0 and x < 0:
print('s... |
input_list = []
for i in range(2):
input_list.append(input())
T = input_list[0]
S = input_list[1]
cyclic_list = []
for _ in range(len(S)):
cyclic = S[1:] + S[0]
cyclic_list.append(cyclic)
S = cyclic
result = 'no'
for cyclic in cyclic_list:
if cyclic in T:
result = 'yes'
print(result) | input_list = []
for i in range(2):
input_list.append(input())
t = input_list[0]
s = input_list[1]
cyclic_list = []
for _ in range(len(S)):
cyclic = S[1:] + S[0]
cyclic_list.append(cyclic)
s = cyclic
result = 'no'
for cyclic in cyclic_list:
if cyclic in T:
result = 'yes'
print(result) |
class QRCode:
def __init__(self, queryString):
self.queryString = queryString
| class Qrcode:
def __init__(self, queryString):
self.queryString = queryString |
'''https://leetcode.com/problems/find-all-numbers-disappeared-in-an-numsay/submissions/
448. Find All Numbers Disappeared in an Array
Easy
5401
344
Add to List
Share
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in ... | """https://leetcode.com/problems/find-all-numbers-disappeared-in-an-numsay/submissions/
448. Find All Numbers Disappeared in an Array
Easy
5401
344
Add to List
Share
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in ... |
# Program FindMin
# program ini akan mengembalikan elemen minimum dari array
# Asumsi: array tidak kosong.
# Input: T : TabInt, input N : int
# Output: Min : int, IMin : int
# KAMUS
# type TabInt : array of integer
# Variabel
# T : TabInt
# N : int
def FindMin(T, N):
# I.S. Tabel T tidak kosong, N > 0
# F.S. Menghas... | def find_min(T, N):
min = T[0]
i_min = 0
i = 1
while i <= N - 1:
if MIN > T[i]:
min = T[i]
i_min = i
i = i + 1
print(IMin)
'\nProgram FindMin\n{ program ini akan mengembalikan elemen minimum dari array\n Asumsi: array tidak kosong. }\n\nKAMUS\n constant NMax... |
class HeapPriorityQueue:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def _parent(self, index):
if index % 2 == 0:
index -= 1
return index // 2
def _left(self, index):
return index * 2 + 1
def _right(self, inde... | class Heappriorityqueue:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def _parent(self, index):
if index % 2 == 0:
index -= 1
return index // 2
def _left(self, index):
return index * 2 + 1
def _right(self, inde... |
# using iteration to achieve factorial function
def factorial(a):
fList = [i for i in range(1, a+1)]
while(len(fList) != 1):
fList[-1] = fList[-1]*fList[-2]
fList.pop(-2)
print(fList[1])
# factorial(4)
def forFactorial(a):
r = 0
for i in range(1, a+1, 2):
if(i+1 < a... | def factorial(a):
f_list = [i for i in range(1, a + 1)]
while len(fList) != 1:
fList[-1] = fList[-1] * fList[-2]
fList.pop(-2)
print(fList[1])
def for_factorial(a):
r = 0
for i in range(1, a + 1, 2):
if i + 1 < a:
r += i * (i + 1)
else:
r ... |
#
# @lc app=leetcode id=55 lang=python3
#
# [55] Jump Game
#
# https://leetcode.com/problems/jump-game/description/
#
# algorithms
# Medium (32.70%)
# Likes: 2490
# Dislikes: 237
# Total Accepted: 316K
# Total Submissions: 966.5K
# Testcase Example: '[2,3,1,1,4]'
#
# Given an array of non-negative integers, you ... | class Solution:
def can_jump(self, nums: List[int]) -> bool:
f = [False] * len(nums)
f[0] = True
for i in range(len(nums)):
for j in range(i):
if f[j] and f[j] + j >= i:
f[i] = True
break
return f[-1] |
class Pool:
def __init__(self, name_stream: AsyncIterator[Address]):
pass
| class Pool:
def __init__(self, name_stream: AsyncIterator[Address]):
pass |
#!/usr/bin/python
# Time-stamp: <2015-12-14 17:08:23 marine>
# Project : Snow in the F - layer
# Subproject : parameters file
# Author : Marine Lasbleis
# Computation parameters
hmin = 1.
hmax = 0.
nst = 100.
dt = (hmax - hmin) / nst
AbsTol = 1.e-10
RelTol = 1.e-12
Nddy = 30
# Physical parameters
X0 = 0.1 # mass ... | hmin = 1.0
hmax = 0.0
nst = 100.0
dt = (hmax - hmin) / nst
abs_tol = 1e-10
rel_tol = 1e-12
nddy = 30
x0 = 0.1
tliq0 = 6250.0
d = 200000.0
r_i_cp = 1221000.0
alpha = 1.95e-05
g = 4.4
mp = 9e-09
m_x = 11000.0
rho0 = 12530.0
lambda_x = 1e-09
k = 2e-05
vs0 = 0.0001
rdot = 1e-11
k0 = 1403000000000.0
kprim0 = 3.567
lrho = 80... |
def join_punctuation(seq, characters='.,;?!'):
characters = set(characters)
seq = iter(seq)
current = next(seq)
for nxt in seq:
if nxt in characters:
current += nxt
else:
yield current
current = nxt
yield current
| def join_punctuation(seq, characters='.,;?!'):
characters = set(characters)
seq = iter(seq)
current = next(seq)
for nxt in seq:
if nxt in characters:
current += nxt
else:
yield current
current = nxt
yield current |
'''''
Main helper to clean house
'''''
def clean_master_bedroom():
group_clothes()
def group_clothes():
group_ranga_clothes()
group_jaanu_clothes()
group_akshu_clothes()
def group_ranga_clothes():
group_tops()
group_bottoms()
group_accesories()
# These are tshirts which will be used onl... | """''
Main helper to clean house
"""
def clean_master_bedroom():
group_clothes()
def group_clothes():
group_ranga_clothes()
group_jaanu_clothes()
group_akshu_clothes()
def group_ranga_clothes():
group_tops()
group_bottoms()
group_accesories()
def fix_tshirt_indoor_spot():
print('Fixe... |
lr=0.0001
dropout_rate=0.5
max_epoch=3317
batch_size=4096
w=19
u=9
num_hidden_1=512
num_hidden_2=512
| lr = 0.0001
dropout_rate = 0.5
max_epoch = 3317
batch_size = 4096
w = 19
u = 9
num_hidden_1 = 512
num_hidden_2 = 512 |
# Check if input is valid number, make int to float by adding .0 or check if entered string is correct float
def manageInput(number):
if number.count(",") > 1 or not number.replace(",","",1).isdigit():
return -1.1
return float(number.replace(",",".",1))
print("Started Typer")
#Guess if i want comma separated num... | def manage_input(number):
if number.count(',') > 1 or not number.replace(',', '', 1).isdigit():
return -1.1
return float(number.replace(',', '.', 1))
print('Started Typer')
while True:
values = []
basics = []
print('Enter your numbers and "finished" to end')
number = input('')
while ... |
class InitialValues:
def __init__(self,
cutoff_methods,
best_config,
n_iter,
best_cutoff_method,
best_silhouette,
initial_best_metric,
state_of_art):
self.state_of_art = state_of_art
... | class Initialvalues:
def __init__(self, cutoff_methods, best_config, n_iter, best_cutoff_method, best_silhouette, initial_best_metric, state_of_art):
self.state_of_art = state_of_art
self.cutoff_methods = cutoff_methods
self.best_config = best_config
self.n_iter = n_iter
sel... |
# Position redistributors.
source("testDistributeByPosition1d.py")
source("testDistributeByPosition2d.py")
# ParMETIS redistributor.
# source("testParmetisDistribute.py")
# The space filling curve redistributors.
source("testMortonOrderDistribute.py")
source("testPeanoHilbertOrderDistribute.py")
# DistributedBoundar... | source('testDistributeByPosition1d.py')
source('testDistributeByPosition2d.py')
source('testMortonOrderDistribute.py')
source('testPeanoHilbertOrderDistribute.py')
source('testDistributed1d.py')
source('testDistributed2d.py')
source('testDistributed3d.py') |
x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x))
print("originally, x = ", x)
#remove the third element
x.pop(2)
print(x)
#remove the element equal to 2.5
x.remove(2.5)
print(x)
#add an element at the end
x.append(1.2)
print(x)
#get a copy of x
y = x.copy()
print(y)
#how many elements equal to zero... | x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x))
print('originally, x = ', x)
x.pop(2)
print(x)
x.remove(2.5)
print(x)
x.append(1.2)
print(x)
y = x.copy()
print(y)
print(y.count(0.0))
print(y.index(3.7))
print("i'm gonna insert 7.9 at the beginning of array y")
y.insert(0, 7.9)
print('unsorted: ', y)
y.sort()
print('sorted... |
numbers = list("123456789")
nos = numbers
nos2 = numbers.copy()
numbers.remove("9")
print(nos)
print(nos2) | numbers = list('123456789')
nos = numbers
nos2 = numbers.copy()
numbers.remove('9')
print(nos)
print(nos2) |
def swap_jmp_and_nop(command):
if "jmp" in command:
return command.replace("jmp", "nop")
return command.replace("nop", "jmp")
class CodeRunner:
def __init__(self, commands):
self.commands = commands
self.acc = 0
self.commands_exec_counts = [0] * len(commands)
s... | def swap_jmp_and_nop(command):
if 'jmp' in command:
return command.replace('jmp', 'nop')
return command.replace('nop', 'jmp')
class Coderunner:
def __init__(self, commands):
self.commands = commands
self.acc = 0
self.commands_exec_counts = [0] * len(commands)
self.i... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
DEPENDENCIES = ["azure-ml"]
| dependencies = ['azure-ml'] |
num = float(input('Digite um valor em metro: '))
dec = mum * 10
cent = num * 100
mili = num * 1000
print(f'Metro: {num}m'
f'\nDecimetro: {dec:.0f}dm'
f'\nCentimetro: {cent:.0f}cm'
f'\nMilimetro: {mili:.0f}mm')
| num = float(input('Digite um valor em metro: '))
dec = mum * 10
cent = num * 100
mili = num * 1000
print(f'Metro: {num}m\nDecimetro: {dec:.0f}dm\nCentimetro: {cent:.0f}cm\nMilimetro: {mili:.0f}mm') |
UNUSED_READ_VARS = {
"agir1",
"efi",
"elect",
"flpdmo",
"f3800",
"f8582",
"f8606",
"n20",
"n25",
"prep",
"schb",
"schcf",
"sche",
"tform",
"ie",
"txst",
"xfpt",
"xfst",
"xocah",
"xocawh",
"xoodep",
"xopar",
"s008",
"s009",
... | unused_read_vars = {'agir1', 'efi', 'elect', 'flpdmo', 'f3800', 'f8582', 'f8606', 'n20', 'n25', 'prep', 'schb', 'schcf', 'sche', 'tform', 'ie', 'txst', 'xfpt', 'xfst', 'xocah', 'xocawh', 'xoodep', 'xopar', 's008', 's009', 'wsamp', 'txrt', 'e30400', 'e24598', 'e11300', 'e24535', 'e30500', 'e07180', 'e53458', 'e33000', '... |
n = int(input())
def conNS(x, si1 ,si2):
x = int(str(x), si1)
b = ''
while x > 0:
b, x = str(x%si2)+b, x//si2
return b
n = conNS(n, 5, 7)
n = sum(list(map(int, str(n))))
n = conNS(n, 10, 3)
print(n)
| n = int(input())
def con_ns(x, si1, si2):
x = int(str(x), si1)
b = ''
while x > 0:
(b, x) = (str(x % si2) + b, x // si2)
return b
n = con_ns(n, 5, 7)
n = sum(list(map(int, str(n))))
n = con_ns(n, 10, 3)
print(n) |
name = "nose2rt"
| name = 'nose2rt' |
def evaluate(predicted_y, test_y):
n = 0
good = 0
for p_y, t_y in zip(predicted_y, test_y):
t_y = t_y[0]
if p_y == t_y:
good = good + 1
n = n + 1
return {'accuracy': (good / n), 'num_samples': n}
| def evaluate(predicted_y, test_y):
n = 0
good = 0
for (p_y, t_y) in zip(predicted_y, test_y):
t_y = t_y[0]
if p_y == t_y:
good = good + 1
n = n + 1
return {'accuracy': good / n, 'num_samples': n} |
'''
Created on Sun 04/05/2020 07:07:14
Armstrong Number
@author: MarsCandyBars
'''
def armstrong(user_num):
'''
Description:
This function assesses a number and determines if it
is an armstrong number.
Args:
user_num
Returns:
Prints whether or not user_num is an arm... | """
Created on Sun 04/05/2020 07:07:14
Armstrong Number
@author: MarsCandyBars
"""
def armstrong(user_num):
"""
Description:
This function assesses a number and determines if it
is an armstrong number.
Args:
user_num
Returns:
Prints whether or not user_num is an armstron... |
l, r, n = map(int, input().split())
a = [(r + 1) // n] * n
for i in range((r + 1) % n):
a[i] += 1
b = [l // n] * n
for i in range(l % n):
b[i] += 1
for i in range(n):
a[i] -= b[i]
print(*a, sep='\n')
| (l, r, n) = map(int, input().split())
a = [(r + 1) // n] * n
for i in range((r + 1) % n):
a[i] += 1
b = [l // n] * n
for i in range(l % n):
b[i] += 1
for i in range(n):
a[i] -= b[i]
print(*a, sep='\n') |
deposit = float(input())
period = int(input())
rate = float(input()) * 0.01
print(deposit + period * ((deposit * rate) / 12))
| deposit = float(input())
period = int(input())
rate = float(input()) * 0.01
print(deposit + period * (deposit * rate / 12)) |
# 5. Write a function which takes in N (the number of users) and s_N (the state
# probability for the last user in the chain) and returns the maximum likelihood estimate
# of s_0 (rounded to 2 decimal places).
def estimate_s_0(N, s_N):
return s_0_mle
| def estimate_s_0(N, s_N):
return s_0_mle |
''' Binary Search (No working for me)
Binary search is more efficient and quicker than a linear search.
It can only be appDictionary Search example
Dictionary Search example.
Pseudocode
1. Start
2. Initialize list data
3. Set LOC = -1
4. Take Key from user
5. Set L = 0 and U = len(DATA) - 1
6. Set MID ... | """ Binary Search (No working for me)
Binary search is more efficient and quicker than a linear search.
It can only be appDictionary Search example
Dictionary Search example.
Pseudocode
1. Start
2. Initialize list data
3. Set LOC = -1
4. Take Key from user
5. Set L = 0 and U = len(DATA) - 1
6. Set MID ... |
#
# PySNMP MIB module GDC7616-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GDC7616-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:18:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, constraints_union, single_value_constraint) ... |
n = int(input())
edges = [0]*(n+1)
isPossible = True
for i in range(n-1):
a,b = [int(i) for i in input().split()]
edges[a]+=1
edges[b]+=1
for d in edges:
if d == 2:
isPossible = False
break
print("YES" if isPossible else "NO") | n = int(input())
edges = [0] * (n + 1)
is_possible = True
for i in range(n - 1):
(a, b) = [int(i) for i in input().split()]
edges[a] += 1
edges[b] += 1
for d in edges:
if d == 2:
is_possible = False
break
print('YES' if isPossible else 'NO') |
VERSIONS = {
"3.3.17 hybrid": {
"nomenclature": {
"extensions": [
{
"filename": "Classifications_v_3_3_17.xlsx",
"worksheet": "Resources",
"mapping": {"Resource name": "name", "Unit": "unit"},
"kind":... | versions = {'3.3.17 hybrid': {'nomenclature': {'extensions': [{'filename': 'Classifications_v_3_3_17.xlsx', 'worksheet': 'Resources', 'mapping': {'Resource name': 'name', 'Unit': 'unit'}, 'kind': 'resource'}, {'filename': 'Classifications_v_3_3_17.xlsx', 'worksheet': 'Land', 'mapping': {'Land type': 'name', 'Unit': 'un... |
# from ['image']['imagedata']['analysis_report']['analyzer_meta']
def test_distro_metadata(analyzed_data):
result = analyzed_data()
actual = result['image']['imagedata']['analysis_report']['analyzer_meta']
# This is odd, it nests another `analyzer_meta` in there
expected = {
"analyzer_meta": {... | def test_distro_metadata(analyzed_data):
result = analyzed_data()
actual = result['image']['imagedata']['analysis_report']['analyzer_meta']
expected = {'analyzer_meta': {'base': {'DISTRO': 'centos', 'DISTROVERS': '8', 'LIKEDISTRO': 'rhel,fedora'}}}
assert actual == expected
def test_alpine_metadata(ana... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.