content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Tree(object):
def __init__(self):
self.children = []
self.metadata = []
def add_child(self, leaf):
self.children.append(leaf)
def add_metadata(self, metadata):
self.metadata.append(metadata)
def sum_metadata(self):
metasum = sum(self.metadata)
for... | class Tree(object):
def __init__(self):
self.children = []
self.metadata = []
def add_child(self, leaf):
self.children.append(leaf)
def add_metadata(self, metadata):
self.metadata.append(metadata)
def sum_metadata(self):
metasum = sum(self.metadata)
fo... |
print("RENTAL MOBIL ABCD")
print("-------------------------------")
#Input
nama = input("Masukkan Nama Anda : ")
umur = int(input("Masukkan Umur Anda : "))
if umur < 18:
print("Maaf", nama, "anda belum bisa meminjam kendaraan")
else:
ktp = int(input("Masukkan Nomor KTP Anda : "))
k_mobil = in... | print('RENTAL MOBIL ABCD')
print('-------------------------------')
nama = input('Masukkan Nama Anda : ')
umur = int(input('Masukkan Umur Anda : '))
if umur < 18:
print('Maaf', nama, 'anda belum bisa meminjam kendaraan')
else:
ktp = int(input('Masukkan Nomor KTP Anda : '))
k_mobil = input('Kategori Mobil [4... |
def func_that_raises():
raise ValueError('Error message')
def func_no_catch():
func_that_raises()
| def func_that_raises():
raise value_error('Error message')
def func_no_catch():
func_that_raises() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 07:34:02 2020
@author: krishan
"""
class BaseClass:
num_base_calls = 0
def call_me(self):
print("Calling method on Base Class")
self.num_base_calls += 1
class LeftSubclass(BaseClass):
num_left_calls = 0
... | """
Created on Tue Jun 16 07:34:02 2020
@author: krishan
"""
class Baseclass:
num_base_calls = 0
def call_me(self):
print('Calling method on Base Class')
self.num_base_calls += 1
class Leftsubclass(BaseClass):
num_left_calls = 0
def call_me(self):
BaseClass.call_me(self)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2017 JiNong Inc. All right reserved.
#
__title__ = 'python-pyjns'
__version__ = '0.40'
__author__ = 'Kim, JoonYong'
__email__ = 'joonyong.jinong@gmail.com'
__copyright__ = 'Copyright 2016-2017 JiNong Inc.'
| __title__ = 'python-pyjns'
__version__ = '0.40'
__author__ = 'Kim, JoonYong'
__email__ = 'joonyong.jinong@gmail.com'
__copyright__ = 'Copyright 2016-2017 JiNong Inc.' |
"""
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines,
which, together with the x-axis forms a container, such that the container contains the most water.
... | """
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines,
which, together with the x-axis forms a container, such that the container contains the most water.
... |
extensions = [
"cogs.help",
"cogs.game_punishments.ban",
"cogs.game_punishments.kick",
"cogs.game_punishments.unban",
"cogs.game_punishments.warn",
"cogs.settings.setchannel",
"cogs.verification.verify"
]
| extensions = ['cogs.help', 'cogs.game_punishments.ban', 'cogs.game_punishments.kick', 'cogs.game_punishments.unban', 'cogs.game_punishments.warn', 'cogs.settings.setchannel', 'cogs.verification.verify'] |
def __getitem__(self,idx):
if idx < self.lastIndex:
return self.myArray[idx]
else:
raise LookupError('index out of bounds')
def __setitem__(self,idx,val):
if idx < self.lastIndex:
self.myArray[idx] = val
else:
raise LookupError('index out of bounds')
| def __getitem__(self, idx):
if idx < self.lastIndex:
return self.myArray[idx]
else:
raise lookup_error('index out of bounds')
def __setitem__(self, idx, val):
if idx < self.lastIndex:
self.myArray[idx] = val
else:
raise lookup_error('index out of bounds') |
__author__ = "Amane Katagiri"
__contact__ = "amane@ama.ne.jp"
__copyright__ = "Copyright (C) 2016 Amane Katagiri"
__credits__ = ""
__date__ = "2016-12-07"
__license__ = "MIT License"
__version__ = "0.1.0"
| __author__ = 'Amane Katagiri'
__contact__ = 'amane@ama.ne.jp'
__copyright__ = 'Copyright (C) 2016 Amane Katagiri'
__credits__ = ''
__date__ = '2016-12-07'
__license__ = 'MIT License'
__version__ = '0.1.0' |
example_dict = {}
for idx in range(0, 10):
example_dict[idx] = idx
for key, value in example_dict.items():
formmating = f'key is {key}, value is {value}'
print(formmating) | example_dict = {}
for idx in range(0, 10):
example_dict[idx] = idx
for (key, value) in example_dict.items():
formmating = f'key is {key}, value is {value}'
print(formmating) |
def minimumSwaps(arr):
a = dict(enumerate(arr,1))
b = {v:k for k,v in a.items()}
count = 0
for i in a:
x = a[i]
if x!=i:
y = b[i]
a[y] = x
b[x] = y
count+=1
return count
n = int(input())
arr = list(map(int,input(... | def minimum_swaps(arr):
a = dict(enumerate(arr, 1))
b = {v: k for (k, v) in a.items()}
count = 0
for i in a:
x = a[i]
if x != i:
y = b[i]
a[y] = x
b[x] = y
count += 1
return count
n = int(input())
arr = list(map(int, input().split()))
p... |
class TMVError(Exception):
""" Base exception """
class CameraError(Exception):
"""" Hardware camera problem"""
class ButtonError(Exception):
""" Problem with (usually hardware) buttons """
class VideoMakerError(Exception):
""" Problem making images into a video """
class ImageError(Exception):
... | class Tmverror(Exception):
""" Base exception """
class Cameraerror(Exception):
"""" Hardware camera problem"""
class Buttonerror(Exception):
""" Problem with (usually hardware) buttons """
class Videomakererror(Exception):
""" Problem making images into a video """
class Imageerror(Exception):
... |
def extract_characters(*file):
with open("file3.txt") as f:
while True:
c = f.read(1)
if not c:
break
print(c)
extract_characters('file3.txt') | def extract_characters(*file):
with open('file3.txt') as f:
while True:
c = f.read(1)
if not c:
break
print(c)
extract_characters('file3.txt') |
class MTUError(Exception):
pass
class MACError(Exception):
pass
class IPv4AddressError(Exception):
pass
| class Mtuerror(Exception):
pass
class Macerror(Exception):
pass
class Ipv4Addresserror(Exception):
pass |
def cyclesort(lst):
for i in range(len(lst)):
if i != lst[i]:
n = i
while 1:
tmp = lst[int(n)]
if n != i:
lst[int(n)] = last_value
lst.log()
else:
lst[int(n)] = None
... | def cyclesort(lst):
for i in range(len(lst)):
if i != lst[i]:
n = i
while 1:
tmp = lst[int(n)]
if n != i:
lst[int(n)] = last_value
lst.log()
else:
lst[int(n)] = None
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 12 17:16:30 2021
@author: Marchiano
Sudoku solver using backtraking algorithm
Steps followed:
1) Find empty position on grid
2) Check if value on specified grid position is admissible
3) If valid, solve recursively the puzzle by repeating steps 1 and 2 for th... | """
Created on Sun Dec 12 17:16:30 2021
@author: Marchiano
Sudoku solver using backtraking algorithm
Steps followed:
1) Find empty position on grid
2) Check if value on specified grid position is admissible
3) If valid, solve recursively the puzzle by repeating steps 1 and 2 for the entire grid.
Otherwise, reset ... |
# game model
# - holds global game properties
class Game():
def __init__(self, config):
self.config = config
self.pygame = config.pygame
self.screen = self.pygame.display.set_mode(
(
self.config.SCREEN_PX_WIDTH,
self.config.SCREEN_PX_HEIGHT
)
)
self.clock = self.pygame.time.Clock()
self.... | class Game:
def __init__(self, config):
self.config = config
self.pygame = config.pygame
self.screen = self.pygame.display.set_mode((self.config.SCREEN_PX_WIDTH, self.config.SCREEN_PX_HEIGHT))
self.clock = self.pygame.time.Clock()
self.running = True
self.restart = T... |
lexicon_dataset = {
'direction': 'north south east west down up left right back',
'verb': 'go stop kill eat',
'stop': 'the in of from at it',
'noun': 'door bear princess cabinet'
}
def scan(sentence):
result = []
words = sentence.split(' ')
for word in words:
if word.isnumeric():
... | lexicon_dataset = {'direction': 'north south east west down up left right back', 'verb': 'go stop kill eat', 'stop': 'the in of from at it', 'noun': 'door bear princess cabinet'}
def scan(sentence):
result = []
words = sentence.split(' ')
for word in words:
if word.isnumeric():
word = i... |
#
# PHASE: unused deps checker
#
# DOCUMENT THIS
#
load(
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
"get_unused_dependency_checker_mode",
)
def phase_unused_deps_checker(ctx, p):
return get_unused_dependency_checker_mode(ctx)
| load('@io_bazel_rules_scala//scala/private:rule_impls.bzl', 'get_unused_dependency_checker_mode')
def phase_unused_deps_checker(ctx, p):
return get_unused_dependency_checker_mode(ctx) |
def merge_sorted_arr(left, right):
i = 0
j = 0
new_arr = []
while j < len(right) and i < len(left):
if left[i] < right[j]:
new_arr.append(left[i])
i += 1
elif right[j] <= left[i]:
new_arr.append(right[j])
j += 1
while i < len(left):
... | def merge_sorted_arr(left, right):
i = 0
j = 0
new_arr = []
while j < len(right) and i < len(left):
if left[i] < right[j]:
new_arr.append(left[i])
i += 1
elif right[j] <= left[i]:
new_arr.append(right[j])
j += 1
while i < len(left):
... |
{
"targets": [
{
"target_name" : "libtracer",
"type" : "static_library",
"sources" : [
"./libtracer/basic.observer.cpp",
"./libtracer/simple.tracer/simple.tracer.cpp",
"./libtracer/annotated.tracer/TrackingExecutor.cpp",
"./libtracer/annotated.tracer/BitMap.cpp",
"./libtracer... | {'targets': [{'target_name': 'libtracer', 'type': 'static_library', 'sources': ['./libtracer/basic.observer.cpp', './libtracer/simple.tracer/simple.tracer.cpp', './libtracer/annotated.tracer/TrackingExecutor.cpp', './libtracer/annotated.tracer/BitMap.cpp', './libtracer/annotated.tracer/annotated.tracer.cpp'], 'include_... |
pet1 = {'name': 'mr.bubbles', "type":'dog', "owner" : 'joe'}
pet2 = {'name': 'spot', "type":'cat', "owner" : 'bob'}
pet3 = {'name': 'chester', "type":'horse', "owner" : 'chloe'}
pets = [pet1, pet2, pet3]
for pet in pets:
print(pet['name'], pet['type'], pet['owner'])
| pet1 = {'name': 'mr.bubbles', 'type': 'dog', 'owner': 'joe'}
pet2 = {'name': 'spot', 'type': 'cat', 'owner': 'bob'}
pet3 = {'name': 'chester', 'type': 'horse', 'owner': 'chloe'}
pets = [pet1, pet2, pet3]
for pet in pets:
print(pet['name'], pet['type'], pet['owner']) |
'''
Author: ZHAO Zinan
Created: 10. March 2019
1005. Maximize Sum Of Array After K Negations
'''
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A.sort()
for index, a in enumerate(A):
if a <= 0:
if K > 0:
... | """
Author: ZHAO Zinan
Created: 10. March 2019
1005. Maximize Sum Of Array After K Negations
"""
class Solution:
def largest_sum_after_k_negations(self, A: List[int], K: int) -> int:
A.sort()
for (index, a) in enumerate(A):
if a <= 0:
if K > 0:
A[in... |
def main():
N, M = map(int, input().split())
a = list(map(int, input().split()))
A = a[-1]
def is_ok(mid):
last = a[0]
count = 1
for i in range(1,N):
if a[i] - last >= mid:
count += 1
last = a[i]
if count >= M... | def main():
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
a = a[-1]
def is_ok(mid):
last = a[0]
count = 1
for i in range(1, N):
if a[i] - last >= mid:
count += 1
last = a[i]
if count >= M:
r... |
class AddOperation:
def soma(self, number1, number2):
return number1 + number2
| class Addoperation:
def soma(self, number1, number2):
return number1 + number2 |
GOOGLE_SHEET_URL = (
"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/{table_name}"
)
LOGGING_DICT = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {"standard": {"format": "%(message)s"}},
"handlers": {
"file": {
"level": "INFO",
"cl... | google_sheet_url = 'https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/{table_name}'
logging_dict = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'standard': {'format': '%(message)s'}}, 'handlers': {'file': {'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'a... |
N = int(input())
A = [int(x) for x in input().split()]
for i in range(N):
for j in range(i, N):
A[i], A[j] = A[j], A[i]
if sorted(A) == A:
print("YES")
quit()
A[i], A[j] = A[j], A[i]
print("NO")
| n = int(input())
a = [int(x) for x in input().split()]
for i in range(N):
for j in range(i, N):
(A[i], A[j]) = (A[j], A[i])
if sorted(A) == A:
print('YES')
quit()
(A[i], A[j]) = (A[j], A[i])
print('NO') |
"""Top-level package for pycorrel."""
__author__ = """Maxime Godin"""
__email__ = 'maxime.godin@polytechnique.org'
__version__ = '0.1.1'
| """Top-level package for pycorrel."""
__author__ = 'Maxime Godin'
__email__ = 'maxime.godin@polytechnique.org'
__version__ = '0.1.1' |
def add_time(start, duration, start_day = ""):
new_time = ""
#24h_hours = 0
# If a user added a starting day, correct the input to be lower
if start_day:
start_day = start_day.lower()
if start_day == 'monday':
start_day_num = 0
elif start_day == 'tuesday':
start_day_num = 1
elif start_day... | def add_time(start, duration, start_day=''):
new_time = ''
if start_day:
start_day = start_day.lower()
if start_day == 'monday':
start_day_num = 0
elif start_day == 'tuesday':
start_day_num = 1
elif start_day == 'wednesday':
start_day_num = 2
elif start_day == 'th... |
n1 = 36
n2 = 14
m = max(n1, n2)
lcm = n1 * n2
rng = range(m, n1*n2+1)
for i in rng:
if i % n1 == 0 and i % n2 == 0:
print("The lcm is " + str(i))
break
| n1 = 36
n2 = 14
m = max(n1, n2)
lcm = n1 * n2
rng = range(m, n1 * n2 + 1)
for i in rng:
if i % n1 == 0 and i % n2 == 0:
print('The lcm is ' + str(i))
break |
# take linear julia list of lists and convert to julia array format
execfile('../pyprgs/in_out_line.py')
execfile('../pyprgs/in_out_csv.py')
dat1 = lin.reader("../poets/results_poets/cross_validation/EC1.dat")
dat2 = lin.reader("../poets/results_poets/cross_validation/EC2.dat")
dat3 = lin.reader("../poets/results_poe... | execfile('../pyprgs/in_out_line.py')
execfile('../pyprgs/in_out_csv.py')
dat1 = lin.reader('../poets/results_poets/cross_validation/EC1.dat')
dat2 = lin.reader('../poets/results_poets/cross_validation/EC2.dat')
dat3 = lin.reader('../poets/results_poets/cross_validation/EC3.dat')
dat4 = lin.reader('../poets/results_poet... |
#!/usr/bin/env python3
#coding: utf-8
### 1st line allows to execute this script by typing only its name in terminal, with no need to precede it with the python command
### 2nd line declaring source code charset should be not necessary but for exemple pydoc request it
__doc__ = "3D obj file loader"#information descr... | __doc__ = '3D obj file loader'
__status__ = 'Development'
__version__ = '2.0.0'
__license__ = 'public domain'
__date__ = '2010'
__author__ = 'N-zo syslog@laposte.net'
__maintainer__ = 'Nzo'
__credits__ = []
__contact__ = 'syslog@laposte.net'
def load_obj_file(filepath):
"""read 3D obj file and return data"""
o... |
# Quick Sort
# Randomize Pivot to avoid worst case, currently pivot is last element
def quickSort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quickSort(A, si, pi-1)
quickSort(A, pi+1, ei)
# Partition
# Utility function for partitioning the array(used in quick sort)
def partition(A, s... | def quick_sort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quick_sort(A, si, pi - 1)
quick_sort(A, pi + 1, ei)
def partition(A, si, ei):
x = A[ei]
i = si - 1
for j in range(si, ei):
if A[j] <= x:
i += 1
(A[i], A[j]) = (A[j], A[i])
(A[i +... |
# -*- coding:utf-8 -*-
"""
@file name: __init__.py.py
Created on 2019/5/14
@author: kyy_b
@desc:
"""
if __name__ == "__main__":
pass | """
@file name: __init__.py.py
Created on 2019/5/14
@author: kyy_b
@desc:
"""
if __name__ == '__main__':
pass |
class Proxy():
proxies = [] # Will contain proxies [ip, port]
#### adding proxy information so as not to get blocked so fast
def getProxyList(self):
# Retrieve latest proxies
url = 'https://www.sslproxies.org/'
header = {'User-Agent': str(ua.random)}
response = requests.get(ur... | class Proxy:
proxies = []
def get_proxy_list(self):
url = 'https://www.sslproxies.org/'
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header)
soup = beautiful_soup(response.text, 'lxml')
proxies_table = soup.find(id='proxylisttable')
... |
input = """
mysum(X) :- #sum{P: c(P)} = X, dom(X).
mycount(X) :- #count{P: c(P)} = X, dom(X).
dom(0). dom(1).
c(X) | d(X) :- dom(X).
:- not c(0).
:- not c(1).
"""
output = """
mysum(X) :- #sum{P: c(P)} = X, dom(X).
mycount(X) :- #count{P: c(P)} = X, dom(X).
dom(0). dom(1).
c(X) | d(X) :- dom(X).
:- not c(0).
:- not... | input = '\nmysum(X) :- #sum{P: c(P)} = X, dom(X).\nmycount(X) :- #count{P: c(P)} = X, dom(X).\n\ndom(0). dom(1).\nc(X) | d(X) :- dom(X).\n\n:- not c(0).\n:- not c(1).\n'
output = '\nmysum(X) :- #sum{P: c(P)} = X, dom(X).\nmycount(X) :- #count{P: c(P)} = X, dom(X).\n\ndom(0). dom(1).\nc(X) | d(X) :- dom(X).\n\n:- not c(... |
file = open("nomes.txt", "r")
lines = file.readlines()
title = lines[0]
names = title.strip().split(",")
print(names)
for i in lines[1:]:
aux = i.strip().split(",")
print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2])) | file = open('nomes.txt', 'r')
lines = file.readlines()
title = lines[0]
names = title.strip().split(',')
print(names)
for i in lines[1:]:
aux = i.strip().split(',')
print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2])) |
x = 50
def funk():
global x
print("x je ", x)
x = 2
print("Promjena globalne vrijednost promjeljive x na ", x)
funk()
print("Vrijednost promjeljive x sada je ", x)
| x = 50
def funk():
global x
print('x je ', x)
x = 2
print('Promjena globalne vrijednost promjeljive x na ', x)
funk()
print('Vrijednost promjeljive x sada je ', x) |
# https://leetcode.com/contest/weekly-contest-132/problems/maximum-difference-between-node-and-ancestor/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self... | class Solution(object):
def __init__(self):
self.max = 0
self.min = 10000
def max_ancestor_diff(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.findMaxDiff(root, 10000, 0)
def iq_test(self, numbers):
even = []
odd =... |
# Each new term in the Fibonacci sequence is generated by adding
# the previous two terms. By starting with 1 and 2, the first 10
# terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values
# do not exceed four million, find the sum of the even-valu... | def fib_sum(limit):
return fib_calc(limit, 0, 1, 0)
def fib_calc(limit, a, b, accum):
if b > limit:
return accum
else:
if b % 2 == 0:
accum += b
return fib_calc(limit, b, a + b, accum)
if __name__ == '__main__':
print(fib_sum(4000000)) |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Gregorian'},
{'abbr': 1, 'code': 1, 'title': '360-day'},
{'abbr': 2, 'code': 2, 'title': '365-day'},
{'abbr': 3, 'code': 3, 'title': 'Proleptic Gregorian'},
{'abbr': None, 'code': 255, 'title': 'Missing'})
| def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Gregorian'}, {'abbr': 1, 'code': 1, 'title': '360-day'}, {'abbr': 2, 'code': 2, 'title': '365-day'}, {'abbr': 3, 'code': 3, 'title': 'Proleptic Gregorian'}, {'abbr': None, 'code': 255, 'title': 'Missing'}) |
#
# PySNMP MIB module ZXR10-VSWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXR10-VSWITCH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:42:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
del_items(0x80122A40)
SetType(0x80122A40, "struct Creds CreditsTitle[6]")
del_items(0x80122BE8)
SetType(0x80122BE8, "struct Creds CreditsSubTitle[28]")
del_items(0x80123084)
SetType(0x80123084, "struct Creds CreditsText[35]")
del_items(0x8012319C)
SetType(0x8012319C, "int CreditsTable[224]")
del_items(0x801243BC)
SetTy... | del_items(2148674112)
set_type(2148674112, 'struct Creds CreditsTitle[6]')
del_items(2148674536)
set_type(2148674536, 'struct Creds CreditsSubTitle[28]')
del_items(2148675716)
set_type(2148675716, 'struct Creds CreditsText[35]')
del_items(2148675996)
set_type(2148675996, 'int CreditsTable[224]')
del_items(2148680636)
s... |
# -*- coding: utf-8 -*-
class RegisterException(Exception):
"""Exception raised on a registration error."""
| class Registerexception(Exception):
"""Exception raised on a registration error.""" |
has_high_income = True
has_good_credit = True
has_criminal_record = False
if has_high_income and has_good_credit:
print("Eligible for loan")
if has_high_income or has_good_credit:
print("Eligible for consultation")
if has_good_credit and not has_criminal_record:
print("Eligible for credit card") | has_high_income = True
has_good_credit = True
has_criminal_record = False
if has_high_income and has_good_credit:
print('Eligible for loan')
if has_high_income or has_good_credit:
print('Eligible for consultation')
if has_good_credit and (not has_criminal_record):
print('Eligible for credit card') |
#1
def print_factors(n):
#2
for i in range(1, n+1):
#3
if n % i == 0:
print(i)
#4
number = int(input("Enter a number : "))
#5
print("The factors for {} are : ".format(number))
print_factors(number)
| def print_factors(n):
for i in range(1, n + 1):
if n % i == 0:
print(i)
number = int(input('Enter a number : '))
print('The factors for {} are : '.format(number))
print_factors(number) |
# Min Heap implementation
def swap(h, i, j):
h[i], h[j] = h[j], h[i]
def _min_heap_sift_up(h, k):
while k//2 >= 0:
if h[k] < h[k//2]:
swap(h, k, k//2)
k = k//2
else:
break
def _min_heap_sift_down(h, k):
last = len(h)-1
while (2*k+1) < last:
... | def swap(h, i, j):
(h[i], h[j]) = (h[j], h[i])
def _min_heap_sift_up(h, k):
while k // 2 >= 0:
if h[k] < h[k // 2]:
swap(h, k, k // 2)
k = k // 2
else:
break
def _min_heap_sift_down(h, k):
last = len(h) - 1
while 2 * k + 1 < last:
child = 2 *... |
{
"targets": [
{
"target_name": "node-cursor",
"sources": [ "node-cursor.cc" ]
}
]
} | {'targets': [{'target_name': 'node-cursor', 'sources': ['node-cursor.cc']}]} |
"""
A stub module to house pyrolite extensions,
where they are installed.
"""
| """
A stub module to house pyrolite extensions,
where they are installed.
""" |
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = []
common = [res.append(list(set(a))[0]) for a in itertools.takewhile(lambda x: len(set(x)) == 1, [x for x in zip(*strs)])]
return "".join(res)
# Enumeration soln
# def longestCommonPrefix(s... | class Solution:
def longest_common_prefix(self, strs: List[str]) -> str:
res = []
common = [res.append(list(set(a))[0]) for a in itertools.takewhile(lambda x: len(set(x)) == 1, [x for x in zip(*strs)])]
return ''.join(res) |
def solution(coins, amount):
coins = sorted(coins)
minCoins = [0] * (amount + 1)
for k in range(1, amount+1):
minCoins[k] = amount + 1
i = 0
while i < len(coins) and coins[i] <= k:
minCoins[k] = min(minCoins[k], minCoins[k - coins[i]] + 1)
i += 1
... | def solution(coins, amount):
coins = sorted(coins)
min_coins = [0] * (amount + 1)
for k in range(1, amount + 1):
minCoins[k] = amount + 1
i = 0
while i < len(coins) and coins[i] <= k:
minCoins[k] = min(minCoins[k], minCoins[k - coins[i]] + 1)
i += 1
if min... |
class Node:
def __init__(self, value, _next=None):
self._value = value
self._next = _next
def __str__(self):
return f'{self._value}'
def __repr__(self):
return f'<Node | Val: {self._value} | Next: {self._next}>'
| class Node:
def __init__(self, value, _next=None):
self._value = value
self._next = _next
def __str__(self):
return f'{self._value}'
def __repr__(self):
return f'<Node | Val: {self._value} | Next: {self._next}>' |
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
# click to show follow up.
# Follow up:
# Did you use extra space?
# A straight forward solution using O(mn) space is probably a bad idea.
# A simple improvement uses O(m + n) space, but still not the best solution.
# Coul... | class Solution:
def set_zeroes(self, matrix):
fr = fc = False
for i in xrange(len(matrix)):
for j in xrange(len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
if i == 0:
fr = True
... |
x=input('enter str1')
y=input('enter str2')
a=[]
b=[];c=[];max=-1
for i in range(len(x)+1):
for j in range(i+1,len(x)+1):
a.append(x[i:j])
for i in range(len(y)+1):
for j in range(i+1,len(y)+1):
b.append(y[i:j])
for i in range(len(a)):
for j in range(len(b)):
if a[i]==b[j... | x = input('enter str1')
y = input('enter str2')
a = []
b = []
c = []
max = -1
for i in range(len(x) + 1):
for j in range(i + 1, len(x) + 1):
a.append(x[i:j])
for i in range(len(y) + 1):
for j in range(i + 1, len(y) + 1):
b.append(y[i:j])
for i in range(len(a)):
for j in range(len(b)):
... |
altitude = int(input("CURRENT ALTITUDE:"))
if altitude <=1000:
print("You can land the plan")
elif altitude > 1000 and altitude < 5000:
print("Come down to 1000")
else:
print("Turn around")
| altitude = int(input('CURRENT ALTITUDE:'))
if altitude <= 1000:
print('You can land the plan')
elif altitude > 1000 and altitude < 5000:
print('Come down to 1000')
else:
print('Turn around') |
class Solution:
def myPow(self, x: float, n: int) -> float:
'''
x^n = x^2 ^ (n//2) if n is even
x^n = x * x^2 ^ (n//2) is n is odd
'''
if n == 0: return 1
result = self.myPow(x*x, abs(n) //2)
if n % 2:
result *= x
... | class Solution:
def my_pow(self, x: float, n: int) -> float:
"""
x^n = x^2 ^ (n//2) if n is even
x^n = x * x^2 ^ (n//2) is n is odd
"""
if n == 0:
return 1
result = self.myPow(x * x, abs(n) // 2)
if n % 2:
result *= x
if n < 0:... |
# Python snippets
#################################
class MetaClass(type):
"""Return a class object with the __class__ attribute equal to the class object.
This allows interesting things within the class, such as __class__.__name__,
which are otherwise not available.
This class is used as a metaclass... | class Metaclass(type):
"""Return a class object with the __class__ attribute equal to the class object.
This allows interesting things within the class, such as __class__.__name__,
which are otherwise not available.
This class is used as a metaclass by including it in the class definition:
cla... |
# -*- coding: utf-8 -*-
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
return ''.join(reversed(word[:word.find(ch) + 1])) + word[word.find(ch) + 1:]
if __name__ == '__main__':
solution = Solution()
assert 'dcbaefd' == solution.reversePrefix('abcdefd', 'd')
assert 'zxyxxe... | class Solution:
def reverse_prefix(self, word: str, ch: str) -> str:
return ''.join(reversed(word[:word.find(ch) + 1])) + word[word.find(ch) + 1:]
if __name__ == '__main__':
solution = solution()
assert 'dcbaefd' == solution.reversePrefix('abcdefd', 'd')
assert 'zxyxxe' == solution.reversePrefi... |
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start, end = 0, len(nums)- 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] < target:
start =... | class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
(start, end) = (0, len(nums) - 1)
while start <= end:
mid = start + (end - start) // 2
if nums[mid] < target:
s... |
class GameRules:
"""
A list of gamerules used by the world.
Contains all gamerules for Java edition as of 1.16.5.
"""
def __init__(self):
"""
Creates the rules of the class.
"""
self.rules = []
self.create_game_rules()
def create_game_rules(self):
"""
Saves every gamerule to the self.rules arra... | class Gamerules:
"""
A list of gamerules used by the world.
Contains all gamerules for Java edition as of 1.16.5.
"""
def __init__(self):
"""
Creates the rules of the class.
"""
self.rules = []
self.create_game_rules()
def create_game_rules(self):
"""
Saves every g... |
#!/usr/bin/env python3
def mysteryAlgorithm(lst):
for i in range(1,len(lst)):
while i > 0 and lst[i-1] > lst[i]:
lst[i], lst[i-1] = lst[i-1], lst[i]
i -= 1
return lst
print(mysteryAlgorithm([6, 4, 3, 8, 5])) | def mystery_algorithm(lst):
for i in range(1, len(lst)):
while i > 0 and lst[i - 1] > lst[i]:
(lst[i], lst[i - 1]) = (lst[i - 1], lst[i])
i -= 1
return lst
print(mystery_algorithm([6, 4, 3, 8, 5])) |
'''
practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses
by Aashik J Krishnan/Aash Gates
'''
x = 10
y ="ten"
#step 1
temp = x
#temp variable now holds the value of x
#step 2
x = y
#the variable x now holds the value of y
#step 3
y = temp
# y now holds the value of temp which is the orginal value... | """
practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses
by Aashik J Krishnan/Aash Gates
"""
x = 10
y = 'ten'
temp = x
x = y
y = temp
print(x)
print(y)
print(temp) |
#
# @lc app=leetcode id=541 lang=python3
#
# [541] Reverse String II
#
# https://leetcode.com/problems/reverse-string-ii/description/
#
# algorithms
# Easy (49.66%)
# Total Accepted: 117.1K
# Total Submissions: 235.8K
# Testcase Example: '"abcdefg"\n2'
#
# Given a string s and an integer k, reverse the first k char... | class Solution:
def reverse_str(self, s: str, k: int) -> str:
if len(s) < k:
return self.reverseAllStr(s)
elif len(s) >= k and len(s) < 2 * k:
return self.reverseAllStr(s[:k]) + s[k:]
else:
return self.reverseAllStr(s[:k]) + s[k:2 * k] + self.reverseStr(s... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | def load_command_table(self, _):
with self.command_group('approle', is_preview=True) as g:
g.custom_command('list', 'list_app_roles')
g.custom_command('assignment list', 'list_role_assignments')
g.custom_command('assignment add', 'add_role_assignment')
g.custom_command('assignment re... |
'''
Url: https://www.hackerrank.com/challenges/write-a-function/problem
Name: Write a function
'''
def is_leap(year):
'''
For this reason, not every four years is a leap year. The rule is that if the year is divisible by 100 and not divisible by 400, leap year is skipped. The year 2000 was a leap year, for ex... | """
Url: https://www.hackerrank.com/challenges/write-a-function/problem
Name: Write a function
"""
def is_leap(year):
"""
For this reason, not every four years is a leap year. The rule is that if the year is divisible by 100 and not divisible by 400, leap year is skipped. The year 2000 was a leap year, for exa... |
class Solution(object):
# O(Nlog(N))
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
for i in range(len(citations)):
if citations[i] < i + 1:
return i
return len(citation... | class Solution(object):
def h_index(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
for i in range(len(citations)):
if citations[i] < i + 1:
return i
return len(citations)
def h_in... |
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
E = len(trust)
if E < N - 1:
return -1
trustScore = [0] * N
for a, b in trust:
trustScore[a - 1] -= 1
trustScore[b - 1] += 1
for index, t in enumerate(trustScore, 1... | class Solution:
def find_judge(self, N: int, trust: List[List[int]]) -> int:
e = len(trust)
if E < N - 1:
return -1
trust_score = [0] * N
for (a, b) in trust:
trustScore[a - 1] -= 1
trustScore[b - 1] += 1
for (index, t) in enumerate(trustS... |
line = '-'*39
bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|'
blankNum1 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*4 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
blankNum2 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*3 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}... | line = '-' * 39
bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|'
blank_num1 = '|' + ' ' * 6 + '{0}' + ' ' * 4 + '|' + ' ' * 4 + '{1}' + ' ' * 4 + '|' + ' ' * 7 + '{2}' + ' ' * 7 + '|'
blank_num2 = '|' + ' ' * 6 + '{0}' + ' ' * 4 + '|' + ' ' * 3 + '{1}' + ' ' ... |
"""
A feature-based chart parser.
"""
| """
A feature-based chart parser.
""" |
def dfs(u, graph, visited):
visited.add(u)
for v in graph[u]:
if v not in visited:
dfs(v, graph, visited)
def count_dfs(u, graph, visited=None, depth=0):
if visited is None:
visited = set()
visited.add(u)
res = 1
for v, count in graph[u]:
if v not in visite... | def dfs(u, graph, visited):
visited.add(u)
for v in graph[u]:
if v not in visited:
dfs(v, graph, visited)
def count_dfs(u, graph, visited=None, depth=0):
if visited is None:
visited = set()
visited.add(u)
res = 1
for (v, count) in graph[u]:
if v not in visite... |
# -*- coding: utf-8 -*-
def seconds_to_human(seconds):
"""Convert seconds to a human readable format.
Args:
seconds (int): Seconds.
Returns:
str: Return seconds into human readable format.
"""
units = (
('week', 60 * 60 * 24 * 7),
('day', 60 * 60 * 24),
('h... | def seconds_to_human(seconds):
"""Convert seconds to a human readable format.
Args:
seconds (int): Seconds.
Returns:
str: Return seconds into human readable format.
"""
units = (('week', 60 * 60 * 24 * 7), ('day', 60 * 60 * 24), ('hour', 60 * 60), ('min', 60), ('sec', 1))
if s... |
def selection_sort(arr):
for num in range(0, len(arr)):
min_position = num
for i in range(num, len(arr)):
if arr[i] < arr[min_position]:
min_position = i
temp = arr[num]
arr[num] = arr[min_position]
arr[min_position] = temp
arr = [6, 3, 8, 5, 2, 7, 4, 1]
print(f'Unordered: {arr}')
selection_sort(a... | def selection_sort(arr):
for num in range(0, len(arr)):
min_position = num
for i in range(num, len(arr)):
if arr[i] < arr[min_position]:
min_position = i
temp = arr[num]
arr[num] = arr[min_position]
arr[min_position] = temp
arr = [6, 3, 8, 5, 2, 7,... |
def queens(board):
"""
Doesn't work because the solution is not recursive. It constraints to only
checking the possible solutions of plaicng the queen in a given spot.
Another thing, no need to store the whole board, it's just enough to have a
one dimensional array of the columns.
One more thing, the diago... | def queens(board):
"""
Doesn't work because the solution is not recursive. It constraints to only
checking the possible solutions of plaicng the queen in a given spot.
Another thing, no need to store the whole board, it's just enough to have a
one dimensional array of the columns.
One more thing, the dia... |
print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO NO URI >')
print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO >')
| print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO NO URI >')
print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO >') |
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for idx in range(len(image)):
image[idx] = list(reversed(image[idx]))
image[idx] = [1 if b == 0 else 0 for b in image[idx]]
return image
| class Solution:
def flip_and_invert_image(self, image: List[List[int]]) -> List[List[int]]:
for idx in range(len(image)):
image[idx] = list(reversed(image[idx]))
image[idx] = [1 if b == 0 else 0 for b in image[idx]]
return image |
WINSTRIDE = (8, 8)
PADDING = (8, 8)
SCALE = 1.15
MIN_NEIGHBORS = 5
OVERLAP_NMS = 0.9
| winstride = (8, 8)
padding = (8, 8)
scale = 1.15
min_neighbors = 5
overlap_nms = 0.9 |
index_definition = {
"name": "id",
"field_type": "int",
"index_type": "hash",
"is_pk": True,
"is_array": False,
"is_dense": False,
"is_sparse": False,
"collate_mode": "none",
"sort_order_letters": "",
"expire_after": 0,
"config": {
},
"json_paths": [
"id"
]
}
updated_in... | index_definition = {'name': 'id', 'field_type': 'int', 'index_type': 'hash', 'is_pk': True, 'is_array': False, 'is_dense': False, 'is_sparse': False, 'collate_mode': 'none', 'sort_order_letters': '', 'expire_after': 0, 'config': {}, 'json_paths': ['id']}
updated_index_definition = {'name': 'id', 'field_type': 'int64', ... |
def fac(n):
if n==1 or n==0:
return 1
else:
return n*fac(n-1)
print(fac(10))
| def fac(n):
if n == 1 or n == 0:
return 1
else:
return n * fac(n - 1)
print(fac(10)) |
#-------------------------------------------------------------------#
# Returns the value of the given card
#-------------------------------------------------------------------#
def get_value(card):
value = card[0:len(card)-1]
return int(value)
#-----------------------------------------------------------------... | def get_value(card):
value = card[0:len(card) - 1]
return int(value)
def get_suit(card):
suit = card[len(card) - 1:]
return suit
def get_cards_of_same_suit(suit, dealerCards):
cards_of_same_suit = tuple()
for c in dealerCards:
if get_suit(c) == suit:
if cardsOfSameSuit == t... |
# we prompt the user for the code.
# enters beginning meter reading
# Enters ending meter reading.
# we compute the gallons of water as a 10th of the gotten gallons.
# we print out the bill meant to be paid the user
def bill_calculator(code, gallons):
if code == "r":
bill = 5.00 + (gallons * 0.0005)
... | def bill_calculator(code, gallons):
if code == 'r':
bill = 5.0 + gallons * 0.0005
return round(bill, 2)
elif code == 'c':
if gallons <= 4000000:
bill = 1000.0
return round(bill, 2)
else:
first_half = 1000.0
sec_half = (gallons - 400... |
class VoetbalClub:
"""
VoetbalClub is een simpele class.
Gemaakt om het aantal punten van de clubs bij te kunnen houden.
"""
def __init__(self, naam):
self.naam = naam
self.punten = 0
| class Voetbalclub:
"""
VoetbalClub is een simpele class.
Gemaakt om het aantal punten van de clubs bij te kunnen houden.
"""
def __init__(self, naam):
self.naam = naam
self.punten = 0 |
'''
exceptions.py: exceptions defined by textform
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2020 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more ... | """
exceptions.py: exceptions defined by textform
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2020 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more ... |
def default_pipe(data, config):
subjects = config.get("subjects")
mutated_data = []
for row in data:
# Nest the subjects defined in config into a single dict
# and add it to mutated_row with the key "Subjects".
row_subjects = {k: int(v) for k, v in row.items() if k in subjects and bo... | def default_pipe(data, config):
subjects = config.get('subjects')
mutated_data = []
for row in data:
row_subjects = {k: int(v) for (k, v) in row.items() if k in subjects and bool(v)}
mutated_row = {k: v for (k, v) in row.items() if k not in subjects}
mutated_row['Subjects'] = row_sub... |
expected_normal_output = """Title Release Year Estimated Budget
Shawshank Redemption 1994 $25 000 000
The Godfather 1972 $6 000 000
The Godfather: Part II 1974 $13 000 000
The Dark Knight 2008 $185 000 000
12 Angry Men 1957 ... | expected_normal_output = 'Title Release Year Estimated Budget\nShawshank Redemption 1994 $25 000 000\nThe Godfather 1972 $6 000 000\nThe Godfather: Part II 1974 $13 000 000\nThe Dark Knight 2008 $185 000 000\n12 Angry Men 1957 ... |
#Written for Python 3.4.2
data = [line.rstrip('\n') for line in open("input.txt")]
blacklist = ["ab", "cd", "pq", "xy"]
vowels = ['a', 'e', 'i', 'o', 'u']
def contains(string, samples):
for sample in samples:
if string.find(sample) > -1:
return True
return False
def isNicePart1(string):
... | data = [line.rstrip('\n') for line in open('input.txt')]
blacklist = ['ab', 'cd', 'pq', 'xy']
vowels = ['a', 'e', 'i', 'o', 'u']
def contains(string, samples):
for sample in samples:
if string.find(sample) > -1:
return True
return False
def is_nice_part1(string):
if contains(string, bl... |
class MyStr(str):
def __format__(self, *args, **kwargs):
print("my format")
return str.__format__(self, *args, **kwargs)
def __mod__(self, *args, **kwargs):
print("mod")
return str.__mod__(self, *args, **kwargs)
if __name__ == "__main__":
ms = MyStr("- %s - {} -")
prin... | class Mystr(str):
def __format__(self, *args, **kwargs):
print('my format')
return str.__format__(self, *args, **kwargs)
def __mod__(self, *args, **kwargs):
print('mod')
return str.__mod__(self, *args, **kwargs)
if __name__ == '__main__':
ms = my_str('- %s - {} -')
prin... |
#
# AGENT
# Sanjin
#
# STRATEGY
# This agent always defects, if the opponent defected too often. Otherwise it cooperates.
#
def getGameLength(history):
return history.shape[1]
def getChoice(snitch):
return "tell truth" if snitch else "stay silent"
def strategy(history, memory):
if getGameLength(history... | def get_game_length(history):
return history.shape[1]
def get_choice(snitch):
return 'tell truth' if snitch else 'stay silent'
def strategy(history, memory):
if get_game_length(history) == 0:
return (get_choice(False), None)
average = sum(history[1]) / history.shape[1]
snitch = average <= ... |
#! /usr/bin/env python
#-----------------------------------------------------------------------
# COPYRIGHT_BEGIN
# Copyright (C) 2017, FixFlyer, LLC.
# All rights reserved.
# COPYRIGHT_END
#-----------------------------------------------------------------------
class Event(object):
"""Base class for API events.""... | class Event(object):
"""Base class for API events."""
pass
class Onlogonevent(Event):
"""Login response event.
Sent by the Flyer Engine to an application in response to a call
to ApplicationManager::logon()."""
def __init__(self):
self.success = False
return
class Onsessionlo... |
VERSION = (0, 1)
YFANTASY_MAIN = 'yfantasy'
def get_package_version():
return '%s.%s' % (VERSION[0], VERSION[1])
| version = (0, 1)
yfantasy_main = 'yfantasy'
def get_package_version():
return '%s.%s' % (VERSION[0], VERSION[1]) |
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
class Solution:
def maxProfit_as_many_transactions(self, prices):
if not prices:
return 0
profit, prev = 0, prices[0]
for i in range(1, len(prices)):
if prices[i]... | class Solution:
def max_profit_as_many_transactions(self, prices):
if not prices:
return 0
(profit, prev) = (0, prices[0])
for i in range(1, len(prices)):
if prices[i] >= prices[i - 1]:
profit = profit + prices[i] - prices[i - 1]
return profit... |
# -*- coding: utf-8 -*-
"""Dashboard routes that lead to JSONs without providing parameters."""
routes = {
'netwide': {
'client_list': '/usage/client_list_json',
'topology': '/l3_topology/show',
'event_types': '/dashboard/event_autocomplete_types',
'alerts': '/alerts/show',
'... | """Dashboard routes that lead to JSONs without providing parameters."""
routes = {'netwide': {'client_list': '/usage/client_list_json', 'topology': '/l3_topology/show', 'event_types': '/dashboard/event_autocomplete_types', 'alerts': '/alerts/show', 'admin_emails': '/alerts/typeahead_emails', 'possible_clients': '/alert... |
nums = []
with open("day1_input", "r") as f:
for line in f:
nums.append(int(line))
# part 1
# for numA in nums:
# for numB in nums:
# # find two entries that sum to 2020:
# if (numA + numB == 2020):
# print(numA, numB)
# # their product is:
# print(... | nums = []
with open('day1_input', 'r') as f:
for line in f:
nums.append(int(line))
for num_a in nums:
for num_b in nums:
for num_c in nums:
if numA + numB + numC == 2020:
print(numA, numB, numC)
print(numA * numB * numC) |
text = input("Enter A sentence: ")
bad_words = [BADWORDSHERE]
for words in bad_words:
if words in text:
text_length = len(words)
hide_word = "*" * text_length
text = text.replace(words, hide_word)
print(text)
| text = input('Enter A sentence: ')
bad_words = [BADWORDSHERE]
for words in bad_words:
if words in text:
text_length = len(words)
hide_word = '*' * text_length
text = text.replace(words, hide_word)
print(text) |
Clock.clear()
# controll #######################################################
Clock.bpm = 120
Scale.default = Scale.chromatic
Root.default = 0
p1 >> keys(
[4,6,11,13,16,18,23,25]
,dur=[0.25]
,oct=4
,vibdepth=0.3 ,vib=0.01
)
p2 >> blip(
[4,6,11,13,15,16,18,23,25]
,dur=[0.25]
,oct=... | Clock.clear()
Clock.bpm = 120
Scale.default = Scale.chromatic
Root.default = 0
p1 >> keys([4, 6, 11, 13, 16, 18, 23, 25], dur=[0.25], oct=4, vibdepth=0.3, vib=0.01)
p2 >> blip([4, 6, 11, 13, 15, 16, 18, 23, 25], dur=[0.25], oct=3, sus=2, vibdepth=0.3, vib=0.01, amp=0.35)
p3 >> bass([(11, 16), [(11, 16, 18), (11, 16, 23... |
"""
funcs
Descript:
File name: funcs.py
Maintainer: Kyle Gortych
created: 03-22-2022
"""
def skip(s,n):
"""
Returns a copy of s, only including positions that are multiples of n
A position is a multiple of n if pos % n == 0.
Examples:
skip('hello world',1) returns 'hello world'
s... | """
funcs
Descript:
File name: funcs.py
Maintainer: Kyle Gortych
created: 03-22-2022
"""
def skip(s, n):
"""
Returns a copy of s, only including positions that are multiples of n
A position is a multiple of n if pos % n == 0.
Examples:
skip('hello world',1) returns 'hello world'
... |
# How to merge two dicts
x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}
z = {**x, **y}
print(z) | x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}
z = {**x, **y}
print(z) |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include".split(';') if "/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include" != "" else []
PROJECT_CATKIN_DEPENDS = "std_msgs;geometr... | catkin_package_prefix = ''
project_pkg_config_include_dirs = '/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include'.split(';') if '/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include' != '' else []
project_catkin_depends = 'std_msgs;geometry_msgs;tf2_ros;costmap_2d'.replace(';', ' ')
pkg_config_l... |
# Copyright (c) 2008, Michael Lunnay <mlunnay@gmail.com.au>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND T... | """This module provides the ViewElement base class for user interface representations."""
__all__ = ['ViewElement']
class Viewelement(object):
"""This is a base class for user interface items."""
__id_store = {}
__next_id = 1
def __init__(self):
"""ViewElement initialiser."""
self.cont... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
for i in range(int(input())) :
print('Distances: ', end='')
X,Y = input().split()
Z = zip(X, Y)
for S in Z :
x = ord(S[0]) - ord('A') + 1
y = ord(S[1]) - ord('A') + 1
if x <= y :
print(y-x, end= ' ')
else :
... | for i in range(int(input())):
print('Distances: ', end='')
(x, y) = input().split()
z = zip(X, Y)
for s in Z:
x = ord(S[0]) - ord('A') + 1
y = ord(S[1]) - ord('A') + 1
if x <= y:
print(y - x, end=' ')
else:
print(y + 26 - x, end=' ')
print() |
# from sw_site.settings.components import BASE_DIR, config
# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = config('DJANGO_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'127.0.0.1:8000',... | debug = True
cors_origin_whitelist = ('localhost:8000', '127.0.0.1:8000', 'localhost:8080', '127.0.0.1:8080') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.