content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Trainable:
def __init__(self, dataset):
self.dataset = dataset
def train(self, epochs, batch_size=8):
loader = DataLoader(self.dataset,
batch_size=batch_size,
shuffle=True,
num_workers=4)
for ep... | class Trainable:
def __init__(self, dataset):
self.dataset = dataset
def train(self, epochs, batch_size=8):
loader = data_loader(self.dataset, batch_size=batch_size, shuffle=True, num_workers=4)
for epoch in range(epochs):
for (i, batch) in enumerate(dataset_loader):
... |
a = float(input('Type the size of the A side: '))
b = float(input('Type the size of the B side: '))
c = float(input('Type the size of the C side: '))
if not (a + b > c and a + c > b and c + b > a):
print('This sides cannot creates a triagle.')
else:
if a == b and b == c and a == c:
print('This triangle... | a = float(input('Type the size of the A side: '))
b = float(input('Type the size of the B side: '))
c = float(input('Type the size of the C side: '))
if not (a + b > c and a + c > b and (c + b > a)):
print('This sides cannot creates a triagle.')
elif a == b and b == c and (a == c):
print('This triangle is equil... |
# Calculate the number of chunks in a slab and the offset of the first chunk,
# given a list of chunk sizes.
#
# Used to update values in the memory allocator.
CHUNK_SIZES = (8, 64, 256, 1024, 262144)
NUM_CHUNKS = [ ]
FIRST_OFFSET = [ ]
WASTED_BYTES = [ ]
HEADER_SIZE = 40
BITMAP_GROW_BY = 8 # Bitmap is for... | chunk_sizes = (8, 64, 256, 1024, 262144)
num_chunks = []
first_offset = []
wasted_bytes = []
header_size = 40
bitmap_grow_by = 8
slab_size = 2097152
print('Chunk size | Num chunks | First offset | Wasted bytes')
print('-----------|------------|--------------|-------------')
for chunk_size in CHUNK_SIZES:
free_space... |
del_items(0x80135778)
SetType(0x80135778, "struct THEME_LOC themeLoc[50]")
del_items(0x80135EC0)
SetType(0x80135EC0, "unsigned char L5dungeon[80][80]")
del_items(0x80135B60)
SetType(0x80135B60, "struct ShadowStruct SPATS[37]")
del_items(0x80135C64)
SetType(0x80135C64, "unsigned char BSTYPES[206]")
del_items(0x80135D34)... | del_items(2148751224)
set_type(2148751224, 'struct THEME_LOC themeLoc[50]')
del_items(2148753088)
set_type(2148753088, 'unsigned char L5dungeon[80][80]')
del_items(2148752224)
set_type(2148752224, 'struct ShadowStruct SPATS[37]')
del_items(2148752484)
set_type(2148752484, 'unsigned char BSTYPES[206]')
del_items(2148752... |
#!/usr/bin/python
#loss_type = ["Cauchy", "Huber"]
#loss_type = ["SoftLOneLoss", "Huber"]
loss_type = ["Cauchy"]
#robust_loss_scale = [0.5, 0.8, 1.0, 1.3, 1.5, 2.0, 2.5]
#robust_loss_scale = [0.05, 0.1, 0.2, 0.3, 0.4, 0.6]
robust_loss_scale = [0.01, 0.05, 0.1, 0.15, 0.2, 0.3, 10.0]
fp_runscript = open("/home/kivan/Pr... | loss_type = ['Cauchy']
robust_loss_scale = [0.01, 0.05, 0.1, 0.15, 0.2, 0.3, 10.0]
fp_runscript = open('/home/kivan/Projects/cv-stereo/scripts/egomotion_kitti_eval/run_validation_robust_loss.sh', 'w')
fp_runscript.write('#!/bin/bash\n\n')
prefix = '/home/kivan/Projects/cv-stereo/config_files/experiments/kitti/validatio... |
def binomialCoefficient(n, k):
# since C(n, k) = C(n, n - k)
if (k > n - k):
k = n - k
# initialize result
res = 1
# Calculate value of [n * (n-1) *---* (n-k + 1)]
# / [k * (k-1) *----* 1]
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
# A Binomial coefficient based function to
... | def binomial_coefficient(n, k):
if k > n - k:
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
def catalan(n):
c = binomial_coefficient(2 * n, n)
return c / (n + 1)
for i in range(10):
print(catalan(i), end=' ') |
#Load datasets and embedded vectors
def loadData(inpH, emb_file, train_file, test_file, numClasses=0):
#Load the training and the test sets
#Load the text as a sequence of inputs
x_train, y_train = inpH.getSequenceData(train_file, numClasses)
x_test, y_test = inpH.getSequenceData(test_file, nu... | def load_data(inpH, emb_file, train_file, test_file, numClasses=0):
(x_train, y_train) = inpH.getSequenceData(train_file, numClasses)
(x_test, y_test) = inpH.getSequenceData(test_file, numClasses)
for i in range(4):
print('x[{}][:5]..., y[{}] = {}, {}'.format(i, i, x_train[i][:5], y_train[i]))
i... |
# -*- coding: utf-8 -*-
class Digraph():
def __init__(self, v):
self.adj = [[] for i in range(v)]
self.vertexs = [i for i in range(v)]
def DIGRAPHInsert(self, arcs):
for arc in arcs:
self.adj[arc[0]].append(arc[1])
def TOPOLOGICList(self):
finaltVertex = []
... | class Digraph:
def __init__(self, v):
self.adj = [[] for i in range(v)]
self.vertexs = [i for i in range(v)]
def digraph_insert(self, arcs):
for arc in arcs:
self.adj[arc[0]].append(arc[1])
def topologic_list(self):
finalt_vertex = []
init_vertex = self... |
{
"uidPageCalendar": {
W3Const.w3PropType: W3Const.w3TypePanel,
W3Const.w3PropSubUI: [
"uidCalendarPanel",
"uidCalendarAddPanel"
]
},
# Calendar
"uidCalendarPanel": {
W3Const.w3PropType: W3Const.w3TypePanel,
W3Const.w3PropSubUI: [
... | {'uidPageCalendar': {W3Const.w3PropType: W3Const.w3TypePanel, W3Const.w3PropSubUI: ['uidCalendarPanel', 'uidCalendarAddPanel']}, 'uidCalendarPanel': {W3Const.w3PropType: W3Const.w3TypePanel, W3Const.w3PropSubUI: ['uidCalendar', 'uidCalendarAddEventButton']}, 'uidCalendarAddEventButton': {W3Const.w3PropType: W3Const.w3T... |
pl = pyvista.Plotter()
pl.add_mesh(mesh, show_edges=True, line_width=5)
label_coords = mesh.points + [0, 0, 0.01]
pl.add_point_labels(label_coords, [f'Point {i}' for i in range(3)],
font_size=20, point_size=20)
pl.add_point_labels([0.43, 0.2, 0], ['Cell 0'], font_size=20)
pl.camera_position = 'xy'
p... | pl = pyvista.Plotter()
pl.add_mesh(mesh, show_edges=True, line_width=5)
label_coords = mesh.points + [0, 0, 0.01]
pl.add_point_labels(label_coords, [f'Point {i}' for i in range(3)], font_size=20, point_size=20)
pl.add_point_labels([0.43, 0.2, 0], ['Cell 0'], font_size=20)
pl.camera_position = 'xy'
pl.show() |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
pleft, pleft_pos = [], []
toDel = []
for idx, ch in enumerate(s):
if ch == '(':
pleft.append('(')
pleft_pos.append(idx)
elif ch == ')':
if len(plef... | class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
(pleft, pleft_pos) = ([], [])
to_del = []
for (idx, ch) in enumerate(s):
if ch == '(':
pleft.append('(')
pleft_pos.append(idx)
elif ch == ')':
if len(pl... |
def getMax(arr):
mid = (len(arr)-1)//2 # 4
start = 0
end = len(arr) - 1 # 9
while start <= end:
if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]:
return arr[mid]
elif arr[mid] > arr[mid-1] and arr[mid] <= arr[mid+1]:
start = mid+1 # 5
mid = (start + end)//2 # 7
elif arr[mid] >= arr[mid-... | def get_max(arr):
mid = (len(arr) - 1) // 2
start = 0
end = len(arr) - 1
while start <= end:
if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]:
return arr[mid]
elif arr[mid] > arr[mid - 1] and arr[mid] <= arr[mid + 1]:
start = mid + 1
mid = (start... |
# Register Adresses
WHO_AM_I = 0x00
X_OFFS_USRH = 0x0C
X_OFFS_USRL = 0x0D
Y_OFFS_USRH = 0x0E
Y_OFFS_USRL = 0x0F
Z_OFFS_USRH = 0x10
Z_OFFS_USRL = 0x11
FIFO_EN = 0x12
AUX_VDDIO = 0x13
AUX_SLV_ADDR = 0x14
SMPLRT_DIV = 0x15
DLPF_FS = 0x16
INT_CFG = 0x17
... | who_am_i = 0
x_offs_usrh = 12
x_offs_usrl = 13
y_offs_usrh = 14
y_offs_usrl = 15
z_offs_usrh = 16
z_offs_usrl = 17
fifo_en = 18
aux_vddio = 19
aux_slv_addr = 20
smplrt_div = 21
dlpf_fs = 22
int_cfg = 23
aux_burst_addr = 24
int_status = 26
temp_out_h = 27
temp_out_l = 28
gyro_xout_h = 29
gyro_xout_l = 30
gyro_yout_h = 3... |
(columns, rows) = [int(x) for x in input().split(', ')]
matrix = []
for _ in range(columns):
row = [int(x) for x in input().split()]
matrix.append(row)
for r in range(rows):
column_sum = 0
for c in range(columns):
column_sum += matrix[c][r]
print(column_sum)
| (columns, rows) = [int(x) for x in input().split(', ')]
matrix = []
for _ in range(columns):
row = [int(x) for x in input().split()]
matrix.append(row)
for r in range(rows):
column_sum = 0
for c in range(columns):
column_sum += matrix[c][r]
print(column_sum) |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def validate_tag(tag, ctx):
# a valid swarming tag is a string that contains ":"
if ':' not in tag:
ctx.error('does not have ":": %s', tag)
def val... | def validate_tag(tag, ctx):
if ':' not in tag:
ctx.error('does not have ":": %s', tag)
def validate_dimension(dimension, ctx):
if not dimension.key:
ctx.error('no key')
if not dimension.value:
ctx.error('no value')
def validate_recipe_cfg(recipe, ctx):
if not recipe.name:
... |
expected_output = {
"vrf": {
"1": {
"eigrp_instance": {
"100": {
"address_family": {
"ipv4": {
"interface": {
"GigabitEthernet0/0/0.1": {
"mcast_flow_timer": 0,
"mean_srtt": 0,
"pacing_time_reli... | expected_output = {'vrf': {'1': {'eigrp_instance': {'100': {'address_family': {'ipv4': {'interface': {'GigabitEthernet0/0/0.1': {'mcast_flow_timer': 0, 'mean_srtt': 0, 'pacing_time_reliable': 0, 'pacing_time_unreliable': 0, 'peer_q_reliable': 0, 'peer_q_unreliable': 0, 'peers': 0, 'pend_routes': 0, 'xmit_q_reliable': 0... |
{
'includes': ['build/common.gypi'],
'targets': [],
'conditions': [
['OS=="android"', {
'targets': [
{ #test-jni
'target_name': 'libtest-jni',
'type': 'loadable_module',
'dependencies': [
'<(DEPTH)/third_party/icu/icu.gyp:icuuc',
'<(webrtc_root)/syst... | {'includes': ['build/common.gypi'], 'targets': [], 'conditions': [['OS=="android"', {'targets': [{'target_name': 'libtest-jni', 'type': 'loadable_module', 'dependencies': ['<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(webrtc_root)/system_wrappers/system_wrappers.gyp:system_wrappers_default'], 'sources': ['<(webrtc_root)... |
MQTT_ERROR_MESSAGES = {
0: None,
1: "Bad protocol",
2: "Bad client id",
3: "Server unavailable",
4: "Bad username or password",
5: "Not authorised",
7: "The connection was lost",
}
# iRobot_6.3.1-release.apk / res/values-en-rGB/strings.xml
ROOMBA_ERROR_MESSAGES = {
1: "Left wheel off fl... | mqtt_error_messages = {0: None, 1: 'Bad protocol', 2: 'Bad client id', 3: 'Server unavailable', 4: 'Bad username or password', 5: 'Not authorised', 7: 'The connection was lost'}
roomba_error_messages = {1: 'Left wheel off floor', 2: 'Main brushes stuck', 3: 'Right wheel off floor', 4: 'Left wheel stuck', 5: 'Right whee... |
# add your constraints to the var 'sym' using the var 'state'
c = 255
for o in sym.chop(8):
state.se.add(o <= c)
c = o
| c = 255
for o in sym.chop(8):
state.se.add(o <= c)
c = o |
count = 0
print('Before', count)
for i in [9, 41, 12, 3, 74, 15]:
count += 1
print(count, i)
print('After', count)
| count = 0
print('Before', count)
for i in [9, 41, 12, 3, 74, 15]:
count += 1
print(count, i)
print('After', count) |
class Solution(object):
def findCircleNum(self, M):
parent = [-1] * len(M)
rank = dict()
for i in range(len(M)):
for j in range(i):
if M[i][j] == 1:
self.union(i, j, parent, rank)
ans = 0
for i in parent:
... | class Solution(object):
def find_circle_num(self, M):
parent = [-1] * len(M)
rank = dict()
for i in range(len(M)):
for j in range(i):
if M[i][j] == 1:
self.union(i, j, parent, rank)
ans = 0
for i in parent:
if i == ... |
# CORS Settings
X_DOMAINS = '*'
X_HEADERS = ['Content-Type', 'Accept', 'If-Match']
# Please note that MONGO_HOST and MONGO_PORT could very well be left
# out as they already default to a bare bones local 'mongod' instance.
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DBNAME = 'eve-restangular'
# Enable reads (GE... | x_domains = '*'
x_headers = ['Content-Type', 'Accept', 'If-Match']
mongo_host = 'localhost'
mongo_port = 27017
mongo_dbname = 'eve-restangular'
resource_methods = ['GET', 'POST']
item_methods = ['GET', 'PATCH', 'PUT', 'DELETE']
schema = {'firstname': {'type': 'string'}, 'lastname': {'type': 'string'}}
user = {'schema':... |
class openapimethod(object):
def __init__(self, clsref):
self._clsref = clsref
def add(self, obj):
self._clsref._child_add(self, obj)
return self
@property
def value(self):
return self
def isValid(self, typename, nentries):
if nentries is not None and len(s... | class Openapimethod(object):
def __init__(self, clsref):
self._clsref = clsref
def add(self, obj):
self._clsref._child_add(self, obj)
return self
@property
def value(self):
return self
def is_valid(self, typename, nentries):
if nentries is not None and len... |
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text # or whatever
| def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text |
'''
Context:
Given:
method isSubstring
checks if one word is a substring of another
Definitions:
rotation = letters moved n places left/right
split string into two parts
x,y
rotated string = yx
original str... | """
Context:
Given:
method isSubstring
checks if one word is a substring of another
Definitions:
rotation = letters moved n places left/right
split string into two parts
x,y
rotated string = yx
original str... |
def test_PLINKtoLD():
assert bed.shape[0] == n or bed.shape[1] == n, "One of the dimensions of the bed file should be n"
def test1_PLINKtoLD():
assert dtype(ld) == "ndarray", "The LD matrix should be an ndarray"
def test_eig_check():
assert dtype(eig) == "array", "The eigenvalues should be in an a... | def test_plin_kto_ld():
assert bed.shape[0] == n or bed.shape[1] == n, 'One of the dimensions of the bed file should be n'
def test1_plin_kto_ld():
assert dtype(ld) == 'ndarray', 'The LD matrix should be an ndarray'
def test_eig_check():
assert dtype(eig) == 'array', 'The eigenvalues should be in an array... |
'''
bricklink.exceptions
--------------------
A module providing Bricklink exceptions
'''
class BricklinkInvalidResponseException(Exception): pass
class BricklinkInvalidURIException(Exception): pass
class BricklinkInvalidRequestBodyException(Exception): pass
class BricklinkParameterMissingOrInvalidE... | """
bricklink.exceptions
--------------------
A module providing Bricklink exceptions
"""
class Bricklinkinvalidresponseexception(Exception):
pass
class Bricklinkinvaliduriexception(Exception):
pass
class Bricklinkinvalidrequestbodyexception(Exception):
pass
class Bricklinkparametermissingo... |
items = [('"Potion"'), ('"Bandages"'), ('"Bandages"')]
##
##def additem():
## global items
## newitem = ("cookie")
## entry = (newitem)
## items.append(entry)
##
##def removeitem():
#### score = int(input())
## global items
## newitem = ("cookie")
## entry = (newitem)
## it... | items = ['"Potion"', '"Bandages"', '"Bandages"'] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class Format:
def __init__(self):
self.header_file = ''
def get_header(self):
return self.header_file
def getFormat(self, ip):
pass | class Format:
def __init__(self):
self.header_file = ''
def get_header(self):
return self.header_file
def get_format(self, ip):
pass |
DEFAULT_NEAR = 0.1
DEFAULT_FAR = 100.0
# rendering
DEFAULT_IMAGE_SIZE = 256
DEFAULT_ANTI_ALIASING = True
DEFAULT_DRAW_BACKSIDE = True
# others
DEFAULT_EPS = 1e-5
class RasterizeHyperparam:
def __init__(self,
image_size=DEFAULT_IMAGE_SIZE,
near=DEFAULT_NEAR,
far... | default_near = 0.1
default_far = 100.0
default_image_size = 256
default_anti_aliasing = True
default_draw_backside = True
default_eps = 1e-05
class Rasterizehyperparam:
def __init__(self, image_size=DEFAULT_IMAGE_SIZE, near=DEFAULT_NEAR, far=DEFAULT_FAR, eps=DEFAULT_EPS, anti_aliasing=DEFAULT_ANTI_ALIASING, draw_... |
# --------------
# Code starts here
#create class_1 and class_2
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2=['Hilary Mason','Carla Gentry','Corinna Cortes']
#concatenate class_1 and class_2
new_class=class_1+class_2
#show new_class
print(new_class)
#add a missed name
new_class.a... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English... |
class Solution:
def isPerfectSquare(self, num: int) -> bool:
low = 1
high = num
while low <= high:
mid = (low + high) // 2
if mid * mid < num:
low = mid + 1
elif mid * mid > num:
high = mid - 1
else:
... | class Solution:
def is_perfect_square(self, num: int) -> bool:
low = 1
high = num
while low <= high:
mid = (low + high) // 2
if mid * mid < num:
low = mid + 1
elif mid * mid > num:
high = mid - 1
else:
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode:
left = root.left
newRoot = None
if left == None:
return root
else:
n... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def upside_down_binary_tree(self, root: TreeNode) -> TreeNode:
left = root.left
new_root = None
if left == None:
return root
else:
... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 2:
return 0
n = len(prices)
dp = [[0] * n for _ in range(3)]
for k in range(1, 3):
curMin = prices[0]
for i in range(1, n):
# if we buy on day j, sell o... | class Solution:
def max_profit(self, prices: List[int]) -> int:
if len(prices) < 2:
return 0
n = len(prices)
dp = [[0] * n for _ in range(3)]
for k in range(1, 3):
cur_min = prices[0]
for i in range(1, n):
cur_min = min(curMin, pri... |
def solution(sizes: list[list[int]]) -> int:
print(sum(sizes, []))
max_width = 0
max_height = 0
for size in sizes:
if size[0] < size[1]:
size[0], size[1] = size[1], size[0]
max_width = max(max_width, size[0])
max_height = max(max_height, size[1])
return max_width... | def solution(sizes: list[list[int]]) -> int:
print(sum(sizes, []))
max_width = 0
max_height = 0
for size in sizes:
if size[0] < size[1]:
(size[0], size[1]) = (size[1], size[0])
max_width = max(max_width, size[0])
max_height = max(max_height, size[1])
return max_wi... |
class InvalidOperationError(BaseException):
pass
class Node():
def __init__(self, value, next = None):
self.value = value
self.next = next
class Stack():
def __init__(self, node = None):
self.top = node
def __str__(self):
# { a } -> { b } -> { c } -> NULL
outp... | class Invalidoperationerror(BaseException):
pass
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self, node=None):
self.top = node
def __str__(self):
output = ''
current = self.top
while ... |
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 < -2)
print("Is it less or equal?", 5 <= -2) | print("Oh, that's why it's False.")
print('How about some more.')
print('Is it greater?', 5 > -2)
print('Is it greater or equal?', 5 < -2)
print('Is it less or equal?', 5 <= -2) |
def givetheglass():
sleep(2)
i01.setHandSpeed("left", 0.60, 0.60, 0.60, 0.60, 0.60, 0.60)
i01.setHandSpeed("right", 0.60, 0.80, 0.60, 0.60, 0.60, 0.60)
i01.setArmSpeed("left", 0.60, 1.0, 0.60, 0.60)
i01.setArmSpeed("right", 0.60, 0.60, 0.60, 0.60)
i01.setHeadSpeed(0.65, 0.65)
i01.moveHead(84,79)
i01.mov... | def givetheglass():
sleep(2)
i01.setHandSpeed('left', 0.6, 0.6, 0.6, 0.6, 0.6, 0.6)
i01.setHandSpeed('right', 0.6, 0.8, 0.6, 0.6, 0.6, 0.6)
i01.setArmSpeed('left', 0.6, 1.0, 0.6, 0.6)
i01.setArmSpeed('right', 0.6, 0.6, 0.6, 0.6)
i01.setHeadSpeed(0.65, 0.65)
i01.moveHead(84, 79)
i01.moveA... |
text_list = "this is a sentence use to test the specail enviroment of K210"
sentence_list = []
sentence = ""
singel_letter = 0
for word in text_list:
singel_letter += len(word) + 1
if singel_letter < 30:
sentence = sentence + word + " "
else:
sentence_list.append(sentence)
singel_le... | text_list = 'this is a sentence use to test the specail enviroment of K210'
sentence_list = []
sentence = ''
singel_letter = 0
for word in text_list:
singel_letter += len(word) + 1
if singel_letter < 30:
sentence = sentence + word + ' '
else:
sentence_list.append(sentence)
singel_let... |
# OrderedSet.py
#
# Written by Larry Holder (holder@wsu.edu).
#
# Copyright (c) 2017-2021. Washington State University.
#
# This implementation of OrderedSet maintains the set as both an
# actual (unordered) Python set and an ordered list. The main
# difference from other OrderedSet containers is that equality
# is sup... | class Orderedset:
def __init__(self, arg=None):
if arg is None:
arg = []
self.list_container = []
self.set_container = set()
elements = []
if isinstance(arg, (list, set)):
elements = arg
if isinstance(arg, OrderedSet):
elements = a... |
# Geo Location Filter for selecting data within a region of interest
# Lat/Lon used to define circular area of interest
ap_lat = AutoParam(54.13308)
ap_lon = AutoParam(-165.98555)
# Radius of circule of interes (km)
ap_radius = AutoParam(15)
# GeoLocation filter
fl_geo = skdiscovery.data_structure.table.filters.GeoLo... | ap_lat = auto_param(54.13308)
ap_lon = auto_param(-165.98555)
ap_radius = auto_param(15)
fl_geo = skdiscovery.data_structure.table.filters.GeoLocationFilter('GeoFilter', [ap_lat, ap_lon, ap_radius])
sc_geo = stage_container(fl_geo)
fl_stab = skdiscovery.data_structure.table.filters.StabilizationFilter('StabFilter')
sc_... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def xdo():
http_archive(
name = "xdo",
build_file = "//ba... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def xdo():
http_archive(name='xdo', build_file='//bazel/deps/xdo:build.BUILD', sha256='e64cac9d49d1f67e2aa54dcd4352bb1b4f27323778612cb9ad028b3dfc1a50b2', strip_prefix='xdo-dc34b20e... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( a , b ) :
if ( a < 0 ) :
a = - a
if ( b < 0 ) :
b = - b
mod = a
while ( mod >= b ) ... | def f_gold(a, b):
if a < 0:
a = -a
if b < 0:
b = -b
mod = a
while mod >= b:
mod = mod - b
if a < 0:
return -mod
return mod
if __name__ == '__main__':
param = [(3243.229719038493, 5659.926861939672), (-4362.665881044217, -9196.507113304497), (7255.066257575837,... |
# coding: utf-8
# author: Fei Gao
#
# Happy Number
#
# Write an algorithm to determine if a number is "happy".
# A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 ... | class Solution:
def is_happy(self, n):
def tran(m):
return sum(map(lambda x: int(x) ** 2, list(str(m))))
nums = {n}
while True:
n = tran(n)
if n == 1:
return True
elif n in nums:
return False
else:
... |
hyper = {
"GraphSAGE": {
"model": {
"name": "GraphSAGE",
"inputs": [
{"shape": [None], "name": "node_attributes", "dtype": "float32","ragged": True},
{"shape": [None], "name": "edge_attributes", "dtype": "float32","ragged": True},
{"sha... | hyper = {'GraphSAGE': {'model': {'name': 'GraphSAGE', 'inputs': [{'shape': [None], 'name': 'node_attributes', 'dtype': 'float32', 'ragged': True}, {'shape': [None], 'name': 'edge_attributes', 'dtype': 'float32', 'ragged': True}, {'shape': [None, 2], 'name': 'edge_indices', 'dtype': 'int64', 'ragged': True}], 'input_emb... |
'''
generate squares from 1 to 100 using yield hence generator
generator: is a function is defined like a normal one but whenever it needs to generate a value, it does so
by yield keyword rather than return.
'''
def nextSquare():
i=1
while True:
yield i*i
i+=1
for num in next... | """
generate squares from 1 to 100 using yield hence generator
generator: is a function is defined like a normal one but whenever it needs to generate a value, it does so
by yield keyword rather than return.
"""
def next_square():
i = 1
while True:
yield (i * i)
i += 1
for num in next_square():... |
class BencodeFailure(Exception):
pass
class DTOCFailure(Exception):
pass
class HTTPTrackerFailure(Exception):
pass
| class Bencodefailure(Exception):
pass
class Dtocfailure(Exception):
pass
class Httptrackerfailure(Exception):
pass |
class RowKey:
def __init__(self, key):
self.key = key
@staticmethod
def from_str(key):
return RowKey(key)
def to_file_format(self):
return str(self.key)
def __str__(self):
return str(self.key)
def __eq__(self, other_key):
return self.key == other_key.k... | class Rowkey:
def __init__(self, key):
self.key = key
@staticmethod
def from_str(key):
return row_key(key)
def to_file_format(self):
return str(self.key)
def __str__(self):
return str(self.key)
def __eq__(self, other_key):
return self.key == other_key... |
GATEWAY_URL = 'https://kic.lgthinq.com:46030/api/common/gatewayUriList'
APP_KEY = 'wideq'
SECURITY_KEY = 'nuts_securitykey'
DATA_ROOT = 'lgedmRoot'
COUNTRY = 'PL'
LANGUAGE = 'en-EN'
SVC_CODE = 'SVC202'
CLIENT_ID = 'LGAO221A02'
OAUTH_SECRET_KEY = 'c053c2a6ddeb7ad97cb0eed0dcb31cf8'
OAUTH_CLIENT_KEY = 'LGAO221A02'
DATE_FO... | gateway_url = 'https://kic.lgthinq.com:46030/api/common/gatewayUriList'
app_key = 'wideq'
security_key = 'nuts_securitykey'
data_root = 'lgedmRoot'
country = 'PL'
language = 'en-EN'
svc_code = 'SVC202'
client_id = 'LGAO221A02'
oauth_secret_key = 'c053c2a6ddeb7ad97cb0eed0dcb31cf8'
oauth_client_key = 'LGAO221A02'
date_fo... |
#SERVER Configuration
SQLiteENV = "production"
SQLiteConfig = {
'development': {
'PATH': './data/kobosqlite_dev.db',
'DB_NAME': 'kobosqlite',
'USERNAME': '',
'PASSWORD': '',
'PROTOCOL': '',
'SCHEME': 'sqlite',
'IP': '',
'HOST': '',
'PORT': ''... | sq_lite_env = 'production'
sq_lite_config = {'development': {'PATH': './data/kobosqlite_dev.db', 'DB_NAME': 'kobosqlite', 'USERNAME': '', 'PASSWORD': '', 'PROTOCOL': '', 'SCHEME': 'sqlite', 'IP': '', 'HOST': '', 'PORT': '', 'VERSION': 'v1', 'TIMEOUT': 7200}, 'uat': {'PATH': './data/kobosqlite_uat.db', 'DB_NAME': 'kobos... |
class RangeModule:
def __init__(self):
self.intervals = []
def addRange(self, left: int, right: int) -> None:
intervals = self.intervals
temp = []
n = len(intervals)
for i in range(n + 1):
if i == n or intervals[i][0] > right:
temp.a... | class Rangemodule:
def __init__(self):
self.intervals = []
def add_range(self, left: int, right: int) -> None:
intervals = self.intervals
temp = []
n = len(intervals)
for i in range(n + 1):
if i == n or intervals[i][0] > right:
temp.append((l... |
#Collatz Tag Sequence
#a -> bc
#b -> a
#c -> aaa
#inputting any amount of a's ending with 1 letter (a)
LetterChanges = { 'a':'bc' , 'b':'a' , 'c':'aaa'}
Acheck = False
while Acheck == False:
print('Enter any 1 letter to quit')
InputtedString = raw_input('Enter a string of a\'s\n')
Acheck = True
#Er... | letter_changes = {'a': 'bc', 'b': 'a', 'c': 'aaa'}
acheck = False
while Acheck == False:
print('Enter any 1 letter to quit')
inputted_string = raw_input("Enter a string of a's\n")
acheck = True
for i in range(1, len(InputtedString)):
if InputtedString[i] != 'a':
acheck = False
... |
def mochila(pesoMax, enfeites):
resposta = 0
m = [-1 for _ in range(pesoMax + 1)]
m[0] = 0
for enfeite in enfeites:
valor = enfeite[0]
peso = enfeite[1]
for i in range(pesoMax, peso - 1, -1):
if(m[i - peso] != -1):
m[i] = max(m[i], m[i - peso] + valor... | def mochila(pesoMax, enfeites):
resposta = 0
m = [-1 for _ in range(pesoMax + 1)]
m[0] = 0
for enfeite in enfeites:
valor = enfeite[0]
peso = enfeite[1]
for i in range(pesoMax, peso - 1, -1):
if m[i - peso] != -1:
m[i] = max(m[i], m[i - peso] + valor)
... |
class TestRetrieveSongs:
def test_get_songs_with_pagination(self, client):
response = client.get("/api/v1/songs?page_number=2&songs_per_page=2")
response_data = response.json
assert response.status_code == 200
assert response.content_type == "application/json"
assert respons... | class Testretrievesongs:
def test_get_songs_with_pagination(self, client):
response = client.get('/api/v1/songs?page_number=2&songs_per_page=2')
response_data = response.json
assert response.status_code == 200
assert response.content_type == 'application/json'
assert respons... |
def ifFibonacci():
# enter value you want checked
n = int(input('Enter number you want checked:'))
a, b, c = 0, 1, 1
# if the value is 0 or 1 automatically output
if n == 0 or n == 1:
print('Number is part of fibonacci series')
else:
#update values until we find a match
w... | def if_fibonacci():
n = int(input('Enter number you want checked:'))
(a, b, c) = (0, 1, 1)
if n == 0 or n == 1:
print('Number is part of fibonacci series')
else:
while a < n:
a = b + c
c = b
b = a
if a == n:
print('Number is part of... |
SSID1 = 'AP1'
SALASANA1 = 'pass'
SSID2 = 'AP2'
SALASANA2 = 'pass'
MQTT_SERVERI = 'ip'
MQTT_PORTTI = '1883'
MQTT_KAYTTAJA = 'user'
MQTT_SALASANA = 'pass'
CLIENT_ID = "ESP32-gassensor"
DHCP_NIMI = "ESP32-gassensor"
PINNI_NUMERO = 4
MQ135_PINNI = 36
SISA_LAMPO = b'home/indoor/temp'
SISA_KOSTEUS = b'home/indoo... | ssid1 = 'AP1'
salasana1 = 'pass'
ssid2 = 'AP2'
salasana2 = 'pass'
mqtt_serveri = 'ip'
mqtt_portti = '1883'
mqtt_kayttaja = 'user'
mqtt_salasana = 'pass'
client_id = 'ESP32-gassensor'
dhcp_nimi = 'ESP32-gassensor'
pinni_numero = 4
mq135_pinni = 36
sisa_lampo = b'home/indoor/temp'
sisa_kosteus = b'home/indoor/moisture'
s... |
'''Reading Files'''
'''using open'''
# # examples:
# handle = open(filename, mode)
# fhand = open('nbox.txt', 'r')
'''the new line character'''
# stuff = 'Hello\nWorld!'
# print(stuff)
# stuff = 'X\nY'
# print(stuff)
# print(len(stuff))
'''file processing'''
# every line is ended by a new line | """Reading Files"""
'using open'
'the new line character'
'file processing' |
#Displays a summary onto the screen describing what the program does.
print("Welcome to the Tic-Tac-Toe game. You will play as Player X against the computer Player O and compete to get three in a row on the board first. I warn you that it is almost impossible to win against the bot. Thanks to the MINMAX function, this... | print('Welcome to the Tic-Tac-Toe game. You will play as Player X against the computer Player O and compete to get three in a row on the board first. I warn you that it is almost impossible to win against the bot. Thanks to the MINMAX function, this gives Player O (the bot) an advantage making it almost unbeatable. Can... |
#/ <reference path="./testBlocks/basic.ts" />
testNamespace.noArgument()
testNamespace.booleanArgument(True)
testNamespace.numberArgument(5)
testNamespace.stringArgument("okay")
testNamespace.enumArgument(TestEnum.testValue1)
testNamespace.enumFunctionArgument(EnumWithValueBlock.testValue2)
testNamespace.multipleArgum... | testNamespace.noArgument()
testNamespace.booleanArgument(True)
testNamespace.numberArgument(5)
testNamespace.stringArgument('okay')
testNamespace.enumArgument(TestEnum.testValue1)
testNamespace.enumFunctionArgument(EnumWithValueBlock.testValue2)
testNamespace.multipleArguments(2, False) |
class WindType:
def __init__(self, path):
self._is_hrrr, self._is_rtma, self._type = self.type_from_path(path)
self._alts = self.compute_wind_alts()
def type_from_path(self, path):
if "hrrr" in path.lower():
is_hrrr = True
is_rtma = False
wind_type = ... | class Windtype:
def __init__(self, path):
(self._is_hrrr, self._is_rtma, self._type) = self.type_from_path(path)
self._alts = self.compute_wind_alts()
def type_from_path(self, path):
if 'hrrr' in path.lower():
is_hrrr = True
is_rtma = False
wind_type... |
'''
Created on 4 juil. 2016
@author: saldenisov
'''
class MyException(Exception):
def __init__(self, text):
super().__init__(text)
class EmptyConfiguration(MyException):
def __init__(self):
MyException.__init__(self, "Configuration is empty")
class FittingError(MyException):
def __ini... | """
Created on 4 juil. 2016
@author: saldenisov
"""
class Myexception(Exception):
def __init__(self, text):
super().__init__(text)
class Emptyconfiguration(MyException):
def __init__(self):
MyException.__init__(self, 'Configuration is empty')
class Fittingerror(MyException):
def __ini... |
# Python Program implementation
# of binary insertion sort
def binary_search(A, low, high, key):
if high > low:
mid = (high + low) // 2
if A[mid] == key:
return mid
elif A[mid] > key:
return binary_search(A, low, mid-1, key)
else:
return bi... | def binary_search(A, low, high, key):
if high > low:
mid = (high + low) // 2
if A[mid] == key:
return mid
elif A[mid] > key:
return binary_search(A, low, mid - 1, key)
else:
return binary_search(A, mid + 1, high, key)
elif high == low:
... |
ETH_TO_LDO_RATE_PRECISION = 10**18
# 100M LDO in 21600 ETH
# 4629.62962962963 LDO in one ETH
ETH_TO_LDO_RATE = ETH_TO_LDO_RATE_PRECISION * (100 * 10**6) // 21600
VESTING_CLIFF_DELAY = 1 * 60 * 60 * 24 * 365 # one year
VESTING_END_DELAY = 2 * 60 * 60 * 24 * 365 # two years
OFFER_EXPIRATION_DELAY = 2629746 # one month
... | eth_to_ldo_rate_precision = 10 ** 18
eth_to_ldo_rate = ETH_TO_LDO_RATE_PRECISION * (100 * 10 ** 6) // 21600
vesting_cliff_delay = 1 * 60 * 60 * 24 * 365
vesting_end_delay = 2 * 60 * 60 * 24 * 365
offer_expiration_delay = 2629746
ldo_purchasers = [('0x2CAE3a4D4c513026Ecc6af94A4BA89Df31c8cEA3', 1000 * 10 ** 18)]
allocati... |
def bubblesort(a):
swaps = 0
for i in xrange(len(a)):
for j in xrange(len(a)-1):
temp = a[j+1]
if (a[j] > a[j+1]):
swaps += 1
a[j+1] = a[j]
a[j] = temp
first = a[0]
last = a[len(a)-1]
return swaps, first,... | def bubblesort(a):
swaps = 0
for i in xrange(len(a)):
for j in xrange(len(a) - 1):
temp = a[j + 1]
if a[j] > a[j + 1]:
swaps += 1
a[j + 1] = a[j]
a[j] = temp
first = a[0]
last = a[len(a) - 1]
return (swaps, first, last) |
# 15. 3Sum Double pointer
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
arr_size = len(nums)
res = []
for index in range(arr_size-2):
if index >= 1 and nums[index] == nums[index - 1]:
continue
# initial val... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
arr_size = len(nums)
res = []
for index in range(arr_size - 2):
if index >= 1 and nums[index] == nums[index - 1]:
continue
left_ptr = index + 1
ri... |
def longestIncreasingSubSequence(arr):
n = len(arr)
# Inicializamos el arreglo auxiliar con 1
auxArr = [1]*n
# En el primer for recorremos los elementos desde el de posicion 1 hasta n-1
for i in range (1, n):
# En el segundo for recorremos desde el elemento 0 hasta i que depende de n
... | def longest_increasing_sub_sequence(arr):
n = len(arr)
aux_arr = [1] * n
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and auxArr[i] < auxArr[j] + 1:
auxArr[i] = auxArr[j] + 1
max_num = 0
for i in range(n):
max_num = max(maxNum, auxArr[i])... |
class Solution:
def countBits(self, n: int) -> List[int]:
offset = 1
dp = [0] * (n+1)
for i in range(1,n+1):
if offset * 2 == i:
offset = i
dp[i] = dp[i - offset] + 1
return dp | class Solution:
def count_bits(self, n: int) -> List[int]:
offset = 1
dp = [0] * (n + 1)
for i in range(1, n + 1):
if offset * 2 == i:
offset = i
dp[i] = dp[i - offset] + 1
return dp |
# Solution by PauloBA
def fizzbuzz(n):
ans = []
for i in range(n):
if (i + 1) % 3 == 0 and (i + 1) % 5 == 0:
ans.append("FizzBuzz")
elif (i + 1) % 3 == 0:
ans.append("Fizz")
elif (i + 1) % 5 == 0:
ans.append("Buzz")
else:
ans.appen... | def fizzbuzz(n):
ans = []
for i in range(n):
if (i + 1) % 3 == 0 and (i + 1) % 5 == 0:
ans.append('FizzBuzz')
elif (i + 1) % 3 == 0:
ans.append('Fizz')
elif (i + 1) % 5 == 0:
ans.append('Buzz')
else:
ans.append(i + 1)
return ans... |
set_name(0x80135544, "PreGameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x80137608, "DRLG_PlaceDoor__Fii", SN_NOWARN)
set_name(0x80137ADC, "DRLG_L1Shadows__Fv", SN_NOWARN)
set_name(0x80137EF4, "DRLG_PlaceMiniSet__FPCUciiiiiii", SN_NOWARN)
set_name(0x80138360, "DRLG_L1Floor__Fv", SN_NOWARN)
set_name(0x8013844C, "StoreBlo... | set_name(2148750660, 'PreGameOnlyTestRoutine__Fv', SN_NOWARN)
set_name(2148759048, 'DRLG_PlaceDoor__Fii', SN_NOWARN)
set_name(2148760284, 'DRLG_L1Shadows__Fv', SN_NOWARN)
set_name(2148761332, 'DRLG_PlaceMiniSet__FPCUciiiiiii', SN_NOWARN)
set_name(2148762464, 'DRLG_L1Floor__Fv', SN_NOWARN)
set_name(2148762700, 'StoreBlo... |
__________________________________________________________________________________________________
class Solution:
def numberOfDays(self, y: int, m: int) -> int:
add=0
if y%400==0:
add=1
elif y%4==0 and y%100!=0:
add=1
if m==2:
return 28+add
... | __________________________________________________________________________________________________
class Solution:
def number_of_days(self, y: int, m: int) -> int:
add = 0
if y % 400 == 0:
add = 1
elif y % 4 == 0 and y % 100 != 0:
add = 1
if m == 2:
... |
# Batch 7 Day 5 Assignment 2
# Prime numbers between 1 to 2500 using filter
def even(num):
b=2
f=0
cnt=0
for b in range(2,num):
while b<num:
if num%b==0:
f=1
else:
if f==1:
break
... | def even(num):
b = 2
f = 0
cnt = 0
for b in range(2, num):
while b < num:
if num % b == 0:
f = 1
elif f == 1:
break
else:
f = 0
b = b + 1
if f == 0:
cnt += 1
return Tru... |
expected_output = {
'mac_table': {
'Te0/0/1/0/3.3': {
'mac_address': {
'0001.00ff.0002': {
'lc_learned': 'N/A',
'learned_from': 'Te0/0/1/0/3.3',
'mapped_to': 'N/A',
'resync_age': '0d '
... | expected_output = {'mac_table': {'Te0/0/1/0/3.3': {'mac_address': {'0001.00ff.0002': {'lc_learned': 'N/A', 'learned_from': 'Te0/0/1/0/3.3', 'mapped_to': 'N/A', 'resync_age': '0d 0h 0m 14s', 'type': 'dynamic'}, '0001.00ff.0003': {'lc_learned': 'N/A', 'learned_from': 'Te0/0/1/0/3.3', 'mapped_to': 'N/A', 'resync_age': '0d... |
def threeSum(arr, sum):
n = len(arr)
hash = dict()
for i, a in enumerate(arr):
hash[a] = i
for i in range(n-1):
for j in range(i+1, n):
val = sum-(arr[i]+arr[j])
if val in hash:
if hash[val] != i and hash[val] != j:
print(val, arr[i], arr[j])
return True
return False
if __name__ == '__mai... | def three_sum(arr, sum):
n = len(arr)
hash = dict()
for (i, a) in enumerate(arr):
hash[a] = i
for i in range(n - 1):
for j in range(i + 1, n):
val = sum - (arr[i] + arr[j])
if val in hash:
if hash[val] != i and hash[val] != j:
p... |
class NewMember:
total = 0
def __init__(self, name, grade_class):
# your code here
self.Nama = name
self.Kelas = grade_class
NewMember.total += 1
def __del__(self):
print(self.Nama, 'telah keluar')
def info(self):
print(self.__dict__)
... | class Newmember:
total = 0
def __init__(self, name, grade_class):
self.Nama = name
self.Kelas = grade_class
NewMember.total += 1
def __del__(self):
print(self.Nama, 'telah keluar')
def info(self):
print(self.__dict__)
@classmethod
def new_member_total(... |
def part1(dots: list[tuple[int, int]], instructions: list[list[str | int]]):
print('Part 1:', len(fold(dots, instructions[0])))
def part2(dots: list[tuple[int, int]], instructions: list[list[str | int]]):
for instr in instructions:
dots = fold(dots, instr)
width = max(dots, key=lambda d: d[0])[0]... | def part1(dots: list[tuple[int, int]], instructions: list[list[str | int]]):
print('Part 1:', len(fold(dots, instructions[0])))
def part2(dots: list[tuple[int, int]], instructions: list[list[str | int]]):
for instr in instructions:
dots = fold(dots, instr)
width = max(dots, key=lambda d: d[0])[0] +... |
coolingTypes ={
'PASSIVE_COOLING' : [0, 35],
'HI_ACTIVE_COOLING' : [0, 45],
'MED_ACTIVE_COOLING' : [0, 40],
}
email_content = {
'TOO_LOW' : 'Hi, the temperature is too low',
'TOO_HIGH' : 'Hi, the temperature is too high',
}
def infer_breach(value, lowerLimit, upperLimit):
if value < lowe... | cooling_types = {'PASSIVE_COOLING': [0, 35], 'HI_ACTIVE_COOLING': [0, 45], 'MED_ACTIVE_COOLING': [0, 40]}
email_content = {'TOO_LOW': 'Hi, the temperature is too low', 'TOO_HIGH': 'Hi, the temperature is too high'}
def infer_breach(value, lowerLimit, upperLimit):
if value < lowerLimit:
return 'TOO_LOW'
... |
class baseModel():
@classmethod
def getAllWith(cls,filter = None,**extra_fields):
if filter:
return cls.objects.filter(filter)
return cls.objects.filter(**extra_fields)
@classmethod
def get(cls, filter = None, **extra_fields):
if filter:
return cls.object... | class Basemodel:
@classmethod
def get_all_with(cls, filter=None, **extra_fields):
if filter:
return cls.objects.filter(filter)
return cls.objects.filter(**extra_fields)
@classmethod
def get(cls, filter=None, **extra_fields):
if filter:
return cls.objects... |
class TasksCategory:
def __init__(self, name: str, jira_issue_id: str):
self.name = name
self.jira_issue_id = jira_issue_id
| class Taskscategory:
def __init__(self, name: str, jira_issue_id: str):
self.name = name
self.jira_issue_id = jira_issue_id |
#!/usr/bin/python -Wall
# ================================================================
# Please see LICENSE.txt in the same directory as this file.
# John Kerl
# kerl.john.r@gmail.com
# 2007-05-31
# ================================================================
# Do not modify this file. This stub data is set ... | mul_table = []
inv_table = []
name_table = [] |
#string
s = "I am a string"
print(type(s)) #says string
#Boolean
yes = True
print(type(yes))
no = False
print(type(no))
#list -- ordered and changeable
alpha_list = ["a", "b", "c"] #list initialization
print(type(alpha_list)) #says tuple
print(type(alpha_list[0])) #says string
alp... | 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:
pr... |
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
q=student_marks.get(query_name)
res=sum(q)/len(q)
print("%0.2f"%(res)... | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
(name, *line) = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
q = student_marks.get(query_name)
res = sum(q) / len(q)
print('%0.2f' % ... |
hrs = input('Please enter the number of hours you work.')
wage = input('Please enter your hourly rate.')
salary = float(hrs) * float(wage)
print('Based on the information provided, your total salary is',salary)
| hrs = input('Please enter the number of hours you work.')
wage = input('Please enter your hourly rate.')
salary = float(hrs) * float(wage)
print('Based on the information provided, your total salary is', salary) |
lives = ['''
________
| \|
O |
/|\ |
/ \ |
|
=========
''' , '''
________
| \|
O |
/|\ |
\ |
|
=========
''' , '''
________
| \|
O |
/|\ |
|
|
=========
''','''
... | lives = ['\n ________\n | \\|\n O |\n /|\\ |\n / \\ |\n |\n =========\n ', '\n ________\n | \\|\n O |\n /|\\ |\n \\ |\n |\n =========\n ', '\n ________\n | \\|\n O |\n /|\\ |\n |\n |\n =========\n ', '\n _____... |
class Portfolio(object):
'''
Parameters:
trading_cost: Cost of taking a position is 3 pips by default
_prices: Dataframe of Open and Close prices for reward calculation
reward_normalizer: to convert precision of prices (0.0001) to number (1) for reward calculation
total_reward: Keep track of re... | class Portfolio(object):
"""
Parameters:
trading_cost: Cost of taking a position is 3 pips by default
_prices: Dataframe of Open and Close prices for reward calculation
reward_normalizer: to convert precision of prices (0.0001) to number (1) for reward calculation
total_reward: Keep track of rew... |
fname = input('Enter the file name:')
try :
fhand = open('ch09\\' + fname)
except :
print('File cannot be opened:',fname)
quit()
d = {}
for line in fhand :
if not line.startswith('From ') :
continue
words = line.split()
d[ words[1] ] = d.get(words[1] , 0) + 1
max_num = 0
max_man = ''
... | fname = input('Enter the file name:')
try:
fhand = open('ch09\\' + fname)
except:
print('File cannot be opened:', fname)
quit()
d = {}
for line in fhand:
if not line.startswith('From '):
continue
words = line.split()
d[words[1]] = d.get(words[1], 0) + 1
max_num = 0
max_man = ''
for man i... |
# Lecture 6, slide 2
# Making Tuples
t1 = (1, 'two', 3)
print(t1)
# Putting Tuples Together
t2 = (t1, 'four')
print(t2)
# Concatenation on Tuples
print(t1 + t2)
# Indexing on Tuples
print((t1 + t2)[3])
# Slicing on Tuples
print((t1 + t2)[2:5])
# Singleton
t3 = ('five',)
print(t1 + t2 + t3) | t1 = (1, 'two', 3)
print(t1)
t2 = (t1, 'four')
print(t2)
print(t1 + t2)
print((t1 + t2)[3])
print((t1 + t2)[2:5])
t3 = ('five',)
print(t1 + t2 + t3) |
# pylint: disable=missing-function-docstring, missing-module-docstring/
x = 5
y = 0
while y < 3:
y = y + 1
while y < 3 and x > 2:
y = y + 1
x = x - 1
| x = 5
y = 0
while y < 3:
y = y + 1
while y < 3 and x > 2:
y = y + 1
x = x - 1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def shouldSayHint():
f = open('shouldSayHint', 'r')
value = f.readline()
f.close()
return value == 'True'
def updateShouldSayHint():
oldValue = shouldSayHint()
f = open('shouldSayHint', 'w')
if oldValue == True:
f.write('False')
else:
f.write('True')
f.close() | def should_say_hint():
f = open('shouldSayHint', 'r')
value = f.readline()
f.close()
return value == 'True'
def update_should_say_hint():
old_value = should_say_hint()
f = open('shouldSayHint', 'w')
if oldValue == True:
f.write('False')
else:
f.write('True')
f.close(... |
#
# PySNMP MIB module DS0-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/DS0-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:10:48 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ObjectIdenti... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
COMPLETE_CHAT = 'lib/data/chat_complete.csv'
DATA_TXT = 'lib/data/data_txt.txt'
DATA_KBBI = 'lib/data/kata_dasar_kbbi.csv'
KORPUS_NONFORMAL = 'lib/data/korpus_nonformal.csv'
DATASET_CUSTOMERCHAT = 'lib/data/dataset_customerchat.csv'
DATASET_TOKEN = 'lib/data/dataset_token.csv'
DATASET_TOKEN_BAKU = 'lib/data/dataset... | complete_chat = 'lib/data/chat_complete.csv'
data_txt = 'lib/data/data_txt.txt'
data_kbbi = 'lib/data/kata_dasar_kbbi.csv'
korpus_nonformal = 'lib/data/korpus_nonformal.csv'
dataset_customerchat = 'lib/data/dataset_customerchat.csv'
dataset_token = 'lib/data/dataset_token.csv'
dataset_token_baku = 'lib/data/dataset_tok... |
test_cases = int(input())
for t in range(test_cases):
n = int(input())
mat = [list(map(int, input().strip().split())) for _ in range(2)]
dp = [[0] * (n + 1) for _ in range(2)]
dp[0][1] = mat[0][0]
dp[1][1] = mat[1][0]
for i in range(2, n + 1):
dp[0][i] = max(dp[1][i - 1], dp[1][i - 2]... | test_cases = int(input())
for t in range(test_cases):
n = int(input())
mat = [list(map(int, input().strip().split())) for _ in range(2)]
dp = [[0] * (n + 1) for _ in range(2)]
dp[0][1] = mat[0][0]
dp[1][1] = mat[1][0]
for i in range(2, n + 1):
dp[0][i] = max(dp[1][i - 1], dp[1][i - 2]) +... |
a=int(input("Enter a number:"))
sum=0
while(a>0):
digit=a%10
sum=sum+digit
a=a//10
print("The total sum of digits is:",sum) | a = int(input('Enter a number:'))
sum = 0
while a > 0:
digit = a % 10
sum = sum + digit
a = a // 10
print('The total sum of digits is:', sum) |
lar = 0
sm = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
ival = int(num)
except:
print("Invalid input")
continue
if ival > lar:
lar = ival
if sm is None:
sm = ival
elif ival < sm :
sm = ival
print("Maxi... | lar = 0
sm = None
while True:
num = input('Enter a number: ')
if num == 'done':
break
try:
ival = int(num)
except:
print('Invalid input')
continue
if ival > lar:
lar = ival
if sm is None:
sm = ival
elif ival < sm:
sm = ival
print('Maxim... |
class Phonebook(object):
def __init__(self):
self.details = { }
def add_contacts (self, name, contacts, email):
if name in self.details:
raise ValueError
else:
instance = {
"name":name,
"contacts":contacts,
... | class Phonebook(object):
def __init__(self):
self.details = {}
def add_contacts(self, name, contacts, email):
if name in self.details:
raise ValueError
else:
instance = {'name': name, 'contacts': contacts, 'email': email}
self.details[name] = instanc... |
'''
* Project Euler #34: Digit factorials
*
* 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
* Find the sum of all numbers which are equal to the sum of the factorial of their digits.
* Note: as 1! = 1 and 2! = 2 are not sums they are not included.
*
* Answer: 40730
* https://www.hackerrank.com/... | """
* Project Euler #34: Digit factorials
*
* 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
* Find the sum of all numbers which are equal to the sum of the factorial of their digits.
* Note: as 1! = 1 and 2! = 2 are not sums they are not included.
*
* Answer: 40730
* https://www.hackerrank.com/... |
'''
Given two string arrays word1 and word2, return true if the two arrays represent the same string,
and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
'''
def checkArr(word1,word2):
sumw1 = ""
sumw2 = ""
for i in word1:
sumw1+=i
for j... | """
Given two string arrays word1 and word2, return true if the two arrays represent the same string,
and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
"""
def check_arr(word1, word2):
sumw1 = ''
sumw2 = ''
for i in word1:
sumw1 +... |
account = 'k47'
job_name = 'petclaw_job'
wall_time = '15:00'
| account = 'k47'
job_name = 'petclaw_job'
wall_time = '15:00' |
class Pokemon:
def __init__(self, name, type):
self.name = name
self.type = type
def __str__(self):
return f"name={self.name}, type={';'.join(self.type)}"
def say(self):
print(self.name)
| class Pokemon:
def __init__(self, name, type):
self.name = name
self.type = type
def __str__(self):
return f"name={self.name}, type={';'.join(self.type)}"
def say(self):
print(self.name) |
# This file is launched automatically from the outer folder
f = open('tinypy/tests/file.py')
for line in f:
print(line)
| f = open('tinypy/tests/file.py')
for line in f:
print(line) |
# BST implementation using Eytzinger Layout
class binary_search_tree:
def __init__(self, elements):
if not isinstance(elements, list):
raise TypeError("input not a list")
self.node_list = elements
def len(self):
return len(self.node_list)
def right_child(self, pos):
... | class Binary_Search_Tree:
def __init__(self, elements):
if not isinstance(elements, list):
raise type_error('input not a list')
self.node_list = elements
def len(self):
return len(self.node_list)
def right_child(self, pos):
return 2 * pos + 2
def left_chil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.