content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def XXX(self, n):
res = '1'
for i in range(2, n+1):
pre = res
# print(pre)
res = ''
while pre:
p = 1
while p < len(pre) and pre[0] == pre[p]:
p += 1
res += str(p) + pre... | class Solution:
def xxx(self, n):
res = '1'
for i in range(2, n + 1):
pre = res
res = ''
while pre:
p = 1
while p < len(pre) and pre[0] == pre[p]:
p += 1
res += str(p) + pre[0]
if... |
'''
Write a Python program to check whether a given integer is a palindrome or not.
Note: An integer is a palindrome when it reads the same backward
as forward. Negative numbers are not palindromic.
Sample Input:
(100)
(252)
(-838)
Sample Output:
False
True
False
'''
def is_Palindrome(n):
#when you do str[::-1],... | """
Write a Python program to check whether a given integer is a palindrome or not.
Note: An integer is a palindrome when it reads the same backward
as forward. Negative numbers are not palindromic.
Sample Input:
(100)
(252)
(-838)
Sample Output:
False
True
False
"""
def is__palindrome(n):
return str(n) == str(n... |
table_data=[[]for i in range(5)]
print(table_data)
for i in range(4):
table_data[i].append(i)
print(table_data)
| table_data = [[] for i in range(5)]
print(table_data)
for i in range(4):
table_data[i].append(i)
print(table_data) |
task_id = 'cccp_0718'
train_one = False
train_two = False
convert = False
word_model = 'glove300d.vec'
source = 'glove'
mode = 'cca'
dim = 300
max_iter = 1000
threshold = 0.5
guess_sig = 0.1
reg = 0.01
analysis_one = False
analysis_two = True
word_id = 4161
N = 40
| task_id = 'cccp_0718'
train_one = False
train_two = False
convert = False
word_model = 'glove300d.vec'
source = 'glove'
mode = 'cca'
dim = 300
max_iter = 1000
threshold = 0.5
guess_sig = 0.1
reg = 0.01
analysis_one = False
analysis_two = True
word_id = 4161
n = 40 |
#def gp(a,q):
#k = 0
#while True:
#result = a * q**k
#if result <=10000:
#yield result
#else:
#return
#print(k)
#k += 1
#a, q = input().strip().split(' ')
#[a, q] = map(int, [a,q])
#gps = gp(a,q)
##print(list(gp(a,q)) )
##print(gp(a,q))
#print(gps.__next__())
#print(gps.__next... | def counter(start=0):
n = start
while True:
result = (yield n)
print(type(result), result)
if result == 'Q':
break
n += 1
c = counter()
print(next(c))
print(c.send('Wow!'))
print(next(c))
print(c.send('Q')) |
mp = [{} for i in range(6)]
with open('ascii_letters.txt', 'r') as fin:
while (fin.readline()):
letter = fin.readline()[:-1]
for j in range(6):
mp[j][letter] = fin.readline()[:-1].replace('.', ' ').replace('#', '~')
fin.close()
with open('ascii_letters.py', 'w') as fout:
fout.w... | mp = [{} for i in range(6)]
with open('ascii_letters.txt', 'r') as fin:
while fin.readline():
letter = fin.readline()[:-1]
for j in range(6):
mp[j][letter] = fin.readline()[:-1].replace('.', ' ').replace('#', '~')
fin.close()
with open('ascii_letters.py', 'w') as fout:
fout.write... |
class Patient(object):
def __init__(self, name, age, phone, code):
self.name = name
self.age = age
self.phone = phone
self.code = code
def breath(self):
print("I breath 12-18 times per minute")
def walk(self, walkRate):
print("I walk at {}km per hour".forma... | class Patient(object):
def __init__(self, name, age, phone, code):
self.name = name
self.age = age
self.phone = phone
self.code = code
def breath(self):
print('I breath 12-18 times per minute')
def walk(self, walkRate):
print('I walk at {}km per hour'.forma... |
class Item():
def __init__(self, id_, value):
self.id_ = id_
self.value = value
self.left = None
self.right = None
class BinaryTree():
def __init__(self):
self.size = 0
self.root = None
def insert(self, item):
if self.root is None:
self.... | class Item:
def __init__(self, id_, value):
self.id_ = id_
self.value = value
self.left = None
self.right = None
class Binarytree:
def __init__(self):
self.size = 0
self.root = None
def insert(self, item):
if self.root is None:
self.roo... |
# This Python program must be run with
# Python 3 as it won't work with 2.7.
# ends the output with a <space>
print("Welcome to" , end = ' ')
print("Wikitechy", end = ' ') | print('Welcome to', end=' ')
print('Wikitechy', end=' ') |
TEST_NODE1 = "-122.313294, 47.6598762"
TEST_NODE2 = "-122.3141965, 47.659887"
def test_size(G_test):
assert G_test.size() == 8
def test_contains(G_test):
assert TEST_NODE1 in G_test
assert TEST_NODE2 in G_test
assert TEST_NODE1 in G_test._succ
assert TEST_NODE2 in G_test._succ
def test_iter_ed... | test_node1 = '-122.313294, 47.6598762'
test_node2 = '-122.3141965, 47.659887'
def test_size(G_test):
assert G_test.size() == 8
def test_contains(G_test):
assert TEST_NODE1 in G_test
assert TEST_NODE2 in G_test
assert TEST_NODE1 in G_test._succ
assert TEST_NODE2 in G_test._succ
def test_iter_edges... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_list(arr):
if len(arr) == 0:
return None
head = None
tail = None
for x in arr:
new_node = ListNode(x)
if not head:
head = new_node
tail = new_node
... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
def create_list(arr):
if len(arr) == 0:
return None
head = None
tail = None
for x in arr:
new_node = list_node(x)
if not head:
head = new_node
tail = new_node
... |
def permute(s, l, r):
if l == r:
print("".join(s))
else:
for i in range(l, r):
s[l], s[i] = s[i], s[l]
permute(s, l + 1, r)
s[l], s[i] = s[i], s[l]
s = list("abcd")
permute(s, 0, len(s))
| def permute(s, l, r):
if l == r:
print(''.join(s))
else:
for i in range(l, r):
(s[l], s[i]) = (s[i], s[l])
permute(s, l + 1, r)
(s[l], s[i]) = (s[i], s[l])
s = list('abcd')
permute(s, 0, len(s)) |
def persist_image(folder_path:str,url:str):
try:
image_content = requests.get(url).content
except Exception as e:
print(f"ERROR - Could not download {url} - {e}")
try:
image_file = io.BytesIO(image_content)
image = Image.open(image_file).convert('RGB')
file_path = o... | def persist_image(folder_path: str, url: str):
try:
image_content = requests.get(url).content
except Exception as e:
print(f'ERROR - Could not download {url} - {e}')
try:
image_file = io.BytesIO(image_content)
image = Image.open(image_file).convert('RGB')
file_path = ... |
N = int(input())
L = list(map(int, input().split()))
L.sort()
if L[-1] < sum(L[0:N-1]):
print("Yes")
else:
print("No")
| n = int(input())
l = list(map(int, input().split()))
L.sort()
if L[-1] < sum(L[0:N - 1]):
print('Yes')
else:
print('No') |
n=10
a=0
b=1
f=0
print(a)
print(b)
for i in range(2,n+1):
temp=a+b
a=b
b=temp
print(temp)
| n = 10
a = 0
b = 1
f = 0
print(a)
print(b)
for i in range(2, n + 1):
temp = a + b
a = b
b = temp
print(temp) |
def get_request_args(func):
def _get_request_args(self, request):
if request.method == 'GET':
args = request.GET
else:
# body = request.body
body = request.data
if body:
try:
# args = json.loads(body)
... | def get_request_args(func):
def _get_request_args(self, request):
if request.method == 'GET':
args = request.GET
else:
body = request.data
if body:
try:
args = body
except Exception as e:
LOG... |
larg = float(input('largura: '))
alt = float(input('altura: '))
area = larg*alt
tinta = area/2
print('vc precisa de {} Litros de tinta'.format(tinta)) | larg = float(input('largura: '))
alt = float(input('altura: '))
area = larg * alt
tinta = area / 2
print('vc precisa de {} Litros de tinta'.format(tinta)) |
# coding: utf-8
x = [int(i) for i in input()]
for i in range(len(x)):
x[i] = min(x[i],9-x[i])
if x[0] == 0:
x[0] = 9
print(''.join([str(i) for i in x]))
| x = [int(i) for i in input()]
for i in range(len(x)):
x[i] = min(x[i], 9 - x[i])
if x[0] == 0:
x[0] = 9
print(''.join([str(i) for i in x])) |
class PID():
def __init__(self):
self.ref = 1.9
self.kp = 7
self.ki = 0.0
self.kd = 0.2
self.delta_t = 0.05 # 50 ms
self.e_acum = 0.0
self.measu_prev1 = 0.0
self.measu_prev2 = 0.0
self.measu_prev3 = 0.0
self.sat_e_acum = 60.0 # 60 degre... | class Pid:
def __init__(self):
self.ref = 1.9
self.kp = 7
self.ki = 0.0
self.kd = 0.2
self.delta_t = 0.05
self.e_acum = 0.0
self.measu_prev1 = 0.0
self.measu_prev2 = 0.0
self.measu_prev3 = 0.0
self.sat_e_acum = 60.0
def loop(self,... |
frase = input("escriba una frase: ")
for i, c in enumerate(frase):
print('caracter: %s - indice: %i' % (c, i))
indice= int(input("elija el indice de la letra a modificar"))
print(frase[indice])
letra = input("letra nueva")
print(letra)
print(frase.replace((frase[indice]), (letra))) | frase = input('escriba una frase: ')
for (i, c) in enumerate(frase):
print('caracter: %s - indice: %i' % (c, i))
indice = int(input('elija el indice de la letra a modificar'))
print(frase[indice])
letra = input('letra nueva')
print(letra)
print(frase.replace(frase[indice], letra)) |
# -*- coding: utf-8 -*-
def main():
n = int(input())
a = list(map(int, input().split()))
four_count = 0
two_count = 0
for ai in a:
if ai % 4 == 0:
four_count += 1
elif ai % 2 == 0:
two_count += 1
if four_count >= n // 2:
print('... | def main():
n = int(input())
a = list(map(int, input().split()))
four_count = 0
two_count = 0
for ai in a:
if ai % 4 == 0:
four_count += 1
elif ai % 2 == 0:
two_count += 1
if four_count >= n // 2:
print('Yes')
else:
need = n - 2 * four_... |
class Time():
def print_time(self):
print('{}'.format(self.hour).zfill(2)+':'+\
'{}'.format(self.minute).zfill(2)+':'+\
'{}'.format(self.seconds).zfill(2))
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.seconds
... | class Time:
def print_time(self):
print('{}'.format(self.hour).zfill(2) + ':' + '{}'.format(self.minute).zfill(2) + ':' + '{}'.format(self.seconds).zfill(2))
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.seconds
return seconds
time ... |
def bfs(graph, start=0):
used = [False] * len(graph)
used[start] = True
q = [start]
for v in q:
for w in graph[v]:
if not used[w]:
used[w] = True
q.append(w)
def layers(graph, start=0):
used = [False] * len(graph)
used[start] = True
q, re... | def bfs(graph, start=0):
used = [False] * len(graph)
used[start] = True
q = [start]
for v in q:
for w in graph[v]:
if not used[w]:
used[w] = True
q.append(w)
def layers(graph, start=0):
used = [False] * len(graph)
used[start] = True
(q, re... |
# -*- coding: utf-8 -*-
__author__ = 'Johni Douglas Marangon'
__email__ = 'johni.douglas.marangon@gmail.com'
__version__ = '0.1.0'
| __author__ = 'Johni Douglas Marangon'
__email__ = 'johni.douglas.marangon@gmail.com'
__version__ = '0.1.0' |
ipfs_domain = '127.0.0.1'
ipfs_port = 5001
ganache_domain = "127.0.0.1"
ganache_port = 7545
contract_address = '0x49f7342c9e62a359d643abce2cbf49d0c7fbc31c'
contract_abi = '[{"constant":true,"inputs":[],"name":"Project_Info","outputs":[{"name":"c","type":"string"},{"name":"f","type":"string"},{"name":"p_title","type"... | ipfs_domain = '127.0.0.1'
ipfs_port = 5001
ganache_domain = '127.0.0.1'
ganache_port = 7545
contract_address = '0x49f7342c9e62a359d643abce2cbf49d0c7fbc31c'
contract_abi = '[{"constant":true,"inputs":[],"name":"Project_Info","outputs":[{"name":"c","type":"string"},{"name":"f","type":"string"},{"name":"p_title","type":"s... |
# -*- python -*-
load("@drake//tools/workspace:os.bzl", "determine_os")
def _impl(repository_ctx):
os_result = determine_os(repository_ctx)
if os_result.error != None:
fail(os_result.error)
if os_result.is_macos:
repository_ctx.symlink("/usr/local/opt/jpeg/include", "include")
re... | load('@drake//tools/workspace:os.bzl', 'determine_os')
def _impl(repository_ctx):
os_result = determine_os(repository_ctx)
if os_result.error != None:
fail(os_result.error)
if os_result.is_macos:
repository_ctx.symlink('/usr/local/opt/jpeg/include', 'include')
repository_ctx.symlink... |
class Server(object):
url_prefix = '/server'
@classmethod
def status(cls, players=True, rules=True, api=None) -> dict:
api = api or api
data = {
'players': players,
'rules': rules,
}
return api.send_request('/status', data)
@classmethod
def b... | class Server(object):
url_prefix = '/server'
@classmethod
def status(cls, players=True, rules=True, api=None) -> dict:
api = api or api
data = {'players': players, 'rules': rules}
return api.send_request('/status', data)
@classmethod
def broadcast(cls, msg: str, api=None) -... |
def send_message(Parent, message):
Parent.SendStreamMessage(message)
return
def send_whisper(Parent, user, message):
Parent.SendStreamWhisper(user, message)
return
def log(Parent, message):
Parent.Log("Poker Bot", message)
return | def send_message(Parent, message):
Parent.SendStreamMessage(message)
return
def send_whisper(Parent, user, message):
Parent.SendStreamWhisper(user, message)
return
def log(Parent, message):
Parent.Log('Poker Bot', message)
return |
def add_endpoints(disp):
# Versions
disp.add_endpoint('versions', '/')
# V3 API - http://api.openstack.org/api-ref-identity.html#identity-v3
# Tokens
disp.add_endpoint('v3_tokens', '/v3/tokens')
# Service Catalog
disp.add_endpoint('v3_services', '/v3/services')
disp.add_endpoint('v3_... | def add_endpoints(disp):
disp.add_endpoint('versions', '/')
disp.add_endpoint('v3_tokens', '/v3/tokens')
disp.add_endpoint('v3_services', '/v3/services')
disp.add_endpoint('v3_services_with_id', '/v3/services/{service_id}')
disp.add_endpoint('v3_endpoints', '/v3/endpoints')
disp.add_endpoint('v3... |
def solve123(al,sh):
al=list(al)
sh=list(sh)
s=[]
if sh[0]==al[3] and sh[2]==al[1]: s.append(0)
elif sh[0]==al[3] and sh[2]==al[2]: s.append(1)
elif sh[0]==al[4] and sh[2]==al[1]: s.append(4)
elif sh[0]==al[4] and sh[2]==al[2]: s.append(5)
if sh[1]==al[3] and sh[5]==al[1]: s.appe... | def solve123(al, sh):
al = list(al)
sh = list(sh)
s = []
if sh[0] == al[3] and sh[2] == al[1]:
s.append(0)
elif sh[0] == al[3] and sh[2] == al[2]:
s.append(1)
elif sh[0] == al[4] and sh[2] == al[1]:
s.append(4)
elif sh[0] == al[4] and sh[2] == al[2]:
s.append(... |
class Memory:
def __init__(self):
self.setDefault()
def setDefault(self):
#self.memory = ['sw $2, 8($2)'] #'lw $1, 4($2)', 'lw $3, 16($2)', 'sw $4, 8($2)', 'j label', 'addi $4, $1, 3'
self.labelList = [[], []]
def getInstruction(self, address):
return self.memory[address]
| class Memory:
def __init__(self):
self.setDefault()
def set_default(self):
self.labelList = [[], []]
def get_instruction(self, address):
return self.memory[address] |
def main(j, args, params, tags, tasklet):
page = args.page
refresh = int(args.tags.tagGet("time", 60))
if args.doc.destructed is False:
page.head += "<meta http-equiv=\"refresh\" content=\"%s\" >" % refresh
page.head += '<meta http-equiv="Cache-Control" content="no-store, no-cache, must-re... | def main(j, args, params, tags, tasklet):
page = args.page
refresh = int(args.tags.tagGet('time', 60))
if args.doc.destructed is False:
page.head += '<meta http-equiv="refresh" content="%s" >' % refresh
page.head += '<meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalida... |
def backtrack(candidate):
if find_solution(candidate):
output(candidate)
return
# iterate all possible candidates.
for next_candidate in list_of_candidates:
if is_valid(next_candidate):
# try this partial candidate solution
place(next_candidate)
... | def backtrack(candidate):
if find_solution(candidate):
output(candidate)
return
for next_candidate in list_of_candidates:
if is_valid(next_candidate):
place(next_candidate)
backtrack(next_candidate)
remove(next_candidate) |
'''
lec
'''
for item in ['a','b','c']:
print (item)
demo_str = "this is my string"
for c in demo_str:
print (c)
x=0
for word in demo_str.split():
x = x +1
print ("There are", x, "Words")
for num in range(5):
print(num)
for num in range (1,5):
print (num)
num_list = [1234,4... | """
lec
"""
for item in ['a', 'b', 'c']:
print(item)
demo_str = 'this is my string'
for c in demo_str:
print(c)
x = 0
for word in demo_str.split():
x = x + 1
print('There are', x, 'Words')
for num in range(5):
print(num)
for num in range(1, 5):
print(num)
num_list = [1234, 43212, 345, 3, 11, 23, 4, ... |
version_info = (1,55)
version = '.'.join(str(c) for c in version_info)
base_directory = ''
| version_info = (1, 55)
version = '.'.join((str(c) for c in version_info))
base_directory = '' |
def to_rna(dna_strand):
rna_strand = ""
for char in dna_strand:
if char == 'G':
rna_strand += 'C'
elif char == 'C':
rna_strand += 'G'
elif char == 'T':
rna_strand += 'A'
elif char == 'A':
rna_strand += 'U'
else:
... | def to_rna(dna_strand):
rna_strand = ''
for char in dna_strand:
if char == 'G':
rna_strand += 'C'
elif char == 'C':
rna_strand += 'G'
elif char == 'T':
rna_strand += 'A'
elif char == 'A':
rna_strand += 'U'
else:
... |
'''
Problem: Creage averager with following behavior.
>>> avg(10)
10.0
>>> avg(11)
10.5
>>> avg(12)
11.0
Lead to functional implementation, explaining closures.
'''
# Class-based implementation
class Averager():
def __init__(self):
self.series = []
def __call__(self, new_value):
self.seri... | """
Problem: Creage averager with following behavior.
>>> avg(10)
10.0
>>> avg(11)
10.5
>>> avg(12)
11.0
Lead to functional implementation, explaining closures.
"""
class Averager:
def __init__(self):
self.series = []
def __call__(self, new_value):
self.series.append(new_value)
re... |
# OOP fundamentals in Python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
def set_age(self, age): #Now i can mofify age
self.age = age
d =... | class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
def set_age(self, age):
self.age = age
d = dog('Tim', 7)
d2 = dog('Joe', 3)
print(d.get_name(), d.get_age())
print... |
def __after_init_updatehub_ti():
PLATFORM_ROOT_DIR = os.environ['PLATFORM_ROOT_DIR']
append_layers([ os.path.join(PLATFORM_ROOT_DIR, 'sources', p) for p in
[
'meta-ti',
'meta-updatehub-ti',
]])
run_after_init(__after_init_... | def __after_init_updatehub_ti():
platform_root_dir = os.environ['PLATFORM_ROOT_DIR']
append_layers([os.path.join(PLATFORM_ROOT_DIR, 'sources', p) for p in ['meta-ti', 'meta-updatehub-ti']])
run_after_init(__after_init_updatehub_ti) |
#Christina Andrea Putri - Universitas Kristen Duta Wacana
#Selamat datang di FAST FOOD SERBA 20k! Di restoran ini hanya bisa memesan 1 makanan per 1 pemesanan, dengan harga makanan Rp20.000 untuk semua jenis.
# Untuk tambahan topping, penambahan topping lebih dari 3 akan dikenakan biaya @ Rp5.000/topping.
# Tambahan t... | inp_menu = input('Menu : ')
qty = int(input('How many food(s) do you want to buy ? \n =>'))
yn = input('Do you want any additional toppings? (Yes/No) \n => ')
fp = 20000
tp = 5000
def topping(x):
top = tp * x
return top
def total(y):
food = qty * fp
return food
total = total(inp_menu)
if yn == 'Yes':
... |
#$Id$
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library='_pyIrfLoader')
env.Tool('irfLoaderLib')
def exists(env):
return 1
| def generate(env, **kw):
if not kw.get('depsOnly', 0):
env.Tool('addLibrary', library='_pyIrfLoader')
env.Tool('irfLoaderLib')
def exists(env):
return 1 |
def foo(a):
b = a - 1
bar(a, b)
def bar(a, b):
raise Exception("something wrong")
foo(1)
| def foo(a):
b = a - 1
bar(a, b)
def bar(a, b):
raise exception('something wrong')
foo(1) |
#read the input file
print("Calculating transistor counts...")
f=open('input.txt','r')
input=str(f.read())
#load the cell information from celldefs.lib
f=open('celldefs.txt','r')
celldefs=str(f.read())
celldefs=celldefs.replace('\n','')
celldefs=celldefs.split(',')
#array of the different cells in the library
cel... | print('Calculating transistor counts...')
f = open('input.txt', 'r')
input = str(f.read())
f = open('celldefs.txt', 'r')
celldefs = str(f.read())
celldefs = celldefs.replace('\n', '')
celldefs = celldefs.split(',')
cells = []
transcounts = []
cellcounts = []
cellcats = []
i = 1
while i <= len(celldefs) - 3:
cells.a... |
class A(object):
def __new__(cls):
return super().__new__(cls)
def __init__(self):
print('A init', self)
class B(A):
def __new__(cls):
print('B new', cls)
return super().__new__(cls)
def __init__(self):
print('B init', self)
print('B init super', super... | class A(object):
def __new__(cls):
return super().__new__(cls)
def __init__(self):
print('A init', self)
class B(A):
def __new__(cls):
print('B new', cls)
return super().__new__(cls)
def __init__(self):
print('B init', self)
print('B init super', supe... |
simple_example = "x > 42 AND y != true OR z == 'yes'"
parentheses = "(x <= 42 OR y == 'yes' ) AND (y == 'no' OR x >= 17)"
operators_precedence = "x < 5.15 OR x > 10 AND y == 'eligible'"
implicit_boolean_cast = "z OR x AND y"
constant_statements = "444 AND True OR 'yes'"
| simple_example = "x > 42 AND y != true OR z == 'yes'"
parentheses = "(x <= 42 OR y == 'yes' ) AND (y == 'no' OR x >= 17)"
operators_precedence = "x < 5.15 OR x > 10 AND y == 'eligible'"
implicit_boolean_cast = 'z OR x AND y'
constant_statements = "444 AND True OR 'yes'" |
class Solution:
def longestRepeatingSubstring(self, S: str) -> int:
for l in range(len(S), 0, -1):
s = S[:l]
seen = {s}
for j in range(l, len(S)):
s = s[1:] + S[j]
if s in seen:
return l
seen.add(s)
... | class Solution:
def longest_repeating_substring(self, S: str) -> int:
for l in range(len(S), 0, -1):
s = S[:l]
seen = {s}
for j in range(l, len(S)):
s = s[1:] + S[j]
if s in seen:
return l
seen.add(s)
... |
def busca_sequencial(seq, x):
for i in range(len(seq)):
if seq[i] == x:
return i
return False
| def busca_sequencial(seq, x):
for i in range(len(seq)):
if seq[i] == x:
return i
return False |
def t(a):
return a[2:]
a = t([1, 2, 3, 4])
print(a)
print(a[1:-1])
print(a[:2])
| def t(a):
return a[2:]
a = t([1, 2, 3, 4])
print(a)
print(a[1:-1])
print(a[:2]) |
class APIError(IOError):
def __init__(self, service_name, source, original_error):
self.original_error = original_error
self.service_name = service_name
self.source = source
class HTTPError(APIError):
def __init__(self, service_name, source, original_error, response):
super()... | class Apierror(IOError):
def __init__(self, service_name, source, original_error):
self.original_error = original_error
self.service_name = service_name
self.source = source
class Httperror(APIError):
def __init__(self, service_name, source, original_error, response):
super().... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( mat , r , c ) :
a = 0
b = 2
low_row = 0 if ( 0 > a ) else a
low_column = 0 if ( 0 > b ) else b - 1
... | def f_gold(mat, r, c):
a = 0
b = 2
low_row = 0 if 0 > a else a
low_column = 0 if 0 > b else b - 1
high_row = r - 1 if a + 1 >= r else a + 1
high_column = c - 1 if b + 1 >= c else b + 1
while low_row > 0 - r and low_column > 0 - c:
i = low_column + 1
while i <= high_column and... |
# Generates struct declarations
FOClient = { 0x21C : (1, 'byte GameState'),
0x1CE4 : (4, 'int wmX'),
0x1CE8 : (4, 'int wmY'),
0x6BA0 : (4, 'CritterCl* self') }
CritterCl = { 0x00 : (4, 'int id'),
0x04 : (2, 'short pid'),
0x06 : (2, 'short hexX'),
... | fo_client = {540: (1, 'byte GameState'), 7396: (4, 'int wmX'), 7400: (4, 'int wmY'), 27552: (4, 'CritterCl* self')}
critter_cl = {0: (4, 'int id'), 4: (2, 'short pid'), 6: (2, 'short hexX'), 8: (2, 'short hexY'), 10: (1, 'byte dir'), 288: (1, 'byte isPlayer'), 300: (4, 'int hp'), 316: (4, 'int xp'), 320: (4, 'int level... |
class Solution:
def XXX(self, m: int, n: int) -> int:
matrix = [[1]*m for i in range(n)]
for i in range(0,n-1):
for j in range(0,m-1):
matrix[i+1][j+1] = matrix[i][j+1] + matrix[i+1][j]
return matrix[-1][-1]
| class Solution:
def xxx(self, m: int, n: int) -> int:
matrix = [[1] * m for i in range(n)]
for i in range(0, n - 1):
for j in range(0, m - 1):
matrix[i + 1][j + 1] = matrix[i][j + 1] + matrix[i + 1][j]
return matrix[-1][-1] |
def preParse(tokens:list) -> list:
retList = []
curList = []
for i in tokens:
if i.cat == "SEMICOLON":
retList.append(curList)
curList = []
else:
curList.append(i)
| def pre_parse(tokens: list) -> list:
ret_list = []
cur_list = []
for i in tokens:
if i.cat == 'SEMICOLON':
retList.append(curList)
cur_list = []
else:
curList.append(i) |
#!/usr/bin/env python3
class Day04:
guard_map = {}
def __init__(self):
guard_id = 0
state = 0 # 0: Awake, 1: Asleep
pos = 0
with open('sorted_input.txt') as fp:
for line in fp:
minute = int(line[15:17])
if line[19] == 'G':
... | class Day04:
guard_map = {}
def __init__(self):
guard_id = 0
state = 0
pos = 0
with open('sorted_input.txt') as fp:
for line in fp:
minute = int(line[15:17])
if line[19] == 'G':
guard_id = int(line[26:].split(' ')[0... |
# Solved with hint.
# Use array index to your advantage when ever possible.
def first_missing(lst):
for i in range(0, len(lst)):
if lst[i] != i:
if 0 <= lst[i] <= len(lst)-1:
temp = lst[lst[i]]
lst[lst[i]] = lst[i]
lst[i] = temp
for i in range... | def first_missing(lst):
for i in range(0, len(lst)):
if lst[i] != i:
if 0 <= lst[i] <= len(lst) - 1:
temp = lst[lst[i]]
lst[lst[i]] = lst[i]
lst[i] = temp
for i in range(0, len(lst)):
if lst[i] != i:
return i
print(first_mis... |
xpath = {}
xpath["is_user_loged"] = {
"login_button": "//div[text()='Facebook Login']",
}
xpath["login_user"] = {
"input_email": "//input[@name='email']",
"input_password": "//input[@name='pass']",
"login_button": "//div[text()='Facebook Login']",
}
xpath["go_to_instagram_Tab"] = {
"instagram_but... | xpath = {}
xpath['is_user_loged'] = {'login_button': "//div[text()='Facebook Login']"}
xpath['login_user'] = {'input_email': "//input[@name='email']", 'input_password': "//input[@name='pass']", 'login_button': "//div[text()='Facebook Login']"}
xpath['go_to_instagram_Tab'] = {'instagram_button': "//div[@id='media_manage... |
{
'targets': [
{
'target_name': 'sdladdon',
'cflags': ['-fexceptions', '-lSDL2', '-pthread'],
'cflags_cc': ['-fexceptions', '-lSDL2', '-pthread'],
'sources': ['src/main_window.h', 'src/main_window.cpp', 'src/node_addon.h', 'src/node_addon.cpp'],
'i... | {'targets': [{'target_name': 'sdladdon', 'cflags': ['-fexceptions', '-lSDL2', '-pthread'], 'cflags_cc': ['-fexceptions', '-lSDL2', '-pthread'], 'sources': ['src/main_window.h', 'src/main_window.cpp', 'src/node_addon.h', 'src/node_addon.cpp'], 'include_dirs': ['<!@(node -p \'require("node-addon-api").include\')'], 'libr... |
#
# PySNMP MIB module FRF16-MFR-MIB-EXP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FRF16-MFR-MIB-EXP
# Produced by pysmi-0.3.4 at Wed May 1 13:16:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, single_value_constraint, value_size_constraint) ... |
x = 510
y = 510
c = (x + y)
print(c)
| x = 510
y = 510
c = x + y
print(c) |
# @date 2018-08-07
# @author Frederic Scherma, All rights reserved without prejudices.
# @license Copyright (c) 2018 Dream Overflow
#
__version__ = '0.3.7'
APP_SHORT_NAME = "siis"
APP_LONG_NAME = "Self Investor Income System"
APP_VERSION = (0, 3, 7)
APP_RELEASE = 467
| __version__ = '0.3.7'
app_short_name = 'siis'
app_long_name = 'Self Investor Income System'
app_version = (0, 3, 7)
app_release = 467 |
UpperBoundary = 1000000
def IsPrime(a):
if a < 2:
return False
if a == 2:
return True
for i in range(2, int(a**0.5)+1):
if a%i == 0:
return False
else:
return True
def IsCircularPrime(a):
if not IsPrime(a):
return False
aStr = str(a)
for ... | upper_boundary = 1000000
def is_prime(a):
if a < 2:
return False
if a == 2:
return True
for i in range(2, int(a ** 0.5) + 1):
if a % i == 0:
return False
else:
return True
def is_circular_prime(a):
if not is_prime(a):
return False
a_str = str... |
# flake8: noqa
reserved = [
"default",
"include",
"stages",
"variables",
"workflow"
] | reserved = ['default', 'include', 'stages', 'variables', 'workflow'] |
class Person:
def __init__(self, name, age): # Constructor
self.name = name
self.age = age
def outputNameAndAge(self):
print("My name is {}, and I am {}.".format(self.name, self.age))
class Student(Person):
def __init__(self, name, age, graduationYear):
super().__init_... | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def output_name_and_age(self):
print('My name is {}, and I am {}.'.format(self.name, self.age))
class Student(Person):
def __init__(self, name, age, graduationYear):
super().__init__(name, age)
... |
lines = input().split()
stocks = {}
while(lines != ['buy']):
product = lines[0]
price = float(lines[1])
quantity = float(lines[2])
if product not in stocks:
stocks[product] = [price, quantity]
elif product in stocks and stocks[product][0] != price:
updated_price = price
upda... | lines = input().split()
stocks = {}
while lines != ['buy']:
product = lines[0]
price = float(lines[1])
quantity = float(lines[2])
if product not in stocks:
stocks[product] = [price, quantity]
elif product in stocks and stocks[product][0] != price:
updated_price = price
update... |
D, T, S = map(int, input().split())
if (D/S) <= T:
print('Yes')
else:
print('No')
| (d, t, s) = map(int, input().split())
if D / S <= T:
print('Yes')
else:
print('No') |
# # Uzd. 3-1 replace a not bad to good (LV end of the words doesn't work ... ????? should find an answer)
# char_1 = input("Enter the sentence (example: this ship is not bad): ") # Enter a sentence
# no_chr = "not" # 1st Variable for search and exchange
# bad_chr = "bad" # 2nd Variable for search and exchange
# bad_ch... | no_text = 'nav'
bad_text = 'slikt'
rep_text = 'ir lab'
text = input("Enter any sentence that contains words: 'nav', 'slikts/a': ")
new_text = text.find(no_text)
new_bad_t = text.find(bad_text)
if new_bad_t > -1 and new_text > -1 and (new_text < new_bad_t):
head = text[:new_text]
tail = text[new_bad_t + len(bad_... |
#Loop back to this point once code finishes
loop = 1
while (loop < 10):
# All the questions that the program asks the user
noun = input("Choose a noun: ")
p_noun = input("Choose a plural noun: ")
noun2 = input("Choose a noun: ")
place = input("Name a place: ")
adjective = input("Choose an adjective ... | loop = 1
while loop < 10:
noun = input('Choose a noun: ')
p_noun = input('Choose a plural noun: ')
noun2 = input('Choose a noun: ')
place = input('Name a place: ')
adjective = input('Choose an adjective (Describing word): ')
noun3 = input('Choose a noun: ')
print('---------------------------... |
#Definir variables y otros
print("Ejercicio")
Pasajes=0
#Datos de entrada
a=int(input("Cantidad de alumnos:"))
#Proceso
if a>100:
Pasajes=20*a
elif a>=50:
Pasajes=35*a
elif a>=20:
Pasajes=40*a
elif a<20:
Pasajes=70*a
#Datos de salida
print("El pasaje es de:", Pasajes) | print('Ejercicio')
pasajes = 0
a = int(input('Cantidad de alumnos:'))
if a > 100:
pasajes = 20 * a
elif a >= 50:
pasajes = 35 * a
elif a >= 20:
pasajes = 40 * a
elif a < 20:
pasajes = 70 * a
print('El pasaje es de:', Pasajes) |
#
#
#
def tc_code_include(f):
# include
f.write("// created by tc_code_include() in tc_code_include.py\n")
f.write("#include <stdio.h>\n")
f.write("#include <stdlib.h>\n")
f.write("#include <unistd.h>\n")
f.write("#include <sys/time.h>\n")
f.write("#include <locale.h>\n")
f.write("#inclu... | def tc_code_include(f):
f.write('// created by tc_code_include() in tc_code_include.py\n')
f.write('#include <stdio.h>\n')
f.write('#include <stdlib.h>\n')
f.write('#include <unistd.h>\n')
f.write('#include <sys/time.h>\n')
f.write('#include <locale.h>\n')
f.write('#include <algorithm>\n')
... |
#! /usr/bin/python3
# id-DNA.py
# http://rosalind.info/problems/dna/
dna_file = open('/home/steve/Dropbox/Rosalind/rosalind_dna.txt', 'r')
dna_string = str(dna_file.readlines())
base_count = {"A": 0, "G": 0, "C": 0, "T": 0}
for base in dna_string:
base_count[base] += 1
print(base_count)
| dna_file = open('/home/steve/Dropbox/Rosalind/rosalind_dna.txt', 'r')
dna_string = str(dna_file.readlines())
base_count = {'A': 0, 'G': 0, 'C': 0, 'T': 0}
for base in dna_string:
base_count[base] += 1
print(base_count) |
class Repository( object ):
def __init__( self ):
pass
def add( self, object ):
raise NotImplementedError
def update( self, object ):
raise NotImplementedError
def delete( self, object ):
raise NotImplementedError
def get_by_id( self, object ):
raise NotImplementedError | class Repository(object):
def __init__(self):
pass
def add(self, object):
raise NotImplementedError
def update(self, object):
raise NotImplementedError
def delete(self, object):
raise NotImplementedError
def get_by_id(self, object):
raise NotImplementedEr... |
# Jupyter Lab cpmfog
# Documentation of parameters at https://jupyter-notebook.readthedocs.io/en/stable/config.html
c.NotebookApp.allow_root = True
c.NotebookApp.allow_remote_access = True
c.NotebookApp.ip = '*'
c.NotebookApp.iopub_data_rate_limit = 10000000
c.NotebookApp.token = ''
c.NotebookApp.open_browser = False
... | c.NotebookApp.allow_root = True
c.NotebookApp.allow_remote_access = True
c.NotebookApp.ip = '*'
c.NotebookApp.iopub_data_rate_limit = 10000000
c.NotebookApp.token = ''
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
c.NotebookApp.terminado_settings = {'shell_command': ['/bin/bash']} |
# The `addition()` function takes in two integers and adds them together
def addition(x,y):
outcome = x+y
print(str(x) + "+" + str(y) + "=" + str(outcome))
# The `subtraction()` function takes in two integers and subtracts one from the other
def subtraction(x,y):
outcome = x-y
print(str(x) + "-" + str(y) + "="... | def addition(x, y):
outcome = x + y
print(str(x) + '+' + str(y) + '=' + str(outcome))
def subtraction(x, y):
outcome = x - y
print(str(x) + '-' + str(y) + '=' + str(outcome))
def multiplication(x, y):
outcome = x * y
print(str(x) + '*' + str(y) + '=' + str(outcome))
def division(x, y):
ou... |
# -*- coding: utf-8 -*-
__author__ = 'Docker Registry Contributors'
__copyright__ = 'Copyright 2014 Docker'
__credits__ = []
__license__ = 'Apache 2.0'
__version__ = '0.9.0'
__maintainer__ = __author__
__email__ = 'docker-dev@googlegroups.com'
__status__ = 'Production'
__title__ = 'docker-registry'
__build__ = 0x000... | __author__ = 'Docker Registry Contributors'
__copyright__ = 'Copyright 2014 Docker'
__credits__ = []
__license__ = 'Apache 2.0'
__version__ = '0.9.0'
__maintainer__ = __author__
__email__ = 'docker-dev@googlegroups.com'
__status__ = 'Production'
__title__ = 'docker-registry'
__build__ = 0
__url__ = 'https://github.com/... |
class Road:
def __init__(self, length, width, layer=5):
self.__width = width
self.__length = length
self.layer = layer
def value(self):
return self.__width * self.__length * self.layer * 25
r = Road(5000, 20)
print(r.value(), 'kg')
r_1 = Road(4000, 15, 8)
print(r_1.value(), 'k... | class Road:
def __init__(self, length, width, layer=5):
self.__width = width
self.__length = length
self.layer = layer
def value(self):
return self.__width * self.__length * self.layer * 25
r = road(5000, 20)
print(r.value(), 'kg')
r_1 = road(4000, 15, 8)
print(r_1.value(), 'kg... |
def add_viewer(name, fan_list=None):
if fan_list is None:
fan_list = []
fan_list.append(name)
return fan_list
| def add_viewer(name, fan_list=None):
if fan_list is None:
fan_list = []
fan_list.append(name)
return fan_list |
# illustrates split
line = " Twas brillig and the slithy toves Did gyre and gimble in the wabe ".strip().lower()
words = line.split()
for word in words:
print(word) | line = ' Twas brillig and the slithy toves Did gyre and gimble in the wabe '.strip().lower()
words = line.split()
for word in words:
print(word) |
bike = {
'brand':'bajaj',
'model':'avenger',
'year':'2019',
'engine':"220cc"
}
SEARCH = input("Enter key to be searched: ")
if SEARCH in bike:
print("Yes",SEARCH,"is in the bike dictionary")
else:
print("No",SEARCH,"is in the bike dictionary") | bike = {'brand': 'bajaj', 'model': 'avenger', 'year': '2019', 'engine': '220cc'}
search = input('Enter key to be searched: ')
if SEARCH in bike:
print('Yes', SEARCH, 'is in the bike dictionary')
else:
print('No', SEARCH, 'is in the bike dictionary') |
set1 = {
"Naruto", "Sasuke"
}
set2 = {
"Kakashi", "Obito"
}
print(set1.union(set2))
print(set1)
print(set2)
set2.add("Tobi")
print(set2) | set1 = {'Naruto', 'Sasuke'}
set2 = {'Kakashi', 'Obito'}
print(set1.union(set2))
print(set1)
print(set2)
set2.add('Tobi')
print(set2) |
class ExceptionTemplate(Exception):
def __call__(self, *args):
return self.__class__(*(self.args + args))
def __str__(self):
return ': '.join(self.args) | class Exceptiontemplate(Exception):
def __call__(self, *args):
return self.__class__(*self.args + args)
def __str__(self):
return ': '.join(self.args) |
#!/usr/bin/python3
parens = {
'(': ')',
'[': ']',
'{': '}',
'<': '>'
}
def parse_line(line):
values = {
')': 3,
']': 57,
'}': 1197,
'>': 25137
}
stack = []
for char in line:
if char in parens:
stack.append(char)
... | parens = {'(': ')', '[': ']', '{': '}', '<': '>'}
def parse_line(line):
values = {')': 3, ']': 57, '}': 1197, '>': 25137}
stack = []
for char in line:
if char in parens:
stack.append(char)
elif parens[stack[-1]] == char:
stack.pop()
else:
return v... |
def sma(linedict, n, t, index=1):
sum_of_prices = 0
for i in range((t - n) + 1, t + 1):
sum_of_prices += linedict[i][index]
return sum_of_prices / n
def double_sma(linedict, n1, n2, t, index=1):
sum_of_avgs = 0
for i in range((t - n2) + 1, t + 1):
sum_of_avgs += sma(linedict, n1, ... | def sma(linedict, n, t, index=1):
sum_of_prices = 0
for i in range(t - n + 1, t + 1):
sum_of_prices += linedict[i][index]
return sum_of_prices / n
def double_sma(linedict, n1, n2, t, index=1):
sum_of_avgs = 0
for i in range(t - n2 + 1, t + 1):
sum_of_avgs += sma(linedict, n1, i, ind... |
#! /usr/bin/python
def lcm (a,b):
return (a*b)/gcd(b, a%b)
def gcd (a,b):
while b:
a, b = b, a%b
return a
def gcd_understand (a,b):
if(a == 0 and b == 0):
return 0
elif(b == 0):
return a
elif(a == 0):
return b
else:
return gcd(b, a%b)
| def lcm(a, b):
return a * b / gcd(b, a % b)
def gcd(a, b):
while b:
(a, b) = (b, a % b)
return a
def gcd_understand(a, b):
if a == 0 and b == 0:
return 0
elif b == 0:
return a
elif a == 0:
return b
else:
return gcd(b, a % b) |
#
# PySNMP MIB module TPLINK-LLDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-LLDP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
count_arr = [0] * 60
result = 0
for t in time:
remainder = t % 60
complement = (60 - remainder) % 60
result += count_arr[complement]
count_arr[remainder] += 1
retu... | class Solution:
def num_pairs_divisible_by60(self, time: List[int]) -> int:
count_arr = [0] * 60
result = 0
for t in time:
remainder = t % 60
complement = (60 - remainder) % 60
result += count_arr[complement]
count_arr[remainder] += 1
... |
'''
eleting a Table Completely
You're now going to practice dropping individual tables from a database with the .drop() method, as well as all tables in a database with the .drop_all() method!
As Spider-Man's Uncle Ben (as well as Jason, in the video!) said: With great power, comes great responsibility. Do be careful... | """
eleting a Table Completely
You're now going to practice dropping individual tables from a database with the .drop() method, as well as all tables in a database with the .drop_all() method!
As Spider-Man's Uncle Ben (as well as Jason, in the video!) said: With great power, comes great responsibility. Do be careful... |
class PathConverter:
regex = '[-/\w]+/'
def to_python(self, value):
return str(value)
def to_url(self, value):
return str(value) | class Pathconverter:
regex = '[-/\\w]+/'
def to_python(self, value):
return str(value)
def to_url(self, value):
return str(value) |
{
"targets": [
{
"target_name": "mitie",
"sources": [
"src/mitie.cc",
"src/entity_extractor.cc",
"src/relation_extractor.cc",
],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"include_dirs": [
"<!(node -e \"require('na... | {'targets': [{'target_name': 'mitie', 'sources': ['src/mitie.cc', 'src/entity_extractor.cc', 'src/relation_extractor.cc'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'include_dirs': ['<!(node -e "require(\'nan\')")', '/usr/local/include/mitie/', 'mitie/dlib/'], 'link_settings': {'libraries': ['-... |
class Credentials:
'''
class Credentials defines properties of a credential
'''
credentials_list = []
def __init__(self,userAccount,userSite,password):
'''
method init initializes credentials properties
'''
self.userAccount = userAccount
self.userSite = userSite
self.password = passw... | class Credentials:
"""
class Credentials defines properties of a credential
"""
credentials_list = []
def __init__(self, userAccount, userSite, password):
"""
method init initializes credentials properties
"""
self.userAccount = userAccount
self.userSite = userSite
... |
# coding: utf-8
def minmax(data):
''' takes a sequence of one or more numbers'''
min = data[0]
max = data[0]
for val in data:
if val < min:
min = val
elif val > max:
max = val
return min, max
print(minmax([2,56,32,52,34,6,34,6,323,34]))
| def minmax(data):
""" takes a sequence of one or more numbers"""
min = data[0]
max = data[0]
for val in data:
if val < min:
min = val
elif val > max:
max = val
return (min, max)
print(minmax([2, 56, 32, 52, 34, 6, 34, 6, 323, 34])) |
def insertNodeAtHead(llist, data):
if not llist:
return SinglyLinkedListNode(data)
head = SinglyLinkedListNode(data)
head.next = llist
return head
| def insert_node_at_head(llist, data):
if not llist:
return singly_linked_list_node(data)
head = singly_linked_list_node(data)
head.next = llist
return head |
def petMove():
pet.moveXY(50, 21)
pet.on("spawn", petMove)
hero.moveXY(50, 12)
| def pet_move():
pet.moveXY(50, 21)
pet.on('spawn', petMove)
hero.moveXY(50, 12) |
def is_leap_year(year):
ret = False
if year % 4 == 0:
if year % 400 == 0:
ret = True
elif year % 100 == 0:
pass
else:
ret = True
return ret
| def is_leap_year(year):
ret = False
if year % 4 == 0:
if year % 400 == 0:
ret = True
elif year % 100 == 0:
pass
else:
ret = True
return ret |
def findTextEditor(context):
text_editors = []
for window in context.window_manager.windows:
for area in window.screen.areas:
if area.type == "TEXT_EDITOR": text_editors.append(area)
return text_editors | def find_text_editor(context):
text_editors = []
for window in context.window_manager.windows:
for area in window.screen.areas:
if area.type == 'TEXT_EDITOR':
text_editors.append(area)
return text_editors |
num1 = int(input("Please enter an integer: "))
num_rem = num1%2
if num_rem == 0:
print("\nThere is no remainder on dividing", num1, "by 2.\n")
else:
print("\nThe remainder of", num1, "divided by 2 is", num1%2, "\n") | num1 = int(input('Please enter an integer: '))
num_rem = num1 % 2
if num_rem == 0:
print('\nThere is no remainder on dividing', num1, 'by 2.\n')
else:
print('\nThe remainder of', num1, 'divided by 2 is', num1 % 2, '\n') |
def count_substring(string, sub_string):
cnt = 0
for c in range(len(string) - len(sub_string) + 1):
if string[c:c+len(sub_string)] == sub_string:
cnt += 1
return cnt
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(s... | def count_substring(string, sub_string):
cnt = 0
for c in range(len(string) - len(sub_string) + 1):
if string[c:c + len(sub_string)] == sub_string:
cnt += 1
return cnt
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(str... |
file = open('aMazeOfTwistyTrampolinesAllAlike_input.txt', 'r')
lines = file.readlines()
instructions = [0] * len(lines)
for i in range(len(lines)):
instructions[i] = int(lines[i].strip())
steps_taken = 0
current_index = 0
while 0 <= current_index < len(lines):
i = current_index
instruction = instructions... | file = open('aMazeOfTwistyTrampolinesAllAlike_input.txt', 'r')
lines = file.readlines()
instructions = [0] * len(lines)
for i in range(len(lines)):
instructions[i] = int(lines[i].strip())
steps_taken = 0
current_index = 0
while 0 <= current_index < len(lines):
i = current_index
instruction = instructions[cu... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
#import SpImport
#OCIO = SpImport.SpComp2("PyOpenColorIO", 2)
c = OCIO.GetCurrentConfig()
cs_to_lin = c.getProcessor(OCIO.Constants.ROLE_COMPOSITING_LOG, OCIO.Constants.ROLE_SCENE_LINEAR)
node = nuke.createNode("ColorLookup... | c = OCIO.GetCurrentConfig()
cs_to_lin = c.getProcessor(OCIO.Constants.ROLE_COMPOSITING_LOG, OCIO.Constants.ROLE_SCENE_LINEAR)
node = nuke.createNode('ColorLookup')
node.setName('sm2_slg_to_ln')
knob = node['lut']
knob.removeKeyAt(0.0)
knob.removeKeyAt(1.0)
node2 = nuke.createNode('ColorLookup')
node2.setName('sm2_ln_to... |
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, name, description, id=0, x=None, y=None):
self.id = id
self.name = name
self.description = description
self.n_to = None
self.s_to = None
se... | class Room:
def __init__(self, name, description, id=0, x=None, y=None):
self.id = id
self.name = name
self.description = description
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
self.x = x
self.y = y
def __str__(se... |
#modul simple
print("modul 'simple' napunjen")
def funkcija1():
print("'funkcija1' je pozvana")
def funkcija2():
print("'funkcija2' je pozvana")
| print("modul 'simple' napunjen")
def funkcija1():
print("'funkcija1' je pozvana")
def funkcija2():
print("'funkcija2' je pozvana") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.