content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
a = 3
b = "true"
c = 1,2,3
print(a) # a+2 and print(a) both use different forms of a, namely int and str
print(b)
print(c)
| a = 3
b = 'true'
c = (1, 2, 3)
print(a)
print(b)
print(c) |
class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
row_max = grid[0] # first row
col_max = [grid[i][0] for i in range(len(grid))] # first col
bottom = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] != 0: botto... | class Solution:
def projection_area(self, grid: List[List[int]]) -> int:
row_max = grid[0]
col_max = [grid[i][0] for i in range(len(grid))]
bottom = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] != 0:
bottom ... |
class Test:
def __init__(self):
self.a = 1
def func1():
pass
test = Test()
print(hasattr(test, 'a'))
print(hasattr(test, 'b'))
print(hasattr(test, 'func1')) | class Test:
def __init__(self):
self.a = 1
def func1():
pass
test = test()
print(hasattr(test, 'a'))
print(hasattr(test, 'b'))
print(hasattr(test, 'func1')) |
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
maxFreq = 0
count = defaultdict(int)
for row in wall:
prefix = 0
for i in range(len(row) - 1):
prefix += row[i]
count[prefix] += 1
maxFreq = max(maxFreq, count[prefix])
return len(wall) - maxFreq... | class Solution:
def least_bricks(self, wall: List[List[int]]) -> int:
max_freq = 0
count = defaultdict(int)
for row in wall:
prefix = 0
for i in range(len(row) - 1):
prefix += row[i]
count[prefix] += 1
max_freq = max(ma... |
class Solution:
# @param A : list of integers
# @param B : list of integers
# @return an integer
def coverPoints(self, A, B):
stepcount = 0
acount = A[0]
bcount = B[0]
for i in range(len(A)-1):
cx = A[i]
cy = B[i]
nx = A[i+1]
... | class Solution:
def cover_points(self, A, B):
stepcount = 0
acount = A[0]
bcount = B[0]
for i in range(len(A) - 1):
cx = A[i]
cy = B[i]
nx = A[i + 1]
ny = B[i + 1]
xdis = abs(cx - nx)
ydis = abs(cy - ny)
... |
# Camiseta: Escreva uma funcao chamada make_shirt() que aceite um tamanho e o texto de uma mensagem que devera' ser estampada na camiseta. A funcao deve exibir uma frase que mostre o tamanho da camiseta e a mensagem estampada.
# ARGUMENTOS POSICIONAIS
def make_shirt(size, msg):
cont = len(msg)
print("=="*20)
... | def make_shirt(size, msg):
cont = len(msg)
print('==' * 20)
print(f"The requested shirt has '{size}' size and '{msg}' as a mensage whit {cont} caracters.".strip())
print('==' * 20)
make_shirt('M', 'Love Python')
make_shirt(size='M', msg='Love Python') |
q = int(input())
for _ in range(q):
n,m,c_lib,c_road = map(int,input().strip().split(' '))
roads = []
for _ in m:
roads.append([int(x) for x in input().strip().split(' ')])
| q = int(input())
for _ in range(q):
(n, m, c_lib, c_road) = map(int, input().strip().split(' '))
roads = []
for _ in m:
roads.append([int(x) for x in input().strip().split(' ')]) |
class Yaku(object):
yaku_id = None
name = ''
han = {'open': None, 'closed': None}
is_yakuman = False
def __init__(self, yaku_id, name, open_value, closed_value, is_yakuman=False):
self.id = yaku_id
self.name = name
self.han = {'open': open_value, 'closed': closed_value}
... | class Yaku(object):
yaku_id = None
name = ''
han = {'open': None, 'closed': None}
is_yakuman = False
def __init__(self, yaku_id, name, open_value, closed_value, is_yakuman=False):
self.id = yaku_id
self.name = name
self.han = {'open': open_value, 'closed': closed_value}
... |
# Solution to exercise Brackets
# http://www.codility.com/train/
def solution(S):
# Create a stack to track what braces are open
stack = []
opposite_braces = {'(': ')',
'{': '}',
'[': ']'}
for i in S:
# Each time a brace is opened, add it to the stack
if i == '(' or i == '{' or i == '[':... | def solution(S):
stack = []
opposite_braces = {'(': ')', '{': '}', '[': ']'}
for i in S:
if i == '(' or i == '{' or i == '[':
stack.append(i)
else:
if len(stack) == 0:
return 0
j = stack.pop()
if not i == opposite_braces[j]:
... |
with open('input.txt') as f:
input = f.read().splitlines()
heights = []
for line in input:
x = []
for digit in line:
x.append(int(digit))
heights.append(x)
# X and Y are swapped in two dimensional array
# Use dedicated function to avoid confusion
def get_value_coordinate(map, coordinate):
... | with open('input.txt') as f:
input = f.read().splitlines()
heights = []
for line in input:
x = []
for digit in line:
x.append(int(digit))
heights.append(x)
def get_value_coordinate(map, coordinate):
x = coordinate[0]
y = coordinate[1]
if x < 0 or y < 0:
return 100
else:
... |
# The parser accepts properties and methods in implementation-specific entities
# although the code generator will disregard them.
#
# This is useful, for example, for linting or for visualizing the meta-model
# even though no code is generated based on these properties and methods.
@implementation_specific
class Som... | @implementation_specific
class Something:
x: int
def do_something(self) -> None:
pass
__book_url__ = 'dummy'
__book_version__ = 'dummy' |
class NullNode:
def __init__(self, parent):
self.parent = parent
def add(self, key, value):
self.parent.grow(key, value)
def search(self, key):
return None
def get_list(self):
return list()
class LeftNullNode(NullNode):
def add(self, key, value):
self.pare... | class Nullnode:
def __init__(self, parent):
self.parent = parent
def add(self, key, value):
self.parent.grow(key, value)
def search(self, key):
return None
def get_list(self):
return list()
class Leftnullnode(NullNode):
def add(self, key, value):
self.pa... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# head pointer will be used for return value
node = head
... | class Solution:
def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode:
node = head
length = 0
while node:
length += 1
node = node.next
if length == 1:
head = head.next
return head
node = head
index = length ... |
def _gen_build_info(name, maven_coords, multi_release_jar):
if not (maven_coords):
return []
rev = native.read_config("selenium", "rev", "unknown")
time = native.read_config("selenium", "timestamp", "unknown")
multi_release = "false"
if multi_release_jar:
multi_release = "true"
... | def _gen_build_info(name, maven_coords, multi_release_jar):
if not maven_coords:
return []
rev = native.read_config('selenium', 'rev', 'unknown')
time = native.read_config('selenium', 'timestamp', 'unknown')
multi_release = 'false'
if multi_release_jar:
multi_release = 'true'
nat... |
res = 0
for i in range(1000):
if i%3==0:
res+=i
continue
if i%5==0:
res+=i
print(res)
| res = 0
for i in range(1000):
if i % 3 == 0:
res += i
continue
if i % 5 == 0:
res += i
print(res) |
class JADocuments(object):
def __init__(self, document):
self.document = document
def appendObjectInDocument(self, objectToAppend, attribute):
attr = self.document.get(attribute, {})
if not attr:
self.document[attribute] = objectToAppend
else:
if isinstanc... | class Jadocuments(object):
def __init__(self, document):
self.document = document
def append_object_in_document(self, objectToAppend, attribute):
attr = self.document.get(attribute, {})
if not attr:
self.document[attribute] = objectToAppend
elif isinstance(self.docu... |
class smtp:
host, port = ('127.0.0.1', 2025)
class database:
dbname = "database.sqlite"
class site:
host, port = ('127.0.0.1', 5000)
debug = False
SECRET_KEY = "<aslkfhaskldfhasklfhaskldfhaskldfhakslfhlaskdf>"
| class Smtp:
(host, port) = ('127.0.0.1', 2025)
class Database:
dbname = 'database.sqlite'
class Site:
(host, port) = ('127.0.0.1', 5000)
debug = False
secret_key = '<aslkfhaskldfhasklfhaskldfhaskldfhakslfhlaskdf>' |
neighbours = {'1': ['2', '3'],
'2': ['1', '3'],
'3': ['2', '4'],
'4': ['1', '3'],
'T': []
}
colors = dict()
for region in neighbours.keys():
colors[region] = 'black'
def is_valid(colors):
for region, region_neighbours in neighbo... | neighbours = {'1': ['2', '3'], '2': ['1', '3'], '3': ['2', '4'], '4': ['1', '3'], 'T': []}
colors = dict()
for region in neighbours.keys():
colors[region] = 'black'
def is_valid(colors):
for (region, region_neighbours) in neighbours.items():
for neighbour in region_neighbours:
if colors[nei... |
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
# GN version: //gpu:skia_runner
'target_name': 'skia_runner',
'typ... | {'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'skia_runner', 'type': 'executable', 'dependencies': ['../../base/base.gyp:base', '../../gpu/command_buffer/command_buffer.gyp:gles2_utils', '../../gpu/gpu.gyp:command_buffer_service', '../../gpu/gpu.gyp:gles2_implementation', '../../gpu/gpu.gyp:gl_in_proc... |
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
command += testshade("-g 2 2 -debug printbackfacing")
# debug output is very verbose, use regexp to filter down to
# only the... | command += testshade('-g 2 2 -debug printbackfacing')
filter_re = 'Need.*globals.*' |
with open("delete.txt", "w") as f:
f.write("Hello World")
f.write("\n")
f.write("Anthony Lister")
f.write("\n")
f.write("more stringy text here!")
f.write("\n")
| with open('delete.txt', 'w') as f:
f.write('Hello World')
f.write('\n')
f.write('Anthony Lister')
f.write('\n')
f.write('more stringy text here!')
f.write('\n') |
initial_card_deck = (
"Ace of Clubs",
"2 of Clubs",
"3 of Clubs",
"4 of Clubs",
"5 of Clubs",
"6 of Clubs",
"7 of Clubs",
"8 of Clubs",
"9 of Clubs",
"10 of Clubs",
"Jack of Clubs",
"Queen of Clubs",
"King of Clubs",
"Ace of Diamonds",
"2 of Diamonds",
"3 ... | initial_card_deck = ('Ace of Clubs', '2 of Clubs', '3 of Clubs', '4 of Clubs', '5 of Clubs', '6 of Clubs', '7 of Clubs', '8 of Clubs', '9 of Clubs', '10 of Clubs', 'Jack of Clubs', 'Queen of Clubs', 'King of Clubs', 'Ace of Diamonds', '2 of Diamonds', '3 of Diamonds', '4 of Diamonds', '5 of Diamonds', '6 of Diamonds', ... |
n = int(input())
tasks = [0] * (n if n >= 3 else 3)
tasks[0] = 0
tasks[1] = 1
for i in range(2, n):
tasks[i] = tasks[i - 1] * 3 + (i - 1) * 2
print(3 ** n - tasks[n - 1]) | n = int(input())
tasks = [0] * (n if n >= 3 else 3)
tasks[0] = 0
tasks[1] = 1
for i in range(2, n):
tasks[i] = tasks[i - 1] * 3 + (i - 1) * 2
print(3 ** n - tasks[n - 1]) |
class Cipher(object):
def __init__(self, map1, map2):
self.trans=str.maketrans(map1,map2)
self.trans2=str.maketrans(map2,map1)
def encode(self, s):
return s.translate(self.trans)
def decode(self, s):
return s.translate(self.trans2) | class Cipher(object):
def __init__(self, map1, map2):
self.trans = str.maketrans(map1, map2)
self.trans2 = str.maketrans(map2, map1)
def encode(self, s):
return s.translate(self.trans)
def decode(self, s):
return s.translate(self.trans2) |
class Base:
def __init__(self):
print("Base initializer")
def f(self):
print("Base.f()")
class Sub(Base):
def __init__(self):
super().__init__()
print("Sub initializer")
def f(self):
print("Sub.f()")
def main():
b = Base()
b.f()
s = Sub()
s... | class Base:
def __init__(self):
print('Base initializer')
def f(self):
print('Base.f()')
class Sub(Base):
def __init__(self):
super().__init__()
print('Sub initializer')
def f(self):
print('Sub.f()')
def main():
b = base()
b.f()
s = sub()
s.f... |
#!/usr/bin/env python3
class rec:
pass
rec.name = 'Bob'
rec.age = 40
print(rec.name)
x = rec()
y = rec()
print(x.name, y.name)
x.name = 'Sue'
print(x.name, y.name, rec.name)
print(list(rec.__dict__.keys()))
l = [name for name in rec.__dict__ if not name.startswith('__')]
print(l)
print(list(x.__dict__.keys... | class Rec:
pass
rec.name = 'Bob'
rec.age = 40
print(rec.name)
x = rec()
y = rec()
print(x.name, y.name)
x.name = 'Sue'
print(x.name, y.name, rec.name)
print(list(rec.__dict__.keys()))
l = [name for name in rec.__dict__ if not name.startswith('__')]
print(l)
print(list(x.__dict__.keys()))
print(list(y.__dict__.keys(... |
def uppercase(string):
list = []
for i in string:
list.append(i.capitalize())
list = " ".join(list)
return list
string = input().split(" ")
print(uppercase(string))
| def uppercase(string):
list = []
for i in string:
list.append(i.capitalize())
list = ' '.join(list)
return list
string = input().split(' ')
print(uppercase(string)) |
#!/usr/bin/env python3
#Author: Stefan Toman
if __name__ == '__main__':
n = int(input())
t = tuple(map(int, input().split()))
print(hash(t))
| if __name__ == '__main__':
n = int(input())
t = tuple(map(int, input().split()))
print(hash(t)) |
#Reverse string by splitting a string by 1 letter
def rev(s):
b = []
print(type(s))
#Split a string for every nth letter
# a = ([s[i:i+n] for i in range(0, len(s), n)])
a = ([s[i:i+1] for i in range(0, len(s), 1)])
print(a)
print(len(a))
for i in range(len(a)):
b.append(a[i-1])
... | def rev(s):
b = []
print(type(s))
a = [s[i:i + 1] for i in range(0, len(s), 1)]
print(a)
print(len(a))
for i in range(len(a)):
b.append(a[i - 1])
print(b)
rev('aksfgakfgajkfgajkfgaf') |
def rand7():
pass
class Solution:
def rand10(self):
c = rand7() * 7 + rand7() - 8
if c < 40:
return (c % 10) + 1
# Here c ~ [40..48]
# Thus (c % 10) ~ [0..8]
# Thus e ~ [0..62]
e = (c % 10)*7 + rand7() - 1
if e < 60:
return... | def rand7():
pass
class Solution:
def rand10(self):
c = rand7() * 7 + rand7() - 8
if c < 40:
return c % 10 + 1
e = c % 10 * 7 + rand7() - 1
if e < 60:
return e % 10 + 1
return self.rand10() |
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
pushed = collections.deque(pushed)
stack = []
for x in popped:
if len(stack) > 0 and x == stack[-1]:
stack.pop()
continue
while len(pushed... | class Solution:
def validate_stack_sequences(self, pushed: List[int], popped: List[int]) -> bool:
pushed = collections.deque(pushed)
stack = []
for x in popped:
if len(stack) > 0 and x == stack[-1]:
stack.pop()
continue
while len(pushe... |
#Oppretter en funksjon som beregner antall celsius fra fahrenheit som argument.
def celsius(fahrenheit):
celsius = round((fahrenheit-32)*(5/9),1) #Beregner celsius og runder av til ett desimal.
print(fahrenheit, "fahrenheit er lik ", celsius, "celsius.")
#Kaller funksjonen med brukerens input som argument.
cel... | def celsius(fahrenheit):
celsius = round((fahrenheit - 32) * (5 / 9), 1)
print(fahrenheit, 'fahrenheit er lik ', celsius, 'celsius.')
celsius(int(input('Skriv inn antall fahrenheit: '))) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file was part of Flask-Bootstrap and was modified under the terms of
# its BSD License. Copyright (c) 2013, Marc Brinkmann. All rights reserved.
#
# This file was part of Bootstrap-Flask and was modified under the terms of
# its MIT License. Copyright (c) 2018 Grey ... | def test_sample_request(app, client):
@app.get('/sample')
def sample():
return 'OK'
r = client.get('/sample')
assert r.status_code == 200
assert r.data == b'OK' |
f = open('input.txt')
numbers = []
l = 1492208709
numbers = []
for line in f:
numbers.append(int(line[:-1]))
flag = False
for i in range(len(numbers)):
if flag: break
su = numbers[i]
mi = numbers[i]
ma = numbers[i]
for j in range(i+1, len(numbers)):
su += numbers[j]
if number... | f = open('input.txt')
numbers = []
l = 1492208709
numbers = []
for line in f:
numbers.append(int(line[:-1]))
flag = False
for i in range(len(numbers)):
if flag:
break
su = numbers[i]
mi = numbers[i]
ma = numbers[i]
for j in range(i + 1, len(numbers)):
su += numbers[j]
if ... |
#!/usr/bin/env python
# data should have the value of the directory where all of the data is stored.
# Example of data value for dataset: 'data': '/work/csesd/pnnguyen/schnablelab/HCCtools/compressDatasetWorkflow/test_data/*'
file_paths = {'data': '/work/csesd/pnnguyen/schnablelab/HCCtools/compressDatasetWorkflow/tes... | file_paths = {'data': '/work/csesd/pnnguyen/schnablelab/HCCtools/compressDatasetWorkflow/test_data/*'}
use_anonymous = True |
inp = input("Type your mathematical sentence here:\n")
def tokenize(inp):
chars = list(inp)
clean_chars = []
number = ""
for i in chars:
if i.isdigit():
number += i
elif i == "+" or i == "-":
if number != "":
clean_chars.append(number)
clean_chars.append(i)
number = ""
else:
... | inp = input('Type your mathematical sentence here:\n')
def tokenize(inp):
chars = list(inp)
clean_chars = []
number = ''
for i in chars:
if i.isdigit():
number += i
elif i == '+' or i == '-':
if number != '':
clean_chars.append(number)
... |
def print_rangoli(size):
row = (2*size)-1
col = (row * 2) - 1
charater = size + 96
#ascending
for i in range(1, (row//2)+1):
in_row = []
for x in range(i):
in_row.append(chr(charater-x))
for x in reversed(range(i-1)):
in_row.append(chr(charater-x... | def print_rangoli(size):
row = 2 * size - 1
col = row * 2 - 1
charater = size + 96
for i in range(1, row // 2 + 1):
in_row = []
for x in range(i):
in_row.append(chr(charater - x))
for x in reversed(range(i - 1)):
in_row.append(chr(charater - x))
pr... |
rid = 'explorer'
endpoint = 'http://node.karbowanec.com:32348'
host = '0.0.0.0'
port = 3001
debug = True
| rid = 'explorer'
endpoint = 'http://node.karbowanec.com:32348'
host = '0.0.0.0'
port = 3001
debug = True |
# -*- coding: utf-8 -*-
{
"name" : "Website LinkedIn Login/Sign-Up",
"summary" : "When the user clicks on Login/Sign-Up, the requested form appears in a very nice Ajax popup, integrated with Facebook, Odoo, Google+, LinkedIn.",
"category" : "Website",
"version" ... | {'name': 'Website LinkedIn Login/Sign-Up', 'summary': 'When the user clicks on Login/Sign-Up, the requested form appears in a very nice Ajax popup, integrated with Facebook, Odoo, Google+, LinkedIn.', 'category': 'Website', 'version': '1.0', 'author': 'Krishnaram.S', 'license': 'AGPL-3', 'website': 'https://www.techver... |
print('====== DESAFIO 08 ======')
n = float(input('Digite o valor em metros: '))
km = n / 1000
hm = n / 100
dam = n / 10
dm = n * 10
cm = n * 100
mm = n * 1000
print('''O medida de {}m corresponde a
{}km
{}hm
{}dam
{}dm
{}cm
{}mm'''.format(n, km, hm, dam, dm, cm, mm))
| print('====== DESAFIO 08 ======')
n = float(input('Digite o valor em metros: '))
km = n / 1000
hm = n / 100
dam = n / 10
dm = n * 10
cm = n * 100
mm = n * 1000
print('O medida de {}m corresponde a\n{}km\n{}hm\n{}dam\n{}dm\n{}cm\n{}mm'.format(n, km, hm, dam, dm, cm, mm)) |
IMPLICITS = {
"memory_dict": "DictAccess*",
"msize": None,
"pedersen_ptr": "HashBuiltin*",
"range_check_ptr": None,
"syscall_ptr": "felt*",
"bitwise_ptr": "BitwiseBuiltin*",
"exec_env": "ExecutionEnvironment*",
}
IMPLICITS_SET = set(IMPLICITS.keys())
def print_implicit(name):
type_ = ... | implicits = {'memory_dict': 'DictAccess*', 'msize': None, 'pedersen_ptr': 'HashBuiltin*', 'range_check_ptr': None, 'syscall_ptr': 'felt*', 'bitwise_ptr': 'BitwiseBuiltin*', 'exec_env': 'ExecutionEnvironment*'}
implicits_set = set(IMPLICITS.keys())
def print_implicit(name):
type_ = IMPLICITS.get(name, None)
if ... |
def miniMaxSum(arr):
arr.sort()
tot = 0
for num in arr:
tot += num
print(tot-arr[4], tot-arr[0])
| def mini_max_sum(arr):
arr.sort()
tot = 0
for num in arr:
tot += num
print(tot - arr[4], tot - arr[0]) |
#flags to distinguish objects
FLAGS = {
"F_ROCKET" : 1,
"F_ALIEN" : 2,
"F_KIT" : 3,
"F_LASER" : 4,
"F_BALL" : 5} | flags = {'F_ROCKET': 1, 'F_ALIEN': 2, 'F_KIT': 3, 'F_LASER': 4, 'F_BALL': 5} |
# read the input.txt
def read_dossier():
# store information
articles = {'Authors': [], 'Date': [], 'SOURCE': [], 'TEXT': []}
# open file
dossier = open('Steele_dossier.txt', 'r',
encoding='ascii', errors='ignore').read()
# split the individual texts
texts = dossier.split("---... | def read_dossier():
articles = {'Authors': [], 'Date': [], 'SOURCE': [], 'TEXT': []}
dossier = open('Steele_dossier.txt', 'r', encoding='ascii', errors='ignore').read()
texts = dossier.split('-----------------------------------------------------------------------------------')
for t in range(len(texts))... |
####################################
# Author: "BALAVIGNESH" #
# Maintainer: "BALAVIGNESH" #
# License: "CC0 1.0 Universal" #
# Date: "10/05/2021" #
####################################
class Calculator:
def add(*args):
return sum(args)
def multiply(*args):
... | class Calculator:
def add(*args):
return sum(args)
def multiply(*args):
result = 1
for x in args:
result *= x
return result
class Calculatorpool:
_instance_pool = []
def __call__(cls, size):
for x in range(size):
cls._instance_pool.appe... |
class Tile:
def __init__(self, x, y):
'''A black tile'''
self.x = x
self.y = y
def display(self, color):
'''Draws the tile'''
if color == "B":
fill(0)
elif color == "W":
fill(255)
ellipse(self.x, self.y, 90, 90)
| class Tile:
def __init__(self, x, y):
"""A black tile"""
self.x = x
self.y = y
def display(self, color):
"""Draws the tile"""
if color == 'B':
fill(0)
elif color == 'W':
fill(255)
ellipse(self.x, self.y, 90, 90) |
msg= '68 65 32 30 32 32 7b 74 68 31 73 5f 30 6e 33 5f 31 73 5f 72 33 33 33 33 6c 79 5f 73 31 6d 70 6c 33 7d'
res = ''
for n in msg.split(' '):
res += chr(int(n,16))
print(res)
| msg = '68 65 32 30 32 32 7b 74 68 31 73 5f 30 6e 33 5f 31 73 5f 72 33 33 33 33 6c 79 5f 73 31 6d 70 6c 33 7d'
res = ''
for n in msg.split(' '):
res += chr(int(n, 16))
print(res) |
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
mp = {}
for i in cpdomains:
lst = i.split()
cnt = int(lst[0])
domains = lst[1].split('.')
domain = ''
for j, val in enumerate(reversed(domains)):
... | class Solution:
def subdomain_visits(self, cpdomains: List[str]) -> List[str]:
mp = {}
for i in cpdomains:
lst = i.split()
cnt = int(lst[0])
domains = lst[1].split('.')
domain = ''
for (j, val) in enumerate(reversed(domains)):
... |
file1 = open('passwordPhilosophy_input.txt', 'r')
lines_read = file1.readlines()
old_valid_count = 0
new_valid_count = 0
def is_valid_old(letter_rule, test_password):
my_tuple = letter_rule.split(" ")
total_range = my_tuple[0]
letter = my_tuple[1]
min_max = total_range.split("-")
minimum = int(min... | file1 = open('passwordPhilosophy_input.txt', 'r')
lines_read = file1.readlines()
old_valid_count = 0
new_valid_count = 0
def is_valid_old(letter_rule, test_password):
my_tuple = letter_rule.split(' ')
total_range = my_tuple[0]
letter = my_tuple[1]
min_max = total_range.split('-')
minimum = int(min_... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator:
# @param root, a binary search tree's root node
def __init__(self, root):
self.curt = root
self.stack = []
# ... | class Bstiterator:
def __init__(self, root):
self.curt = root
self.stack = []
def has_next(self):
return self.curt or len(self.stack) != 0
def next(self):
curt = self.curt
stack = self.stack
while curt:
stack.append(curt)
curt = curt... |
def power(x):
return x * x
def power2(x, n):
s = 1
while n > 0:
n = n -1
s = s * x
return s
def main():
x = input()
x = int(x)
print(power(x))
print('\n power2: \n',power2(x, 3))
if __name__ == "__main__":
main()
| def power(x):
return x * x
def power2(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
def main():
x = input()
x = int(x)
print(power(x))
print('\n power2: \n', power2(x, 3))
if __name__ == '__main__':
main() |
class o:
"For classes that are mostly data stores, with few (or no) methods."
def __init__(i, **d): i.__dict__.update(d)
def __repr__(i): return i.__class__.__name__ + str(
{k: v for k, v in sorted(i.__dict__.items()) if k[0] != "_"})
def _so(name, d, f):
d, f = d.__dict__, f.__dict__
k = globals()[nam... | class O:
"""For classes that are mostly data stores, with few (or no) methods."""
def __init__(i, **d):
i.__dict__.update(d)
def __repr__(i):
return i.__class__.__name__ + str({k: v for (k, v) in sorted(i.__dict__.items()) if k[0] != '_'})
def _so(name, d, f):
(d, f) = (d.__dict__, f.... |
# Write a function that takes in a string of one or more words,
# and returns the same string, but with all five or more letter words reversed
# (Just like the name of this Kata). Strings passed in will consist of only letters and spaces.
# Spaces will be included only when more than one word is present.
# Exa... | def spin_words(sentence):
revrese = []
words = sentence.split(' ')
for word in words:
if len(word) >= 5:
revrese.append(word[::-1])
else:
revrese.append(word)
return ' '.join((str(i) for i in revrese)) |
def can_build(env, platform):
# should probably change this to only be true on iOS and Android
return False
def configure(env):
pass
def get_doc_classes():
return [
"MobileVRInterface",
]
def get_doc_path():
return "doc_classes"
| def can_build(env, platform):
return False
def configure(env):
pass
def get_doc_classes():
return ['MobileVRInterface']
def get_doc_path():
return 'doc_classes' |
def get_data():
return [[\
[0,0,3,0,2,0,6,0,0],\
[9,0,0,3,0,5,0,0,1],\
[0,0,1,8,0,6,4,0,0],\
[0,0,8,1,0,2,9,0,0],\
[7,0,0,0,0,0,0,0,8],\
[0,0,6,7,0,8,2,0,0],\
[0,0,2,6,0,9,5,0,0],\
[8,0,0,2,0,3,0,0,9],\
[0,0,5,0,1,0,3,0,0]\
],[\
[2,0,0,0,8,0,3,0,0],\
[0,6,0,0,7,0,0,8,4],\
[0,3,0,5,0,0,2,0,9],\
[0,0,0,1,0... | def get_data():
return [[[0, 0, 3, 0, 2, 0, 6, 0, 0], [9, 0, 0, 3, 0, 5, 0, 0, 1], [0, 0, 1, 8, 0, 6, 4, 0, 0], [0, 0, 8, 1, 0, 2, 9, 0, 0], [7, 0, 0, 0, 0, 0, 0, 0, 8], [0, 0, 6, 7, 0, 8, 2, 0, 0], [0, 0, 2, 6, 0, 9, 5, 0, 0], [8, 0, 0, 2, 0, 3, 0, 0, 9], [0, 0, 5, 0, 1, 0, 3, 0, 0]], [[2, 0, 0, 0, 8, 0, 3, 0, 0],... |
# Finding Bell Number using Summation of Sterling's Numbers
def Sterling(N, k):
if n == 0 or k == 0 or k > n:
return 0
if k == 1 or n == k:
return 1
else :
return k*Sterling(N-1, k) + Sterling(N-1, k-1)
def BellNumbers(N):
PARTITIONS = 1
for i in range(N):
... | def sterling(N, k):
if n == 0 or k == 0 or k > n:
return 0
if k == 1 or n == k:
return 1
else:
return k * sterling(N - 1, k) + sterling(N - 1, k - 1)
def bell_numbers(N):
partitions = 1
for i in range(N):
partitions += sterling(N, i)
return PARTITIONS
main_set = ... |
URL_RAW = 'http://www.rda.gov.lk/source/rda_roads.htm'
RAW_HTML_FILE = 'data/raw.html'
ROADS_FILE = 'data/roads.tsv'
GRAPH_PLACES_FILE = 'data/graph.places.json'
GRAPH_ROADS_FILE = 'data/graph.roads.json'
MAP_FILE = 'data/map.svg'
STYLE_PLACE_CIRCLE = dict(
r=6,
fill='white',
stroke='gray',
stroke_wid... | url_raw = 'http://www.rda.gov.lk/source/rda_roads.htm'
raw_html_file = 'data/raw.html'
roads_file = 'data/roads.tsv'
graph_places_file = 'data/graph.places.json'
graph_roads_file = 'data/graph.roads.json'
map_file = 'data/map.svg'
style_place_circle = dict(r=6, fill='white', stroke='gray', stroke_width=3)
style_place_t... |
'''
Greatest common divisor
input :
no = list integers
output :
GCD of those integers
'''
no = input().split()
a = int(no[0])
b = int(no[1])
assert (a >= 0 and b >= 0), "a,b should be >= 0"
def gcd(a, b):
if (a > b):
while (b != 0):
a, b = b, a % b
return a
print ... | """
Greatest common divisor
input :
no = list integers
output :
GCD of those integers
"""
no = input().split()
a = int(no[0])
b = int(no[1])
assert a >= 0 and b >= 0, 'a,b should be >= 0'
def gcd(a, b):
if a > b:
while b != 0:
(a, b) = (b, a % b)
return a
print(gcd(a,... |
# 1
# 2 1
# 3 2 1
# 4 3 2 1
# 5 4 3 2 1
noOfRows=5
for row in range(0,noOfRows):
for col in range(row+1,0,-1):
print(col, end=' ')
print() | no_of_rows = 5
for row in range(0, noOfRows):
for col in range(row + 1, 0, -1):
print(col, end=' ')
print() |
_base_ = ['./slowfast_r50_4x16x1_256e_kinetics400_rgb.py']
model = dict(
backbone=dict(
resample_rate=4, # tau
speed_ratio=4, # alpha
channel_ratio=8, # beta_inv
slow_pathway=dict(fusion_kernel=7)))
work_dir = './work_dirs/slowfast_r50_3d_8x8x1_256e_kinetics400_rgb'
| _base_ = ['./slowfast_r50_4x16x1_256e_kinetics400_rgb.py']
model = dict(backbone=dict(resample_rate=4, speed_ratio=4, channel_ratio=8, slow_pathway=dict(fusion_kernel=7)))
work_dir = './work_dirs/slowfast_r50_3d_8x8x1_256e_kinetics400_rgb' |
# -*- coding: utf-8 -*-
__all__ = ('safestr', 'strictstr')
def safestr(data, encoding='utf8'):
if isinstance(data, str):
return data
try:
try:
if isinstance(data, bytes):
data = str(data, encoding, 'replace')
else:
data = str(data)
except UnicodeError:
data = repr(data)
except Exception as... | __all__ = ('safestr', 'strictstr')
def safestr(data, encoding='utf8'):
if isinstance(data, str):
return data
try:
try:
if isinstance(data, bytes):
data = str(data, encoding, 'replace')
else:
data = str(data)
except UnicodeError:
... |
f = open('input.txt', 'r')
valid = 0
for line in f.readlines():
parts = line.strip().split()
ranges = parts[0].split('-')
minN = int(ranges[0])
maxN = int(ranges[1])
letter = parts[1].split(':')[0]
password = parts[2]
count = password.count(letter)
print(minN, maxN, letter, password, co... | f = open('input.txt', 'r')
valid = 0
for line in f.readlines():
parts = line.strip().split()
ranges = parts[0].split('-')
min_n = int(ranges[0])
max_n = int(ranges[1])
letter = parts[1].split(':')[0]
password = parts[2]
count = password.count(letter)
print(minN, maxN, letter, password, c... |
class LevelCodes:
__parsedLevelCodes = None
def __init__(self, path):
file_io = open(path)
raw_level_codes = file_io.readlines()
self.__parsedLevelCodes = dict()
for line in raw_level_codes:
parsed = line.strip().split(" ")
self.__parsedLevelCodes[int(par... | class Levelcodes:
__parsed_level_codes = None
def __init__(self, path):
file_io = open(path)
raw_level_codes = file_io.readlines()
self.__parsedLevelCodes = dict()
for line in raw_level_codes:
parsed = line.strip().split(' ')
self.__parsedLevelCodes[int(p... |
class Item:
def __init__(self, name="", id="", gender="", age="", birth="", constellation="",
height="", weight="", size="", degree="", marriage="", occupational="",
lives="", origin="", area="", payment="", serve_time="", language="",
serve_type="", hobbits="", c... | class Item:
def __init__(self, name='', id='', gender='', age='', birth='', constellation='', height='', weight='', size='', degree='', marriage='', occupational='', lives='', origin='', area='', payment='', serve_time='', language='', serve_type='', hobbits='', characteristic='', message=''):
self.name = ... |
'''
Implementing Linked list data structure with respect to Sentinel element method.
In this program Sentinel element will be a node which is called nil.
For safe programming reasons, nil.val will be None which will return some exceptions if in any part of the program we want to compare it with another node... | """
Implementing Linked list data structure with respect to Sentinel element method.
In this program Sentinel element will be a node which is called nil.
For safe programming reasons, nil.val will be None which will return some exceptions if in any part of the program we want to compare it with another node... |
# NEW
#
class Track:
subjects = {}
| class Track:
subjects = {} |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | class Abstractextensionhandler:
def on_instance_started_event(self):
raise NotImplementedError
def on_instance_activated_event(self):
raise NotImplementedError
def on_artifact_updated_event(self, artifacts_updated_event):
raise NotImplementedError
def on_artifact_update_sched... |
# Code generated by font-to-py.py.
# Font: digi_italic.ttf Char set: .0123456789:
version = '0.26'
def height():
return 30
def max_width():
return 23
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_c... | version = '0.26'
def height():
return 30
def max_width():
return 23
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 63
_font = b'\x12\x00\x0f\xf8\x00\x1f\xfc\x00?\xfc\x00\x1f\xfb\x00\x00\x07\x00\x00\x07\x0... |
class HttpMethod:
GET = 'GET'
POST = 'POST'
PUT = 'PUT'
DELETE = 'DELETE'
class HttpStatusCode:
HTTP_100_CONTINUE = 100
HTTP_101_SWITCHING_PROTOCOLS = 101
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_202_ACCEPTED = 202
HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203
HTTP_20... | class Httpmethod:
get = 'GET'
post = 'POST'
put = 'PUT'
delete = 'DELETE'
class Httpstatuscode:
http_100_continue = 100
http_101_switching_protocols = 101
http_200_ok = 200
http_201_created = 201
http_202_accepted = 202
http_203_non_authoritative_information = 203
http_204_n... |
class Ball:
def __init__(self):
print("Ball is ready")
def get_class_name(self):
print("Ball")
def play(self):
print("Lets play ball")
class BasketballBall(Ball):
def __init__(self):
# call super() function
super().__init__()
print("Basketball ball is ... | class Ball:
def __init__(self):
print('Ball is ready')
def get_class_name(self):
print('Ball')
def play(self):
print('Lets play ball')
class Basketballball(Ball):
def __init__(self):
super().__init__()
print('Basketball ball is ready')
def get_class_name... |
# Nested List
a=[i for i in range(11)]
b=[i for i in range(11,21)]
c=[b,a]
print(c)
c.sort()
print(c)
# Sorting is done lexographically, i.e. the contents
# of the nested list are not changed | a = [i for i in range(11)]
b = [i for i in range(11, 21)]
c = [b, a]
print(c)
c.sort()
print(c) |
# Optimized Solution
# Time Complexity: O(n) | Space Complexity: O(n)
def arrayOfProducts(array):
resulting_lst = [1] * len(array)
print("resulting_lst = ", resulting_lst)
left_products_lst = [1] * len(array)
print("left_products_lst = ", left_products_lst)
right_products_lst = [1] * len(a... | def array_of_products(array):
resulting_lst = [1] * len(array)
print('resulting_lst = ', resulting_lst)
left_products_lst = [1] * len(array)
print('left_products_lst = ', left_products_lst)
right_products_lst = [1] * len(array)
print('right_products_lst = ', right_products_lst)
left_running_... |
def removeElement(nums, val):
index = 0
for i in nums:
if i == val:
continue
else:
nums[index] = i
index += 1
return index
| def remove_element(nums, val):
index = 0
for i in nums:
if i == val:
continue
else:
nums[index] = i
index += 1
return index |
### Sequence Equation - Solution
def permutationEquation(p):
arr = [0] * len(p)
for i in range(1, len(p)+1):
for j in range(1, len(p)+1):
if p[p[j-1]-1] == i:
arr[i-1] = j
print(*arr, sep='\n')
n = int(input())
p = tuple(map(int, input().split()[:n]))
permutationEquatio... | def permutation_equation(p):
arr = [0] * len(p)
for i in range(1, len(p) + 1):
for j in range(1, len(p) + 1):
if p[p[j - 1] - 1] == i:
arr[i - 1] = j
print(*arr, sep='\n')
n = int(input())
p = tuple(map(int, input().split()[:n]))
permutation_equation(p) |
dataset_type = 'CocoDataset'
classes = ('beading', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog')
data_root = 'data/'
img_norm_cfg = dict(
mean=[123.6... | dataset_type = 'CocoDataset'
classes = ('beading', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog')
data_root = 'data/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.... |
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def get_ratio(a, b):
g = gcd(a, b)
return '{}/{}'.format(a // g, b // g)
_ = int(input())
rings = [int(x) for x in input().split()]
first = rings[0]
for ring in rings[1:]:
print(get_ratio(first, ring)) | def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def get_ratio(a, b):
g = gcd(a, b)
return '{}/{}'.format(a // g, b // g)
_ = int(input())
rings = [int(x) for x in input().split()]
first = rings[0]
for ring in rings[1:]:
print(get_ratio(first, ring)) |
version = "0.8.5"
appDBVersion = 0.70
videoRoot = "/var/www/"
# Build Channel Restream Subprocess Dictionary
restreamSubprocesses = {}
# Build Edge Restream Subprocess Dictionary
activeEdgeNodes = []
edgeRestreamSubprocesses = {}
apiLocation = "http://127.0.0.1"
| version = '0.8.5'
app_db_version = 0.7
video_root = '/var/www/'
restream_subprocesses = {}
active_edge_nodes = []
edge_restream_subprocesses = {}
api_location = 'http://127.0.0.1' |
# numbers = [2,3,1,5]
# min_number = min(numbers)
# max_number = max(numbers)
x = 2
y = 5
min_number = min(x,y)
max_number = max(x,y)
print(min_number)
print(max_number) | x = 2
y = 5
min_number = min(x, y)
max_number = max(x, y)
print(min_number)
print(max_number) |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def glut():
http_archive(
name="glut" ,
build_file="//bazel/deps/glut:build.BUILD" ,
sha256="e1d4e2d38aad559c32985... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def glut():
http_archive(name='glut', build_file='//bazel/deps/glut:build.BUILD', sha256='e1d4e2d38aad559c329859a0dc45c8fc8ff3ec5a1001587d5ca3d7a2b57f9a38', strip_prefix='glut-8cd96cb440f1f2fac3a154227937be39d06efa53', urls=['https://github.com/U... |
d = {'k1': 1, 'k2': 2, 'k3': 3}
d['k10'] = d['k1']
del d['k1']
print(d)
# {'k2': 2, 'k3': 3, 'k10': 1}
d = {'k1': 1, 'k2': 2, 'k3': 3}
print(d.pop('k1'))
# 1
print(d)
# {'k2': 2, 'k3': 3}
d = {'k1': 1, 'k2': 2, 'k3': 3}
d['k10'] = d.pop('k1')
print(d)
# {'k2': 2, 'k3': 3, 'k10': 1}
d = {'k1': 1, 'k2': 2, 'k3':... | d = {'k1': 1, 'k2': 2, 'k3': 3}
d['k10'] = d['k1']
del d['k1']
print(d)
d = {'k1': 1, 'k2': 2, 'k3': 3}
print(d.pop('k1'))
print(d)
d = {'k1': 1, 'k2': 2, 'k3': 3}
d['k10'] = d.pop('k1')
print(d)
d = {'k1': 1, 'k2': 2, 'k3': 3}
print(d.pop('k10', None))
print(d)
def change_dict_key(d, old_key, new_key, default_value=N... |
class Tap():
def __init__(self, client):
self.client = client
def sync(self, query, query_language='ADQL'):
return self.client.post('/tap/sync', {
'QUERY': query,
'LANG': query_language
}, json=False)
| class Tap:
def __init__(self, client):
self.client = client
def sync(self, query, query_language='ADQL'):
return self.client.post('/tap/sync', {'QUERY': query, 'LANG': query_language}, json=False) |
#abc = 'with three people'
#stuff = abc.split()
#print(stuff)
#print(len(stuff))
#for w in stuff:
# print(w)
line = 'first;second;third'
thing = line.split()
print(thing)
print(len(thing))
thing = line.split(';')
print(thing)
print(len(thing))
| line = 'first;second;third'
thing = line.split()
print(thing)
print(len(thing))
thing = line.split(';')
print(thing)
print(len(thing)) |
def rgb(r, g, b):
if r < 0:
r = 0
elif r > 255:
r = 255
if g < 0:
g = 0
elif g > 255:
g = 255
if b < 0:
b = 0
elif b > 255:
b = 255
return ''.join(f'{i:02X}' for i in [r, g, b])
| def rgb(r, g, b):
if r < 0:
r = 0
elif r > 255:
r = 255
if g < 0:
g = 0
elif g > 255:
g = 255
if b < 0:
b = 0
elif b > 255:
b = 255
return ''.join((f'{i:02X}' for i in [r, g, b])) |
# Christina Andrea Putri - Universitas Kristen Duta Wacana
# Anda ingin menginput data diri Anda dan keluarga Anda untuk kepentingan sensus penduduk. Setelah itu untuk memastikan data sudah lengkap, Anda ingin melihat kembali
# data yang Anda input.
# Input : pilihan menu, jml data, data-data yang diperlukan
# Pr... | print('=Data Sensus Penduduk=')
print('Menu : \n 1. Masukkan data \n 2. Cek Data \n 3. Keluar')
inp = 0
handle = open('data.txt', 'w+')
handle.close()
try:
while inp != 3:
inp = int(input('Masukkan menu pilihan Anda:'))
if inp == 1:
inp_sum = int(input('Jumlah data yang ingin dimasukkan:... |
class Solution:
def subtractProductAndSum(self, n: int) -> int:
ans1, ans2 = 1, 0
while n:
tmp = n % 10
n //= 10
ans1 *= tmp
ans2 += tmp
return ans1 - ans2
| class Solution:
def subtract_product_and_sum(self, n: int) -> int:
(ans1, ans2) = (1, 0)
while n:
tmp = n % 10
n //= 10
ans1 *= tmp
ans2 += tmp
return ans1 - ans2 |
def Results(counter,elapsed,Netloc,Path):
#Output of the final result of the program.
print(
f'\n\n\033[38;5;201mNumber of links found: \033[38;5;226m{counter}\033[0m',
f'\n\n\033[38;5;201mTime (seconds):\033[38;5;226m %.4f \033[0m' % (elapsed),
f'\n\n\033[38;5;201mLink URL Root: \033[38;5;226m\033[4m{Netloc}\... | def results(counter, elapsed, Netloc, Path):
print(f'\n\n\x1b[38;5;201mNumber of links found: \x1b[38;5;226m{counter}\x1b[0m', f'\n\n\x1b[38;5;201mTime (seconds):\x1b[38;5;226m %.4f \x1b[0m' % elapsed, f'\n\n\x1b[38;5;201mLink URL Root: \x1b[38;5;226m\x1b[4m{Netloc}\x1b[0m', f'\n\n\x1b[38;5;201mPath file site-map: ... |
class MinMax(object):
def __init__(self,min=None,max=None):
self.min = min
self.max = max
def __str__(self):
return "Min: {:d} Max: {:d}".format(self.min,self.max)
def __repr__(self):
return "<Min: {:d} Max: {:d}>".format(self.min,self.max)
def update(self,val):
if self.min is None:
... | class Minmax(object):
def __init__(self, min=None, max=None):
self.min = min
self.max = max
def __str__(self):
return 'Min: {:d} Max: {:d}'.format(self.min, self.max)
def __repr__(self):
return '<Min: {:d} Max: {:d}>'.format(self.min, self.max)
def update(self, val):
... |
class bird(object):
feather=True
class chicken(bird):
fly=False
def __init__(self,age):
self.age=age
def getAdult(self):
if self.age>1.0:
return True
else:
return False
adult= property(getAdult) #property is built-in
summer=chicken(2)
print(summer.a... | class Bird(object):
feather = True
class Chicken(bird):
fly = False
def __init__(self, age):
self.age = age
def get_adult(self):
if self.age > 1.0:
return True
else:
return False
adult = property(getAdult)
summer = chicken(2)
print(summer.age)
print... |
class GlobalCommands(object):
# so commands can call other commands
def __init__(self):
self.commands = {}
def register(self, cmd, force_name=None):
name = force_name or cmd.callback.__name__
if name in self.commands:
raise Exception()
self.commands[name] = cmd
... | class Globalcommands(object):
def __init__(self):
self.commands = {}
def register(self, cmd, force_name=None):
name = force_name or cmd.callback.__name__
if name in self.commands:
raise exception()
self.commands[name] = cmd
def invoke(self, ctx, cmd, missing_ok... |
get_authors = '''{authors{id name}}'''
bad_get_authors = '''{authors{id name}}}'''
get_authors_siblings = '''
query Siblings($lastName: String!) {
authors(filter: { lastName: $lastName }) {
name
lastName
}
}
'''
get_last_author = '''
{
authors(orderBy:{desc:ID} limit:1){
name
... | get_authors = '{authors{id name}}'
bad_get_authors = '{authors{id name}}}'
get_authors_siblings = '\n query Siblings($lastName: String!) {\n authors(filter: { lastName: $lastName }) {\n name\n lastName\n }\n }\n'
get_last_author = '\n {\n authors(orderBy:{desc:ID} limit:1){\n name\n last... |
n = input()
k = input()
count = 0
for i in n:
if k==i:
count+=1
print(count) | n = input()
k = input()
count = 0
for i in n:
if k == i:
count += 1
print(count) |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
h = {}
ans = i = 0
for j in range(n):
if s[j] in h:
i = max(i, h[s[j]])
ans = max(ans, j - i + 1)
h[s[j]] = j + 1
return ans
| class Solution:
def length_of_longest_substring(self, s: str) -> int:
n = len(s)
h = {}
ans = i = 0
for j in range(n):
if s[j] in h:
i = max(i, h[s[j]])
ans = max(ans, j - i + 1)
h[s[j]] = j + 1
return ans |
class GenyratorError(Exception):
pass
| class Genyratorerror(Exception):
pass |
COLUMNS = [
'tipo_registro',
'nro_pv',
'nro_rv',
'nro_banco',
'nro_agencia',
'nro_conta_corrente',
'dt_rv',
'qtde_cvnsu',
'vl_bruto',
'vl_gorjeta',
'vl_rejeitado',
'vl_desconto',
'vl_liquido',
'dt_credito_primeira_parcela',
'bandeira'
] | columns = ['tipo_registro', 'nro_pv', 'nro_rv', 'nro_banco', 'nro_agencia', 'nro_conta_corrente', 'dt_rv', 'qtde_cvnsu', 'vl_bruto', 'vl_gorjeta', 'vl_rejeitado', 'vl_desconto', 'vl_liquido', 'dt_credito_primeira_parcela', 'bandeira'] |
#!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
"prints a dictionary by ordered keys"
for i in sorted(a_dictionary.keys()):
print("{}: {}".format(i, a_dictionary[i]))
| def print_sorted_dictionary(a_dictionary):
"""prints a dictionary by ordered keys"""
for i in sorted(a_dictionary.keys()):
print('{}: {}'.format(i, a_dictionary[i])) |
def error(e: Exception):
print("error")
print(e)
| def error(e: Exception):
print('error')
print(e) |
class Solution:
def fullJustify(self, words: [str], maxWidth: int) -> [str]:
res = []
cur = []
cnt = 0
for w in words:
if cnt + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - cnt):
cur[i % (len(cur) - 1 or 1)] += ' '
... | class Solution:
def full_justify(self, words: [str], maxWidth: int) -> [str]:
res = []
cur = []
cnt = 0
for w in words:
if cnt + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - cnt):
cur[i % (len(cur) - 1 or 1)] += ' '
... |
# O(n) time complexity
# O(n) space complexity
def reverse1(a):
i = 0
j = len(a)
b = a[:]
while j > 0:
#b.append(a[j - 1]) -> not efficient
b[i] = a[j - 1]
i += 1
j -= 1
return b
# O(n) time complexity
# O(1) space complexity
def reverse2(a... | def reverse1(a):
i = 0
j = len(a)
b = a[:]
while j > 0:
b[i] = a[j - 1]
i += 1
j -= 1
return b
def reverse2(a):
temp = None
i = 0
j = len(a)
half_len = int(j / 2)
for _ in range(half_len):
temp = a[i]
a[i] = a[j - 1]
a[j - 1] = tem... |
# This program reads all of the values in
# the sales.txt file.
def main():
# Open the sales.txt file for reading.
sales_file = open('sales.txt', 'r')
# Read the first line from the file, but
# don't convert to a number yet. We still
# need to test for an empty string.
line = sales_file.readli... | def main():
sales_file = open('sales.txt', 'r')
line = sales_file.readline()
while line != '':
amount = float(line)
print(format(amount, '.2f'))
line = sales_file.readline()
sales_file.close()
main() |
def get_db_uri(dbinfo):
ENGINE = dbinfo.get("ENGINE") or 'mysql'
DRIVER = dbinfo.get("DRIVER") or "pymysql"
USER = dbinfo.get("USER") or "root"
PASSWORD = dbinfo.get("PASSWORD") or "root"
HOST = dbinfo.get("HOST") or "localhost"
PORT = dbinfo.get("PORT") or "3306"
NAME = dbinfo.get("NAME") ... | def get_db_uri(dbinfo):
engine = dbinfo.get('ENGINE') or 'mysql'
driver = dbinfo.get('DRIVER') or 'pymysql'
user = dbinfo.get('USER') or 'root'
password = dbinfo.get('PASSWORD') or 'root'
host = dbinfo.get('HOST') or 'localhost'
port = dbinfo.get('PORT') or '3306'
name = dbinfo.get('NAME') o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.