content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Authenticate via OAuth
client = pytumblr.TumblrRestClient(
'OwkaLncuZlxDpofwTpcfCz87kEIEuWRRjEpl0i2tvRWLpVTeJX',
'QooQH16tPvKNmGjFK5l2fHeMdIyoWd4p6FNkhVlXenivh3fPSt',
'lXZMoziJiSDpEPzJYoHTEhMNFFt12emtiAJfvq6EBMf7bFglSt',
'LGeRorUaZFZeBdfwB7D0sNkp6nCMcr4MNZ455DZ9bjGAhsAQ1e'
)
# Make the request
client.info()
| client = pytumblr.TumblrRestClient('OwkaLncuZlxDpofwTpcfCz87kEIEuWRRjEpl0i2tvRWLpVTeJX', 'QooQH16tPvKNmGjFK5l2fHeMdIyoWd4p6FNkhVlXenivh3fPSt', 'lXZMoziJiSDpEPzJYoHTEhMNFFt12emtiAJfvq6EBMf7bFglSt', 'LGeRorUaZFZeBdfwB7D0sNkp6nCMcr4MNZ455DZ9bjGAhsAQ1e')
client.info() |
'''
Created on Oct 8, 2018
@author: cat_t
'''
class Scoresheet(object):
'''
used for evaluating and scoring worldstates by various metrics
'''
def __init__(self, worldstate):
'''
Constructor
'''
self.world = worldstate
def count_civil_deaths(self... | """
Created on Oct 8, 2018
@author: cat_t
"""
class Scoresheet(object):
"""
used for evaluating and scoring worldstates by various metrics
"""
def __init__(self, worldstate):
"""
Constructor
"""
self.world = worldstate
def count_civil_deaths(self):
pass
... |
# ### LEAP YEARS ###
i_year = int(input("First year: "))
f_year = int(input("Last year: "))
c_year = i_year
while c_year != f_year + 1:
if c_year % 4 == 0:
if c_year % 100 != 0:
print(c_year)
elif c_year % 400 == 0:
print(c_year)
c_year = c_year + 1
if c_year == f_year + 1:
break | i_year = int(input('First year: '))
f_year = int(input('Last year: '))
c_year = i_year
while c_year != f_year + 1:
if c_year % 4 == 0:
if c_year % 100 != 0:
print(c_year)
elif c_year % 400 == 0:
print(c_year)
c_year = c_year + 1
if c_year == f_year + 1:
break |
#!/usr/bin/python3
with open('10_input', 'r') as f:
lines = f.readlines()
nums = [int(l.strip()) for l in lines]
nums = sorted(nums) + [max(nums)+3]
cur = 0
diffs = [0,0,0]
for num in nums:
diff = num - cur
cur = num
diffs[diff-1] += 1
#print(diffs[0])
#print(diffs[2])
print(diffs[0] * diffs[2])
| with open('10_input', 'r') as f:
lines = f.readlines()
nums = [int(l.strip()) for l in lines]
nums = sorted(nums) + [max(nums) + 3]
cur = 0
diffs = [0, 0, 0]
for num in nums:
diff = num - cur
cur = num
diffs[diff - 1] += 1
print(diffs[0] * diffs[2]) |
class Solution:
def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
def ones(x):
return bin(x).count('1')
dp = [0] * (len(s) + 1)
for i in range(1, len(s) + 1):
dp[i] = dp[i - 1] ^ 1 << ord(s[i - 1]) - ord('a')
return [
ones(dp[right + 1] ^ dp[left]) //... | class Solution:
def can_make_pali_queries(self, s: str, queries: List[List[int]]) -> List[bool]:
def ones(x):
return bin(x).count('1')
dp = [0] * (len(s) + 1)
for i in range(1, len(s) + 1):
dp[i] = dp[i - 1] ^ 1 << ord(s[i - 1]) - ord('a')
return [ones(dp[ri... |
def shortestWithBaseCase(makeRecursiveCall):
print('shortestWithBaseCase(%s) called.' % makeRecursiveCall)
if not makeRecursiveCall:
# BASE CASE
print('Returning from base case.')
return
else:
# RECURSIVE CASE
shortestWithBaseCase(False)
print('Returning from ... | def shortest_with_base_case(makeRecursiveCall):
print('shortestWithBaseCase(%s) called.' % makeRecursiveCall)
if not makeRecursiveCall:
print('Returning from base case.')
return
else:
shortest_with_base_case(False)
print('Returning from recursive case.')
return
print(... |
# text details for english texts: https://wiki.cloudmodding.com/oot/Text_Format
# text details for japanese texts: "Messages.py" >> CONTROL_CHARS_JP and IGNORE_CHARS
# ID: text,
# Control codes for japanese: Use double codes(CONTROL_CHARS_JP_1)
# text id details: https://wiki.cloudmodding.com/oot/Text_I... | new_items_x = {1: '', 36865: '', 2: '', 3: '', 4: '', 5: '', 7: '', 8: '', 9: '', 10: '', 11: '', 12: '', 13: '', 14: '', 16: '', 17: '', 18: '', 19: '', 20: '', 21: '', 22: '', 23: '', 48: '', 49: '', 50: '', 51: '', 52: '', 53: '', 54: '', 55: '', 56: '', 57: '', 58: '', 60: '', 61: '', 62: '', 63: '', 64: '', 65: ''... |
# Base settings file. Put all default settings in here, in either single dictionary format if you are using plain SOA
# settings, or in Django format if you are using Django.
SOA_SERVER_SETTINGS = {
'transport': {
'path': 'pysoa.common.transport.http2.server:Http2ServerTransport',
},
'middleware': [... | soa_server_settings = {'transport': {'path': 'pysoa.common.transport.http2.server:Http2ServerTransport'}, 'middleware': []} |
class test():
def add(x, y):
return x + y
| class Test:
def add(x, y):
return x + y |
def main():
a, b = [int(x) for x in input().split()]
count = 1
while True:
a = a * 3
b = b * 2
if a > b:
break
else:
count = count + 1
print(count)
if __name__ == "__main__":
main()
| def main():
(a, b) = [int(x) for x in input().split()]
count = 1
while True:
a = a * 3
b = b * 2
if a > b:
break
else:
count = count + 1
print(count)
if __name__ == '__main__':
main() |
quantity = int(input())
days = int(input())
price_ornament_set = 2
price_tree_skirt = 5
price_tree_garlands = 3
price_tree_lights = 15
total_cost = 0
christmas_spirit = 0
for current_day in range(1, days + 1):
if current_day % 11 == 0:
quantity += 2
if current_day % 10 == 0:
total_cost += (... | quantity = int(input())
days = int(input())
price_ornament_set = 2
price_tree_skirt = 5
price_tree_garlands = 3
price_tree_lights = 15
total_cost = 0
christmas_spirit = 0
for current_day in range(1, days + 1):
if current_day % 11 == 0:
quantity += 2
if current_day % 10 == 0:
total_cost += price_... |
def get_lines():
with open("input.txt") as f:
return [line.strip() for line in f.readlines() if line.strip()]
Lines = get_lines()
Width = len(Lines[0])
Height = len(Lines)
def mathable(stack):
return len(stack) > 2 and isinstance(stack[len(stack) - 3], int) and (stack[len(stack) - 2] == "+" o... | def get_lines():
with open('input.txt') as f:
return [line.strip() for line in f.readlines() if line.strip()]
lines = get_lines()
width = len(Lines[0])
height = len(Lines)
def mathable(stack):
return len(stack) > 2 and isinstance(stack[len(stack) - 3], int) and (stack[len(stack) - 2] == '+' or stack[le... |
#
# PySNMP MIB module CYAN-DTM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CYAN-DTM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:18:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) ... |
jfdb = open("jfdbTrim.txt", mode="r", encoding="UTF-8")
cnt = 0
with open("a.txt", mode="w", encoding="UTF-8") as f:
for i in jfdb:
flag = False
for j in open("jcdbTrim.txt", mode="r", encoding="UTF-8"):
if i == j:
flag = True
break
if fla... | jfdb = open('jfdbTrim.txt', mode='r', encoding='UTF-8')
cnt = 0
with open('a.txt', mode='w', encoding='UTF-8') as f:
for i in jfdb:
flag = False
for j in open('jcdbTrim.txt', mode='r', encoding='UTF-8'):
if i == j:
flag = True
break
if flag == Fals... |
def main():
N = int(input())
S = input()
rcs = [0] * N
gcs = [0] * N
bcs = [0] * N
for i in range(N):
if S[i] == 'R':
rcs[i] = 1
elif S[i] == 'G':
gcs[i] = 1
elif S[i] == 'B':
bcs[i] = 1
for i in range(1, N):
rcs[i] += rc... | def main():
n = int(input())
s = input()
rcs = [0] * N
gcs = [0] * N
bcs = [0] * N
for i in range(N):
if S[i] == 'R':
rcs[i] = 1
elif S[i] == 'G':
gcs[i] = 1
elif S[i] == 'B':
bcs[i] = 1
for i in range(1, N):
rcs[i] += rcs[i... |
def refine_INSTALLED_APPS(original):
return ['schnippjs'] + list(original)
| def refine_installed_apps(original):
return ['schnippjs'] + list(original) |
# unpack range object
[*range(1,3)]
# [1,2]
# unpack enumerate
[*enumerate('abc')]
[(0, 'a'), (1, 'b'), (2, 'c')]
# unpack enumerate and turn into dict
dict([*enumerate('abc')])
{0: 'a', 1: 'b', 2: 'c'}
# TODO
# - funct w/ *args
# - funct w/ **kwargs
| [*range(1, 3)]
[*enumerate('abc')]
[(0, 'a'), (1, 'b'), (2, 'c')]
dict([*enumerate('abc')])
{0: 'a', 1: 'b', 2: 'c'} |
f = open('subsir.txt', 'r')
v = [int(i) for i in f.readline().split()]
n = len(v)
lmax = [1 for i in range(n)]
succ = [-1 for i in range(n)]
lmax[n-1] = 0
def gasesteSuccesor(i):
global v, lmax, n
nrMinSuccesor = 1
Succesor = -1
for j in range(i+1, n):
if v[i] <= v[j]:
if... | f = open('subsir.txt', 'r')
v = [int(i) for i in f.readline().split()]
n = len(v)
lmax = [1 for i in range(n)]
succ = [-1 for i in range(n)]
lmax[n - 1] = 0
def gaseste_succesor(i):
global v, lmax, n
nr_min_succesor = 1
succesor = -1
for j in range(i + 1, n):
if v[i] <= v[j]:
if lma... |
# nested1.py
#
# Nested loop Example 1
# the inner loop iterates completely (4 times) for every one iteration
# of the outer loop
# CSC 110
# Fall 2011
for outer in [1, 2, 3]:
print('Outer loop iteration', outer)
for inner in [1, 2, 3, 4]:
print(' Inner loop iteration', inner)
| for outer in [1, 2, 3]:
print('Outer loop iteration', outer)
for inner in [1, 2, 3, 4]:
print(' Inner loop iteration', inner) |
# https://binarysearch.com/problems/Merging-Binary-Trees
class Solution:
def solve(self, node0, node1):
if node0 == None:
return node1
if node1 == None:
return node0
def merge(root0,root1):
if root0 == None or root1 == None:
retur... | class Solution:
def solve(self, node0, node1):
if node0 == None:
return node1
if node1 == None:
return node0
def merge(root0, root1):
if root0 == None or root1 == None:
return
if root0.left == None:
root0.left ... |
def quadratic(a, b, c):
d = b**2 - 4*a*c
if d < 0:
return "This equation has 2 complex roots."
elif d > 0:
return "This equation has 2 real roots."
else:
return "This equation has 1 real root."
print(quadratic(1,2,3))
print(quadratic(1,3,2))
print(quadratic(1,4,4))
| def quadratic(a, b, c):
d = b ** 2 - 4 * a * c
if d < 0:
return 'This equation has 2 complex roots.'
elif d > 0:
return 'This equation has 2 real roots.'
else:
return 'This equation has 1 real root.'
print(quadratic(1, 2, 3))
print(quadratic(1, 3, 2))
print(quadratic(1, 4, 4)) |
all_notes = [0] * 11
command = input()
while command != "End":
command = command.split("-")
importance = int(command[0])
current_note = command[1]
all_notes[importance] = current_note
command = input()
# sorted_notes = [i for i in all_notes if i != 0]
sorted_notes = list(filter(lambda x: x != ... | all_notes = [0] * 11
command = input()
while command != 'End':
command = command.split('-')
importance = int(command[0])
current_note = command[1]
all_notes[importance] = current_note
command = input()
sorted_notes = list(filter(lambda x: x != 0, all_notes))
print(sorted_notes) |
max_length = 20
batch_size = 16
learning_rate = 2e-5
number_of_epochs = 1
training_file_name = 'train.csv'
testing_file_name = 'test.csv' | max_length = 20
batch_size = 16
learning_rate = 2e-05
number_of_epochs = 1
training_file_name = 'train.csv'
testing_file_name = 'test.csv' |
# Using recursion
def sum_digits(n):
if n < 0:
ValueError("Inputs 0 or greater only!")
elif n < 10:
return n
else:
last_digit = n % 10
return last_digit + sum_digits(n // 10)
# Using iteration
## Linear - O(N), where "N" is the number of digits in the number
# def sum_digits(n):
# if n < 0:
# ... | def sum_digits(n):
if n < 0:
value_error('Inputs 0 or greater only!')
elif n < 10:
return n
else:
last_digit = n % 10
return last_digit + sum_digits(n // 10) |
class PartOne:
def load_data(self, filename):
with open(filename) as f:
lines = f.readlines()
groups = []
group = []
for line in lines:
line = line.replace("\n", "")
if line == "":
groups.append(group)
group = ... | class Partone:
def load_data(self, filename):
with open(filename) as f:
lines = f.readlines()
groups = []
group = []
for line in lines:
line = line.replace('\n', '')
if line == '':
groups.append(group)
group = []
... |
def max_2(a, b):
if a > b:
return a
else:
return b
def max_3(a, b, c):
x = max_2(a, b)
return max_2(x, c)
| def max_2(a, b):
if a > b:
return a
else:
return b
def max_3(a, b, c):
x = max_2(a, b)
return max_2(x, c) |
def str_split(string, idx=0, typ=str):
return typ(string.split()[idx])
def str_split_multi(string, idx=None, typ=None):
if idx is None:
idx = []
if typ is None:
typ = []
col = string.split()
return [typ[j](col[i]) for j, i in enumerate(idx)]
def identity(obj):
return obj
de... | def str_split(string, idx=0, typ=str):
return typ(string.split()[idx])
def str_split_multi(string, idx=None, typ=None):
if idx is None:
idx = []
if typ is None:
typ = []
col = string.split()
return [typ[j](col[i]) for (j, i) in enumerate(idx)]
def identity(obj):
return obj
def... |
#
# PySNMP MIB module Wellfleet-5000-CHASSIS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-5000-CHASSIS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:32:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
REPO_TYPES = (
('git', 'GIT'),
)
REPO_UPDATES = (
('created', 'Repository created'),
('changed', 'Repository changed'),
('deleted', 'Repository deleted'),
('key_added', 'Key added'),
('key_changed', 'Key changed'),
('key_deleted', 'Key deleted'),
)
REPO_UPDATES_DICT = dict(REPO_UPDATES)
| repo_types = (('git', 'GIT'),)
repo_updates = (('created', 'Repository created'), ('changed', 'Repository changed'), ('deleted', 'Repository deleted'), ('key_added', 'Key added'), ('key_changed', 'Key changed'), ('key_deleted', 'Key deleted'))
repo_updates_dict = dict(REPO_UPDATES) |
# https://www.codewars.com/kata/54e6533c92449cc251001667
def unique_in_order(elems):
prev = None
uniques = []
for elem in elems:
if elem != prev:
uniques.append(elem)
prev = elem
return uniques
| def unique_in_order(elems):
prev = None
uniques = []
for elem in elems:
if elem != prev:
uniques.append(elem)
prev = elem
return uniques |
x = 10
while x >= 0:
print(x)
x = x - 1
print('Fogo')
| x = 10
while x >= 0:
print(x)
x = x - 1
print('Fogo') |
'''
The ESGF PID system relies on a RabbitMQ instance consisting
of various exchanges and queues. Messages are routed to
these queues using routing keys.
This file contains the various routing keys that are used.
The esgfpid library uses routing keys for topic exchanges,
consisting of four "words" (separated by dots)... | """
The ESGF PID system relies on a RabbitMQ instance consisting
of various exchanges and queues. Messages are routed to
these queues using routing keys.
This file contains the various routing keys that are used.
The esgfpid library uses routing keys for topic exchanges,
consisting of four "words" (separated by dots)... |
i = 4
d = 4.0
s = 'HackerRank '
'''Declare second integer, double, and String variables.
Read and save an integer, double, and String to your variables.'''
ii, dd, ss = int(input()), float(input()), input()
'''Print the sum of both integer variables on a new line.
Print the sum of the double variables on a new line.... | i = 4
d = 4.0
s = 'HackerRank '
'Declare second integer, double, and String variables.\nRead and save an integer, double, and String to your variables.'
(ii, dd, ss) = (int(input()), float(input()), input())
"Print the sum of both integer variables on a new line.\nPrint the sum of the double variables on a new line.\nC... |
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return '{} says {}'.format(self.name, self.sound())
class Cow(Animal):
def sound(self):
return 'moooo'
class Horse(Animal):
def sound(self):
return 'neigh'
class Sheep(Animal):
def sound(self... | class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return '{} says {}'.format(self.name, self.sound())
class Cow(Animal):
def sound(self):
return 'moooo'
class Horse(Animal):
def sound(self):
return 'neigh'
class Sheep(Animal):
def sound... |
#print an F
numbers=[5,2,5,2,2]
for x in range(len(numbers)):
for y in range(numbers[x]):
print('*',end='')
print()
#Alternatively
'''
numbers=[5,2,5,2,2]
for x_count in numbers:
output=''
for count in range(x_count):
output+='*'
print(output)
'''
print()
print()
print()
#p... | numbers = [5, 2, 5, 2, 2]
for x in range(len(numbers)):
for y in range(numbers[x]):
print('*', end='')
print()
"\nnumbers=[5,2,5,2,2]\nfor x_count in numbers:\n output=''\n for count in range(x_count):\n output+='*'\n print(output)\n\n "
print()
print()
print()
lnum = [2, 2, 2, 2,... |
# Solution
def dfs_recursion_start(start_node, search_value):
visited = set() # Set to keep track of visited nodes.
return dfs_recursion(start_node, visited, search_value)
# Recursive function
def dfs_recursion(node, visited, search_value):
if node.value == search_value:
found = True ... | def dfs_recursion_start(start_node, search_value):
visited = set()
return dfs_recursion(start_node, visited, search_value)
def dfs_recursion(node, visited, search_value):
if node.value == search_value:
found = True
return node
visited.add(node)
found = False
result = None
fo... |
n = int(input())
lista = list(map(int,input().split()))
lista.sort()
maxval = 0
if n % 2 == 1:
maxval = lista.pop()
n -= 1
listb = lista
for i in range(int(n/2)):
if maxval < lista[i] + listb[n-i-1]:
maxval = lista[i] + listb[n-i-1]
print(maxval) | n = int(input())
lista = list(map(int, input().split()))
lista.sort()
maxval = 0
if n % 2 == 1:
maxval = lista.pop()
n -= 1
listb = lista
for i in range(int(n / 2)):
if maxval < lista[i] + listb[n - i - 1]:
maxval = lista[i] + listb[n - i - 1]
print(maxval) |
time=3
batt=100
read=0
nap=0
north=0
south=1
east=2
west=3
# The Place class has 3 variables: a description, a list of exits and a list of things.
# The description and list of things are passed as parameters when a new Place is created;
# the list of exits is set to None,None,None,None. (An exit can onl... | time = 3
batt = 100
read = 0
nap = 0
north = 0
south = 1
east = 2
west = 3
class Place:
def __init__(self, description, things):
self.description = description
self.exits = [None, None, None, None]
self.things = things
def describe(self):
print()
print(self.description... |
class PeerDIDError(Exception):
pass
class MalformedPeerDIDError(PeerDIDError):
def __init__(self, msg: str) -> None:
super().__init__("Invalid peer DID provided. {}.".format(msg))
class MalformedPeerDIDDocError(PeerDIDError, ValueError):
def __init__(self, msg: str) -> None:
super().__in... | class Peerdiderror(Exception):
pass
class Malformedpeerdiderror(PeerDIDError):
def __init__(self, msg: str) -> None:
super().__init__('Invalid peer DID provided. {}.'.format(msg))
class Malformedpeerdiddocerror(PeerDIDError, ValueError):
def __init__(self, msg: str) -> None:
super().__in... |
#
# PySNMP MIB module NBS-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-STATS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:07:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ... |
sentence='His expression went dark.'
index=-1
print(sentence.split(' ')[index])
noun = sentence.split(' ')[index]
print(noun)
if noun[len(noun)-1]=='.':
noun=noun[:len(noun)-1]
print(noun)
verb=noun+'en'
print(verb)
| sentence = 'His expression went dark.'
index = -1
print(sentence.split(' ')[index])
noun = sentence.split(' ')[index]
print(noun)
if noun[len(noun) - 1] == '.':
noun = noun[:len(noun) - 1]
print(noun)
verb = noun + 'en'
print(verb) |
# -*- coding: utf-8 -*-
neutral = [
'Zer dira 8 Bocabits? BocaByte bat ',
'Zer esaten dio bit batek besteari? Busean ikusten gara!',
'Zer da terapeuta bat? - 1024 Gigapeuta',
'Aita, aita, aita!!! Utziko al didazu telebista iksten? Bai! Baina piztu ez!',
'Matematika liburu batek bere buruaz beste eg... | neutral = ['Zer dira 8 Bocabits? BocaByte bat ', 'Zer esaten dio bit batek besteari? Busean ikusten gara!', 'Zer da terapeuta bat? - 1024 Gigapeuta', 'Aita, aita, aita!!! Utziko al didazu telebista iksten? Bai! Baina piztu ez!', 'Matematika liburu batek bere buruaz beste egin zuen...zergatik? Problema asko zituelako.']... |
def InsertionSort(array):
for i in range(1,len(array)):
#using first element of the array as key then comparing it with other values until smaller value is found,
#that value becomes new key
key=array[i]
# Move elements of arr[0..i-1], that are greater than key, to one posit... | def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j -= 1
array[j + 1] = key
array = [1, 3, 10, 5, 7, 23, 11, 30, 2, 35]
insertion_sort(array)
print('Sorted array is:')
fo... |
def func2():
pass
def func(a):
a()
a = func
b = func2
a(a=b)
| def func2():
pass
def func(a):
a()
a = func
b = func2
a(a=b) |
class Solution:
def winnerOfGame(self, colors: str) -> bool:
if colors.count('A') < 3:
return False
alice = 0
bob = 0
for i in range(1, len(colors)-1):
print(alice, bob)
if colors[i-1] == colors[i] == colors[i+1] == 'A':
al... | class Solution:
def winner_of_game(self, colors: str) -> bool:
if colors.count('A') < 3:
return False
alice = 0
bob = 0
for i in range(1, len(colors) - 1):
print(alice, bob)
if colors[i - 1] == colors[i] == colors[i + 1] == 'A':
al... |
# Jim Lawless
# License: https://github.com/jimlawless/AoC2020/LICENSE
rules=[]
used=""
def searchRules(srch):
global rules
global used
count=0
for rule in rules:
if rule.find(srch) >= 0:
contain=rule.find(" bags contain")
has=rule.find(srch)
i... | rules = []
used = ''
def search_rules(srch):
global rules
global used
count = 0
for rule in rules:
if rule.find(srch) >= 0:
contain = rule.find(' bags contain')
has = rule.find(srch)
if has > contain:
bagtype = rule[0:contain]
... |
{
"targets": [
{
"target_name": "lnplib",
"sources": [ "swig_wrap.cxx" ],
"libraries": [
'-L<(module_root_dir)/../../liblnp/target/release',
'-llnp',
],
"include_dirs": [
'../../liblnp',
],
"ldflags": [
'-Wl,-rpath,../../libln... | {'targets': [{'target_name': 'lnplib', 'sources': ['swig_wrap.cxx'], 'libraries': ['-L<(module_root_dir)/../../liblnp/target/release', '-llnp'], 'include_dirs': ['../../liblnp'], 'ldflags': ['-Wl,-rpath,../../liblnp/target/release/'], 'cflags!': ['-std=c++11']}]} |
class ControllerModelNotSet(Exception):
def __init__(self, controller):
Exception.__init__(
self,
f"layabase.load must be called with this {controller.__class__.__name__} instance before using any provided CRUDController feature.",
)
class MultiSchemaNotSupported(Exception)... | class Controllermodelnotset(Exception):
def __init__(self, controller):
Exception.__init__(self, f'layabase.load must be called with this {controller.__class__.__name__} instance before using any provided CRUDController feature.')
class Multischemanotsupported(Exception):
def __init__(self):
... |
number = int(input('Enter number: '))
temporary = number
rev = 0
while number > 0:
digits = number % 10
rev = rev * 10 + digits
number = number // 10
if (temporary == rev):
print(f'The number is palindrome')
else:
print(f'The number isn\'t a palindrome')
| number = int(input('Enter number: '))
temporary = number
rev = 0
while number > 0:
digits = number % 10
rev = rev * 10 + digits
number = number // 10
if temporary == rev:
print(f'The number is palindrome')
else:
print(f"The number isn't a palindrome") |
NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
NOTE_INDICES = {n: i for i, n in enumerate(NOTES)}
def midi_to_note(midi_number):
octave = midi_number // len(NOTES)
note_name = NOTES[int(midi_number % len(NOTES))]
return f'{note_name}{octave}'
def note_to_midi(note):
if not... | notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
note_indices = {n: i for (i, n) in enumerate(NOTES)}
def midi_to_note(midi_number):
octave = midi_number // len(NOTES)
note_name = NOTES[int(midi_number % len(NOTES))]
return f'{note_name}{octave}'
def note_to_midi(note):
if not... |
def binarySearch(arr,l,r,x):
while l <= r:
mid = l + (r - l)
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1
arr = [2,3,4,40,11]
x = 40
res = binarySearch(arr,0,len(arr)-1,x)
if res != -1:
print("e... | def binary_search(arr, l, r, x):
while l <= r:
mid = l + (r - l)
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1
arr = [2, 3, 4, 40, 11]
x = 40
res = binary_search(arr, 0, len(arr) - 1, x)
if res != -1:
... |
# GENERATED VERSION FILE
# TIME: Sat Jul 3 23:57:03 2021
__version__ = '1.0.0rc1+d492845'
short_version = '1.0.0rc1'
| __version__ = '1.0.0rc1+d492845'
short_version = '1.0.0rc1' |
leaderboard_response_example_200 = [
{
"rank": 1,
"username": "priyanshisharma",
"points": 50,
"pr_opened": 3,
"pr_merged": 1,
"good_first_issue": True,
"milestone_achieved": True,
"medium_issues_solved": 2,
"hard_issues_solved": 0
},
{... | leaderboard_response_example_200 = [{'rank': 1, 'username': 'priyanshisharma', 'points': 50, 'pr_opened': 3, 'pr_merged': 1, 'good_first_issue': True, 'milestone_achieved': True, 'medium_issues_solved': 2, 'hard_issues_solved': 0}, {'rank': 2, 'username': 'priyanshi', 'points': 30, 'pr_opened': 2, 'pr_merged': 1, 'good... |
#1614. Maximum Nesting Depth
class Solution:
def maxDepth(self, s: str) -> int:
d = 0
m=[0]
for a in s:
if a=="(":
d+=1
m.append(d)
elif a==")":
d-=1
return max(m)
#1021. Remove Outermost Parentheses
... | class Solution:
def max_depth(self, s: str) -> int:
d = 0
m = [0]
for a in s:
if a == '(':
d += 1
m.append(d)
elif a == ')':
d -= 1
return max(m)
class Solution:
def remove_outer_parentheses(self, S: str) ... |
__all__ = [
'__author__',
'__author_email__',
'__copyright__',
'__license__',
'__summary__',
'__title__',
'__url__',
'__version__',
'__version_info__'
]
__title__ = 'tbm_utils'
__summary__ = 'A commonly-used set of utilities used by me (thebigmunch).'
__url__ = 'https://github.com/thebigmunch/tbm_utils'
__ve... | __all__ = ['__author__', '__author_email__', '__copyright__', '__license__', '__summary__', '__title__', '__url__', '__version__', '__version_info__']
__title__ = 'tbm_utils'
__summary__ = 'A commonly-used set of utilities used by me (thebigmunch).'
__url__ = 'https://github.com/thebigmunch/tbm_utils'
__version__ = '2.... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res, currMin = 0, float('inf')
for i in range(len(prices)):
res = max(res, prices[i]-currMin)
currMin = min(currMin, prices[i])
return 0 if res<0 else res
| class Solution:
def max_profit(self, prices: List[int]) -> int:
(res, curr_min) = (0, float('inf'))
for i in range(len(prices)):
res = max(res, prices[i] - currMin)
curr_min = min(currMin, prices[i])
return 0 if res < 0 else res |
def autodesk_3ds(filepath="", axis_forward='Y', axis_up='Z', filter_glob="*.3ds", constrain_size=10.0, use_image_search=True, use_apply_transform=True):
pass
def fbx(filepath="", axis_forward='-Z', axis_up='Y', directory="", filter_glob="*.fbx", ui_tab='MAIN', use_manual_orientation=False, global_scale=1.0, bake_... | def autodesk_3ds(filepath='', axis_forward='Y', axis_up='Z', filter_glob='*.3ds', constrain_size=10.0, use_image_search=True, use_apply_transform=True):
pass
def fbx(filepath='', axis_forward='-Z', axis_up='Y', directory='', filter_glob='*.fbx', ui_tab='MAIN', use_manual_orientation=False, global_scale=1.0, bake_s... |
# -*- coding: utf-8 -*-
class Foo:
pass
class Logger:
def record(self, *args):
pass
settings = {}
class User:
pass
class Product:
pass
class ShipmentDetails:
pass
class Robot:
def __init__(self, servo, controller, settings):
pass
def work(self):
pass
cl... | class Foo:
pass
class Logger:
def record(self, *args):
pass
settings = {}
class User:
pass
class Product:
pass
class Shipmentdetails:
pass
class Robot:
def __init__(self, servo, controller, settings):
pass
def work(self):
pass
class Servo:
def __init__(s... |
filename = input("Enter file path: ")
filehandle = open(filename,'r')
content = filehandle.read()
words = content.split()
dictionary = {}
for word in words:
if len(word) in dictionary:
dictionary[len(word)] = dictionary[len(word)] + 1
else:
dictionary[len(word)] = 1
for letters in dictionary:
... | filename = input('Enter file path: ')
filehandle = open(filename, 'r')
content = filehandle.read()
words = content.split()
dictionary = {}
for word in words:
if len(word) in dictionary:
dictionary[len(word)] = dictionary[len(word)] + 1
else:
dictionary[len(word)] = 1
for letters in dictionary:
... |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/lowest-triangle
b,a=map(int,input().split())
print((a*2-1)//b+1)
| (b, a) = map(int, input().split())
print((a * 2 - 1) // b + 1) |
# Best know sorting networks
#
sort3 = [
[[1,2]],
[[0,2]],
[[0,1]]
]
sort4 = [
[[0,1],[2,3]],
[[0,2],[1,3]],
[[1,2]]
]
sort5 = [
[[0,1],[3,4]],
[[2,4]],
[[2,3],[1,4]],
[[0,3]],
[[0,2],[1,3]],
[[1,2]]
]
sort6 = [
[[1,2],[4,5]],
[[0,2],[3,5]],
[[0,1],[3,4],[... | sort3 = [[[1, 2]], [[0, 2]], [[0, 1]]]
sort4 = [[[0, 1], [2, 3]], [[0, 2], [1, 3]], [[1, 2]]]
sort5 = [[[0, 1], [3, 4]], [[2, 4]], [[2, 3], [1, 4]], [[0, 3]], [[0, 2], [1, 3]], [[1, 2]]]
sort6 = [[[1, 2], [4, 5]], [[0, 2], [3, 5]], [[0, 1], [3, 4], [2, 5]], [[0, 3], [1, 4]], [[2, 4], [1, 3]], [[2, 3]]]
sort7 = [[[1, 2]... |
def from_psi_to_pascals(P):
P_psi = P
P_pascal = P * 1.0
return P_pascal
def from_pascals_to_psi(P):
return P_psi
| def from_psi_to_pascals(P):
p_psi = P
p_pascal = P * 1.0
return P_pascal
def from_pascals_to_psi(P):
return P_psi |
def rectangle_area(histogram, i, j):
if i == j:
return 0
minimum_height = min(histogram[i:j])
return minimum_height * (j - i)
def max_rectangles(histogram):
n = len(histogram)
S = [0] * (n + 1)
for j in range(1, n+1):
maximum = rectangle_area(histogram, 0, j)
for k in ... | def rectangle_area(histogram, i, j):
if i == j:
return 0
minimum_height = min(histogram[i:j])
return minimum_height * (j - i)
def max_rectangles(histogram):
n = len(histogram)
s = [0] * (n + 1)
for j in range(1, n + 1):
maximum = rectangle_area(histogram, 0, j)
for k in ... |
# From dashcore-lib
class SimplifiedMNList:
pass
class SimplifiedMNListDiff:
pass
class MerkleBlock:
pass
class BlockHeader:
pass
| class Simplifiedmnlist:
pass
class Simplifiedmnlistdiff:
pass
class Merkleblock:
pass
class Blockheader:
pass |
def is_ok(s):
if len(s) > 1 and s[0] == '0':
return False
for c in s:
if c not in '0123456789':
return False
if int(s) > 12345:
return False
return True
A = input()
B = input()
if is_ok(A) and is_ok(B):
print('OK')
else:
print('NG')
| def is_ok(s):
if len(s) > 1 and s[0] == '0':
return False
for c in s:
if c not in '0123456789':
return False
if int(s) > 12345:
return False
return True
a = input()
b = input()
if is_ok(A) and is_ok(B):
print('OK')
else:
print('NG') |
# atualiza os valores do C100
def exec(conexao):
cursor = conexao.cursor()
print("RULE 23 - Inicializando",end=' ')
select = "SELECT r0 FROM principal WHERE r1 = \"C100\" "
select = cursor.execute(select)
select = select.fetchall()
ids = [i[0] for i in select]
for i in ids:
ini ... | def exec(conexao):
cursor = conexao.cursor()
print('RULE 23 - Inicializando', end=' ')
select = 'SELECT r0 FROM principal WHERE r1 = "C100" '
select = cursor.execute(select)
select = select.fetchall()
ids = [i[0] for i in select]
for i in ids:
ini = i
select = 'SELECT min(r0)... |
# model settings
dataset_type = 'CocoWiderfaceDataset'
data_root = '/root/dataset/'
base_lr = 0.02
warmup_iters = 500
model = dict(
type='TTFNet',
backbone=dict(
type='RepVGGNet',
stem_channels=32,
stage_channels=(32, 64, 96, 128),
block_per_stage=(1, 3, 6, 8, 6, 6),
ke... | dataset_type = 'CocoWiderfaceDataset'
data_root = '/root/dataset/'
base_lr = 0.02
warmup_iters = 500
model = dict(type='TTFNet', backbone=dict(type='RepVGGNet', stem_channels=32, stage_channels=(32, 64, 96, 128), block_per_stage=(1, 3, 6, 8, 6, 6), kernel_size=[3, 3, 3, 3], num_out=4), neck=dict(type='FuseFPN', in_chan... |
# usage per month
perMonth = int(input())
# the number of months
months = int(input())
# determin next month based on usage
nextMonth = perMonth*(months+1) - sum([int(input()) for x in range(months)])
print(nextMonth)
| per_month = int(input())
months = int(input())
next_month = perMonth * (months + 1) - sum([int(input()) for x in range(months)])
print(nextMonth) |
people = ['Nathaniel', 'Ngethe']
print()
for name in people:
print(name)
index = 0
while index < len(people):
print(people[index])
index = index + 1
print()
| people = ['Nathaniel', 'Ngethe']
print()
for name in people:
print(name)
index = 0
while index < len(people):
print(people[index])
index = index + 1
print() |
a = {0, 1, 12, 'b', 'ab', 3, 2, 'a'}
print(a)
#{0, 1, 'b', 3, 12, 'ab', 'a'}
a = {0, 1, 12, 3, 2}
print(a)
#{0, 1, 2, 3, 12}
a = {0, 1, 12, 3, 2}
b = list(a)
print(b)
#[0, 1, 2, 3, 12] | a = {0, 1, 12, 'b', 'ab', 3, 2, 'a'}
print(a)
a = {0, 1, 12, 3, 2}
print(a)
a = {0, 1, 12, 3, 2}
b = list(a)
print(b) |
#
# PySNMP MIB module NLS-BBNIDENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NLS-BBNIDENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:20:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) ... |
# Adding a Point Feature to a Vector Layer
# https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
vpr = vectorLyr.dataProvider()
pnt = QgsGeometry.fromPoint(QgsPoint(-74.80,40.549))
f = QgsFeature()
f.setGeomet... | vector_lyr = qgs_vector_layer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums', 'ogr')
vpr = vectorLyr.dataProvider()
pnt = QgsGeometry.fromPoint(qgs_point(-74.8, 40.549))
f = qgs_feature()
f.setGeometry(pnt)
vpr.addFeatures([f])
vectorLyr.updateExtents() |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Custom filters for use in openshift-ansible
'''
class FilterModule(object):
''' Custom ansible filters '''
@staticmethod
def translate_volume_name(volumes, target_volume):
'''
This filter matches a device string /dev/sdX to /dev/xvdX
... | """
Custom filters for use in openshift-ansible
"""
class Filtermodule(object):
""" Custom ansible filters """
@staticmethod
def translate_volume_name(volumes, target_volume):
"""
This filter matches a device string /dev/sdX to /dev/xvdX
It will then return the AWS volume I... |
n = int(input())
p = int(input())
total = 0
for i in range(p-1, -1, -1):
w, h = (int(x) for x in input().split())
total += h*w
print(int(total/n))
| n = int(input())
p = int(input())
total = 0
for i in range(p - 1, -1, -1):
(w, h) = (int(x) for x in input().split())
total += h * w
print(int(total / n)) |
def makeArrayConsecutive2(statues):
sorted_status = sorted(statues)
missing = 0
for i in range(sorted_status[0], sorted_status[-1]+1):
if i not in statues:
missing += 1
return missing
| def make_array_consecutive2(statues):
sorted_status = sorted(statues)
missing = 0
for i in range(sorted_status[0], sorted_status[-1] + 1):
if i not in statues:
missing += 1
return missing |
#
# PySNMP MIB module HH3C-ISSU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-ISSU-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:27:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, constraints_union, single_value_constraint) ... |
# Copyright 2019 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
DEPS = [
'context',
'futures',
'step',
]
def RunSteps(api):
# We want to make sure that context is kept per-greenlet.
chan = api.futur... | deps = ['context', 'futures', 'step']
def run_steps(api):
chan = api.futures.make_channel()
with api.context(infra_steps=True):
assert api.context.infra_step
def _assert_still_true():
chan.get()
assert api.context.infra_step
future = api.futures.spawn(_assert_st... |
'''
This file is automatically generated; Do not edit it. :)
'''
VERSION_INFO = {
'final': True,
'version': '1.24.1',
'branch_nick': 'patch-0-Release__1_24_1_preparation',
'revision_id': 'b8f02733b0474729ffccba85f93e95bc19721f2f',
'revno': 10290
}
| """
This file is automatically generated; Do not edit it. :)
"""
version_info = {'final': True, 'version': '1.24.1', 'branch_nick': 'patch-0-Release__1_24_1_preparation', 'revision_id': 'b8f02733b0474729ffccba85f93e95bc19721f2f', 'revno': 10290} |
class QID(Element):
def configure(self):
self.inp = Input()
self.out = Output()
def impl(self):
self.run_c(r'''
state->qid = state->hash %s %d;
output { out(); }
''' % ('%', n_cores))
# Queue
RxEnq, RxDeq, RxScan = queue_smart.smart_queue("rx_queue", entry_size=192, size=256... | class Qid(Element):
def configure(self):
self.inp = input()
self.out = output()
def impl(self):
self.run_c('\nstate->qid = state->hash %s %d;\noutput { out(); }\n' % ('%', n_cores))
(rx_enq, rx_deq, rx_scan) = queue_smart.smart_queue('rx_queue', entry_size=192, size=256, insts=n_cores,... |
# Twitter API Keys
consumer_key = "AwnXAIelLfH3yVTgCM7W4bqjT"
consumer_secret = "uMKCqXfRlsk2IrjxxurNPvPu7WeRtc0eJru7DLDR3sTqdvXIEf"
access_token = "998710031108329472-lZFESYFZjxoItvGe6tirZELxhbgrCjh"
access_token_secret = "kpCY3tjkDUomOudY6vGW2W6PZgs8CgnjILhv2uDluqEIJ" | consumer_key = 'AwnXAIelLfH3yVTgCM7W4bqjT'
consumer_secret = 'uMKCqXfRlsk2IrjxxurNPvPu7WeRtc0eJru7DLDR3sTqdvXIEf'
access_token = '998710031108329472-lZFESYFZjxoItvGe6tirZELxhbgrCjh'
access_token_secret = 'kpCY3tjkDUomOudY6vGW2W6PZgs8CgnjILhv2uDluqEIJ' |
class Cached(object):
_cache_enabled = False
_cache = {}
def _cache_result(func):
def wrapper(self, *args, **kwargs):
key = (func.__name__, args, *list(kwargs.keys()))
if self._cache.get(key):
return self._cache.get(key)
result = func(self, *args... | class Cached(object):
_cache_enabled = False
_cache = {}
def _cache_result(func):
def wrapper(self, *args, **kwargs):
key = (func.__name__, args, *list(kwargs.keys()))
if self._cache.get(key):
return self._cache.get(key)
result = func(self, *args... |
def settitle(user, args):
try:
titleToSet = ' '.join(args)
except:
queueEvent = {
'msg' : ("Hey %s, you need to actually give me a title to "
"set!" % user),
'eventType' : 'electrical',
'event' : 'red toggle'
}
... | def settitle(user, args):
try:
title_to_set = ' '.join(args)
except:
queue_event = {'msg': 'Hey %s, you need to actually give me a title to set!' % user, 'eventType': 'electrical', 'event': 'red toggle'}
return queueEvent
queue_event = {'eventType': 'twitchapi', 'event': 'settitle %s... |
class Param:
def __init__(self, type, default=None):
self.default = default
self.type = type
def __get__(self, instance, owner):
if self.default is None:
return instance.__dict__[self.name]
else:
return instance.__dict__.get(self.name, self.default)
... | class Param:
def __init__(self, type, default=None):
self.default = default
self.type = type
def __get__(self, instance, owner):
if self.default is None:
return instance.__dict__[self.name]
else:
return instance.__dict__.get(self.name, self.default)
... |
# INPUT YOUR NTU USERNAME AND PASSWORD HERE.
# Example: your ntu email->EG0001@e.ntu.edu.sg, pwd-> 123
# username= EG0001
# pwd= 123
username= 'replace with username here'
password= 'replace with password here'
| username = 'replace with username here'
password = 'replace with password here' |
class RemovedInWagtailMenus3Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtailMenus3Warning
class RemovedInWagtailMenus31Warning(PendingDeprecationWarning):
pass
class RemovedInWagtailMenus32Warning(PendingDeprecationWarning):
pass
| class Removedinwagtailmenus3Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtailMenus3Warning
class Removedinwagtailmenus31Warning(PendingDeprecationWarning):
pass
class Removedinwagtailmenus32Warning(PendingDeprecationWarning):
pass |
previous = 0
match = 0
with open('input', 'r') as file:
data = file.read().split('\n')[:-1]
for i in range(1, len(data)):
this = data[i:(i + 3)]
if len(this) == 3:
window = int(this[0]) + int(this[1]) + int(this[2])
if window > previous:
match += 1
... | previous = 0
match = 0
with open('input', 'r') as file:
data = file.read().split('\n')[:-1]
for i in range(1, len(data)):
this = data[i:i + 3]
if len(this) == 3:
window = int(this[0]) + int(this[1]) + int(this[2])
if window > previous:
match += 1
... |
for _ in range(int(input())):
S = input()
D = 0
Z = ''
for C in S:
X = int(C) - D
if X > 0:
Z+='('*X+C
D = int(C)
elif X < 0:
Z+=')'*(-X)+C
D = int(C)
else:
Z+=C
Z+=')'*D
print('Case #{}: {}'.format(_+1, ... | for _ in range(int(input())):
s = input()
d = 0
z = ''
for c in S:
x = int(C) - D
if X > 0:
z += '(' * X + C
d = int(C)
elif X < 0:
z += ')' * -X + C
d = int(C)
else:
z += C
z += ')' * D
print('Case #{}: ... |
class DocumentNotFoundError(Exception):
pass
class DocumentDeletedError(DocumentNotFoundError):
pass
class DocumentMissingError(DocumentNotFoundError):
pass
class DocumentMismatchError(Exception):
pass
| class Documentnotfounderror(Exception):
pass
class Documentdeletederror(DocumentNotFoundError):
pass
class Documentmissingerror(DocumentNotFoundError):
pass
class Documentmismatcherror(Exception):
pass |
def somatorio(numero):
b=0
for i in range(len(numero)):
b+=int(numero[i])
return b
def filtra_divisores(lista):
for i in range(len(lista)-1,-1,-1):
a=somatorio(str(lista[i]))
if (lista[i]%a)==0:
pass
else:
lista.pop(i)
return None
| def somatorio(numero):
b = 0
for i in range(len(numero)):
b += int(numero[i])
return b
def filtra_divisores(lista):
for i in range(len(lista) - 1, -1, -1):
a = somatorio(str(lista[i]))
if lista[i] % a == 0:
pass
else:
lista.pop(i)
return None |
fieldnames = set()
for row in DATA:
fieldnames.update(row.keys())
with open(FILE, mode='w', encoding='utf-8') as file:
writer = csv.DictWriter(f=file,
fieldnames=sorted(fieldnames),
delimiter=',',
quotechar='"',
... | fieldnames = set()
for row in DATA:
fieldnames.update(row.keys())
with open(FILE, mode='w', encoding='utf-8') as file:
writer = csv.DictWriter(f=file, fieldnames=sorted(fieldnames), delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n')
writer.writeheader()
writer.writerows(DATA) |
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is %s."
print(format_string % data)
| data = ('John', 'Doe', 53.44)
format_string = 'Hello %s %s. Your current balance is %s.'
print(format_string % data) |
{
"targets": [
{
"target_name": "expand",
"sources": [
"src/expand.cc"
],
"libraries": [
"-lpostal", "-L/usr/local/lib"
],
"include_dirs": [
"<!(node -e \"require('nan')\")",
... | {'targets': [{'target_name': 'expand', 'sources': ['src/expand.cc'], 'libraries': ['-lpostal', '-L/usr/local/lib'], 'include_dirs': ['<!(node -e "require(\'nan\')")', '/usr/local/include']}, {'target_name': 'parser', 'sources': ['src/parser.cc'], 'libraries': ['-lpostal', '-L/usr/local/lib'], 'include_dirs': ['<!(node ... |
# -*- coding: utf-8 -*-
# Maximum number of components in a RPM
MAX_COMPONENTS = 2
# Canvas parameters
IMAGE_SIZE = 160
CENTER = (IMAGE_SIZE / 2, IMAGE_SIZE / 2)
DEFAULT_RADIUS = IMAGE_SIZE / 4
DEFAULT_WIDTH = 2
# Attribute parameters
# Number
NUM_VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9]
NUM_MIN = 0
NUM_MAX = len(NUM_V... | max_components = 2
image_size = 160
center = (IMAGE_SIZE / 2, IMAGE_SIZE / 2)
default_radius = IMAGE_SIZE / 4
default_width = 2
num_values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
num_min = 0
num_max = len(NUM_VALUES) - 1
uni_values = [False, False, False, True]
uni_min = 0
uni_max = len(UNI_VALUES) - 1
type_values = ['none', 'tr... |
class camera_view_config():
SPECIAL_OBJECT = [
".\\resources\\interface\\option.png",
".\\resources\\interface\\modules\\camera_view\\zoom_controller.png",
".\\resources\\interface\\inventor.png",
];
COORDINATE_OPTIONS = [
35,25,25,25,25
]; | class Camera_View_Config:
special_object = ['.\\resources\\interface\\option.png', '.\\resources\\interface\\modules\\camera_view\\zoom_controller.png', '.\\resources\\interface\\inventor.png']
coordinate_options = [35, 25, 25, 25, 25] |
class Solution:
def lastRemaining(self, n: int) -> int:
return self.help(n, True)
def help(self, n, flag):
if n == 1:
return 1
if flag:
return 2 * self.help(n // 2, False)
else:
return 2 * self.help(n // 2, True) - 1 + n % 2 | class Solution:
def last_remaining(self, n: int) -> int:
return self.help(n, True)
def help(self, n, flag):
if n == 1:
return 1
if flag:
return 2 * self.help(n // 2, False)
else:
return 2 * self.help(n // 2, True) - 1 + n % 2 |
count = int(input())
result = []
temp = input()
for i in range(len(temp)):
result.append(temp[i])
for i in range(count-1):
temp = input()
for i in range(len(result)):
if result[i] != temp[i]:
result[i] = "?"
for i in result:
print(i,end="")
| count = int(input())
result = []
temp = input()
for i in range(len(temp)):
result.append(temp[i])
for i in range(count - 1):
temp = input()
for i in range(len(result)):
if result[i] != temp[i]:
result[i] = '?'
for i in result:
print(i, end='') |
peso = float(input("Digite o sue peso em Kg: "))
altura = input("Digite sua altura em metros: ").strip().replace(",",".")
altura = float(altura)
def IMC(peso,altura):
imc = peso/(altura**2)
if imc < 18.5:
return f"seu IMC e de {imc:.1f} ABAIXO DO PESO"
elif imc >= 18.5 and imc < 25:
return ... | peso = float(input('Digite o sue peso em Kg: '))
altura = input('Digite sua altura em metros: ').strip().replace(',', '.')
altura = float(altura)
def imc(peso, altura):
imc = peso / altura ** 2
if imc < 18.5:
return f'seu IMC e de {imc:.1f} ABAIXO DO PESO'
elif imc >= 18.5 and imc < 25:
ret... |
# Problem Set 4A
# Name: Vikram S. Negi
# Collaborators: None
# Time Spent: 03:00 hrs
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part.... | def get_permutations(sequence):
"""
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequen... |
'''
Copyright 2019-2020 Secure Shed Project Dev Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | """
Copyright 2019-2020 Secure Shed Project Dev Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
'''
Created on Nov 10, 2018
@author: Winterberger
'''
##from math import
def average(*args):
num = sum(args)
print(num)
den = len(args)
print (den)
average = float(num/den)
return average
Argument = []
i = 0
print(Argument[i])
while (Argument[i] >= 0):
Argument[i] = in... | """
Created on Nov 10, 2018
@author: Winterberger
"""
def average(*args):
num = sum(args)
print(num)
den = len(args)
print(den)
average = float(num / den)
return average
argument = []
i = 0
print(Argument[i])
while Argument[i] >= 0:
Argument[i] = input('Input next value to take average of:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.