content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Implementation of EDA-specific components
"""
def mk_clock(ctx, name):
"""
Creates a clock signal
"""
bool_t = ctx.mk_boolean_type()
i = ctx.mk_input(name + '_input', bool_t)
first = ctx.mk_latch(name + '_first', bool_t)
ctx.set_latch_init_next(first, ctx.mk_true(), ctx.mk_false())
... | """
Implementation of EDA-specific components
"""
def mk_clock(ctx, name):
"""
Creates a clock signal
"""
bool_t = ctx.mk_boolean_type()
i = ctx.mk_input(name + '_input', bool_t)
first = ctx.mk_latch(name + '_first', bool_t)
ctx.set_latch_init_next(first, ctx.mk_true(), ctx.mk_false())
... |
word_to_find = "box"
def get_puzzle():
o = []
with open("puzzle.txt","r") as file:
x = file.readlines()
for i in x:
o.append(i.split(",")[:-1])
return o
def chunks(lst, n):
f = []
for i in range(0, len(lst), n):
f.append(lst[i:i + n])
return f
def find_letters_in_list(lst,word):
... | word_to_find = 'box'
def get_puzzle():
o = []
with open('puzzle.txt', 'r') as file:
x = file.readlines()
for i in x:
o.append(i.split(',')[:-1])
return o
def chunks(lst, n):
f = []
for i in range(0, len(lst), n):
f.append(lst[i:i + n])
return f
def find_let... |
dataset_paths = {
# Face Datasets (In the paper: FFHQ - train, CelebAHQ - test)
'ffhq': '',
'celeba_test': '',
# Cars Dataset (In the paper: Stanford cars)
'cars_train': '',
'cars_test': '',
# Horse Dataset (In the paper: LSUN Horse)
'horse_train': '',
'horse_test': '',
# Church Dataset (In the paper: ... | dataset_paths = {'ffhq': '', 'celeba_test': '', 'cars_train': '', 'cars_test': '', 'horse_train': '', 'horse_test': '', 'church_train': '', 'church_test': '', 'cats_train': '', 'cats_test': ''}
model_paths = {'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pt... |
class Stop():
def __init__(self, name):
self.name = name
self.schedule = {}
self.previous_stop = dict()
self.next_stop = dict()
self.neighbords = [self.previous_stop, self.next_stop]
self.left_stop = None
self.right_stop = None
def set_schedule(self, line, schedule):
self.schedule[line] = schedule
... | class Stop:
def __init__(self, name):
self.name = name
self.schedule = {}
self.previous_stop = dict()
self.next_stop = dict()
self.neighbords = [self.previous_stop, self.next_stop]
self.left_stop = None
self.right_stop = None
def set_schedule(self, line,... |
def sum_of_two_numbers(number_1, number_2):
return number_1 + number_2
#print(sum(5,6))
if __name__ == '____':
a, b= map(int, input().split())
print(sum(a, b))
| def sum_of_two_numbers(number_1, number_2):
return number_1 + number_2
if __name__ == '____':
(a, b) = map(int, input().split())
print(sum(a, b)) |
#from DebugLogger00110 import DebugLogger00100
#import fbxsdk as fbx
#from fbxsdk import *
#import fbx as fbxsdk
#from fbx import *
# -*- coding: utf-8 -*-
#from fbx import *
#import DebugLogger00100
#import DebugLogger00100
#import WriteReadTrans_Z_00310
#import GetKeyCurve00110
#===================class Node=========... | print('fbx_____.py') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Notifier(object):
"""
Base class for all notifiers
"""
def __init__(self, name=None):
self._name = name
def notify(self, event):
"""Create notification of event.
:param event: The event for which to create a notificatio... | class Notifier(object):
"""
Base class for all notifiers
"""
def __init__(self, name=None):
self._name = name
def notify(self, event):
"""Create notification of event.
:param event: The event for which to create a notification
"""
pass |
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016
class SourceTuples:
def __init__(self, tuples=[]):
self.tuples = tuples
def __call__(self):
return self.tuples
| class Sourcetuples:
def __init__(self, tuples=[]):
self.tuples = tuples
def __call__(self):
return self.tuples |
years = range(2008, 2010)
vars = ['ta_2m', 'pr', 'psl', 'rss', 'rls', 'wss_10m', 'hur_2m',
'albedo', 'ps', 'ts_0m']
hourres = ['1H', '1H', '1H', '3H', '3H', '1H', '1H', '1H', '3H', '1H']
b11b = 'NORA10'
b11c = '11km'
paths = ['%s_%s_%s_%s_%s.nc' % (b11b, hourres[vi], b11c, vars[vi], y)
for vi in ran... | years = range(2008, 2010)
vars = ['ta_2m', 'pr', 'psl', 'rss', 'rls', 'wss_10m', 'hur_2m', 'albedo', 'ps', 'ts_0m']
hourres = ['1H', '1H', '1H', '3H', '3H', '1H', '1H', '1H', '3H', '1H']
b11b = 'NORA10'
b11c = '11km'
paths = ['%s_%s_%s_%s_%s.nc' % (b11b, hourres[vi], b11c, vars[vi], y) for vi in range(9) for y in years... |
class Demo:
a1 = 1
b1 = 2
c1 = 3
d1 = 4
def __init__(self):
print(self.a1) # access SV inside constructor using self
print(Demo.a1) # access SV inside constructor using classname
def mymethod1(self):
print(self.b1) # access SV inside instance method using ... | class Demo:
a1 = 1
b1 = 2
c1 = 3
d1 = 4
def __init__(self):
print(self.a1)
print(Demo.a1)
def mymethod1(self):
print(self.b1)
print(Demo.b1)
@classmethod
def mymethod2(cls):
print(cls.c1)
print(Demo.c1)
@staticmethod
def mymetho... |
bits = []
val = 190
while val > 0:
bits.append(val & 1)
val = int(val / 2)
print(bits)
# find the longest length of bits of 1s with one flip or None
lens = []
count = 0
if len(bits) == 1:
print(bits[0])
for bit in bits:
if bit:
count += 1
else:
lens.append(count)
lens.append(bit)
count = 0
... | bits = []
val = 190
while val > 0:
bits.append(val & 1)
val = int(val / 2)
print(bits)
lens = []
count = 0
if len(bits) == 1:
print(bits[0])
for bit in bits:
if bit:
count += 1
else:
lens.append(count)
lens.append(bit)
count = 0
if count:
lens.append(count)
print(... |
def isPalindrome(x: int) -> bool:
if x < 0:
return False
reverse_num = contador = 0
while x // 10**contador != 0:
reverse_num = (reverse_num*10) + (x // 10**contador % 10)
contador += 1
return x == reverse_num
| def is_palindrome(x: int) -> bool:
if x < 0:
return False
reverse_num = contador = 0
while x // 10 ** contador != 0:
reverse_num = reverse_num * 10 + x // 10 ** contador % 10
contador += 1
return x == reverse_num |
# Ex-1 Update Values in Dictionaries and Lists
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Roo... | x = [[5, 2, 3], [10, 8, 9]]
students = [{'first_name': 'Michael', 'last_name': 'Jordan'}, {'first_name': 'John', 'last_name': 'Rosales'}]
sports_directory = {'basketball': ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer': ['Messi', 'Ronaldo', 'Rooney']}
z = [{'x': 10, 'y': 20}]
x[1][0] = 15
students[0]['last_name'] = 'Br... |
__all__ = [
'Dcscn',
'DnCnn',
'Espcn',
'Idn',
'Rdn',
'Srcnn',
'Vdsr',
'Drcn',
'LapSrn',
'Drrn',
'Dbpn',
'Edsr',
'SrGan',
'Exp',
]
| __all__ = ['Dcscn', 'DnCnn', 'Espcn', 'Idn', 'Rdn', 'Srcnn', 'Vdsr', 'Drcn', 'LapSrn', 'Drrn', 'Dbpn', 'Edsr', 'SrGan', 'Exp'] |
class Solution:
def XXX(self, root: TreeNode) -> int:
def XXX(root):
if not root: return 0
if not root.left: return XXX(root.right) + 1
if not root.right: return XXX(root.left) + 1
leftDepth = XXX(root.left)
rightDepth = XXX(root.right)
... | class Solution:
def xxx(self, root: TreeNode) -> int:
def xxx(root):
if not root:
return 0
if not root.left:
return xxx(root.right) + 1
if not root.right:
return xxx(root.left) + 1
left_depth = xxx(root.left)
... |
def handle_error_by_throwing_exception():
raise Exception("ERROR: something went wrong")
def handle_error_by_returning_none(input_data):
try:
return int(input_data)
except ValueError:
return None
def handle_error_by_returning_tuple(input_data):
try:
return True, int(input_... | def handle_error_by_throwing_exception():
raise exception('ERROR: something went wrong')
def handle_error_by_returning_none(input_data):
try:
return int(input_data)
except ValueError:
return None
def handle_error_by_returning_tuple(input_data):
try:
return (True, int(input_data... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
m = {} # { value: index }
for i in range(0, len(nums)):
remainder = target - nums[i]
if remainder in m:
return [i, m[remainder]]
m[nums[i]] = i
| class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
m = {}
for i in range(0, len(nums)):
remainder = target - nums[i]
if remainder in m:
return [i, m[remainder]]
m[nums[i]] = i |
def f04(s):
within = lambda n : n in [1, 5, 6, 7, 8, 9, 15, 16, 19]
get_letters = lambda pred, w: [w[:2], w[0]][pred]
wt, wdic = ((i + 1, w) for i, w in enumerate(s.split())), {}
for index, word in wt:
wdic[get_letters(within(index), word)] = index
return wdic
s = 'Hi He Lied Because Boron Could Not... | def f04(s):
within = lambda n: n in [1, 5, 6, 7, 8, 9, 15, 16, 19]
get_letters = lambda pred, w: [w[:2], w[0]][pred]
(wt, wdic) = (((i + 1, w) for (i, w) in enumerate(s.split())), {})
for (index, word) in wt:
wdic[get_letters(within(index), word)] = index
return wdic
s = 'Hi He Lied Because ... |
def special_case_2003(request):
pass
def year_archive(request,year):
pass
def month_archive(request,year,month):
pass
def article_detail(request,year,month,title):
pass
| def special_case_2003(request):
pass
def year_archive(request, year):
pass
def month_archive(request, year, month):
pass
def article_detail(request, year, month, title):
pass |
class UF:
def __init__(self, n: int):
self.id = list(range(n))
def union(self, u: int, v: int) -> None:
self.id[self.find(u)] = self.find(v)
def connected(self, u: int, v: int) -> bool:
return self.find(self.id[u]) == self.find(self.id[v])
def reset(self, u: int):
self.id[u] = u
def find(s... | class Uf:
def __init__(self, n: int):
self.id = list(range(n))
def union(self, u: int, v: int) -> None:
self.id[self.find(u)] = self.find(v)
def connected(self, u: int, v: int) -> bool:
return self.find(self.id[u]) == self.find(self.id[v])
def reset(self, u: int):
sel... |
class Templates:
NotAnyMessage = '$var cannot be empty (should contain at least one element).'
NotEqualMessage = 'Equality precondition not met.'
NotNullMessage = '$var cannot be Null.'
NotGreaterThanMessage = "$var cannot be greater than $value."
NotLessThanMessage = "$var cannot be less than $valu... | class Templates:
not_any_message = '$var cannot be empty (should contain at least one element).'
not_equal_message = 'Equality precondition not met.'
not_null_message = '$var cannot be Null.'
not_greater_than_message = '$var cannot be greater than $value.'
not_less_than_message = '$var cannot be les... |
class FunnyRect:
cx =0.
cy=0.
fsize=0.
def setCenter (self, x, y):
self.cx = x
self.cy = y
def setSize (self, size):
self.fsize = size
def render (self):
rect (self.cx , self.cy , self.fsize , self.fsize )
funnyRectObj = FunnyRect ()
de... | class Funnyrect:
cx = 0.0
cy = 0.0
fsize = 0.0
def set_center(self, x, y):
self.cx = x
self.cy = y
def set_size(self, size):
self.fsize = size
def render(self):
rect(self.cx, self.cy, self.fsize, self.fsize)
funny_rect_obj = funny_rect()
def setup():
globa... |
class FloorLayout:
def countBoards(self, layout):
c = 0
for i in xrange(len(layout)):
for j in xrange(len(layout[i])):
if j > 0 and layout[i][j] == '-' and layout[i][j-1] == '-':
continue
if i > 0 and layout[i][j] == '|' and layout[i-1]... | class Floorlayout:
def count_boards(self, layout):
c = 0
for i in xrange(len(layout)):
for j in xrange(len(layout[i])):
if j > 0 and layout[i][j] == '-' and (layout[i][j - 1] == '-'):
continue
if i > 0 and layout[i][j] == '|' and (layo... |
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class SequenceWrapper(object):
def __init__(self, function, start, stop):
self._function = function
self._start = start
self._size = max(0, stop - start)
de... | class Sequencewrapper(object):
def __init__(self, function, start, stop):
self._function = function
self._start = start
self._size = max(0, stop - start)
def __len__(self):
return self._size
def __getitem__(self, index):
if index < self._size:
return se... |
def main():
choice='z'
if choice == 'a':
print("You chose 'a'.")
elif choice == 'b':
print("You chose 'b'.")
elif choice == 'c':
print("You chose 'c'.")
else:
print("Invalid choice.")
if __name__ == '__main__':
main()
| def main():
choice = 'z'
if choice == 'a':
print("You chose 'a'.")
elif choice == 'b':
print("You chose 'b'.")
elif choice == 'c':
print("You chose 'c'.")
else:
print('Invalid choice.')
if __name__ == '__main__':
main() |
{
'conditions': [
['OS=="win"', {
'variables': {
'GTK_Root%': 'C:/GTK', # Set the location of GTK all-in-one bundle
'with_jpeg%': 'false',
'with_gif%': 'false',
'with_pango%': 'false',
'with_freetype%': 'false'
}
}, { # 'OS!="win"'
'variables': {
... | {'conditions': [['OS=="win"', {'variables': {'GTK_Root%': 'C:/GTK', 'with_jpeg%': 'false', 'with_gif%': 'false', 'with_pango%': 'false', 'with_freetype%': 'false'}}, {'variables': {'with_jpeg%': '<!(./util/has_lib.sh jpeg)', 'with_gif%': '<!(./util/has_lib.sh gif)', 'with_pango%': '<!(./util/has_lib.sh pangocairo)', 'w... |
# Funcion para hacer flat un arreglo
def flatten_array(array):
return [item for sublist in array for item in sublist]
# Funcion para calcular matriz transpuesta
def transpose(matA):
transMatrix=[[0 for j in range(len(matA))] for i in range(len(matA[0]))]
for i in range(len(matA)):
for j in range(... | def flatten_array(array):
return [item for sublist in array for item in sublist]
def transpose(matA):
trans_matrix = [[0 for j in range(len(matA))] for i in range(len(matA[0]))]
for i in range(len(matA)):
for j in range(len(matA[0])):
transMatrix[j][i] = matA[i][j]
return transMatri... |
class FeatureExtractor:
def __init__(self):
preprocess = False
data_dir = "H:/data/createddata/feature/"
os.mkdirs(data_dir)
years = {2016, 2017}
for year in years:
splitFiles(year)
print("year\tday\tmeanValue\tmedianValue\thoMedian\tmean... | class Featureextractor:
def __init__(self):
preprocess = False
data_dir = 'H:/data/createddata/feature/'
os.mkdirs(data_dir)
years = {2016, 2017}
for year in years:
split_files(year)
print('year\tday\tmeanValue\tmedianValue\thoMedian\tmeanDegree\tmedianDe... |
# -*- coding: utf-8 -*-
class ThreeStacks(object):
""" 3.1 Three in One: Describe how you could use a
single array to implement three stacks.
"""
def __init__(self, size):
self.arr = [None] * size
self.stack1_ptr = 0
self.stack2_ptr = 1
self.stack3_ptr = 2
def pop(s... | class Threestacks(object):
""" 3.1 Three in One: Describe how you could use a
single array to implement three stacks.
"""
def __init__(self, size):
self.arr = [None] * size
self.stack1_ptr = 0
self.stack2_ptr = 1
self.stack3_ptr = 2
def pop(self, stack_no):
... |
"""
Copyright 2019 Skyscanner Ltd
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 applicable law or agreed to in writing, software dis... | """
Copyright 2019 Skyscanner Ltd
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 applicable law or agreed to in writing, software dis... |
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
index = 0
for i in range(len(t)):
if index < len(s) and t[i] == s[index]:
index += 1
return index == len(s)
| class Solution:
def is_subsequence(self, s: str, t: str) -> bool:
index = 0
for i in range(len(t)):
if index < len(s) and t[i] == s[index]:
index += 1
return index == len(s) |
"""Common bits of functionality shared between all efro projects.
Things in here should be hardened, highly type-safe, and well-covered by unit
tests since they are widely used in live client and server code.
license : MIT, see LICENSE for more details.
"""
| """Common bits of functionality shared between all efro projects.
Things in here should be hardened, highly type-safe, and well-covered by unit
tests since they are widely used in live client and server code.
license : MIT, see LICENSE for more details.
""" |
inputs = open('../input.txt', 'r')
data = inputs.readlines()
frequency = 0
for frequency_change in data:
try:
change = int(frequency_change.rstrip())
if change:
frequency += change
except:
print('Bad value: {}'.format(repr(frequency_change)))
print('frequency: {}'.format(fr... | inputs = open('../input.txt', 'r')
data = inputs.readlines()
frequency = 0
for frequency_change in data:
try:
change = int(frequency_change.rstrip())
if change:
frequency += change
except:
print('Bad value: {}'.format(repr(frequency_change)))
print('frequency: {}'.format(freq... |
"""
Before going through the code, have a look at the following blog about AVL Tree:
https://en.wikipedia.org/wiki/AVL_tree
@author: lashuk1729
"""
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
class AVL_Tree():
def ge... | """
Before going through the code, have a look at the following blog about AVL Tree:
https://en.wikipedia.org/wiki/AVL_tree
@author: lashuk1729
"""
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
class Avl_Tree:
def get... |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Ziang Lu'
def karatsuba(x: int, y: int) -> int:
"""
Calculates the multiplication of two integers using Karatsuba
Multiplication.
Naive calculation: O(n^2)
:param x: int
:param y: int
:return: int
"""
# We assume that the... | __author__ = 'Ziang Lu'
def karatsuba(x: int, y: int) -> int:
"""
Calculates the multiplication of two integers using Karatsuba
Multiplication.
Naive calculation: O(n^2)
:param x: int
:param y: int
:return: int
"""
(x_s, y_s) = (str(x), str(y))
if len(x_s) > len(y_s):
y_... |
#
# PySNMP MIB module LINKSWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LINKSWITCH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:56:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (a3_com,) = mibBuilder.importSymbols('A3Com-products-MIB', 'a3Com')
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, c... |
error_messages = {
'type_invalid': 'Expected value of type %s, found %s',
'field_type_invalid': 'Expected value of type %s for field %s, found %s',
'length_invalid': 'value is not of required length',
'object_length_invalid': 'object does not have required number of elements',
'not_in_options': 'val... | error_messages = {'type_invalid': 'Expected value of type %s, found %s', 'field_type_invalid': 'Expected value of type %s for field %s, found %s', 'length_invalid': 'value is not of required length', 'object_length_invalid': 'object does not have required number of elements', 'not_in_options': 'value not in list of opt... |
''' Compound Conditions
Logical Operators
AND Operator
Or operator
Not operator
A type of condition where we combine or connect differient relational expressions using some connectors
Example: if x> 10 and y <= 9
if p == 5 or q < 10
P | Q | P and Q # P and Q is a com... | """ Compound Conditions
Logical Operators
AND Operator
Or operator
Not operator
A type of condition where we combine or connect differient relational expressions using some connectors
Example: if x> 10 and y <= 9
if p == 5 or q < 10
P | Q | P and Q # P and Q is a com... |
"""This problem was asked by Dropbox.
Sudoku is a puzzle where you're given a partially-filled 9 by 9
grid with digits. The objective is to fill the grid with the
constraint that every row, column, and box (3 by 3 subgrid) must contain all of
the digits from 1 to 9.
Implement an efficient sudoku solver.
""" | """This problem was asked by Dropbox.
Sudoku is a puzzle where you're given a partially-filled 9 by 9
grid with digits. The objective is to fill the grid with the
constraint that every row, column, and box (3 by 3 subgrid) must contain all of
the digits from 1 to 9.
Implement an efficient sudoku solver.
""" |
class InvalidParametersException(Exception):
"""
Exception added to handle invalid constructor parameters
"""
def __init__(self, msg: str):
super().__init__(msg)
| class Invalidparametersexception(Exception):
"""
Exception added to handle invalid constructor parameters
"""
def __init__(self, msg: str):
super().__init__(msg) |
class EmptyStackError(Exception):
"""
Custom Error for empty stack.
"""
pass
class Stack:
"""
Stack: LIFO Data Structure.
Operations:
push(item)
pop()
peek()
isEmpty()
size()
"""
def __init__(self):
"""... | class Emptystackerror(Exception):
"""
Custom Error for empty stack.
"""
pass
class Stack:
"""
Stack: LIFO Data Structure.
Operations:
push(item)
pop()
peek()
isEmpty()
size()
"""
def __init__(self):
"""... |
input() # Ignore first line
s = input().split(' ')
L = len(s)
N = sorted([int(i) for i in s])
median = N[L//2] if L % 2 != 0 else (N[(L//2) - 1] + N[L//2])/2
total = 0
mode, mode_c = None, 0
cmode, cmode_c = None, 0
for n in N:
total += n
if cmode_c > mode_c:
mode = cmode
mode_c = cmode_c
... | input()
s = input().split(' ')
l = len(s)
n = sorted([int(i) for i in s])
median = N[L // 2] if L % 2 != 0 else (N[L // 2 - 1] + N[L // 2]) / 2
total = 0
(mode, mode_c) = (None, 0)
(cmode, cmode_c) = (None, 0)
for n in N:
total += n
if cmode_c > mode_c:
mode = cmode
mode_c = cmode_c
if n != ... |
for i in range(10):
print(i)
for i in range(ord('a'), ord('z')+1):
print(chr(i))
| for i in range(10):
print(i)
for i in range(ord('a'), ord('z') + 1):
print(chr(i)) |
class S:
def __init__(self, name):
self.name = name
def __repr__(self):
return f'{self.__dict__}'
def __str__(self):
return f'Name: {self.name}'
def __add__(self, other):
return S(f'{self.name} {other.name}')
class Deck:
def __init__(self):
self.cards = [... | class S:
def __init__(self, name):
self.name = name
def __repr__(self):
return f'{self.__dict__}'
def __str__(self):
return f'Name: {self.name}'
def __add__(self, other):
return s(f'{self.name} {other.name}')
class Deck:
def __init__(self):
self.cards = ... |
#
# PySNMP MIB module RADLAN-ippreflist-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-ippreflist-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:42:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, constraints_union, value_range_constraint) ... |
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def __add__(self, other):
return Point2D(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point2D(self.x - other.x, self.y - other.y)
... | class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
def __add__(self, other):
return point2_d(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return point2_d(self.x... |
def is_pesel_valid(pesel):
if re.match(PATTERN, pesel):
return True
else:
return False
def is_pesel_woman(pesel):
if int(pesel[-2]) % 2 == 0:
return True
else:
return False
| def is_pesel_valid(pesel):
if re.match(PATTERN, pesel):
return True
else:
return False
def is_pesel_woman(pesel):
if int(pesel[-2]) % 2 == 0:
return True
else:
return False |
def default_dict():
dict_ = {
'Name': '',
'Mobile': '',
'Email': '',
'City': '',
'State': '',
'Resources': '',
'Description': ''
}
return dict_
def default_chat_dict():
dict_ = {
'updateID': '',
'chatID': '',
'Text': ''
... | def default_dict():
dict_ = {'Name': '', 'Mobile': '', 'Email': '', 'City': '', 'State': '', 'Resources': '', 'Description': ''}
return dict_
def default_chat_dict():
dict_ = {'updateID': '', 'chatID': '', 'Text': ''}
return dict_ |
# BSD Licence
# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
# All rights reserved.
#
# See the LICENSE file in the source distribution of this software for
# the full license text.
"""
The classes in this module define the base interface between the OWS
Pylons server and components that provide ... | """
The classes in this module define the base interface between the OWS
Pylons server and components that provide Web X Server layers. The
intention is that a WXS can be created for a given datatype and
rendering engine by creating classes that implement these base
interfaces and implement service specific interface ... |
# -*- coding: utf-8 -*-
"""
GistAgent represents a generic gist agent.
"""
class GistAgent():
@property
def host(self): ...
@property
def username(self): ...
def get_gists(self): ...
def create_gist(self, files, desc="", public=False): ...
| """
GistAgent represents a generic gist agent.
"""
class Gistagent:
@property
def host(self):
...
@property
def username(self):
...
def get_gists(self):
...
def create_gist(self, files, desc='', public=False):
... |
class ProductQuantity(object):
def __init__(self, str_quantity):
self.StrQuantity = str_quantity
def __str__(self):
return self.StrQuantity
| class Productquantity(object):
def __init__(self, str_quantity):
self.StrQuantity = str_quantity
def __str__(self):
return self.StrQuantity |
# https://blog.dreamshire.com/project-euler-5-solution/
# https://code.mikeyaworski.com/python/project_euler/problem_5"""
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numb... | def find_smallest_multiple(n):
for i in range(n, factorial(n) + 1, n):
if is_multiple(i, n):
return i
return -1
def is_multiple(x, n):
for i in range(1, n):
if x % i != 0:
return False
return True
def factorial(n):
if n > 1:
return n * factorial(n - ... |
def three_LCS(A,B,C):
m=len(A)
n=len(B)
o=len(C)
L=[[[0 for i in range(o+1)]for j in range(n+1)]for k in range(m+1)]
for i in range(m+1):
for j in range(n+1):
for k in range(o+1):
if (i==0 or j==0 or k==0):
L[i][j][k]=0
elif (A[... | def three_lcs(A, B, C):
m = len(A)
n = len(B)
o = len(C)
l = [[[0 for i in range(o + 1)] for j in range(n + 1)] for k in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
for k in range(o + 1):
if i == 0 or j == 0 or k == 0:
L[i][j][k... |
pytest_plugins = (
"tests.plugins.home",
"tests.plugins.about",
"tests.plugins.login",
"tests.plugins.register",
"tests.plugins.account",
"tests.plugins.posts",
"tests.plugins.status_codes",
"tests.plugins.endpoints",
"tests.plugins.hooks",
)
| pytest_plugins = ('tests.plugins.home', 'tests.plugins.about', 'tests.plugins.login', 'tests.plugins.register', 'tests.plugins.account', 'tests.plugins.posts', 'tests.plugins.status_codes', 'tests.plugins.endpoints', 'tests.plugins.hooks') |
def length_message(x):
print("The length of", repr(x), "is", len(x))
length_message('Fnord')
length_message([1, 2, 3])
print()
| def length_message(x):
print('The length of', repr(x), 'is', len(x))
length_message('Fnord')
length_message([1, 2, 3])
print() |
sum=0
for j in range(int(input())):
sum += (j+1)
print(sum)
| sum = 0
for j in range(int(input())):
sum += j + 1
print(sum) |
"""The `cargo_bootstrap` rule is used for bootstrapping cargo binaries in a repository rule."""
load("//cargo/private:cargo_utils.bzl", "get_host_triple", "get_rust_tools")
load("//rust:defs.bzl", "rust_common")
_CARGO_BUILD_MODES = [
"release",
"debug",
]
_FAIL_MESSAGE = """\
Process exited with code '{code... | """The `cargo_bootstrap` rule is used for bootstrapping cargo binaries in a repository rule."""
load('//cargo/private:cargo_utils.bzl', 'get_host_triple', 'get_rust_tools')
load('//rust:defs.bzl', 'rust_common')
_cargo_build_modes = ['release', 'debug']
_fail_message = "Process exited with code '{code}'\n# ARGV #######... |
# Copyright 2015 Google Inc. 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 applicable ... | """Convinence module to hold default constants for C2D components.
There should not be any logic in this module. Its purpose is to simplify
analysis of commonly used GCP and properties names and identify the names
that were custom created for these modules.
"""
c2_d_images = 'click-to-deploy-images'
compute_url_base =... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# ProjectName: HW2
# FileName: write
# Description:
# TodoList:
def writeOutput(result, path="output.txt"):
res = ""
if result == "PASS":
res = "PASS"
else:
res += str(result[0]) + ',' + str(result[1])
with open(path, 'w') as f:
f.write(re... | def write_output(result, path='output.txt'):
res = ''
if result == 'PASS':
res = 'PASS'
else:
res += str(result[0]) + ',' + str(result[1])
with open(path, 'w') as f:
f.write(res)
def write_pass(path='output.txt'):
with open(path, 'w') as f:
f.write('PASS')
def write... |
# https://www.hackerrank.com/challenges/bigger-is-greater
def bigger_is_greater(string):
s = list(string)
if len(set(s)) == 1:
return 'no answer'
else:
last = s[-1]
for i, c in reversed(list(enumerate(s))):
if c > last:
last = c
elif c < last... | def bigger_is_greater(string):
s = list(string)
if len(set(s)) == 1:
return 'no answer'
else:
last = s[-1]
for (i, c) in reversed(list(enumerate(s))):
if c > last:
last = c
elif c < last:
sub = s.index(min((char for char in s[i ... |
class ApiError(Exception):
def __init__(self, error, status_code):
self.message = error
self.status_code = status_code
def __str__(self):
return self.message
| class Apierror(Exception):
def __init__(self, error, status_code):
self.message = error
self.status_code = status_code
def __str__(self):
return self.message |
""" version which can be consumed from within the module """
VERSION_STR = "0.0.6"
DESCRIPTION = "module to help you maintain third party apt repos in a sane way"
APP_NAME = "pyapt"
LOGGER_NAME = "pyapt"
| """ version which can be consumed from within the module """
version_str = '0.0.6'
description = 'module to help you maintain third party apt repos in a sane way'
app_name = 'pyapt'
logger_name = 'pyapt' |
value = input('Digite a chave de entrada: ')
flag = 0
sample = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for i in value:
if i in sample:
flag += 1
if flag == 1:
print("Chave correta.")
elif flag > 1:
print("A chave possui mais de um interiro.")
else:
print("A chave faltando o caracter ... | value = input('Digite a chave de entrada: ')
flag = 0
sample = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for i in value:
if i in sample:
flag += 1
if flag == 1:
print('Chave correta.')
elif flag > 1:
print('A chave possui mais de um interiro.')
else:
print('A chave faltando o caracter n... |
# Copyright 2010-2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | {'variables': {'relative_dir': 'chrome/nacl', 'gen_out_dir': '<(SHARED_INTERMEDIATE_DIR)/<(relative_dir)', 'dummy_input_file': 'nacl_extension.gyp', 'browser_tester_dir': '../../third_party/browser_tester', 'nacl_mozc_files': ['<(gen_out_dir)/nacl_mozc/_locales/en/messages.json', '<(gen_out_dir)/nacl_mozc/_locales/ja/m... |
# Python Program To Handle IO Error Produced By Open() Function
'''
Function Name : Open() Function
Function Date : 23 Sep 2020
Function Author : Prasad Dangare
Input : String
Output : String
'''
try:
name = input('Enter Filename : ')
f = open(name, 'r')
exc... | """
Function Name : Open() Function
Function Date : 23 Sep 2020
Function Author : Prasad Dangare
Input : String
Output : String
"""
try:
name = input('Enter Filename : ')
f = open(name, 'r')
except IOError:
print('File Not Found : ', name)
else:
n = len(f.readlines())
... |
#!/usr/bin/env python3
def foo():
print('This is foo')
print('Starting the program')
foo()
print('Ending the program')
| def foo():
print('This is foo')
print('Starting the program')
foo()
print('Ending the program') |
#
# PySNMP MIB module REDLINE-AN50-PMP-V2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDLINE-AN50-PMP-V2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:55:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
#
# PySNMP MIB module ALCATEL-IND1-TIMETRA-OAM-TEST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-TIMETRA-OAM-TEST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:19:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | (timetra_srmib_modules, tmnx_sr_objs, tmnx_sr_confs, tmnx_sr_notify_prefix) = mibBuilder.importSymbols('ALCATEL-IND1-TIMETRA-GLOBAL-MIB', 'timetraSRMIBModules', 'tmnxSRObjs', 'tmnxSRConfs', 'tmnxSRNotifyPrefix')
(t_profile,) = mibBuilder.importSymbols('ALCATEL-IND1-TIMETRA-QOS-MIB', 'TProfile')
(sdp_id, sdp_bind_vc_typ... |
class HashMapList(object):
def __init__(self, size=None, hash_function=hash):
assert isinstance(size, int)
self.array = list()
for x in range(size):
self.array.append(list())
self.size = size
self.hash_function = hash_function
def __setitem__(self, key, valu... | class Hashmaplist(object):
def __init__(self, size=None, hash_function=hash):
assert isinstance(size, int)
self.array = list()
for x in range(size):
self.array.append(list())
self.size = size
self.hash_function = hash_function
def __setitem__(self, key, valu... |
#! /usr/bin/python3
def backpack(value_1, value_2, weight, i, capacity, store={}):
if i in store:
if capacity in store[i]:
return store[i][capacity]
else:
store[i] = {}
result = 0
if i != len(weight) and capacity != 0:
if weight[i] > capacity:
return ... | def backpack(value_1, value_2, weight, i, capacity, store={}):
if i in store:
if capacity in store[i]:
return store[i][capacity]
else:
store[i] = {}
result = 0
if i != len(weight) and capacity != 0:
if weight[i] > capacity:
return value_1[i] + backpack(val... |
# -*- coding: utf-8 -*-
"""
This package offers access to the standard database structure. All defined sources are belonging directly to
the so called "standard configuration". Whenever you use a standard configuration for a topic (you configure
this in your YAML see: :ref:`configuration`)you can find further informati... | """
This package offers access to the standard database structure. All defined sources are belonging directly to
the so called "standard configuration". Whenever you use a standard configuration for a topic (you configure
this in your YAML see: :ref:`configuration`)you can find further information here. All standard so... |
def flatten_list(arr):
result = []
for item in arr:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result
def flatten_list(mapping):
for key in mapping:
if isinstance(mapping[key], dict):
value = ... | def flatten_list(arr):
result = []
for item in arr:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result
def flatten_list(mapping):
for key in mapping:
if isinstance(mapping[key], dict):
value = ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
if not root: return -inf
prev = -inf... | class Solution:
def get_minimum_difference(self, root: TreeNode) -> int:
if not root:
return -inf
prev = -inf
result = inf
node = root
nodes = []
while True:
while node:
nodes.append(node)
node = node.left
... |
def isBadVersion(version):
return True
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 1, n
while left <= right:
mid = left + (right - left) / 2
if isBadVersion(mid):
ri... | def is_bad_version(version):
return True
class Solution(object):
def first_bad_version(self, n):
"""
:type n: int
:rtype: int
"""
(left, right) = (1, n)
while left <= right:
mid = left + (right - left) / 2
if is_bad_version(mid):
... |
class ContainerRegistry:
def __init__(self, server, username, password):
self.server = server
self.username = username
self.password = password
| class Containerregistry:
def __init__(self, server, username, password):
self.server = server
self.username = username
self.password = password |
class Solution:
def countPrimes(self, n: 'int') -> 'int':
primeChecker = [True] * n
if n < 2:
return 0
primeChecker[0] = primeChecker[1] = False
for i in range(2, int(n ** 0.5) + 1):
if primeChecker[i]:
primeChecker[i*i:n:i] = [False] * len(pri... | class Solution:
def count_primes(self, n: 'int') -> 'int':
prime_checker = [True] * n
if n < 2:
return 0
primeChecker[0] = primeChecker[1] = False
for i in range(2, int(n ** 0.5) + 1):
if primeChecker[i]:
primeChecker[i * i:n:i] = [False] * le... |
NUM_LEN = 12
def extract_with_bit(numbers, index, bit_value):
return [number for number in numbers if number[index] == bit_value]
def count_frequencies(numbers):
# for each of the NUM_LEN bits, count the frequency of each bit
freqs = [{"0": 0, "1": 0} for _ in range(NUM_LEN)]
for number in numbers:... | num_len = 12
def extract_with_bit(numbers, index, bit_value):
return [number for number in numbers if number[index] == bit_value]
def count_frequencies(numbers):
freqs = [{'0': 0, '1': 0} for _ in range(NUM_LEN)]
for number in numbers:
number = number.strip()
for i in range(NUM_LEN):
... |
SERVICE_PATTERNS = {
"LATEST": {
"Stopping": re.compile(r'.*Stopping.*(service|container).*'),
"Stopped": re.compile(r'.*Stopped.*(service|container).*'),
"Starting": re.compile(r'.*Starting.*(service|container).*'),
"Started": re.compile(r'.*Started.*(service|container).*')
},
... | service_patterns = {'LATEST': {'Stopping': re.compile('.*Stopping.*(service|container).*'), 'Stopped': re.compile('.*Stopped.*(service|container).*'), 'Starting': re.compile('.*Starting.*(service|container).*'), 'Started': re.compile('.*Started.*(service|container).*')}, '201911': {'Stopping': re.compile('.*Stopping.*'... |
has_bi_direction = False
consider_literal = False
kb_prefix = 'http://dbpedia.org/resource/'
# kb_prefix = 'http://rdf.freebase.com/ns/'
kb_type_predicate_list = ['a', 'rdf:type', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type']
oracle_canidates_file = 'E:\kb_oracle_canidates_file'
| has_bi_direction = False
consider_literal = False
kb_prefix = 'http://dbpedia.org/resource/'
kb_type_predicate_list = ['a', 'rdf:type', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type']
oracle_canidates_file = 'E:\\kb_oracle_canidates_file' |
n = int(input().strip())
N = n
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
if n == N:
print(True)
else:
print(False)
| n = int(input().strip())
n = n
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
if n == N:
print(True)
else:
print(False) |
#
# Copyright (c) 2011-2015 Advanced Micro Devices, Inc.
# All rights reserved.
#
# For use for simulation and test purposes only
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source co... | def tlb_options(parser):
parser.add_option('--TLB-config', type='string', default='perCU', help='Options are: perCU (default), mono, 2CU, or perLane')
parser.add_option('--L1TLBentries', type='int', default='32')
parser.add_option('--L1TLBassoc', type='int', default='32')
parser.add_option('--L1AccessLa... |
# Write your code here
string = input()
dict = {}
maximum = 0
for i in string :
if i in dict :
dict[i] += 1
if dict[i] > maximum :
maximum = dict[i]
else :
dict[i] = 1
for key,value in sorted(dict.items()) :
if value == maximum :
print(str(key),str(value))
... | string = input()
dict = {}
maximum = 0
for i in string:
if i in dict:
dict[i] += 1
if dict[i] > maximum:
maximum = dict[i]
else:
dict[i] = 1
for (key, value) in sorted(dict.items()):
if value == maximum:
print(str(key), str(value))
break |
TRANSPARENT = 0
BLACK = 1
RED = 2
GREEN = 3
YELLOW = 4
BLUE = 5
MAGENTA = 6
CYAN = 7
WHITE = 8
| transparent = 0
black = 1
red = 2
green = 3
yellow = 4
blue = 5
magenta = 6
cyan = 7
white = 8 |
# -*- coding: utf-8 -*-
"""
>>> from pycm import *
>>> from pytest import warns
>>> large_cm = ConfusionMatrix(list(range(10))+[2,3,5],list(range(10))+[1,7,2])
>>> with warns(RuntimeWarning, match='The confusion matrix is a high dimension matrix'):
... large_cm.print_matrix()
Predict 0 1 2 3 ... | """
>>> from pycm import *
>>> from pytest import warns
>>> large_cm = ConfusionMatrix(list(range(10))+[2,3,5],list(range(10))+[1,7,2])
>>> with warns(RuntimeWarning, match='The confusion matrix is a high dimension matrix'):
... large_cm.print_matrix()
Predict 0 1 2 3 4 5 6 ... |
"""
basic package information
"""
# This file is also parsed by setup.py, so it should
# be limited to simple value definitions.
# Single source of truth for package version
__version__ = "0.3.1"
__all__ = [
"__version__",
]
| """
basic package information
"""
__version__ = '0.3.1'
__all__ = ['__version__'] |
class UnregisteredHandlerException(Exception):
"""
Raised when the registry is unable to find a handler for a provided
translations domain.
"""
| class Unregisteredhandlerexception(Exception):
"""
Raised when the registry is unable to find a handler for a provided
translations domain.
""" |
a = []
def splitter(n, user_num):
user_num_str = str(user_num)
for i in range(0, n, 1):
x = str(user_num_str[i])
a.append(x)
x = 0
def mainer():
try:
user = str(input())
a.append(user.split())
print(*a[0], sep='\n')
except EOFError:
print... | a = []
def splitter(n, user_num):
user_num_str = str(user_num)
for i in range(0, n, 1):
x = str(user_num_str[i])
a.append(x)
x = 0
def mainer():
try:
user = str(input())
a.append(user.split())
print(*a[0], sep='\n')
except EOFError:
print('')
mai... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def has_cycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
p = head.next
... |
#Special Pythagorean triplet
def Euler9(sum):
for a in range(1,sum):
for b in range(1,sum):
c=sum-a-b
#print(str(a)+'\t\t'+str(b)+'\t\t'+str(c))
if (a*a+b*b)==(c*c):
return (a,b,c,a*b*c)
for i in range(1000,1001):
print(str(i)+'\t\t'+str(Euler9(i))) | def euler9(sum):
for a in range(1, sum):
for b in range(1, sum):
c = sum - a - b
if a * a + b * b == c * c:
return (a, b, c, a * b * c)
for i in range(1000, 1001):
print(str(i) + '\t\t' + str(euler9(i))) |
t = int(input())
for i in range(t):
n,a,b = map(int, input().split())
s = []
for j in range(n):
s.append(chr(97 + (j%b)))
print(''.join(s))
| t = int(input())
for i in range(t):
(n, a, b) = map(int, input().split())
s = []
for j in range(n):
s.append(chr(97 + j % b))
print(''.join(s)) |
while True:
flagGreen = hero.findFlag("green")
flagBlack = hero.findFlag("black")
if flagGreen:
pos = flagGreen.pos
hero.buildXY("fence", pos.x, pos.y)
hero.pickUpFlag(flagGreen)
if flagBlack:
pos = flagBlack.pos
hero.buildXY("fire-trap", pos.x, pos.y)
... | while True:
flag_green = hero.findFlag('green')
flag_black = hero.findFlag('black')
if flagGreen:
pos = flagGreen.pos
hero.buildXY('fence', pos.x, pos.y)
hero.pickUpFlag(flagGreen)
if flagBlack:
pos = flagBlack.pos
hero.buildXY('fire-trap', pos.x, pos.y)
h... |
# This function modifies global variable 's'
def f():
global s
print (s)
s = "Look for Wikitechy Python Section"
print (s)
# Global Scope
s = "Python is great!"
f()
print (s) | def f():
global s
print(s)
s = 'Look for Wikitechy Python Section'
print(s)
s = 'Python is great!'
f()
print(s) |
data = input("File where data is stored: ")
content = open(data, 'r')
text = content.read()
option = input("Read or write: ")
if option == "read":
for i in content.readlines():
first_name, last_name, dob = i.split(",")
print(first_name, last_name, dob)
content.close()
elif option == "write":
... | data = input('File where data is stored: ')
content = open(data, 'r')
text = content.read()
option = input('Read or write: ')
if option == 'read':
for i in content.readlines():
(first_name, last_name, dob) = i.split(',')
print(first_name, last_name, dob)
content.close()
elif option == 'write':
... |
"""
{{cookiecutter.package_name}}.data
{% for _ in cookiecutter.package_name %}{{"~"}}{% endfor %}~~~~~
This module contains functionality for downloading, cleansing, and/or
generating data for this project.
**Module functions:**
.. autosummary::
placeholder
|
"""
def placeholder():
"Placeholder function ... | """
{{cookiecutter.package_name}}.data
{% for _ in cookiecutter.package_name %}{{"~"}}{% endfor %}~~~~~
This module contains functionality for downloading, cleansing, and/or
generating data for this project.
**Module functions:**
.. autosummary::
placeholder
|
"""
def placeholder():
"""Placeholder function... |
class TwoHeadDragon():
def __init__(self):
self.left_head = IceDragon(self)
self.right_head = FireDragon(self)
def ice_breath(self):
return self.left_head.ice_breath()
def fire_breath(self):
return self.right_head.fire_breath()
def get_left_head(self):
return s... | class Twoheaddragon:
def __init__(self):
self.left_head = ice_dragon(self)
self.right_head = fire_dragon(self)
def ice_breath(self):
return self.left_head.ice_breath()
def fire_breath(self):
return self.right_head.fire_breath()
def get_left_head(self):
return ... |
def grader(score: float) -> str:
"Translated scores into grade code letter."
TRANSLATE = ((0.9,"A"), (0.8,"B"), (0.7,"C"), (0.6,"D"))
if score > 1 or score < 0:
# Error case, score out of range
return 'F'
for limit,code in TRANSLATE:
if score >= limit:
return code
... | def grader(score: float) -> str:
"""Translated scores into grade code letter."""
translate = ((0.9, 'A'), (0.8, 'B'), (0.7, 'C'), (0.6, 'D'))
if score > 1 or score < 0:
return 'F'
for (limit, code) in TRANSLATE:
if score >= limit:
return code
return 'F' |
#!/bin/python3
t = int(input().strip())
for _ in range(0, t):
n = int(input().strip())
flag = False
strings = [''.join(sorted(input().strip())) for line in range(0, n)]
for column in range(0, len(strings[0])):
for row in range(1, n):
up = strings[row-1][column]
now = s... | t = int(input().strip())
for _ in range(0, t):
n = int(input().strip())
flag = False
strings = [''.join(sorted(input().strip())) for line in range(0, n)]
for column in range(0, len(strings[0])):
for row in range(1, n):
up = strings[row - 1][column]
now = strings[row][colu... |
N = int(input())
m2 = 0
m3 = 0
m4 = 0
m5 = 0
values = input().split(' ')
values_correctly = values[:N]
for i in range(N):
values_correctly[i] = int(values_correctly[i])
if(values_correctly[i] % 2 ==0):
m2+=1
if(values_correctly[i] % 3 ==0):
m3+=1
if(values_correctly[i] % 4 ==0):
... | n = int(input())
m2 = 0
m3 = 0
m4 = 0
m5 = 0
values = input().split(' ')
values_correctly = values[:N]
for i in range(N):
values_correctly[i] = int(values_correctly[i])
if values_correctly[i] % 2 == 0:
m2 += 1
if values_correctly[i] % 3 == 0:
m3 += 1
if values_correctly[i] % 4 == 0:
... |
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
# two pass
# check adjacent elements
return all(A[i]<=A[i+1] for i in range(len(A)-1)) or all(A[i]>=A[i+1] for i in range(len(A)-1))
# Time: O(N)
# Space:O(1)
# One pass
class Solution(object):
def isMonotonic(se... | class Solution:
def is_monotonic(self, A: List[int]) -> bool:
return all((A[i] <= A[i + 1] for i in range(len(A) - 1))) or all((A[i] >= A[i + 1] for i in range(len(A) - 1)))
class Solution(object):
def is_monotonic(self, A):
increasing = decreasing = True
for i in xrange(len(A) - 1):
... |
# Data parsing constants
US_STATE_CODE_DICT = {'alabama': 0,
'alaska': 1,
'arizona': 2,
'arkansas': 3,
'california': 4,
'colorado': 5,
'connecticut': 6,
'delaware': 7,
... | us_state_code_dict = {'alabama': 0, 'alaska': 1, 'arizona': 2, 'arkansas': 3, 'california': 4, 'colorado': 5, 'connecticut': 6, 'delaware': 7, 'florida': 8, 'georgia': 9, 'hawaii': 10, 'idaho': 11, 'illinois': 12, 'indiana': 13, 'iowa': 14, 'kansas': 15, 'kentucky': 16, 'louisiana': 17, 'maine': 18, 'maryland': 19, 'ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.