content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def is_funny(string):
data = list(zip(string, reversed(string)))
for i in range(len(string)-1):
if abs(ord(data[i+1][0]) - ord(data[i][0])) != \
abs(ord(data[i+1][1]) - ord(data[i][1])):
return "Not Funny"
return "Funny"
N = int(input())
for i in range(N):
print(is_fu... | def is_funny(string):
data = list(zip(string, reversed(string)))
for i in range(len(string) - 1):
if abs(ord(data[i + 1][0]) - ord(data[i][0])) != abs(ord(data[i + 1][1]) - ord(data[i][1])):
return 'Not Funny'
return 'Funny'
n = int(input())
for i in range(N):
print(is_funny(inpu... |
#
# Common methods for the a2gtrad and a2advrad scripts.
#
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 08/13/2014 3393 nabowle Initial creation to contain common
# ... | def get_datetime_str(record):
"""
Get the datetime string for a record.
Args:
record: the record to get data for.
Returns:
datetime string.
"""
return str(record.getDataTime())[0:19].replace(' ', '_') + '.0'
def get_data_type(azdat):
"""
Get the radar file type... |
#!/usr/bin/env python
def mtx_pivot(mtx) -> list:
piv=[]
pivr=[[] for c in mtx[0]]
for r,row in enumerate(mtx):
for c,col in enumerate(row):
pivr[c]+=[col]
piv+=pivr
return piv | def mtx_pivot(mtx) -> list:
piv = []
pivr = [[] for c in mtx[0]]
for (r, row) in enumerate(mtx):
for (c, col) in enumerate(row):
pivr[c] += [col]
piv += pivr
return piv |
# #class
# # terms
# # i. features/attributes
# # ii. methods
# # i. a class with args
# # ii a class without args
# # task
# # crate a person class
# # features; age, sex, name, occupation, height
# class Person(object):
# """
# docstring for Person:
# """
# def __init__(self, name, age, occupation, heig... | class Parent(object):
"""docstring for Parent"""
def __init__(self, name):
self.name = name
self.height = 6.0
def get_height(self):
print(self.height)
class Child(Parent):
"""docstring for Child"""
def __init__(self, name):
super(Parent, self).__init__()
s... |
"""
LC 6014
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s.
Return the lexicographically largest repeatLimitedString possible.
A str... | """
LC 6014
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s.
Return the lexicographically largest repeatLimitedString possible.
A str... |
def add_native_methods(clazz):
def floatToRawIntBits__float__(a0):
raise NotImplementedError()
def intBitsToFloat__int__(a0):
raise NotImplementedError()
clazz.floatToRawIntBits__float__ = staticmethod(floatToRawIntBits__float__)
clazz.intBitsToFloat__int__ = staticmethod(intBitsToFloa... | def add_native_methods(clazz):
def float_to_raw_int_bits__float__(a0):
raise not_implemented_error()
def int_bits_to_float__int__(a0):
raise not_implemented_error()
clazz.floatToRawIntBits__float__ = staticmethod(floatToRawIntBits__float__)
clazz.intBitsToFloat__int__ = staticmethod(in... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 04_device.ipynb (unless otherwise specified).
__all__ = ['versions']
# Cell
def versions():
"Checks if GPU enabled and if so displays device details with cuda, pytorch, fastai versions"
print("GPU: ", torch.cuda.is_available())
if torch.cuda.is_available() == True:
... | __all__ = ['versions']
def versions():
"""Checks if GPU enabled and if so displays device details with cuda, pytorch, fastai versions"""
print('GPU: ', torch.cuda.is_available())
if torch.cuda.is_available() == True:
print('Device = ', torch.device(torch.cuda.current_device()))
print('Cuda ... |
class PDB_container:
'''
Use to read a pdb file from a cocrystal structure and parse
it for further use
Note this class cannot write any files and we do not want any
files to be added by this class
This is good for IO management although the code might be hard to
understand
'''
... | class Pdb_Container:
"""
Use to read a pdb file from a cocrystal structure and parse
it for further use
Note this class cannot write any files and we do not want any
files to be added by this class
This is good for IO management although the code might be hard to
understand
"""
... |
def method():
if True:
return 1
else:
return 2
def method2():
x = 2
if x:
y = 3
z = 1
| def method():
if True:
return 1
else:
return 2
def method2():
x = 2
if x:
y = 3
z = 1 |
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General P... | name = 'SINQ Double Monochromator'
includes = ['stdsystem']
description = 'Test setup for the SINQ double monochromator'
devices = dict(mth1=device('nicos.devices.generic.VirtualMotor', unit='degree', description='First blade rotation', abslimits=(-180, 180), precision=0.01), mth2=device('nicos.devices.generic.VirtualM... |
"""
https://leetcode.com/problems/reverse-integer
"""
# define an input for testing purposes
x = 1534236469
# actual code to submit
test = []
for i in str(x):
test += i
for z in range(len(test)):
if test[-1] == "0":
test.pop(-1)
else:
break
if test == []:
test.append("0")
if test[0... | """
https://leetcode.com/problems/reverse-integer
"""
x = 1534236469
test = []
for i in str(x):
test += i
for z in range(len(test)):
if test[-1] == '0':
test.pop(-1)
else:
break
if test == []:
test.append('0')
if test[0] == '-':
test.append('-')
test.pop(0)
test.reverse()
solved ... |
class Fluorescence:
def __init__(self, user_input, input_ceon):
self.user_input = user_input
self.input_ceons = [input_ceon]
self.number_trajectories = user_input.n_snapshots_ex
self.child_root = 'nasqm_fluorescence_'
self.job_suffix = 'fluorescence'
self.parent_rest... | class Fluorescence:
def __init__(self, user_input, input_ceon):
self.user_input = user_input
self.input_ceons = [input_ceon]
self.number_trajectories = user_input.n_snapshots_ex
self.child_root = 'nasqm_fluorescence_'
self.job_suffix = 'fluorescence'
self.parent_rest... |
#
# PySNMP MIB module COMPANY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COMPANY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:26:32 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, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) ... |
input_tokenizer = {}
input_tokenizer['en-bg'] = '-l en -a'
input_tokenizer['en-cs'] = '-l en -a'
input_tokenizer['en-de'] = '-l en -a'
input_tokenizer['en-el'] = '-l en -a'
input_tokenizer['en-hr'] = '-l en -a'
input_tokenizer['en-it'] = '-l en -a'
input_tokenizer['en-nl'] = '-l en -a'
input_tokenizer['en-pl'] = '-l en... | input_tokenizer = {}
input_tokenizer['en-bg'] = '-l en -a'
input_tokenizer['en-cs'] = '-l en -a'
input_tokenizer['en-de'] = '-l en -a'
input_tokenizer['en-el'] = '-l en -a'
input_tokenizer['en-hr'] = '-l en -a'
input_tokenizer['en-it'] = '-l en -a'
input_tokenizer['en-nl'] = '-l en -a'
input_tokenizer['en-pl'] = '-l en... |
"""
The TreeNode represents node in a Tree.
This module is perfect for Binary Tree but their implementation needs restructuring of the TreeNode
for other Tree types.
"""
class TreeNode(object):
"""
Node in a Tree has arguments
data,link[0]-leftlink,link[0]-right link
emptiness of a TreeNode is indicated by self... | """
The TreeNode represents node in a Tree.
This module is perfect for Binary Tree but their implementation needs restructuring of the TreeNode
for other Tree types.
"""
class Treenode(object):
"""
Node in a Tree has arguments
data,link[0]-leftlink,link[0]-right link
emptiness of a TreeNode is indicated by s... |
#Task No. 3
def FindPath(graph,start,end,path=[]):
path = path + [start];
if (start == end):
return path
if (start not in graph):
return None
for node in graph[start]:
if node not in path:
path = FindPath(graph,node,end,path)
if path:
... | def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
path = find_path(graph, node, end, path)
if path:
return path
return... |
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class linkedList:
def __init__(self):
self.head=None
self.tail=None
def __iter__ (self):
curNode = self.head
while curNode:
yield curNode
curN... | class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
cur_node = self.head
while curNode:
yield curNode
cur_node =... |
#!/usr/bin/env python3
class Node:
def __init__(self, value, left=None, right=None) -> None:
self.value = value
self.left = left
self.right = right
def right_most_child_with_parent(self):
parent, curr = None, self
while curr.right:
parent = curr
c... | class Node:
def __init__(self, value, left=None, right=None) -> None:
self.value = value
self.left = left
self.right = right
def right_most_child_with_parent(self):
(parent, curr) = (None, self)
while curr.right:
parent = curr
curr = curr.right
... |
#!/usr/bin/python
def is_member(item_to_check, list_to_check):
'''
Checks if an item is in a list
'''
for list_item in list_to_check:
if item_to_check == list_item:
return(True)
return(False)
| def is_member(item_to_check, list_to_check):
"""
Checks if an item is in a list
"""
for list_item in list_to_check:
if item_to_check == list_item:
return True
return False |
"""Generics support via go_generics.
A Go template is similar to a go library, except that it has certain types that
can be replaced before usage. For example, one could define a templatized List
struct, whose elements are of type T, then instantiate that template for
T=segment, where "segment" is the concrete type.
"... | """Generics support via go_generics.
A Go template is similar to a go library, except that it has certain types that
can be replaced before usage. For example, one could define a templatized List
struct, whose elements are of type T, then instantiate that template for
T=segment, where "segment" is the concrete type.
"... |
def includeme(config):
# config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('hitori_boards', r'/hitori_boards')
config.add_route('hitori_board', r'/hitori_boards/{board_id:\d+}')
config.add_route('hitori_board_solve', r'/hitori_boards/{boar... | def includeme(config):
config.add_route('home', '/')
config.add_route('hitori_boards', '/hitori_boards')
config.add_route('hitori_board', '/hitori_boards/{board_id:\\d+}')
config.add_route('hitori_board_solve', '/hitori_boards/{board_id:\\d+}/solve')
config.add_route('hitori_board_clone', '/hitori_b... |
vetor = []
i = 1
while(i <= 100):
valor = int(input())
vetor.append(valor)
i = i + 1
print(max(vetor))
print(vetor.index(max(vetor)) + 1) | vetor = []
i = 1
while i <= 100:
valor = int(input())
vetor.append(valor)
i = i + 1
print(max(vetor))
print(vetor.index(max(vetor)) + 1) |
def test_length_ko_1_adb(style_checker):
"""Check length-ko-1.adb
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('gnat', 'length-ko-1.adb')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
length-ko-1.adb:50:80: (style) this line... | def test_length_ko_1_adb(style_checker):
"""Check length-ko-1.adb
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('gnat', 'length-ko-1.adb')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, 'length-ko-1.adb:50:80: (style) this line is ... |
"""Constants for dice-ml package."""
class BackEndTypes:
Sklearn = 'sklearn'
Tensorflow1 = 'TF1'
Tensorflow2 = 'TF2'
Pytorch = 'PYT'
class SamplingStrategy:
Random = 'random'
Genetic = 'genetic'
KdTree = 'kdtree'
| """Constants for dice-ml package."""
class Backendtypes:
sklearn = 'sklearn'
tensorflow1 = 'TF1'
tensorflow2 = 'TF2'
pytorch = 'PYT'
class Samplingstrategy:
random = 'random'
genetic = 'genetic'
kd_tree = 'kdtree' |
class BasePairType:
def __init__( self, nt1, nt2, Kd, match_lowercase = False ):
'''
Two sequence characters that get matched to base pair, e.g., 'C' and 'G';
and the dissociation constant K_d (in M) associated with initial pair formation.
match_lowercase means match 'x' to 'x', '... | class Basepairtype:
def __init__(self, nt1, nt2, Kd, match_lowercase=False):
"""
Two sequence characters that get matched to base pair, e.g., 'C' and 'G';
and the dissociation constant K_d (in M) associated with initial pair formation.
match_lowercase means match 'x' to 'x', 'y' ... |
def getdefaultencoding(space):
"""Return the current default string encoding used by the Unicode
implementation."""
return space.wrap(space.sys.defaultencoding)
def setdefaultencoding(space, w_encoding):
"""Set the current default string encoding used by the Unicode
implementation."""
encoding = spac... | def getdefaultencoding(space):
"""Return the current default string encoding used by the Unicode
implementation."""
return space.wrap(space.sys.defaultencoding)
def setdefaultencoding(space, w_encoding):
"""Set the current default string encoding used by the Unicode
implementation."""
encoding = spac... |
class StructLayoutAttribute(Attribute, _Attribute):
"""
Lets you control the physical layout of the data fields of a class or structure.
StructLayoutAttribute(layoutKind: LayoutKind)
StructLayoutAttribute(layoutKind: Int16)
"""
def __init__(self, *args):
""" x.__init__(...) initial... | class Structlayoutattribute(Attribute, _Attribute):
"""
Lets you control the physical layout of the data fields of a class or structure.
StructLayoutAttribute(layoutKind: LayoutKind)
StructLayoutAttribute(layoutKind: Int16)
"""
def __init__(self, *args):
""" x.__init__(...) initializes x; see ... |
#lista de cores para menu:
#cor da letra
limpa = '\033[m'
Lbranco = '\033[30m'
Lvermelho = '\033[31m'
Lverde = '\033[32m'
Lamarelo = '\033[33m'
Lazul = '\033[34m'
Lroxo = '\033[35m'
Lazulclaro = '\033[36'
Lcinza = '\033[37'
#Fundo
Fbranco = '\033[40m'
Fvermelho = '\033[41m'
Fverde = '\033[42m'
Famarelo = '\033[43m'
F... | limpa = '\x1b[m'
lbranco = '\x1b[30m'
lvermelho = '\x1b[31m'
lverde = '\x1b[32m'
lamarelo = '\x1b[33m'
lazul = '\x1b[34m'
lroxo = '\x1b[35m'
lazulclaro = '\x1b[36'
lcinza = '\x1b[37'
fbranco = '\x1b[40m'
fvermelho = '\x1b[41m'
fverde = '\x1b[42m'
famarelo = '\x1b[43m'
fazul = '\x1b[44m'
froxo = '\x1b[45m'
fazulclaro = ... |
def get_user_id(user_or_id):
if type(user_or_id) is str or type(user_or_id) is int:
return str(user_or_id)
elif hasattr(user_or_id, '__getitem__') and 'user_id' in user_or_id:
return str(user_or_id['user_id'])
elif hasattr(user_or_id, 'user_id'):
return str(user_or_id.user_id)
re... | def get_user_id(user_or_id):
if type(user_or_id) is str or type(user_or_id) is int:
return str(user_or_id)
elif hasattr(user_or_id, '__getitem__') and 'user_id' in user_or_id:
return str(user_or_id['user_id'])
elif hasattr(user_or_id, 'user_id'):
return str(user_or_id.user_id)
re... |
load("@io_bazel_rules_docker//container:container.bzl", _container_push = "container_push")
def container_push(*args, **kwargs):
"""Creates a script to push a container image to a Docker registry. The
target name must be specified when invoking the push script."""
if "registry" in kwargs:
fail(
... | load('@io_bazel_rules_docker//container:container.bzl', _container_push='container_push')
def container_push(*args, **kwargs):
"""Creates a script to push a container image to a Docker registry. The
target name must be specified when invoking the push script."""
if 'registry' in kwargs:
fail("Canno... |
#!/usr/bin/env python
class bresenham:
def __init__(self, start, end):
self.start = list(start)
self.end = list(end)
self.path = []
self.steep = abs(self.end[1]-self.start[1]) > abs(self.end[0]-self.start[0])
if self.steep:
# print 'Steep'
self.start = self.swap(self.start[0],self.start[1])
self.... | class Bresenham:
def __init__(self, start, end):
self.start = list(start)
self.end = list(end)
self.path = []
self.steep = abs(self.end[1] - self.start[1]) > abs(self.end[0] - self.start[0])
if self.steep:
self.start = self.swap(self.start[0], self.start[1])
... |
#
# PySNMP MIB module PROXY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PROXY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
def removcaract(cnpj):
documento = []
for x in cnpj:
if x.isnumeric():
documento.append(x)
documento = ''.join(documento)
return documento
| def removcaract(cnpj):
documento = []
for x in cnpj:
if x.isnumeric():
documento.append(x)
documento = ''.join(documento)
return documento |
#!/usr/bin/env python
"""
_DQMCat_
"""
__all__ = []
| """
_DQMCat_
"""
__all__ = [] |
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def condition(divisor) -> bool:
return sum((num - 1) // divisor + 1 for num in nums) <= threshold
lo, hi = 1, max(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if... | class Solution:
def smallest_divisor(self, nums: List[int], threshold: int) -> int:
def condition(divisor) -> bool:
return sum(((num - 1) // divisor + 1 for num in nums)) <= threshold
(lo, hi) = (1, max(nums))
while lo < hi:
mid = lo + (hi - lo) // 2
if ... |
__author__ = 'maartenbreddels'
matplotlib = """import pylab
import numpy as np
import os
import json
import sys
name = "{name}" if len(sys.argv) == 1 else sys.argv[1]
filename_grid = name + "_grid.npy"
filename_grid_vector = name + "_grid_vector.npy"
filename_grid_selection = name + "_grid_selection.npy"
filename_m... | __author__ = 'maartenbreddels'
matplotlib = 'import pylab\nimport numpy as np\nimport os\nimport json\nimport sys\n\nname = "{name}" if len(sys.argv) == 1 else sys.argv[1]\n\nfilename_grid = name + "_grid.npy"\nfilename_grid_vector = name + "_grid_vector.npy"\nfilename_grid_selection = name + "_grid_selection.npy"\nfil... |
"""This program finds the total number of possible combinations that can be used to
climb statirs . EG : for 3 stairs ,combination and output will be 1,1,1 , 1,2 , 2,1 i.e 3 . """
def counting_stairs(stair_number):
result = stair_number
# This function uses Recursion.
if(stair_number <=1):
... | """This program finds the total number of possible combinations that can be used to
climb statirs . EG : for 3 stairs ,combination and output will be 1,1,1 , 1,2 , 2,1 i.e 3 . """
def counting_stairs(stair_number):
result = stair_number
if stair_number <= 1:
result = 1
else:
result = count... |
def parse_eval_info(cur_eval_video_info):
length_eval_info = len(cur_eval_video_info)
cur_epoch = int(cur_eval_video_info[0].split(' ')[2].split('-')[1])
cur_video_auc = float(cur_eval_video_info[-1].split(' ')[-3].split('-')[1].split(',')[0])
return cur_epoch, cur_video_auc
file = '/home/mry/Desktop... | def parse_eval_info(cur_eval_video_info):
length_eval_info = len(cur_eval_video_info)
cur_epoch = int(cur_eval_video_info[0].split(' ')[2].split('-')[1])
cur_video_auc = float(cur_eval_video_info[-1].split(' ')[-3].split('-')[1].split(',')[0])
return (cur_epoch, cur_video_auc)
file = '/home/mry/Desktop/... |
class ExitMixin():
def do_exit(self, _):
'''
Exit the shell.
'''
print(self._exit_msg)
return True
def do_EOF(self, params):
print()
return self.do_exit(params)
| class Exitmixin:
def do_exit(self, _):
"""
Exit the shell.
"""
print(self._exit_msg)
return True
def do_eof(self, params):
print()
return self.do_exit(params) |
class Solution:
def calculateSum(self, N, A, B):
A_count = N//A
B_count = N//B
result = A*A_count*(1+A_count)//2 + B*B_count*(1+B_count)//2
a = min(A,B)
b = max(A,B)
while a > 0:
b, a= a, b%a
lcm = (A*B)//b
AB_count = (N - N%lcm)//lc... | class Solution:
def calculate_sum(self, N, A, B):
a_count = N // A
b_count = N // B
result = A * A_count * (1 + A_count) // 2 + B * B_count * (1 + B_count) // 2
a = min(A, B)
b = max(A, B)
while a > 0:
(b, a) = (a, b % a)
lcm = A * B // b
... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Children, obj[8]: Education, obj[9]: Occupation, obj[10]: Income, obj[11]: Bar, obj[12]: Coffeehouse, obj[13]: Restaurant20to50, obj[14]: Direction_same, obj[15]: Dista... | def find_decision(obj):
if obj[8] <= 2:
if obj[6] <= 5:
if obj[0] <= 2:
if obj[9] <= 17:
if obj[11] <= 3.0:
if obj[2] <= 3:
if obj[4] <= 0:
if obj[3] <= 2:
... |
class Cup:
def __init__(self,size,quantity):
self.size = size
self.quantity = quantity
def status(self):
return self.size-self.quantity
def fill(self, quantity):
if self.quantity<=self.status():
self.quantity+=quantity
cup = Cup(100, 50)
print(cup.status())
... | class Cup:
def __init__(self, size, quantity):
self.size = size
self.quantity = quantity
def status(self):
return self.size - self.quantity
def fill(self, quantity):
if self.quantity <= self.status():
self.quantity += quantity
cup = cup(100, 50)
print(cup.statu... |
__author__ = 'croxis'
def convertToPatches(model):
"""Sets up a model for autotesselation."""
for node in model.find_all_matches("**/+GeomNode"):
geom_node = node.node()
num_geoms = geom_node.get_num_geoms()
for i in range(num_geoms):
geom_node.modify_geom(i).make_pa... | __author__ = 'croxis'
def convert_to_patches(model):
"""Sets up a model for autotesselation."""
for node in model.find_all_matches('**/+GeomNode'):
geom_node = node.node()
num_geoms = geom_node.get_num_geoms()
for i in range(num_geoms):
geom_node.modify_geom(i).make_patches_... |
class BinaryConfusionMatrix:
def __init__(self, pos_tag="SPAM", neg_tag="OK"):
self.pos_tag = pos_tag
self.neg_tag = neg_tag
self.tp = 0
self.tn = 0
self.fp = 0
self.fn = 0
def as_dict(self):
return {"tp": self.tp, "tn": self.tn, "fp": self.fp, "fn": self... | class Binaryconfusionmatrix:
def __init__(self, pos_tag='SPAM', neg_tag='OK'):
self.pos_tag = pos_tag
self.neg_tag = neg_tag
self.tp = 0
self.tn = 0
self.fp = 0
self.fn = 0
def as_dict(self):
return {'tp': self.tp, 'tn': self.tn, 'fp': self.fp, 'fn': sel... |
def karp_rabin(text, word, n, m):
MOD = 257
A = random.randint(2, MOD - 1)
Am = pow(A, m, MOD)
def generate(t):
return sum(ord(c) * pow(A, i, MOD) for i, c in enumerate(t[::-1])) % MOD
text += '$'
hash_text, hash_word = generate(text[1:m + 1]), generate(word[1:])
for i in range(1, n - m + 2):
if h... | def karp_rabin(text, word, n, m):
mod = 257
a = random.randint(2, MOD - 1)
am = pow(A, m, MOD)
def generate(t):
return sum((ord(c) * pow(A, i, MOD) for (i, c) in enumerate(t[::-1]))) % MOD
text += '$'
(hash_text, hash_word) = (generate(text[1:m + 1]), generate(word[1:]))
for i in ra... |
n = 1000000
# n = 100
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
primes = []
for i in range(2,n+1):
if prime[i]:
primes.append(i)
count = 0
ans = 0
for index,elem in enumerate(prime... | n = 1000000
prime = [True for i in range(n + 1)]
p = 2
while p * p <= n:
if prime[p] == True:
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
primes = []
for i in range(2, n + 1):
if prime[i]:
primes.append(i)
count = 0
ans = 0
for (index, elem) in enumerate(primes):
... |
STARLARK_BINARY_PATH = {
"java": "external/io_bazel/src/main/java/net/starlark/java/cmd/Starlark",
"go": "external/net_starlark_go/cmd/starlark/*/starlark",
"rust": "external/starlark-rust/target/debug/starlark-repl",
}
STARLARK_TESTDATA_PATH = "test_suite/"
| starlark_binary_path = {'java': 'external/io_bazel/src/main/java/net/starlark/java/cmd/Starlark', 'go': 'external/net_starlark_go/cmd/starlark/*/starlark', 'rust': 'external/starlark-rust/target/debug/starlark-repl'}
starlark_testdata_path = 'test_suite/' |
#
# @lc app=leetcode id=868 lang=python3
#
# [868] Binary Gap
#
# @lc code=start
class Solution:
def binaryGap(self, N: int) -> int:
s = bin(N)
res = 0
i = float('inf')
for j, n in enumerate(s[2:]):
if n == '1':
res = max(res, j - i)
i = j... | class Solution:
def binary_gap(self, N: int) -> int:
s = bin(N)
res = 0
i = float('inf')
for (j, n) in enumerate(s[2:]):
if n == '1':
res = max(res, j - i)
i = j
return res |
class Solution:
def convertToBase7(self, num: int) -> str:
result = ''
n = abs(num)
while n:
n, curr = divmod(n, 7)
result = str(curr) + result
return '-' * (num < 0) + result or '0'
| class Solution:
def convert_to_base7(self, num: int) -> str:
result = ''
n = abs(num)
while n:
(n, curr) = divmod(n, 7)
result = str(curr) + result
return '-' * (num < 0) + result or '0' |
########import random
abcd=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
k=list(input("Enter your String"))
key="HACK"
scn=[['']*4 for i in range(0,4)]
p=sorted(list(key))
ci=[key.index(i) for i in p]
print(ci,p)
i,j=0,0
for m in k:
if j>3:
i+=1
... | abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
k = list(input('Enter your String'))
key = 'HACK'
scn = [[''] * 4 for i in range(0, 4)]
p = sorted(list(key))
ci = [key.index(i) for i in p]
print(ci, p)
(i, j) = (0, 0)
for m in k:
... |
start = int(input())
stop = int(input())
result = ""
for number in range(start, stop + 1):
print(chr(number), end=" ")
| start = int(input())
stop = int(input())
result = ''
for number in range(start, stop + 1):
print(chr(number), end=' ') |
H, W = map(int, input().split())
field = [[str(i) for i in input()] for _ in range(H)]
count = 0
for x in range(W-1):
for y in range(H-1):
black_num = 0
for x1, y1 in [(x, y), (x+1, y), (x, y+1), (x+1, y+1)]:
if field[y1][x1] == '#':
black_num += 1
if black_num % ... | (h, w) = map(int, input().split())
field = [[str(i) for i in input()] for _ in range(H)]
count = 0
for x in range(W - 1):
for y in range(H - 1):
black_num = 0
for (x1, y1) in [(x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1)]:
if field[y1][x1] == '#':
black_num += 1
... |
"""
test:
"""
def sum_function(a, b, c):
"""
returns sum of a and b
:param a: array
:param b: integer
:return: sum of a and b
change
"""
c = a
return c
def average_function(a, b):
"""
returns the average of the squares of a and b
:param a: integer
:param b: inte... | """
test:
"""
def sum_function(a, b, c):
"""
returns sum of a and b
:param a: array
:param b: integer
:return: sum of a and b
change
"""
c = a
return c
def average_function(a, b):
"""
returns the average of the squares of a and b
:param a: integer
:param b: integer... |
GET_REPOS = [
{
'name': 'sample_repo',
'nameWithOwner': 'example_org/sample_repo',
'primaryLanguage': {
'name': 'Python',
},
'url': 'https://github.com/example_org/sample_repo',
'sshUrl': 'git@github.com:example_org/sample_repo.git',
'createdAt': '... | get_repos = [{'name': 'sample_repo', 'nameWithOwner': 'example_org/sample_repo', 'primaryLanguage': {'name': 'Python'}, 'url': 'https://github.com/example_org/sample_repo', 'sshUrl': 'git@github.com:example_org/sample_repo.git', 'createdAt': '2011-02-15T18:40:15Z', 'description': 'My description', 'updatedAt': '2020-01... |
class Node():
def __init__(self, valor):
self.valor = valor
self.next = None
class Stack:
def __init__(self):
self.head = Node("head")
self.size = 0
def __str__(self):
actual = self.head.next
str1 = "["
while actual:
str1 += str(actual.valor) + ", "
actual = actual.next
s... | class Node:
def __init__(self, valor):
self.valor = valor
self.next = None
class Stack:
def __init__(self):
self.head = node('head')
self.size = 0
def __str__(self):
actual = self.head.next
str1 = '['
while actual:
str1 += str(actual.va... |
"""This settings module defines the benchmark driver settings"""
EXPORT_GRAPHVIZ = False
EXPORT_JSON = False
REPEATS = 1
LOGICAL_DOT = ''
FRAGMENTED_DOT = ''
LOGICAL_JSON = ''
FRAGMENTED_JSON = ''
PRESTO_SETTINGS = {}
| """This settings module defines the benchmark driver settings"""
export_graphviz = False
export_json = False
repeats = 1
logical_dot = ''
fragmented_dot = ''
logical_json = ''
fragmented_json = ''
presto_settings = {} |
# Databricks notebook source
# MAGIC %run ./includes/utils
# COMMAND ----------
mountDataLake(clientId="64492359-3450-4f1e-be01-8717789fd01e",
clientSecret=dbutils.secrets.get(scope="dpdatalake",key="adappsecret"),
tokenEndPoint="https://login.microsoftonline.com/0b55e01a-573a-4060-b656-d... | mount_data_lake(clientId='64492359-3450-4f1e-be01-8717789fd01e', clientSecret=dbutils.secrets.get(scope='dpdatalake', key='adappsecret'), tokenEndPoint='https://login.microsoftonline.com/0b55e01a-573a-4060-b656-d1a3d5815791/oauth2/token', storageAccountName='dpdatalake', containerName='data') |
class Artist:
def __init__(self, artist_id, uri, title):
self.id = artist_id
self.uri = uri
self.title = title
def __str__(self):
return '{} (id={})'.format(self.title, self.id)
def to_tuple(self):
return (self.id, self.uri, self.title)
| class Artist:
def __init__(self, artist_id, uri, title):
self.id = artist_id
self.uri = uri
self.title = title
def __str__(self):
return '{} (id={})'.format(self.title, self.id)
def to_tuple(self):
return (self.id, self.uri, self.title) |
description = 'Actuators and feedback of the shutter, detector, and valves'
group = 'lowlevel'
excludes = ['IOcard']
devices = dict(
I1_pnCCD_Active = device('nicos.devices.generic.ManualSwitch',
description = 'high: Detector is turned on',
states = [0, 1],
),
I2_Shutter_safe = device('ni... | description = 'Actuators and feedback of the shutter, detector, and valves'
group = 'lowlevel'
excludes = ['IOcard']
devices = dict(I1_pnCCD_Active=device('nicos.devices.generic.ManualSwitch', description='high: Detector is turned on', states=[0, 1]), I2_Shutter_safe=device('nicos.devices.generic.ManualSwitch', descrip... |
def multiple_of(num, multiple):
return num % multiple == 0
def sum_of_multiples(limit):
return sum(x for x in range(limit) if multiple_of(x, 3) or multiple_of(x, 5))
if __name__ == "__main__":
print(sum_of_multiples(1000)) | def multiple_of(num, multiple):
return num % multiple == 0
def sum_of_multiples(limit):
return sum((x for x in range(limit) if multiple_of(x, 3) or multiple_of(x, 5)))
if __name__ == '__main__':
print(sum_of_multiples(1000)) |
# nobully.py
# Metadata
NAME = 'nobully'
ENABLE = True
PATTERN = r'^!nobully (?P<nick>[^\s]+)'
USAGE = '''Usage: !nobully <nick>
This informs the user identified by nick that they should no longer bully other (innocent) users.
'''
# Constants
NOBULLY_URL = 'https://www.stop-irc-bullying.info/'
# Command
asy... | name = 'nobully'
enable = True
pattern = '^!nobully (?P<nick>[^\\s]+)'
usage = 'Usage: !nobully <nick>\nThis informs the user identified by nick that they should no longer bully other (innocent) users.\n'
nobully_url = 'https://www.stop-irc-bullying.info/'
async def nobully(bot, message, nick):
if nick not in bot.... |
"""
Misc. imported libs.
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
#############################################
def eigen():
new_git_repository(
name = "eigen",
commit = "954879183b1e008d7f0fe... | """
Misc. imported libs.
"""
load('@bazel_tools//tools/build_defs/repo:git.bzl', 'new_git_repository')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def eigen():
new_git_repository(name='eigen', commit='954879183b1e008d7f0fefb97e48a925c4e3fb16', remote='https://gitlab.com/libeigen/eigen.git'... |
# Copyright (c) 2018, WSO2 Inc. (http://wso2.com) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | ns = {'d': 'http://maven.apache.org/POM/4.0.0'}
zip_file_extension = '.zip'
carbon_name = 'carbon.zip'
value_tag = '{http://maven.apache.org/POM/4.0.0}value'
surface_plugin_artifact_id = 'maven-surefire-plugin'
datasource_paths = {'product-iots': {'CORE': ['conf/datasources/master-datasources.xml', 'conf/datasources/cd... |
name = "Angela"
letters_list = [x for x in name]
print(letters_list)
doubled = [x * 2 for x in range(1, 5)]
print(doubled)
maybe_tripled = [x * 3 for x in range(1, 10) if x > 5]
print(maybe_tripled)
def foo(value):
if value > 5:
return True
return False
with_fn = [x * 3 for x in range(1, 10) if fo... | name = 'Angela'
letters_list = [x for x in name]
print(letters_list)
doubled = [x * 2 for x in range(1, 5)]
print(doubled)
maybe_tripled = [x * 3 for x in range(1, 10) if x > 5]
print(maybe_tripled)
def foo(value):
if value > 5:
return True
return False
with_fn = [x * 3 for x in range(1, 10) if foo(x)]... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
left -= 1
right -= 1
newHead = ListNode(-1)
... | class Solution:
def reverse_between(self, head: ListNode, left: int, right: int) -> ListNode:
left -= 1
right -= 1
new_head = list_node(-1)
newHead.next = head
deque = collections.deque()
current = newHead.next
for index in range(right + 1):
if le... |
# entrada 3 float
A = float(input())
B = float(input())
C = float(input())
# variaveis (pesos)
P1 = 2
P2 = 3
P3 = 5
# calculo da media
MEDIA = ((A * P1) + (B*P2) + (C*P3)) / (P1+P2+P3)
print('MEDIA = {:.1f}'.format(MEDIA))
| a = float(input())
b = float(input())
c = float(input())
p1 = 2
p2 = 3
p3 = 5
media = (A * P1 + B * P2 + C * P3) / (P1 + P2 + P3)
print('MEDIA = {:.1f}'.format(MEDIA)) |
def get_CUDA(vectorSize = 10, func = "sin(2*pi*X/Lx)", px = "0.", py = "0.", pz = "0.", **kwargs):
return '''__global__ void initialize(dcmplx *QField, int* lattice, int* gpu_params){
int deviceNum = gpu_params[0];
int numGPUs = gpu_params[2];
int xSize = lattice[0]*numGPUs;
int ySize = lattice[2];
int zSize = l... | def get_cuda(vectorSize=10, func='sin(2*pi*X/Lx)', px='0.', py='0.', pz='0.', **kwargs):
return '__global__ void initialize(dcmplx *QField, int* lattice, int* gpu_params){\n\tint deviceNum = gpu_params[0];\n\tint numGPUs = gpu_params[2];\n\tint xSize = lattice[0]*numGPUs;\n\tint ySize = lattice[2];\n\tint zSize = l... |
"""
Empty files are not supported by Signed VSO Builds. Adding dummy file
@author: shagup
"""
| """
Empty files are not supported by Signed VSO Builds. Adding dummy file
@author: shagup
""" |
answer1 = widget_inputs["radio1"]
answer2 = widget_inputs["radio2"]
answer3 = widget_inputs["radio3"]
answer4 = widget_inputs["radio4"]
is_correct = False
comments = []
def commentizer(new):
if new not in comments:
comments.append(new)
if answer2 == True:
is_correct = True
else:
is_correct = is_c... | answer1 = widget_inputs['radio1']
answer2 = widget_inputs['radio2']
answer3 = widget_inputs['radio3']
answer4 = widget_inputs['radio4']
is_correct = False
comments = []
def commentizer(new):
if new not in comments:
comments.append(new)
if answer2 == True:
is_correct = True
else:
is_correct = is_cor... |
#
# Copyright (c) 2016, Prometheus Research, LLC
#
__import__('pkg_resources').declare_namespace(__name__)
| __import__('pkg_resources').declare_namespace(__name__) |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""initialize a n * m array"""
paths = [[0 for col in range(m)] for row in range(n)]
""" init all item in last row to 1"""
for col in range(m):
paths[n - 1][col] = 1
""" init all item in last col to ... | class Solution:
def unique_paths(self, m: int, n: int) -> int:
"""initialize a n * m array"""
paths = [[0 for col in range(m)] for row in range(n)]
' init all item in last row to 1'
for col in range(m):
paths[n - 1][col] = 1
' init all item in last col to 1'
... |
#task1: print the \\ double backslash
print("This is \\\\ double backslash")
#task2: print the mountains
print ("this is /\\/\\/\\/\\/\\ mountain")
#task3:he is awesome(using escape sequence)
print ("he is \t awesome")
#task4: \" \n \t \'
print ("\\\" \\n \\t \\\'") | print('This is \\\\ double backslash')
print('this is /\\/\\/\\/\\/\\ mountain')
print('he is \t awesome')
print('\\" \\n \\t \\\'') |
class TaskError(Exception):
pass
class StrategyError(Exception):
pass
| class Taskerror(Exception):
pass
class Strategyerror(Exception):
pass |
# 1 = Ace, 10 = Jack, 10 = Queen, 10 = King
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
deck = deck * 4
# TODO: Add cut-card functionality
def initiate_deck():
"""Asks the user how many decks are in play and generates the shoe"""
while True:
try:
deck_count = int(input("How many de... | deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
deck = deck * 4
def initiate_deck():
"""Asks the user how many decks are in play and generates the shoe"""
while True:
try:
deck_count = int(input('How many decks in play? (Max: 8)'))
if not 0 < deck_count < 9:
r... |
class Controller:
def __init__(self, period, init_cores, st=0.8):
self.period = period
self.init_cores = init_cores
self.st = st
self.name = type(self).__name__
def setName(self, name):
self.name = name
def setSLA(self, sla):
self.sla = sla
self.setp... | class Controller:
def __init__(self, period, init_cores, st=0.8):
self.period = period
self.init_cores = init_cores
self.st = st
self.name = type(self).__name__
def set_name(self, name):
self.name = name
def set_sla(self, sla):
self.sla = sla
self.s... |
r"""
Utility functions for building Sage
"""
# ****************************************************************************
# Copyright (C) 2017 Jeroen Demeyer <J.Demeyer@UGent.be>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as p... | """
Utility functions for building Sage
"""
def stable_uniq(L):
"""
Given an iterable L, remove duplicate items from L by keeping only
the last occurrence of any item.
The items must be hashable.
EXAMPLES::
sage: from sage_setup.util import stable_uniq
sage: stable_uniq( (1, 2, 3... |
# ***************************************************************************************
# ***************************************************************************************
#
# Name : democodegenerator.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 17th December 2018
# Purpose : Imaginary langu... | class Democodegenerator(object):
def __init__(self, optimise=False):
self.addr = 4096
self.memoryAddr = 12288
self.opNames = {}
for op in '+add;-sub;*mult;/div;%mod;∧|or;^xor'.split(';'):
self.opNames[op[0]] = op[1:]
self.jumpTypes = {'': 'jmp', '#': 'jnz', '... |
# Sphinx helper for Django-specific references
def setup(app):
app.add_crossref_type(
directivename = "label",
rolename = "djterm",
indextemplate = "pair: %s; label",
)
app.add_crossref_type(
directivename = "setting",
rolename = "setting",
indextemplate = "p... | def setup(app):
app.add_crossref_type(directivename='label', rolename='djterm', indextemplate='pair: %s; label')
app.add_crossref_type(directivename='setting', rolename='setting', indextemplate='pair: %s; setting')
app.add_crossref_type(directivename='templatetag', rolename='ttag', indextemplate='pair: %s; ... |
"""
Contains utility functions to works with learning-object get many.
"""
def get_many(db_client, filter_, range_, sorted_, user, learning_object_format):
"""Get learning objects with query."""
start, end = range_
field, order = sorted_
user_role = user.get('role')
user_id = user.get('id')
... | """
Contains utility functions to works with learning-object get many.
"""
def get_many(db_client, filter_, range_, sorted_, user, learning_object_format):
"""Get learning objects with query."""
(start, end) = range_
(field, order) = sorted_
user_role = user.get('role')
user_id = user.get('id')
... |
#
# PySNMP MIB module SMON2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SMON2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:59:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (smon,) = mibBuilder.importSymbols('APPLIC-MIB', 'smon')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints... |
delta_vector = [(1, 0), (0, -1), (-1, 0), (0, 1)]
current_east_pos = 0
current_north_pos = 0
current_delta = 0
for _ in range(747):
instruction = input()
movement = instruction[0]
value = int(instruction[1:])
if movement == 'N':
current_north_pos += value
if movement == 'S':
curre... | delta_vector = [(1, 0), (0, -1), (-1, 0), (0, 1)]
current_east_pos = 0
current_north_pos = 0
current_delta = 0
for _ in range(747):
instruction = input()
movement = instruction[0]
value = int(instruction[1:])
if movement == 'N':
current_north_pos += value
if movement == 'S':
current_... |
"""
Creating some co-ordinates with nested loops.
Output will be something like
(0,1)
(0,2)
(0,3)
(1,0)
(1,1) and so on.
"""
#Initiationg the loop
for x in range(3):
for y in range(3):
print(f"({x}, {y})") | """
Creating some co-ordinates with nested loops.
Output will be something like
(0,1)
(0,2)
(0,3)
(1,0)
(1,1) and so on.
"""
for x in range(3):
for y in range(3):
print(f'({x}, {y})') |
# input
n = int(input())
cont1 = int(input())
conttot = 1
# grafo
contador = 0
g = [[0 for i in range(n)] for j in range(n)]
lista = input().split()
for col in range(n):
for linha in range(n):
g[col][linha] = int(lista[contador])
contador += 1
if col == linha:
g[col][linha] = 0
... | n = int(input())
cont1 = int(input())
conttot = 1
contador = 0
g = [[0 for i in range(n)] for j in range(n)]
lista = input().split()
for col in range(n):
for linha in range(n):
g[col][linha] = int(lista[contador])
contador += 1
if col == linha:
g[col][linha] = 0
contaminados = []... |
class gbXMLConditionType(Enum,IComparable,IFormattable,IConvertible):
"""
This enumeration corresponds to the conditionType attribute in gbXML.
The enumerated attribute identifies the type of heating,cooling,
or ventilation the space has.
enum gbXMLConditionType,values: Cooled (1),Heated (0),Heat... | class Gbxmlconditiontype(Enum, IComparable, IFormattable, IConvertible):
"""
This enumeration corresponds to the conditionType attribute in gbXML.
The enumerated attribute identifies the type of heating,cooling,
or ventilation the space has.
enum gbXMLConditionType,values: Cooled (1),Heated (0),Heat... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
r... | class Solution:
def max_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
(current_level, depth) = ([root], 0)
while current_level:
next_level = []
while current_level:
to... |
with open("Actions.txt") as f:
print(f)
lines = f.readlines()
trim_list = list(map(lambda line: line.strip(), lines))
sig = "-- HERE --"
sig_indx = trim_list.index(sig)
pure_inst = trim_list[sig_indx:]
print(pure_inst)
res = []
for p in pure_inst:
split = p.split(" ", 1)
... | with open('Actions.txt') as f:
print(f)
lines = f.readlines()
trim_list = list(map(lambda line: line.strip(), lines))
sig = '-- HERE --'
sig_indx = trim_list.index(sig)
pure_inst = trim_list[sig_indx:]
print(pure_inst)
res = []
for p in pure_inst:
split = p.split(' ', 1)
... |
c = int()
def hanoi(discs, main, target, aux):
global c
if discs >= 1:
c = c + 1
hanoi(discs - 1, main, aux, target)
print("[{}] -> Move disc {} from {} to {}".format(c, discs, main, target))
hanoi(discs - 1, aux, target, main)
if __name__ == "__main__":
discs = int(input())
hanoi(discs, "mai... | c = int()
def hanoi(discs, main, target, aux):
global c
if discs >= 1:
c = c + 1
hanoi(discs - 1, main, aux, target)
print('[{}] -> Move disc {} from {} to {}'.format(c, discs, main, target))
hanoi(discs - 1, aux, target, main)
if __name__ == '__main__':
discs = int(input())... |
def f():
def g():
pass
if __name__ == '__main__':
g()
print(1)
f()
| def f():
def g():
pass
if __name__ == '__main__':
g()
print(1)
f() |
lst = [int(x) for x in input().split()]
k = int(input())
lst.sort()
print(lst[-k], end="") | lst = [int(x) for x in input().split()]
k = int(input())
lst.sort()
print(lst[-k], end='') |
n,k=map(int,input().split());a=[int(i) for i in input().split()];m=sum(a[:k]);s=m
for i in range(k,n):
s+=(a[i]-a[i-k])
if s>m:m=s
print(m)
| (n, k) = map(int, input().split())
a = [int(i) for i in input().split()]
m = sum(a[:k])
s = m
for i in range(k, n):
s += a[i] - a[i - k]
if s > m:
m = s
print(m) |
with open("day-02/input.txt", "r") as file:
puzzle_input = [i.split() for i in file.readlines()]
def part_1(puzzle_input):
depth = 0
horizontal = 0
for command, value in puzzle_input:
value = int(value)
if command == "forward":
horizontal += value
elif command == ... | with open('day-02/input.txt', 'r') as file:
puzzle_input = [i.split() for i in file.readlines()]
def part_1(puzzle_input):
depth = 0
horizontal = 0
for (command, value) in puzzle_input:
value = int(value)
if command == 'forward':
horizontal += value
elif command == '... |
obj = {
'Profiles' : [ {
'Source' : 'sfmc_sg10004_programmes_genrelevel1fan548day_oc_uas_dae',
'Media': ['audio','video'],
'Preferences' : [ {
'Score' : 1,
'Label' : 'Religion & Ethics'
}, {
'Score' : 4,
'Label' : 'Entertainment'
}, {
'Score' : 5... | obj = {'Profiles': [{'Source': 'sfmc_sg10004_programmes_genrelevel1fan548day_oc_uas_dae', 'Media': ['audio', 'video'], 'Preferences': [{'Score': 1, 'Label': 'Religion & Ethics'}, {'Score': 4, 'Label': 'Entertainment'}, {'Score': 5, 'Label': 'Music'}, {'Score': 5, 'Label': 'Comedy'}, {'Score': 5, 'Label': 'News'}, {'Sco... |
def kb_ids2known_facts(kb_ids):
"""
:param kb_ids: a knowledge base of facts that are already mapped to ids
:return: a set of all known facts (used later for negative sampling)
"""
facts = set()
for struct in kb_ids:
arrays = kb_ids[struct][0]
num_facts = len(arrays[0])
... | def kb_ids2known_facts(kb_ids):
"""
:param kb_ids: a knowledge base of facts that are already mapped to ids
:return: a set of all known facts (used later for negative sampling)
"""
facts = set()
for struct in kb_ids:
arrays = kb_ids[struct][0]
num_facts = len(arrays[0])
f... |
"""
1025. Divisor Game
Easy
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N - x.
Also, if... | """
1025. Divisor Game
Easy
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N - x.
Also, if... |
'''
Created on 05.03.2018
@author: Alex
'''
class ImageSorterException(Exception):
pass
| """
Created on 05.03.2018
@author: Alex
"""
class Imagesorterexception(Exception):
pass |
# Copyright 2017 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | vnic_type_normal = 'normal'
vnic_type_direct = 'direct'
vnic_type_macvtap = 'macvtap'
vnic_type_direct_physical = 'direct-physical'
vnic_type_baremetal = 'baremetal'
vnic_type_virtio_forwarder = 'virtio-forwarder'
vnic_types_sriov = (VNIC_TYPE_DIRECT, VNIC_TYPE_MACVTAP, VNIC_TYPE_DIRECT_PHYSICAL, VNIC_TYPE_VIRTIO_FORWA... |
# coding=utf-8
"""
Some utilities related to numbers.
"""
def is_even(num: int) -> bool:
"""Is num even?
:param num: number to check.
:type num: int
:returns: True if num is even.
:rtype: bool
:raises: ``TypeError`` if num is not an int.
"""
if not isinstance(num, int):
raise ... | """
Some utilities related to numbers.
"""
def is_even(num: int) -> bool:
"""Is num even?
:param num: number to check.
:type num: int
:returns: True if num is even.
:rtype: bool
:raises: ``TypeError`` if num is not an int.
"""
if not isinstance(num, int):
raise type_error('{} i... |
# writing a function to find the maximum and minmimum integer in a list
numbers = []
while True:
inp = (input('Please enter a number: '))
if inp == 'done!':
break
try:
val = int(inp)
except:
print('Invalid input')
print('Please provide a n... | numbers = []
while True:
inp = input('Please enter a number: ')
if inp == 'done!':
break
try:
val = int(inp)
except:
print('Invalid input')
print('Please provide a number')
continue
numbers.append(val)
print(numbers)
"\nlargest = 0\nfor i in numbers:\n prin... |
class Animal:
nombre: str
edad: int
nPatas: int
raza: str
ruido: str
color: str
def __init__(self, nombre, edad, nPatas, raza, ruido, color):
self.nombre = nombre
self.edad = edad
self.nPatas = nPatas
self.raza = raza
self.ruido = ruido
... | class Animal:
nombre: str
edad: int
n_patas: int
raza: str
ruido: str
color: str
def __init__(self, nombre, edad, nPatas, raza, ruido, color):
self.nombre = nombre
self.edad = edad
self.nPatas = nPatas
self.raza = raza
self.ruido = ruido
self.... |
# This file is part of the Pygame SGE.
#
# The Pygame SGE is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The Pygame SGE i... | """
This module provides input event classes. Input event objects are used
to consolidate all necessary information about input events in a clean
way.
You normally don't need to use input event objects directly. Input
events are handled automatically in each frame of the SGE's main loop.
You only need to use input e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.