content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
name = "popcorntime"
source = "https://aur.archlinux.org/popcorntime-bin.git"
def pre_build():
for line in edit_file("PKGBUILD"):
if line.startswith("pkgname="):
print("pkgname=popcorntime")
else:
print(line)
| name = 'popcorntime'
source = 'https://aur.archlinux.org/popcorntime-bin.git'
def pre_build():
for line in edit_file('PKGBUILD'):
if line.startswith('pkgname='):
print('pkgname=popcorntime')
else:
print(line) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.scanTree(root, None, None)
def scanTr... | class Solution:
def is_valid_bst(self, root: TreeNode) -> bool:
return self.scanTree(root, None, None)
def scan_tree(self, root, minEnd, maxEnd):
outcome = True
if root.left != None:
if root.left.val >= root.val:
outcome = False
if minEnd != None... |
for c in range(10, -1, -1):
print(c)
print('FOGOOOOOS !!!')
| for c in range(10, -1, -1):
print(c)
print('FOGOOOOOS !!!') |
class Animal:
def __init__(self,*args,**kwargs):
animalArgs = args[0]
animalArgs.update(kwargs)
self.__dict__.update(animalArgs)
def update(self,val):
self.__dict__.update(val)
def get(self):
print(self)
return vars(self)
def addSponsor(self,sponsor):
self.sponsor = sponsor
... | class Animal:
def __init__(self, *args, **kwargs):
animal_args = args[0]
animalArgs.update(kwargs)
self.__dict__.update(animalArgs)
def update(self, val):
self.__dict__.update(val)
def get(self):
print(self)
return vars(self)
def add_sponsor(self, spon... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 16:17:26 2019
@author: Administrator
"""
class Solution:
def trailingZeroes(self, n: int) -> int:
# ans = []
# for num in n:
# res = 1
# for k in range(1, num+1):
# res = res * k
# tmp = 0
# ... | """
Created on Thu Jun 20 16:17:26 2019
@author: Administrator
"""
class Solution:
def trailing_zeroes(self, n: int) -> int:
ans = 0
while n:
n //= 5
ans += n
return ans
solu = solution()
n = 3
n = 5
n = 10
n = 30
n = 200
print(solu.trailingZeroes(n)) |
# Copyright (c) 2015-2019 Patricio Cubillos and contributors.
# MC3 is open-source software under the MIT license (see LICENSE).
# MC3 Version:
MC3_VER = 3 # Major version
MC3_MIN = 0 # Minor version
MC3_REV = 0 # Revision
__version__ = '{}.{}.{}'.format(MC3_VER, MC3_MIN, MC3_REV)
| mc3_ver = 3
mc3_min = 0
mc3_rev = 0
__version__ = '{}.{}.{}'.format(MC3_VER, MC3_MIN, MC3_REV) |
class FactorUniverseSelectionModel():
def __init__(self, algorithm):
self.algorithm = algorithm
def SelectCoarse(self, coarse):
# self.algorithm.Log("Generating universe...")
universe = self.FilterDollarPriceVolume(coarse)
return [c.Symbol for c in universe]
def Se... | class Factoruniverseselectionmodel:
def __init__(self, algorithm):
self.algorithm = algorithm
def select_coarse(self, coarse):
universe = self.FilterDollarPriceVolume(coarse)
return [c.Symbol for c in universe]
def select_fine(self, fine):
universe = self.FilterFactor(self... |
"Day 25: Combo Breaker"
def find_loop_size_of(key: int) -> int:
"""Determine loop size from public key."""
value = 1
subject = 7
loop = 0
while value != key:
value *= subject
value = value % 20201227
loop += 1
return loop
def calculate_encryption(first_key: int, secon... | """Day 25: Combo Breaker"""
def find_loop_size_of(key: int) -> int:
"""Determine loop size from public key."""
value = 1
subject = 7
loop = 0
while value != key:
value *= subject
value = value % 20201227
loop += 1
return loop
def calculate_encryption(first_key: int, sec... |
def isAnagram(string1, string2):
"""Checks if two strings are an anagram
An anagram is a word or phrase formed by rearranging the letters
of a different word or phrase.
This implementation ignores spaces and case.
@param string1 The first word or phrase
@param string2 The second word or phras... | def is_anagram(string1, string2):
"""Checks if two strings are an anagram
An anagram is a word or phrase formed by rearranging the letters
of a different word or phrase.
This implementation ignores spaces and case.
@param string1 The first word or phrase
@param string2 The second word or phra... |
#
# PySNMP MIB module MITEL-IPFILTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-IPFILTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:03:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
def title(string, rng, color=0):
"""
--> Function to create a title in the project.
:param string: Written part of the title.
:param rng: Title range.
:param color: Title color. (30 = White; 31 = Red; 32 = Green; 33 = Yellow;
34 = Blue; 35 = Purple; 36 = Cyan; 37... | def title(string, rng, color=0):
"""
--> Function to create a title in the project.
:param string: Written part of the title.
:param rng: Title range.
:param color: Title color. (30 = White; 31 = Red; 32 = Green; 33 = Yellow;
34 = Blue; 35 = Purple; 36 = Cyan; 37... |
# Name: Yahya Eldarieby
# Course: CS30
# Date: 01/10/2019
# Description: RPG Pseudocode
# A text based game following the demo at: https://www.youtube.com/watch?v=higMRrO5AkU
# Start
# Display a welcoming branding image
# Pick an intial location for snake
# Pick an initial location for fruits and obstacles
# Forever ... | print('# Explanation of game')
print('The game works by you being a snake and that same snake has to eat fruits to increase your score and there will be obstacles in your way to make you lose.')
print('# How will you survive')
print('You will survive the game by avoiding the obstacles and by avoiding hitting the boarde... |
class NotAllowedException(Exception):
pass
class CannotDeleteLoadedItem(Exception):
pass
class UnknownUserException(Exception):
pass
class UnknownLoanItemException(Exception):
pass
class InitialAdminRoleException(Exception):
pass
class InvalidTokenException(Exception):
pass
class Inv... | class Notallowedexception(Exception):
pass
class Cannotdeleteloadeditem(Exception):
pass
class Unknownuserexception(Exception):
pass
class Unknownloanitemexception(Exception):
pass
class Initialadminroleexception(Exception):
pass
class Invalidtokenexception(Exception):
pass
class Invalidre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
MESSAGE_INDENT_NUM = 'indent steps must be {} multiples'
MESSAGE_DUPLICATED_SPACE = 'too many spaces'
MESSAGE_COMMA_HEAD = 'comma must be head of line'
MESSAGE_COMMA_END = 'comma must be end of line'
MESSAGE_WHITESPACE_AFTER_COMMA = 'whitespace must be after comma: ,'
MESS... | message_indent_num = 'indent steps must be {} multiples'
message_duplicated_space = 'too many spaces'
message_comma_head = 'comma must be head of line'
message_comma_end = 'comma must be end of line'
message_whitespace_after_comma = 'whitespace must be after comma: ,'
message_whitespace_before_comma = 'whitespace must ... |
def max_sum(d):
res = d[0]
max_i = 0
max_j = 1
i = 0
j = 0
max_count = 0
for item in d:
max_count += item
j += 1
if max_count > res:
res = max_count
max_i, max_j = i, j
if max_count <= 0:
max_count = 0
i = j
... | def max_sum(d):
res = d[0]
max_i = 0
max_j = 1
i = 0
j = 0
max_count = 0
for item in d:
max_count += item
j += 1
if max_count > res:
res = max_count
(max_i, max_j) = (i, j)
if max_count <= 0:
max_count = 0
i = j
... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Analog.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Digital.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fm... | messages_str = '/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Analog.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Digital.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/IOStates.msg;/home/k... |
"""
Utilities for working with arrays of timestamps
Generally, i = index, T = array of ordered timestamps, t = timestamp
"""
def get_closest_index(i1, i2, T, t0):
""" Returns the index i such that abs(T[i]-t0) is minimum for i1,i2 """
if abs(T[i1]-t0) <= abs(T[i2]-t0):
return i1
else:
... | """
Utilities for working with arrays of timestamps
Generally, i = index, T = array of ordered timestamps, t = timestamp
"""
def get_closest_index(i1, i2, T, t0):
""" Returns the index i such that abs(T[i]-t0) is minimum for i1,i2 """
if abs(T[i1] - t0) <= abs(T[i2] - t0):
return i1
else:... |
def FordFulkerson(graph,start,end):
n = len(graph)
GPrime = [[None]*n for _ in range(n)]
for v in range(n):
for u, w in graph[v]:
GPrime[v][u] = w
for v in range(n):
for u in range(n):
if GPrime[v][u] != None and GPrime[u][v] == None:
GPrime[u][v] ... | def ford_fulkerson(graph, start, end):
n = len(graph)
g_prime = [[None] * n for _ in range(n)]
for v in range(n):
for (u, w) in graph[v]:
GPrime[v][u] = w
for v in range(n):
for u in range(n):
if GPrime[v][u] != None and GPrime[u][v] == None:
GPrim... |
class AbstractCodeGen(object):
def genCode(self, ast, symbolTable, **kwargs):
raise NotImplementedError()
def genIndex(self, mibsMap, **kwargs):
raise NotImplementedError()
| class Abstractcodegen(object):
def gen_code(self, ast, symbolTable, **kwargs):
raise not_implemented_error()
def gen_index(self, mibsMap, **kwargs):
raise not_implemented_error() |
z = 100
while z > 10:
a, b = input().split(" ")
a = int(a)
b = int(b)
if a < b :
print("Crescente")
elif b < a:
print("Decrescente")
elif a == b:
exit()
| z = 100
while z > 10:
(a, b) = input().split(' ')
a = int(a)
b = int(b)
if a < b:
print('Crescente')
elif b < a:
print('Decrescente')
elif a == b:
exit() |
def main():
palindrome = [it1*it2 for it1 in range(100,1000) for it2 in range(it1,1000) if str(it1*it2)==str(it1*it2)[::-1]]
for tc in range(int(input())):
N = int(input())
print(max(filter(lambda x: x<N,palindrome)))
if __name__=="__main__":
main()
| def main():
palindrome = [it1 * it2 for it1 in range(100, 1000) for it2 in range(it1, 1000) if str(it1 * it2) == str(it1 * it2)[::-1]]
for tc in range(int(input())):
n = int(input())
print(max(filter(lambda x: x < N, palindrome)))
if __name__ == '__main__':
main() |
"""
This uses test262 to test the interpreter
"""
# pylint: disable=relative-beyond-top-level, protected-access, no-self-use, missing-function-docstring, missing-class-docstring
class Test262:
def test_one(self):
assert True, "This parses!"
| """
This uses test262 to test the interpreter
"""
class Test262:
def test_one(self):
assert True, 'This parses!' |
print("Starting adding")
total = [1]
base = 2
power = 1000
for i in range(0, power):
for i in range(0, len(total)):
total[i] *= base
carrier = 0
for i in range(0, len(total)):
total[i] += carrier
head = total[i] % 10
carrier = (total[i] - head) / 10
total[i] = int(head)
while carr... | print('Starting adding')
total = [1]
base = 2
power = 1000
for i in range(0, power):
for i in range(0, len(total)):
total[i] *= base
carrier = 0
for i in range(0, len(total)):
total[i] += carrier
head = total[i] % 10
carrier = (total[i] - head) / 10
total[i] = int(hea... |
# LC 735
class Solution:
def collide(self, a: int, b:int) -> int:
if abs(a) == abs(b):
return None
res = max(abs(a),abs(b))
if abs(a) < abs(b):
res *= (b // abs(b))
else:
res *= (a // abs(a))
return res
def asteroidCollision(self, aste... | class Solution:
def collide(self, a: int, b: int) -> int:
if abs(a) == abs(b):
return None
res = max(abs(a), abs(b))
if abs(a) < abs(b):
res *= b // abs(b)
else:
res *= a // abs(a)
return res
def asteroid_collision(self, asteroids: Li... |
with open('c:\\mine\\No.txt') as noTxt:
with open('c:\\mine\\number.txt','w') as numberTxt:
for line in noTxt:
nos = line.split(',')
start,end = int(nos[0]), int(nos[1])
for i in range(start, end):
numberTxt.write(str(i) + '\n') | with open('c:\\mine\\No.txt') as no_txt:
with open('c:\\mine\\number.txt', 'w') as number_txt:
for line in noTxt:
nos = line.split(',')
(start, end) = (int(nos[0]), int(nos[1]))
for i in range(start, end):
numberTxt.write(str(i) + '\n') |
lines = open("input").read().strip().splitlines()
# lines = """
# ..##.......
# #...#...#..
# .#....#..#.
# ..#.#...#.#
# .#...##..#.
# ..#.##.....
# .#.#.#....#
# .#........#
# #.##...#...
# #...##....#
# .#..#...#.#
# """.strip().splitlines()
def p1():
TREE = "#"
pos = [0, 0]
trees = 0
while True... | lines = open('input').read().strip().splitlines()
def p1():
tree = '#'
pos = [0, 0]
trees = 0
while True:
pos[0] += 3
pos[1] += 1
(x, y) = pos
try:
if lines[y][x % len(lines[0])] == TREE:
trees += 1
except IndexError:
break... |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
#
# Shared utilities
#
# Author: Martin Paces <martin.paces@eox.at>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2016 EOX IT Services GmbH
#
# Permission is hereb... | class Progress(object):
""" Simple CLI progress indicator. """
progres_string = ['0', '.', '.', '.', '10', '.', '.', '.', '20', '.', '.', '.', '30', '.', '.', '.', '40', '.', '.', '.', '50', '.', '.', '.', '60', '.', '.', '.', '70', '.', '.', '.', '80', '.', '.', '.', '90', '.', '.', '.', '100\n']
def __in... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def trim_bst(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
if not root:
... |
def GLSL_type(a):
if(isinstance(a, str)):
return "int["+str(len(a))+"]"
elif(isinstance(a, list)):
return GLSL_type(a)+"["+str(len(a))+"]"
elif(type(a) == bool):
return "bool"
| def glsl_type(a):
if isinstance(a, str):
return 'int[' + str(len(a)) + ']'
elif isinstance(a, list):
return glsl_type(a) + '[' + str(len(a)) + ']'
elif type(a) == bool:
return 'bool' |
{
"targets": [
{
"target_name": "roo",
"sources": [ "./src/c/roo/roo.c",
"./src/c/roo/roo_node.c",
"./src/c/roo/callbacks.c",
"./src/c/roo/startup.c",
"./src/c/roo/interface.c",
"./src/c/roo/log.c",
"./src/c/roo/plugin.c",
"./src/c/roo/map.c",
... | {'targets': [{'target_name': 'roo', 'sources': ['./src/c/roo/roo.c', './src/c/roo/roo_node.c', './src/c/roo/callbacks.c', './src/c/roo/startup.c', './src/c/roo/interface.c', './src/c/roo/log.c', './src/c/roo/plugin.c', './src/c/roo/map.c', './src/c/roo/lane.c', './src/c/roo/operations.c'], 'libraries': ['-ljack', '-lca... |
""" Defines an instance of stock which is cut to produce needed pieces."""
class Stock(object):
""" Defines a piece of stock, including planned cuts """
def __init__(self, length):
self.pieces = []
self.length = length
self.remaining_length = length
def __str__(self):
pie... | """ Defines an instance of stock which is cut to produce needed pieces."""
class Stock(object):
""" Defines a piece of stock, including planned cuts """
def __init__(self, length):
self.pieces = []
self.length = length
self.remaining_length = length
def __str__(self):
piec... |
"""Factories for the leapmotion app."""
# import factory
# from ..models import YourModel
| """Factories for the leapmotion app.""" |
num = 1
for i in range(16):
print(num<<i, end=', ')
print(); print()
for i in range(16):
print('0x%x'%(num<<i), end=',')
| num = 1
for i in range(16):
print(num << i, end=', ')
print()
print()
for i in range(16):
print('0x%x' % (num << i), end=',') |
x=[]
for i in range(20):
val=int(input())
x.append(val)
x.reverse()
for k in range(20):
print("N[{}] = {}".format(k,x[k])) | x = []
for i in range(20):
val = int(input())
x.append(val)
x.reverse()
for k in range(20):
print('N[{}] = {}'.format(k, x[k])) |
def swap(a, b): #function logic
print("Original: ",a, b)
if (a > b or a < b): #doing the swap when the two numbers aren't equal
temp = a
a = b
b = temp
print("Swapped: ",a, b)
else: #just returning the numbers in same order b/c they're equal, no need to swap
print("No s... | def swap(a, b):
print('Original: ', a, b)
if a > b or a < b:
temp = a
a = b
b = temp
print('Swapped: ', a, b)
else:
print('No swap: ', a, b)
def driver():
swap(10, 1)
swap(5, 5)
swap(3, 7)
swap('aaa', 'aaa')
swap('aaa', 'bbb')
swap('bbb', 'aaa... |
def rank(graph, res):
rank_page= {}
for page in res.keys():
word_count=res[page]
ingoing=graph.ingoing_links(page)
num_links=len(ingoing)
num_in_links=0
for link in ingoing:
if link in res.keys():
num_in_links+=res[link]
rank_page[pa... | def rank(graph, res):
rank_page = {}
for page in res.keys():
word_count = res[page]
ingoing = graph.ingoing_links(page)
num_links = len(ingoing)
num_in_links = 0
for link in ingoing:
if link in res.keys():
num_in_links += res[link]
rank... |
class Student(object):
"""docstring for Student"""
def __init__(self, name,score,*age):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s'% (self.__name,self.__score))
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self,score):
... | class Student(object):
"""docstring for Student"""
def __init__(self, name, score, *age):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
def get_name(self):
return self.__name
def get_score(self):
... |
# Write a program which replaces all vowels in the string with '*'
str=input('enter the string : ')
str2='aeiou'
str3='AEIOU'
l=len(str)
str4=''
for x in str:
if x in str2 or x in str3:
str4=str4+'*'
else:
str4=str4+x
print(str4)
| str = input('enter the string : ')
str2 = 'aeiou'
str3 = 'AEIOU'
l = len(str)
str4 = ''
for x in str:
if x in str2 or x in str3:
str4 = str4 + '*'
else:
str4 = str4 + x
print(str4) |
## CONSTRUCTING GRAPH
v, e = map(int, raw_input().split())
grafo = [[] for i in range(v+1)]
for i in range(e):
v1, v2, w = map(int, raw_input().split())
# save edges that are getting in me, not edges from me to another v
grafo[v2].append((v1, w))
## INITIALIZING
beginning = input()
dp = ... | (v, e) = map(int, raw_input().split())
grafo = [[] for i in range(v + 1)]
for i in range(e):
(v1, v2, w) = map(int, raw_input().split())
grafo[v2].append((v1, w))
beginning = input()
dp = [[float('inf') for i in range(v + 1)] for j in range(v + 1)]
for i in range(v + 1):
dp[i][beginning] = 0
for i in range(... |
LINE_COLORS = [
(255, 127, 127),
(255, 127, 182),
(102, 51, 73),
(214, 127, 255),
(85, 51, 102),
(161, 127, 255),
(63, 51, 102),
(127, 146, 255),
(51, 58, 102),
(127, 201, 255),
(51, 80, 1... | line_colors = [(255, 127, 127), (255, 127, 182), (102, 51, 73), (214, 127, 255), (85, 51, 102), (161, 127, 255), (63, 51, 102), (127, 146, 255), (51, 58, 102), (127, 201, 255), (51, 80, 102), (127, 255, 197), (51, 102, 78), (127, 255, 142), (51, 102, 56), (165, 255, 127), (66, 102, 51), (218, 255, 127), (87, 102, 51), ... |
class BadSetting(Exception):
"""
Exception raised when an invalid value is provided
for one or more settings when updating settings.
"""
class UnknownSetting(Exception):
"""
Exception raised when attempting to access a setting
that does not exist.
""" | class Badsetting(Exception):
"""
Exception raised when an invalid value is provided
for one or more settings when updating settings.
"""
class Unknownsetting(Exception):
"""
Exception raised when attempting to access a setting
that does not exist.
""" |
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
print(inventory)
del inventory['pears'] # deletes a <key,value>
print(inventory)
inventory['apples'] = 10 # change value associated with key apples
print(inventory)
inventory['bananas'] = inventory['bananas'] * 2
print(inventory)
num_... | inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
print(inventory)
del inventory['pears']
print(inventory)
inventory['apples'] = 10
print(inventory)
inventory['bananas'] = inventory['bananas'] * 2
print(inventory)
num_items = len(inventory)
print('Items in inventory: ', num_items) |
"""Helper enum for defining possible states of tagging in a chat."""
class TagMode:
"""Helper enum for defining possible states of tagging in a chat."""
STICKER_SET = 'sticker_set'
RANDOM = 'random'
SINGLE_STICKER = 'single_sticker'
| """Helper enum for defining possible states of tagging in a chat."""
class Tagmode:
"""Helper enum for defining possible states of tagging in a chat."""
sticker_set = 'sticker_set'
random = 'random'
single_sticker = 'single_sticker' |
#
# PHASE: collect jars
#
# DOCUMENT THIS
#
load(
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
"collect_jars_from_common_ctx",
)
def phase_scalatest_collect_jars(ctx, p):
args = struct(
base_classpath = p.scalac_provider.default_classpath + [ctx.attr._scalatest],
extra_runtime_dep... | load('@io_bazel_rules_scala//scala/private:rule_impls.bzl', 'collect_jars_from_common_ctx')
def phase_scalatest_collect_jars(ctx, p):
args = struct(base_classpath=p.scalac_provider.default_classpath + [ctx.attr._scalatest], extra_runtime_deps=[ctx.attr._scalatest_reporter, ctx.attr._scalatest_runner])
return _... |
#!/usr/bin/env python3
# https://abc059.contest.atcoder.jp/tasks/abc059_b
a = int(input())
b = int(input())
if a == b: print('EQUAL')
elif a < b: print('LESS')
else: print('GREATER')
| a = int(input())
b = int(input())
if a == b:
print('EQUAL')
elif a < b:
print('LESS')
else:
print('GREATER') |
# noinspection DuplicatedCode
class InsertConflictException(Exception):
pass
class OptimisticLockException(Exception):
pass
class UnexpectedStorageException(Exception):
pass
class UnsupportedCriteriaException(UnexpectedStorageException):
pass
class UnsupportedComputationException(UnexpectedStorageException)... | class Insertconflictexception(Exception):
pass
class Optimisticlockexception(Exception):
pass
class Unexpectedstorageexception(Exception):
pass
class Unsupportedcriteriaexception(UnexpectedStorageException):
pass
class Unsupportedcomputationexception(UnexpectedStorageException):
pass
class Unsu... |
N, K, S = map(int, input().split())
str_S = str(S)
str_S1 = str(S+1)
ans = []
for _ in range(K):
ans.append(str_S)
for _ in range(N-K):
if S != 1000000000:
ans.append(str_S1)
else:
ans.append('1')
print(' '.join(ans))
| (n, k, s) = map(int, input().split())
str_s = str(S)
str_s1 = str(S + 1)
ans = []
for _ in range(K):
ans.append(str_S)
for _ in range(N - K):
if S != 1000000000:
ans.append(str_S1)
else:
ans.append('1')
print(' '.join(ans)) |
def epu_calib_gr1800_Aug2019(dets = [sclr, ring_curr]):
print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!')
yield from gcdiag.diode
# srs settings for diode = SRS settings: 5 x1 uA/v , time = 1.0
yield from mv(m1_simple_fbk,0)
yield from mv(m3_simple_fbk,... | def epu_calib_gr1800__aug2019(dets=[sclr, ring_curr]):
print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!')
yield from gcdiag.diode
yield from mv(m1_simple_fbk, 0)
yield from mv(m3_simple_fbk, 0)
yield from mv(epu1.phase, 0)
yield from mv(epu1.table, 1)
yi... |
#!/usr/bin/python3.6
""" A perfect number is a number for which the sum of its proper divisors is
exactly equal to the number. For example, the sum of the proper divisors of 28
would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is... | """ A perfect number is a number for which the sum of its proper divisors is
exactly equal to the number. For example, the sum of the proper divisors of 28
would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n
and it ... |
def duplicate(s):
if(len(s)<=1):
return s
if s[0]==s[1]:
return duplicate(s[1:])
return s[0]+duplicate(s[1:])
s = input()
print(duplicate(s))
| def duplicate(s):
if len(s) <= 1:
return s
if s[0] == s[1]:
return duplicate(s[1:])
return s[0] + duplicate(s[1:])
s = input()
print(duplicate(s)) |
# %%
#######################################
def access_nested_dict(thedict: dict):
"""Demo of how to access a nested dictionary with a two dictionary comprehensions
Examples:
>>> a_dictionary = {
... "1-2017": {
... "Win7": "0.47",
... "Vista": "0.2",
... | def access_nested_dict(thedict: dict):
"""Demo of how to access a nested dictionary with a two dictionary comprehensions
Examples:
>>> a_dictionary = {
... "1-2017": {
... "Win7": "0.47",
... "Vista": "0.2",
... "NT*": "0.09",
... ... |
linhas = int(input('Quantas linhas vai querer?: '))
colunas = int(input('quantas colunas vai querer?: '))
m = []
n = []
for l in range(linhas):
ln = []
lon = 0
for c in range(colunas):
t = int(input(f'qual o valor de [{l},{c}]?: '))
ln.append(t)
lon += t
m.append(ln)
n.appen... | linhas = int(input('Quantas linhas vai querer?: '))
colunas = int(input('quantas colunas vai querer?: '))
m = []
n = []
for l in range(linhas):
ln = []
lon = 0
for c in range(colunas):
t = int(input(f'qual o valor de [{l},{c}]?: '))
ln.append(t)
lon += t
m.append(ln)
n.append... |
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
SNAKE_TO_CAMEL_CASE_TABLE = {
"access_token_secret": "accessTokenSecret",
"api_version": "apiVersion",
"destroy_on_finalize": "destroyOnFinalize",
"e... | snake_to_camel_case_table = {'access_token_secret': 'accessTokenSecret', 'api_version': 'apiVersion', 'destroy_on_finalize': 'destroyOnFinalize', 'env_secrets': 'envSecrets', 'expect_no_refresh_changes': 'expectNoRefreshChanges', 'git_auth_secret': 'gitAuthSecret', 'last_attempted_commit': 'lastAttemptedCommit', 'last_... |
def maxSubsetSumNoAdjacent(array):
# Write your code here.
if not array:
return 0
if len(array) < 3:
return max(array)
dp = [0]*len(array)
dp[0] = array[0]
dp[1] = max(array[1], dp[0])
for i in range(2, len(array)):
dp[i] = max(dp[i - 1], array[i] + dp[i - 2])
... | def max_subset_sum_no_adjacent(array):
if not array:
return 0
if len(array) < 3:
return max(array)
dp = [0] * len(array)
dp[0] = array[0]
dp[1] = max(array[1], dp[0])
for i in range(2, len(array)):
dp[i] = max(dp[i - 1], array[i] + dp[i - 2])
return max(dp) |
# Check if string is palindrom or not....using in-built fxn
a = str(input("Input String"))
b = a.reverse
if a==b:
print("string is palindrome")
else:
print("String is not palindrome")
| a = str(input('Input String'))
b = a.reverse
if a == b:
print('string is palindrome')
else:
print('String is not palindrome') |
__all__ = ['batch_tasks']
def batch_tasks(n_batches, n_tasks=None, arr=None, args=None, start_idx=0,
include_idx=True):
"""Split tasks into some number of batches to send out to workers.
By default, returns index ranges that split the number of tasks into the
specified number of batches. ... | __all__ = ['batch_tasks']
def batch_tasks(n_batches, n_tasks=None, arr=None, args=None, start_idx=0, include_idx=True):
"""Split tasks into some number of batches to send out to workers.
By default, returns index ranges that split the number of tasks into the
specified number of batches. If an array is pa... |
def orf_single(seq):
startss = []
stopss = []
starts_ = []
stop_s = []
start = 0
sslen = 0
s_len1 = 0
s_len2 = 0
newseq = seq
newseq_6 = []
max_l = len(seq)
l = len(seq)
for i in range(len(seq)):
if (seq[i:i+3]=="ATG"):
start = 1 # has start co... | def orf_single(seq):
startss = []
stopss = []
starts_ = []
stop_s = []
start = 0
sslen = 0
s_len1 = 0
s_len2 = 0
newseq = seq
newseq_6 = []
max_l = len(seq)
l = len(seq)
for i in range(len(seq)):
if seq[i:i + 3] == 'ATG':
start = 1
for ... |
numerotabuada = int(input("Escreva um numero e veja sua tabuada: "))
tabuada = []
for x in range(1,10+1):
mult = numerotabuada * x
tabuada.append(mult)
print(tabuada)
| numerotabuada = int(input('Escreva um numero e veja sua tabuada: '))
tabuada = []
for x in range(1, 10 + 1):
mult = numerotabuada * x
tabuada.append(mult)
print(tabuada) |
"""
mpiece.renderer
~~~~~~~~~~~~~~~~~~~~~~~~~
Renderer Classes.
:license: BSD, see LICENSE for details.
:author: David Casado Martinez <dcasadomartinez@gmail.com>
"""
class Renderer(object):
"""
Base renderer class.
All renderer classes should be subclasses of this class.
This class and their subclass ... | """
mpiece.renderer
~~~~~~~~~~~~~~~~~~~~~~~~~
Renderer Classes.
:license: BSD, see LICENSE for details.
:author: David Casado Martinez <dcasadomartinez@gmail.com>
"""
class Renderer(object):
"""
Base renderer class.
All renderer classes should be subclasses of this class.
This class and their subclas... |
class Sense:
def __init__(self, short: str, ident: int):
self.ident = ident
self.short = short
self.pref_label = ''
self.alt_labels = []
def add_pref_label(self, pref_label: str):
self.__check_pref_label_not_set(pref_label)
self.pref_label = pref_label
def a... | class Sense:
def __init__(self, short: str, ident: int):
self.ident = ident
self.short = short
self.pref_label = ''
self.alt_labels = []
def add_pref_label(self, pref_label: str):
self.__check_pref_label_not_set(pref_label)
self.pref_label = pref_label
def ... |
"""
TFIDF + SGD Model for text classification
"""
class GloveRNNModel(object):
"""Recurrent Neural Network Model for text classification"""
def __init__(self, data_dir):
super(GloveRNNModel, self).__init__()
self.data_dir = data_dir
def get_details(self):
""" Get a dictionary of ... | """
TFIDF + SGD Model for text classification
"""
class Glovernnmodel(object):
"""Recurrent Neural Network Model for text classification"""
def __init__(self, data_dir):
super(GloveRNNModel, self).__init__()
self.data_dir = data_dir
def get_details(self):
""" Get a dictionary of a... |
# Test the connection to the database
def test_ping(client):
response = client.get("/ping")
assert response.status_code == 200
assert response.json() == {"ping": "pong!"}
def test_root(client):
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Message": ... | def test_ping(client):
response = client.get('/ping')
assert response.status_code == 200
assert response.json() == {'ping': 'pong!'}
def test_root(client):
response = client.get('/')
assert response.status_code == 200
assert response.json() == {'Message': 'Try /docs or /redoc'} |
def power(a,b):
if b==0:
return 1
elif b%2 == 0:
val = power(a,int(b/2))
return val*val
else:
oddval = power(a,b-1)
return a*oddval
# take base
a = int(input())
#take exponent
b = int(input())
# to find a^b we divide b in two halves recursively.
answer=power(a,b)
print(answer) | def power(a, b):
if b == 0:
return 1
elif b % 2 == 0:
val = power(a, int(b / 2))
return val * val
else:
oddval = power(a, b - 1)
return a * oddval
a = int(input())
b = int(input())
answer = power(a, b)
print(answer) |
senha = int(input())
while senha != 2002:
print("Senha Invalida")
senha = int(input())
print("Acesso Permitido")
| senha = int(input())
while senha != 2002:
print('Senha Invalida')
senha = int(input())
print('Acesso Permitido') |
"""
Practising classes and OOPs
"""
class Robot:
def __init__(self, name=None, build_year=None) -> None:
self.name = name
self.build_year = build_year
def say_hi(self):
if self.name:
print(f"Hi i am {self.name}")
else:
print("Robot without name")
if self.build_year:
print(f"I ... | """
Practising classes and OOPs
"""
class Robot:
def __init__(self, name=None, build_year=None) -> None:
self.name = name
self.build_year = build_year
def say_hi(self):
if self.name:
print(f'Hi i am {self.name}')
else:
print('Robot without name')
... |
#body_x = 120
body_x = 140
body_y = 160
bottom_z = 15
bottom_wall_thikness = 1.5
dist_between_whells = 90
| body_x = 140
body_y = 160
bottom_z = 15
bottom_wall_thikness = 1.5
dist_between_whells = 90 |
DARKEST_GREEN = (15, 56, 15)
DARK_GREEN = (48, 98, 48)
LIGHT_GREEN = (111, 135, 12)
LIGHTEST_GREEN = (155, 188, 15)
DARKEST_GREEN_VAL = 3
DARK_GREEN_VAL = 2
LIGHT_GREEN_VAL = 1
LIGHTEST_GREEN_VAL = 0
| darkest_green = (15, 56, 15)
dark_green = (48, 98, 48)
light_green = (111, 135, 12)
lightest_green = (155, 188, 15)
darkest_green_val = 3
dark_green_val = 2
light_green_val = 1
lightest_green_val = 0 |
RUN_CONFIGURATIONS = {
"Python.DjangoServer": [
]
}
class RunConfiguration:
pass
# workspace.xml
# <?xml version="1.0" encoding="UTF-8"?>
# <project version="4">
# <component name="RunManager" selected="npm.build-prod">
# <configuration name="Worker" type="Python.DjangoServer" factoryName="Django ... | run_configurations = {'Python.DjangoServer': []}
class Runconfiguration:
pass |
# DEBUG
ERROR="\033[31mERROR\033[0m"
SUCCESS="\033[32mSUCCESS\033[0m"
#ALGORITHM CONFIGS
NUM_ATTRS = 8
NUM_TARGETS = 1
NORMALIZE_TARGETS = False
TRAIN_RATIO = (2.0/3.0)
INPUT_DELIMITER = ','
HAS_HEADER=False
NUM_DIGITS = 5
NUM_NEIGHBOURS = 5
EXCLUDE_ATTRS= []
PREDICT_TARGET = 8
NUM_NEURONS_HIDDEN_LAYER = 9
LEARNING_RA... | error = '\x1b[31mERROR\x1b[0m'
success = '\x1b[32mSUCCESS\x1b[0m'
num_attrs = 8
num_targets = 1
normalize_targets = False
train_ratio = 2.0 / 3.0
input_delimiter = ','
has_header = False
num_digits = 5
num_neighbours = 5
exclude_attrs = []
predict_target = 8
num_neurons_hidden_layer = 9
learning_rate = 0.2
num_epochs =... |
CLIENT_ID_ENV_VAR = 'SPOTIFY_CLIENT_ID'
CLIENT_SECRET_ENV_VAR = 'SPOTIFY_CLIENT_SECRET'
USERNAME_ENV_VAR = 'SPOTIFY_USERNAME'
SPOTIFY_API_SCOPE = 'playlist-modify-private,playlist-read-private,user-library-modify,user-library-read'
DEFAULT_REDIRECT_URL = 'http://localhost:8888/callback' | client_id_env_var = 'SPOTIFY_CLIENT_ID'
client_secret_env_var = 'SPOTIFY_CLIENT_SECRET'
username_env_var = 'SPOTIFY_USERNAME'
spotify_api_scope = 'playlist-modify-private,playlist-read-private,user-library-modify,user-library-read'
default_redirect_url = 'http://localhost:8888/callback' |
class Data:
#Class Data is designed to hold an object in a tree
# name: the name of the node, generally more for the leaves and root
# length: the length of the branch from its top node
def __init__( self, name, length, id = 0 ):
self.name = name
self.length = length
s... | class Data:
def __init__(self, name, length, id=0):
self.name = name
self.length = length
self.id = id
def __str__(self):
return '[' + self.name + ', ' + str(self.length) + ']'
def name(self):
return self.name
def length(self):
return self.length
... |
nested = {}
for i, v in mut.iterrows():
if i not in nested:
nested[i] = {}
sample = v['Tumor_Sample_Barcode']
if sample not in nested[i]:
nested[i][sample] = {}
mut_type = v['Variant_Classification']
if mut_type not in nested[i][sample]:
nested[i][sample][mut_type] = []
h... | nested = {}
for (i, v) in mut.iterrows():
if i not in nested:
nested[i] = {}
sample = v['Tumor_Sample_Barcode']
if sample not in nested[i]:
nested[i][sample] = {}
mut_type = v['Variant_Classification']
if mut_type not in nested[i][sample]:
nested[i][sample][mut_type] = []
... |
# Config for automato
# WTF config
WTF_CSRF_ENABLED = True
SECRET_KEY = 'the_very_secure_secret_security_key_that_no_will_ever_guess'
# MySQL Config
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:alpine@127.0.0.1/automato'
SQLALCHEMY_TRACK_MODIFICATIONS = False
RABBITMQ_HOST = "localhost"
WEBDRIVER_PATH = r"C:\Us... | wtf_csrf_enabled = True
secret_key = 'the_very_secure_secret_security_key_that_no_will_ever_guess'
sqlalchemy_database_uri = 'mysql+pymysql://root:alpine@127.0.0.1/automato'
sqlalchemy_track_modifications = False
rabbitmq_host = 'localhost'
webdriver_path = 'C:\\Users\\padam\\Downloads\\chromedriver_win32\\chromedriver... |
def rmtree(root):
""" Function to remove a directory and its contents
:param root: The root directory
:type root: pathlib.Path
"""
for p in root.iterdir():
if p.is_dir():
rmtree(p)
else:
p.unlink()
root.rmdir() | def rmtree(root):
""" Function to remove a directory and its contents
:param root: The root directory
:type root: pathlib.Path
"""
for p in root.iterdir():
if p.is_dir():
rmtree(p)
else:
p.unlink()
root.rmdir() |
class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results
def findNsum(self, sorted_nums, target, N, result, results):... | class Solution:
def four_sum(self, nums, target):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results
def find_nsum(self, sorted_nums, target, N, result, result... |
# Copyright 2017 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 = [
'raw_io',
'step',
]
def RunSteps(api):
# Read command's stdout and stderr.
step_result = api.step('echo', ['echo', 'Hello World... | deps = ['raw_io', 'step']
def run_steps(api):
step_result = api.step('echo', ['echo', 'Hello World'], stdout=api.raw_io.output(), stderr=api.raw_io.output())
step_result = api.step('cat', ['cat'], stdin=api.raw_io.input_text(data='hello'), stdout=api.raw_io.output('out'))
step_result = api.step('automock',... |
numbers = [int(i) for i in input().split()]
average = sum(numbers) / len(numbers)
all_greater_than_average = [greater for greater in numbers if greater > average]
top_five = []
for j in range(5):
if len(all_greater_than_average) == 0:
break
top_five.append(str(max(all_greater_than_average)))
all_gr... | numbers = [int(i) for i in input().split()]
average = sum(numbers) / len(numbers)
all_greater_than_average = [greater for greater in numbers if greater > average]
top_five = []
for j in range(5):
if len(all_greater_than_average) == 0:
break
top_five.append(str(max(all_greater_than_average)))
all_gre... |
"""
@author: acfromspace
"""
def unique_chars_in_string(input_string):
return len(set(input_string)) == len(input_string)
input_string = str(input("Input a string: "))
print("unique_chars_in_string():", unique_chars_in_string(input_string))
| """
@author: acfromspace
"""
def unique_chars_in_string(input_string):
return len(set(input_string)) == len(input_string)
input_string = str(input('Input a string: '))
print('unique_chars_in_string():', unique_chars_in_string(input_string)) |
class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
mx = len(sequence) // len(word)
for repeat in range(1, mx + 2):
sub = word * repeat
if sub not in sequence:
return repeat - 1
return 0
| class Solution:
def max_repeating(self, sequence: str, word: str) -> int:
mx = len(sequence) // len(word)
for repeat in range(1, mx + 2):
sub = word * repeat
if sub not in sequence:
return repeat - 1
return 0 |
class Node(object):
"""simple node for a linked list"""
def __init__(self, e):
self.next_ = None
self.e = e
class LinkedList(object):
"""linked list with simple built-in iterator"""
def __init__(self):
self.first = None
self.last = None
self.current = None
self.size = 0
def next_(sel... | class Node(object):
"""simple node for a linked list"""
def __init__(self, e):
self.next_ = None
self.e = e
class Linkedlist(object):
"""linked list with simple built-in iterator"""
def __init__(self):
self.first = None
self.last = None
self.current = None
... |
"""Export2D - Export Fusion 360 model faces as PDF or DXF files"""
__version__ = '0.1.0'
__author__ = 'Patrick Rainsberry <patrick.rainsberry@autodesk.com>'
__all__ = []
| """Export2D - Export Fusion 360 model faces as PDF or DXF files"""
__version__ = '0.1.0'
__author__ = 'Patrick Rainsberry <patrick.rainsberry@autodesk.com>'
__all__ = [] |
test = { 'name': 'q2a',
'points': 1,
'suites': [ { 'cases': [ {'code': '>>> 600 < num_schools < 700\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> # Come back to this, not sure if it works;\n>>> num_schools == 659\nTrue', 'hidden': False, 'locked': False}],
... | test = {'name': 'q2a', 'points': 1, 'suites': [{'cases': [{'code': '>>> 600 < num_schools < 700\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Come back to this, not sure if it works;\n>>> num_schools == 659\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'do... |
__all__ = ['__name__', '__version__', '__author__', '__author_email__', '__description__']
__name__ = 'ssec'
__version__ = '2.0.0'
__author__ = 'Justin Baudisch'
__author_email__ = 'baudischjustin1995@gmail.com'
__description__ = 'Yet another client library for server-sent events (sse).'
| __all__ = ['__name__', '__version__', '__author__', '__author_email__', '__description__']
__name__ = 'ssec'
__version__ = '2.0.0'
__author__ = 'Justin Baudisch'
__author_email__ = 'baudischjustin1995@gmail.com'
__description__ = 'Yet another client library for server-sent events (sse).' |
# calculate the hamming distance between two numbers
# count the number of 1 after xor operation of two number
# citation: https://leetcode.com/articles/hamming-distance/
# approach 1: using library function
def hamming_distance_using_library(x, y):
xor = x ^ y
return bin(xor).count('1')
# approach 2: using... | def hamming_distance_using_library(x, y):
xor = x ^ y
return bin(xor).count('1')
def hamming_distance_bit_shift(x, y):
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance = distance + 1
xor = xor >> 1
return distance
def hamming_distance_brian_kernighan(x, y):
... |
# -*- coding: utf-8 -*-
__version__ = '1.4.0'
default_app_config = 'djangocms_translations.apps.DjangocmsTranslationsConfig'
| __version__ = '1.4.0'
default_app_config = 'djangocms_translations.apps.DjangocmsTranslationsConfig' |
_base_ = './tood_r50_fpn_1x_coco.py'
model = dict(
bbox_head=dict(
anchor_type='anchor_based'
)
)
| _base_ = './tood_r50_fpn_1x_coco.py'
model = dict(bbox_head=dict(anchor_type='anchor_based')) |
# https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent
def array_strings_are_equal(word1, word2):
return ''.join(word1) == ''.join(word2) | def array_strings_are_equal(word1, word2):
return ''.join(word1) == ''.join(word2) |
A=[list(map(int,input().split())) for i in range(4)]
flag=0
for x in range(4):
for y in range(3):
if A[x][y]==A[x][y+1] or A[y][x]==A[y+1][x]:flag=1
print("CONTINUE" if flag==1 else "GAMEOVER") | a = [list(map(int, input().split())) for i in range(4)]
flag = 0
for x in range(4):
for y in range(3):
if A[x][y] == A[x][y + 1] or A[y][x] == A[y + 1][x]:
flag = 1
print('CONTINUE' if flag == 1 else 'GAMEOVER') |
#!/usr/bin/env python3
def betolt(file):
megallok = []
with open(file, "rt") as f:
for sor in f:
megallok.append(sor.rstrip("\n"))
return megallok
def metszi_e(alista, blista):
for elem in alista:
if elem in blista:
return elem
return None
def main():
print(metszi_e(betolt("... | def betolt(file):
megallok = []
with open(file, 'rt') as f:
for sor in f:
megallok.append(sor.rstrip('\n'))
return megallok
def metszi_e(alista, blista):
for elem in alista:
if elem in blista:
return elem
return None
def main():
print(metszi_e(betolt('4_... |
'''
994. Rotting Oranges Medium
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Retur... | """
994. Rotting Oranges Medium
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Retur... |
"""
Algorithm (BFS):
1. Collect all positions of the zombies into a queue. Then we will use this queue for collecting positions of humans only.
2. Find adjacent humans around each enqueued position.
3. Convert them into zombies.
4. Add their positions into a turned-into-zombie queue.
5. Increase number of the hours.
6.... | """
Algorithm (BFS):
1. Collect all positions of the zombies into a queue. Then we will use this queue for collecting positions of humans only.
2. Find adjacent humans around each enqueued position.
3. Convert them into zombies.
4. Add their positions into a turned-into-zombie queue.
5. Increase number of the hours.
6.... |
def sort(nums):
for i in range(len(nums)-1, 0, -1):
for j in range (i):
if nums[j] > nums[j + 1]:
temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
nums = [2,6,4,1,8,7]
sort(nums)
print(nums) | def sort(nums):
for i in range(len(nums) - 1, 0, -1):
for j in range(i):
if nums[j] > nums[j + 1]:
temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
nums = [2, 6, 4, 1, 8, 7]
sort(nums)
print(nums) |
counter=1
def setup():
size(500,500)
smooth()
def draw():
global counter
noStroke()
fill (10, 50)
rect (-1,-1, width//2 +1, height +1)
ny = sin( counter ) *100+200
nx = counter *10
stroke (250)
strokeWeight (20)
line(nx , ny , nx , ny)
counter =... | counter = 1
def setup():
size(500, 500)
smooth()
def draw():
global counter
no_stroke()
fill(10, 50)
rect(-1, -1, width // 2 + 1, height + 1)
ny = sin(counter) * 100 + 200
nx = counter * 10
stroke(250)
stroke_weight(20)
line(nx, ny, nx, ny)
counter = counter + 0.1
i... |
class Calc:
"""Simple calculator."""
def __init__(self, a, b):
self.a = a
self.b = b
def do(self):
"""Perform calculation."""
return self.a + self.b
| class Calc:
"""Simple calculator."""
def __init__(self, a, b):
self.a = a
self.b = b
def do(self):
"""Perform calculation."""
return self.a + self.b |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
class WikiBase(object):
WikiLineSep = '\r\n'
def __init__(self, wikiId, client):
self.client = client
self.wikiPage = client.wiki(wikiId)
def writeWikiPage(self, content, mailNotify=False):
wikiName = self.wikiPage['name']
para... | class Wikibase(object):
wiki_line_sep = '\r\n'
def __init__(self, wikiId, client):
self.client = client
self.wikiPage = client.wiki(wikiId)
def write_wiki_page(self, content, mailNotify=False):
wiki_name = self.wikiPage['name']
params = {'name': wikiName, 'content': content... |
# The final segments are shown by calling the property ``t_masked`` which returns the
# target data as an ndarray with NaN values for areas not found to be segments.
plt.figure(figsize=(15,3)) # doctest: +SKIP
plt.plot(s.t_masked.T) # doctest: +SKIP
plt.xlabel("time in s") # doctest: +SKIP
plt.ylabel("ECG in mV") ... | plt.figure(figsize=(15, 3))
plt.plot(s.t_masked.T)
plt.xlabel('time in s')
plt.ylabel('ECG in mV')
plt.tight_layout()
plt.show() |
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"] # python3
#return ["Hello World"] # python2
# uwsgi --http :8000 --wsgi-file test.py
# uwsgi --http :8000 --home /home/ubuntu/venv --chdir /home/ubuntu/ShirtGeeks/src/ --module conf.wsgi | def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'Hello World'] |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Initialization module for NAAS. Sets version
"""
__version__ = "0.6.2"
__base_response__ = {"app": "naas", "version": __version__}
| """
Initialization module for NAAS. Sets version
"""
__version__ = '0.6.2'
__base_response__ = {'app': 'naas', 'version': __version__} |
def count_bags(balls, diff):
count = 0
target = diff
while balls >= target:
print(f"Target {target} Balls {balls}")
count += 1
balls -= target
target += diff
return count
if __name__ == '__main__':
bags, balls, diff = map(int, input().split())
print(bags - co... | def count_bags(balls, diff):
count = 0
target = diff
while balls >= target:
print(f'Target {target} Balls {balls}')
count += 1
balls -= target
target += diff
return count
if __name__ == '__main__':
(bags, balls, diff) = map(int, input().split())
print(bags - count... |
class AddrStats:
"""A simple class detailing stats on the read addresses ...
Keeps track of address info AND writes to the results
file specified, no parsing in this class"""
# Constructor
def __init__(self, resultsFile='results.txt', hasOffset=True, debug=False, debugAll=False):
... | class Addrstats:
"""A simple class detailing stats on the read addresses ...
Keeps track of address info AND writes to the results
file specified, no parsing in this class"""
def __init__(self, resultsFile='results.txt', hasOffset=True, debug=False, debugAll=False):
self.hasOffset = has... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.