content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class InvalidTemplateError(Exception):
"""
Raised when a CloudFormation template fails the Validate Template call
"""
pass
| class Invalidtemplateerror(Exception):
"""
Raised when a CloudFormation template fails the Validate Template call
"""
pass |
class BinarySearch:
def __init__(self, arr, target):
self.arr = arr
self.target = target
def binary_search(self):
lo, hi = 0, len(self.arr)
while lo<hi:
mid = lo + (hi-lo)//2
# dont use (lo+hi)//2. Integer overflow.
# https://en.wikipedia.or... | class Binarysearch:
def __init__(self, arr, target):
self.arr = arr
self.target = target
def binary_search(self):
(lo, hi) = (0, len(self.arr))
while lo < hi:
mid = lo + (hi - lo) // 2
if self.arr[mid] == self.target:
return mid
... |
class Solution(object):
# def validPalindrome(self, s):
# """
# :type s: str
# :rtype: bool
# """
# def is_pali_range(i, j):
# return all(s[k] == s[j - k + i] for k in range(i, j))
# for i in xrange(len(s) / 2):
# if s[i] != s[~i]:
# ... | class Solution(object):
def valid_palindrome(self, s):
return self.validPalindromeHelper(s, 0, len(s) - 1, 1)
def valid_palindrome_helper(self, s, left, right, budget):
while left < len(s) and right >= 0 and (left <= right) and (s[left] == s[right]):
left += 1
right -= ... |
class connectionFinder:
def __init__(self, length):
self.id = [0] * length
self.size = [0] * length
for i in range(length):
self.id[i] = i
self.size[i] = i
# Id2 will become a root of Id1 :
def union(self, id1, id2):
rootA = self.find(id1)
ro... | class Connectionfinder:
def __init__(self, length):
self.id = [0] * length
self.size = [0] * length
for i in range(length):
self.id[i] = i
self.size[i] = i
def union(self, id1, id2):
root_a = self.find(id1)
root_b = self.find(id2)
self.id... |
expected_output = {
"vrf": {
"vrf1": {
"lib_entry": {
"10.11.0.0/24": {
"rev": "7",
"remote_binding": {
"label": {
"imp-null": {
"lsr_id": {"10.132.0.1": {"... | expected_output = {'vrf': {'vrf1': {'lib_entry': {'10.11.0.0/24': {'rev': '7', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}, '10.12.0.0/24': {'label_binding': {'label': {'17': {}}}, 'rev': '8', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'la... |
nmr = int(input("Digite um numero: "))
if nmr %2 == 0:
print("Numero par")
else:
print("Numero impar") | nmr = int(input('Digite um numero: '))
if nmr % 2 == 0:
print('Numero par')
else:
print('Numero impar') |
class DefaultConfig(object):
# Flask Settings
# ------------------------------
# There is a whole bunch of more settings available here:
# http://flask.pocoo.org/docs/0.11/config/#builtin-configuration-values
DEBUG = False
TESTING = False
| class Defaultconfig(object):
debug = False
testing = False |
n = int(input())
ss = input().split()
s = int(ss[0])
a = []
for i in range(n):
ss = input().split()
a.append((int(ss[0]), int(ss[1])))
a.sort(key=lambda x: x[0] * x[1])
ans = 0
for i in range(n):
if (s // (a[i])[1] > ans):
ans = s // (a[i])[1]
s *= (a[i])[0]
print(ans) | n = int(input())
ss = input().split()
s = int(ss[0])
a = []
for i in range(n):
ss = input().split()
a.append((int(ss[0]), int(ss[1])))
a.sort(key=lambda x: x[0] * x[1])
ans = 0
for i in range(n):
if s // a[i][1] > ans:
ans = s // a[i][1]
s *= a[i][0]
print(ans) |
def city_formatter(city, country):
formatted = f"{city.title()}, {country.title()}"
return formatted
print(city_formatter('hello', 'world')) | def city_formatter(city, country):
formatted = f'{city.title()}, {country.title()}'
return formatted
print(city_formatter('hello', 'world')) |
'''
Given an integer array sorted in non-decreasing order,
there is exactly one integer in the array that occurs
more than 25% of the time.
Return that integer.
Example:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:
- 1 <= arr.length <= 10^4
- 0 <= arr[i] ... | """
Given an integer array sorted in non-decreasing order,
there is exactly one integer in the array that occurs
more than 25% of the time.
Return that integer.
Example:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:
- 1 <= arr.length <= 10^4
- 0 <= arr[i] ... |
class json_to_csv():
def __init__(self):
self.stri=''
self.st=''
self.a=[]
self.b=[]
self.p=''
def read_js(self,path):
self.p=path
l=open(path,'r').readlines()
for i in l:
i=i.replace('\t','')
i=i.replace('... | class Json_To_Csv:
def __init__(self):
self.stri = ''
self.st = ''
self.a = []
self.b = []
self.p = ''
def read_js(self, path):
self.p = path
l = open(path, 'r').readlines()
for i in l:
i = i.replace('\t', '')
i = i.replac... |
def es5(tree):
# inserisci qui il tuo codice
d={}
for x in tree.f:
d1=es5(x)
for x in d1:
if x in d:
d[x]=d[x] | d1[x]
else:
d[x]=d1[x]
y=len(tree.f)
if y in d:
d[y]=d[y]| {tree.id}
else: d[y]= {tree.id}
... | def es5(tree):
d = {}
for x in tree.f:
d1 = es5(x)
for x in d1:
if x in d:
d[x] = d[x] | d1[x]
else:
d[x] = d1[x]
y = len(tree.f)
if y in d:
d[y] = d[y] | {tree.id}
else:
d[y] = {tree.id}
return d |
#!/home/jepoy/anaconda3/bin/python
def main():
x = dict(Buffy = 'meow', Zilla = 'grrr', Angel = 'purr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k, kwargs[k]))
else:
print('Meow.')
if __name__ == '__main__':
ma... | def main():
x = dict(Buffy='meow', Zilla='grrr', Angel='purr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k, kwargs[k]))
else:
print('Meow.')
if __name__ == '__main__':
main() |
def resolve():
'''
code here
'''
x, y = [int(item) for item in input().split()]
res = 0
if x < 0 and abs(y) - abs(x) >= 0:
res += 1
elif x > 0 and abs(y) - abs(x) <= 0:
res += 1
res += abs(abs(x) - abs(y))
if y > 0 and abs(y) - abs(x) < 0:
res += 1
eli... | def resolve():
"""
code here
"""
(x, y) = [int(item) for item in input().split()]
res = 0
if x < 0 and abs(y) - abs(x) >= 0:
res += 1
elif x > 0 and abs(y) - abs(x) <= 0:
res += 1
res += abs(abs(x) - abs(y))
if y > 0 and abs(y) - abs(x) < 0:
res += 1
elif ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : 1410.py
@Contact : huanghoward@foxmail.com
@Modify Time : 2022/4/12 16:18
------------
"""
class Solution:
def entityParser(self, text: str) -> str:
l = 0
r = 0
reading = False
result = ""
con... | """
@File : 1410.py
@Contact : huanghoward@foxmail.com
@Modify Time : 2022/4/12 16:18
------------
"""
class Solution:
def entity_parser(self, text: str) -> str:
l = 0
r = 0
reading = False
result = ''
convert = {'"': '"', ''': "'", '&': ... |
def asm2(param_1, param_2): # push ebp
# mov ebp,esp
# sub esp,0x10
eax = param_2 # mov eax,DWORD PTR [ebp+0xc]
local_1 = eax # mov DWORD PTR [ebp-0x4],eax
eax = param_1 # mov eax,DWORD PTR [ebp+... | def asm2(param_1, param_2):
eax = param_2
local_1 = eax
eax = param_1
local_2 = eax
while param_1 <= 39046:
local_1 += 1
param_1 += 65
eax = local_1
return eax
print(hex(asm2(14, 33))) |
class _SpeechOperation():
def add_done_callback(callback):
pass | class _Speechoperation:
def add_done_callback(callback):
pass |
class BaseHyperParameter:
"""
This is a base class for all hyper-parameters. It should not be instantiated. Use concrete implementations instead.
"""
def __init__(self, name):
self.name = name
| class Basehyperparameter:
"""
This is a base class for all hyper-parameters. It should not be instantiated. Use concrete implementations instead.
"""
def __init__(self, name):
self.name = name |
def main():
a = 1 if True else 2
print(a)
if __name__ == '__main__':
main()
| def main():
a = 1 if True else 2
print(a)
if __name__ == '__main__':
main() |
# Birth should occur before death of an individual
def userStory03(listOfPeople):
flag = True
def changeDateToNum(date): # date format must be like "2018-10-06"
if date == "NA":
return 0 # 0 will not larger than any date, for later comparison
else:
tempDate = dat... | def user_story03(listOfPeople):
flag = True
def change_date_to_num(date):
if date == 'NA':
return 0
else:
temp_date = date.split('-')
return int(tempDate[0] + tempDate[1] + tempDate[2])
for people in listOfPeople:
if people.Death != 'NA':
... |
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + " ! Your are " + age + " Years old now.")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = num1 + num2
print(result)
# We need int casting number num1 and num2
result = int(num1) + int(num2)
print(... | name = input('Enter your name: ')
age = input('Enter your age: ')
print('Hello ' + name + ' ! Your are ' + age + ' Years old now.')
num1 = input('Enter a number: ')
num2 = input('Enter another number: ')
result = num1 + num2
print(result)
result = int(num1) + int(num2)
print(result)
num1 = input('Enter a number: ')
num... |
# -*- coding: utf-8 -*-
def find_message(message: str) -> str:
result: str = ""
for i in list(message):
if i.isupper():
result += i
return result
# another pattern
return ''.join(i for i in message if i.isupper())
if __name__ == '__main__':
print("Example:")
print(fin... | def find_message(message: str) -> str:
result: str = ''
for i in list(message):
if i.isupper():
result += i
return result
return ''.join((i for i in message if i.isupper()))
if __name__ == '__main__':
print('Example:')
print(find_message('How are you? Eh, ok. Low or Lower? ' ... |
#
# Copyright 2019 Delphix
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | """This module contains the "sdb.Error" exception."""
class Error(Exception):
"""
This is the superclass of all SDB error exceptions.
"""
text: str = ''
def __init__(self, text: str) -> None:
self.text = 'sdb: {}'.format(text)
super().__init__(self.text)
class Commandnotfounderror... |
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """`dtrace_compile` Starlark tests."""
load(':rules/output_text_match_test.bzl', 'output_text_match_test')
def dtrace_compile_test_suite(name):
"""Test suite for `dtrace_compile`.
Args:
name: the base name to be used in things created by this macro
"""
output_text_match_test(name='{}_generates_e... |
class Vector(object):
SHORTHAND = 'V'
def __init__(self, **kwargs):
super(Vector, self).__init__()
self.vector = kwargs
def dot(self, other):
product = 0
for member, value in self.vector.items():
product += value * other.member(member)
return product
... | class Vector(object):
shorthand = 'V'
def __init__(self, **kwargs):
super(Vector, self).__init__()
self.vector = kwargs
def dot(self, other):
product = 0
for (member, value) in self.vector.items():
product += value * other.member(member)
return product
... |
#!/usr/bin/env python3
def first(iterable, default=None, key=None):
if key is None:
for el in iterable:
if el is not None:
return el
else:
for el in iterable:
if key(el) is not None:
return el
return default
| def first(iterable, default=None, key=None):
if key is None:
for el in iterable:
if el is not None:
return el
else:
for el in iterable:
if key(el) is not None:
return el
return default |
class Foo:
def qux2(self):
z = 12
x = z * 3
self.baz = x
for q in range(10):
x += q
lst = ["foo", "bar", "baz"]
lst = lst[1:2]
assert len(lst) == 2, 201
def qux(self):
self.baz = self.bar
self.blah = "hello"
self._priv = 1
self._prot = self.baz
def _prot2(self):
... | class Foo:
def qux2(self):
z = 12
x = z * 3
self.baz = x
for q in range(10):
x += q
lst = ['foo', 'bar', 'baz']
lst = lst[1:2]
assert len(lst) == 2, 201
def qux(self):
self.baz = self.bar
self.blah = 'hello'
self._priv... |
pattern_zero=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_odd=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667,... | pattern_zero = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_odd = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666... |
class Solution(object):
def isReflected(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
if not points:
return True
positions=set()
sumk=0
for p in points:
positions.add((p[0],p[1]))
... | class Solution(object):
def is_reflected(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
if not points:
return True
positions = set()
sumk = 0
for p in points:
positions.add((p[0], p[1]))
for p in posi... |
Pathogen = {
'name': 'pathogen',
'fields': [
{'name': 'reported_name'},
{'name': 'drug_resistance'},
{'name': 'authority'},
{'name': 'tax_order'},
{'name': 'class'},
{'name': 'family'},
{'name': 'genus'},
{'name': 'species'},
{'name': 'sub_... | pathogen = {'name': 'pathogen', 'fields': [{'name': 'reported_name'}, {'name': 'drug_resistance'}, {'name': 'authority'}, {'name': 'tax_order'}, {'name': 'class'}, {'name': 'family'}, {'name': 'genus'}, {'name': 'species'}, {'name': 'sub_species'}]} |
def merge(di1, di2, fu=None):
di3 = {}
for ke in sorted(di1.keys() | di2.keys()):
if ke in di1 and ke in di2:
if fu is None:
va1 = di1[ke]
va2 = di2[ke]
if isinstance(va1, dict) and isinstance(va2, dict):
di3[ke] = m... | def merge(di1, di2, fu=None):
di3 = {}
for ke in sorted(di1.keys() | di2.keys()):
if ke in di1 and ke in di2:
if fu is None:
va1 = di1[ke]
va2 = di2[ke]
if isinstance(va1, dict) and isinstance(va2, dict):
di3[ke] = merge(va1... |
def read_list(t): return [t(x) for x in input().split()]
def read_line(t): return t(input())
def read_lines(t, N): return [t(input()) for _ in range(N)]
N, Q = read_list(int)
array = read_list(int)
C = [[0, 0, 0]]
for a in array:
c = C[-1][:]
c[a % 3] += 1
C.append(c)
for _ in range(Q):
l, r = read_li... | def read_list(t):
return [t(x) for x in input().split()]
def read_line(t):
return t(input())
def read_lines(t, N):
return [t(input()) for _ in range(N)]
(n, q) = read_list(int)
array = read_list(int)
c = [[0, 0, 0]]
for a in array:
c = C[-1][:]
c[a % 3] += 1
C.append(c)
for _ in range(Q):
... |
arr=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
n=4#col
m=4#row
#print matrix in spiral form
loop=0
while(loop<n/2):
for i in range(loop,n-loop-1):
print(arr[loop][i],end=" ")
for i in range(loop,m-loop-1):
print(arr[i][m-loop-1],end=" ")
for i in range(n-1-loop,loop-1+1,-... | arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
n = 4
m = 4
loop = 0
while loop < n / 2:
for i in range(loop, n - loop - 1):
print(arr[loop][i], end=' ')
for i in range(loop, m - loop - 1):
print(arr[i][m - loop - 1], end=' ')
for i in range(n - 1 - loop, loop - 1 + 1, ... |
class Color:
red = None
green = None
blue = None
white = None
bit_color = None
def __init__(self, red, green, blue, white=0):
self.red = red
self.green = green
self.blue = blue
self.white = white
def get_rgb(self):
return 'rgb(%d,%d,%d)' % (self.re... | class Color:
red = None
green = None
blue = None
white = None
bit_color = None
def __init__(self, red, green, blue, white=0):
self.red = red
self.green = green
self.blue = blue
self.white = white
def get_rgb(self):
return 'rgb(%d,%d,%d)' % (self.red,... |
N = int(input())
ano = N // 365
resto = N % 365
mes = resto // 30
dia = resto % 30
print(str(ano) + " ano(s)")
print(str(mes) + " mes(es)")
print(str(dia) + " dia(s)")
| n = int(input())
ano = N // 365
resto = N % 365
mes = resto // 30
dia = resto % 30
print(str(ano) + ' ano(s)')
print(str(mes) + ' mes(es)')
print(str(dia) + ' dia(s)') |
r, c = (map(int, input().split(' ')))
for row in range(r):
for col in range(c):
print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ')
print() | (r, c) = map(int, input().split(' '))
for row in range(r):
for col in range(c):
print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ')
print() |
'''Colocando cores no terminal do python'''
# \033[0;033;44m codigo para colocar as cores
# tipo de texto em cod (estilo do texto)
# 0 - sem estilo nenhum
# 1 - negrito
# 4 - sublinhado
# 7 - inverter as confgs
# cores em cod (cores do texto)
# 30 - branco
# 31 - vermelho
# 32 - verde
# 33 - amarelo
# 34 - azul
# 35... | """Colocando cores no terminal do python""" |
"""
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Outpu... | """
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Outpu... |
valid_passport = 0
invalid_passport = 0
def get_key(p_line):
keys = []
for i in p_line.split():
keys.append(i.split(':')[0])
return keys
def check_validation(keys):
for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']))
# CID is optional
if 'cid' in keys:
... | valid_passport = 0
invalid_passport = 0
def get_key(p_line):
keys = []
for i in p_line.split():
keys.append(i.split(':')[0])
return keys
def check_validation(keys):
for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']))
if 'cid' in keys:
keys.remove('cid')
... |
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | """Fake folders data."""
fake_folders_db_rows = [{'folder_id': '111111111111', 'name': 'folders/111111111111', 'display_name': 'Folder1', 'lifecycle_state': 'ACTIVE', 'create_time': '2015-09-09 00:01:01', 'parent_id': '9999', 'parent_type': 'organization'}, {'folder_id': '222222222222', 'name': 'folders/222222222222', ... |
class Security:
def __init__(self, name, ticker, country, ir_website, currency):
self.name = name.strip()
self.ticker = ticker.strip()
self.country = country.strip()
self.currency = currency.strip()
self.ir_website = ir_website.strip()
@staticmethod
def summary(name,... | class Security:
def __init__(self, name, ticker, country, ir_website, currency):
self.name = name.strip()
self.ticker = ticker.strip()
self.country = country.strip()
self.currency = currency.strip()
self.ir_website = ir_website.strip()
@staticmethod
def summary(name... |
def plot_frames(motion, ax, times=1, fps=0.01):
joints = [j for j in motion.joint_names() if not j.startswith('ignore_')]
x, ys = [], []
for t, frame in motion.frames(fps):
x.append(t)
ys.append(frame.positions)
if t > motion.length() * times:
break
for joint in join... | def plot_frames(motion, ax, times=1, fps=0.01):
joints = [j for j in motion.joint_names() if not j.startswith('ignore_')]
(x, ys) = ([], [])
for (t, frame) in motion.frames(fps):
x.append(t)
ys.append(frame.positions)
if t > motion.length() * times:
break
for joint in... |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | """Wait messages for the compute instance groups managed commands."""
_current_action_types = ['abandoning', 'creating', 'creatingWithoutRetries', 'deleting', 'recreating', 'refreshing', 'restarting', 'verifying']
_pending_action_types = ['creating', 'deleting', 'restarting', 'recreating']
def is_group_stable(igm_ref)... |
default_vimrc = "\
set fileencoding=utf-8 fileformat=unix\n\
call plug#begin('~/.vim/plugged')\n\
Plug 'prabirshrestha/async.vim'\n\
Plug 'prabirshrestha/vim-lsp'\n\
Plug 'prabirshrestha/asyncomplete.vim'\n\
Plug 'prabirshrestha/asyncomplete-lsp.vim'\n\
Plug 'mattn/vim-lsp-settings'\n\
Plug 'prabirshrestha/asyncomplete... | default_vimrc = "set fileencoding=utf-8 fileformat=unix\ncall plug#begin('~/.vim/plugged')\nPlug 'prabirshrestha/async.vim'\nPlug 'prabirshrestha/vim-lsp'\nPlug 'prabirshrestha/asyncomplete.vim'\nPlug 'prabirshrestha/asyncomplete-lsp.vim'\nPlug 'mattn/vim-lsp-settings'\nPlug 'prabirshrestha/asyncomplete-file.vim'\nPlug... |
extensions = ["myst_parser"]
exclude_patterns = ["_build"]
copyright = "2020, Executable Book Project"
myst_enable_extensions = ["deflist"]
| extensions = ['myst_parser']
exclude_patterns = ['_build']
copyright = '2020, Executable Book Project'
myst_enable_extensions = ['deflist'] |
# encoding: utf-8
"""
Configuration file. Please prefix application specific config values with
the application name.
"""
# Slack settings
SLACKBACK_CHANNEL = '#feedback'
SLACKBACK_EMOJI = ':goberserk:'
SLACKBACK_USERNAME = 'TownCrier'
# These values are necessary only if the app needs to be a client of the API
FEEDB... | """
Configuration file. Please prefix application specific config values with
the application name.
"""
slackback_channel = '#feedback'
slackback_emoji = ':goberserk:'
slackback_username = 'TownCrier'
feedback_slack_end_point = 'https://hooks.slack.com/services/TOKEN/TOKEN'
google_recaptcha_endpoint = 'https://www.goog... |
# Given a list and a num. Write a function to return boolean if that element is not in the list.
def check_num_in_list(alist, num):
for i in alist:
if num in alist and num%2 != 0:
return True
else:
return False
sample = check_num_in_list([2,7,3,1,6,9], 6)
print(sample)
| def check_num_in_list(alist, num):
for i in alist:
if num in alist and num % 2 != 0:
return True
else:
return False
sample = check_num_in_list([2, 7, 3, 1, 6, 9], 6)
print(sample) |
z = 10
y = 0
x = y < z and z > y or y > z and z < y
print(x)
# X = True
| z = 10
y = 0
x = y < z and z > y or (y > z and z < y)
print(x) |
"""
Global constants.
"""
# Instrument message fields
INSTRUMENTS = 'instruments'
INSTRUMENT_ID = 'instrumentID'
EXCHANGE_ID = 'exchangeID'
INSTRUMENT_SYMBOL = 'symbol'
INSTRUMENT_TRADING_HOURS = 'instrument_trading_hours'
UNIT_SIZE = 'unit_size' # future's contract unit size
TICK_SIZE = 'tick_size'
MARGIN_TYPE = 'm... | """
Global constants.
"""
instruments = 'instruments'
instrument_id = 'instrumentID'
exchange_id = 'exchangeID'
instrument_symbol = 'symbol'
instrument_trading_hours = 'instrument_trading_hours'
unit_size = 'unit_size'
tick_size = 'tick_size'
margin_type = 'margin_type'
margin_rate = 'margin_rate'
open_comm_type = 'ope... |
# Merge Sort: D&C Algo, Breaks data into individual pieces and merges them, uses recursion to operate on datasets. Key is to understand how to merge 2 sorted arrays.
items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53]
def mergesort(dataset):
if len(dataset) > 1:
mid = len(dataset) // 2
leftarr = da... | items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53]
def mergesort(dataset):
if len(dataset) > 1:
mid = len(dataset) // 2
leftarr = dataset[:mid]
rightarr = dataset[mid:]
mergesort(leftarr)
mergesort(rightarr)
i = 0
j = 0
k = 0
while i < len(left... |
def nameCreator(playerName):
firstLetter = playerName.split(" ")[1][0]
try:
lastName = playerName.split(" ")[1][0:5]
except:
lastNameSize = len(playerName.split(" ")[1])
lastName = playerName.split(" ")[1][len(lastNameSize)]
firstName = playerName[0:2]
return lastName + fi... | def name_creator(playerName):
first_letter = playerName.split(' ')[1][0]
try:
last_name = playerName.split(' ')[1][0:5]
except:
last_name_size = len(playerName.split(' ')[1])
last_name = playerName.split(' ')[1][len(lastNameSize)]
first_name = playerName[0:2]
return (lastName... |
# Copyright: 2005-2008 Brian Harring <ferringb@gmail.com>
# License: GPL2/BSD
"""
exceptions thrown by repository classes.
Need to extend the usage a bit further still.
"""
__all__ = ("TreeCorruption", "InitializationError")
class TreeCorruption(Exception):
def __init__(self, err):
Exception.__init__(se... | """
exceptions thrown by repository classes.
Need to extend the usage a bit further still.
"""
__all__ = ('TreeCorruption', 'InitializationError')
class Treecorruption(Exception):
def __init__(self, err):
Exception.__init__(self, 'unexpected tree corruption: %s' % (err,))
self.err = err
class In... |
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
ret = [[0 for j in range(len(B[0]))] for i in range(len(A))]
for i, row in enumerate(A):
for k, a in enum... | class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
ret = [[0 for j in range(len(B[0]))] for i in range(len(A))]
for (i, row) in enumerate(A):
for (k, a) in enumerate(... |
# Author : Aniruddha Krishna Jha
# Date : 22/10/2021
'''**********************************************************************************
Given an array nums of positive integers, return the longest possible length of an array prefix of nums,
such that it is possible to remove exactly one element from this pref... | """**********************************************************************************
Given an array nums of positive integers, return the longest possible length of an array prefix of nums,
such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have t... |
#!/usr/bin/env python3
"""
Write a function called sed that takes as arguments a pattern string, a replacement
string, and two filenames; it should read the first file and write the contents into the second file
(creating it if necessary). If the pattern string appears anywhere in the file, it should be re... | """
Write a function called sed that takes as arguments a pattern string, a replacement
string, and two filenames; it should read the first file and write the contents into the second file
(creating it if necessary). If the pattern string appears anywhere in the file, it should be replaced
with the repl... |
class BTNode:
'''Binary Tree Node class - do not modify'''
def __init__(self, value, left, right):
'''Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None.'''
self.value = value
self.left = left
self.right =... | class Btnode:
"""Binary Tree Node class - do not modify"""
def __init__(self, value, left, right):
"""Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None."""
self.value = value
self.left = left
self.right =... |
checksum = 0
with open("Day 2 - input", "r") as file:
for line in file:
row = [int(i) for i in line.split()]
result = max(row) - min(row)
checksum += result
print(f"The checksum is {checksum}")
| checksum = 0
with open('Day 2 - input', 'r') as file:
for line in file:
row = [int(i) for i in line.split()]
result = max(row) - min(row)
checksum += result
print(f'The checksum is {checksum}') |
def bytes_to(bytes_value, to_unit, bytes_size=1024):
units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
return round(float(bytes_value) / (bytes_size ** units[to_unit]), 2)
def convert_to_human(value):
if value < 1024:
return str(value) + 'b'
if value < 1048576:
return str(bytes_... | def bytes_to(bytes_value, to_unit, bytes_size=1024):
units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
return round(float(bytes_value) / bytes_size ** units[to_unit], 2)
def convert_to_human(value):
if value < 1024:
return str(value) + 'b'
if value < 1048576:
return str(bytes_to(... |
TLDS = [
"ABB",
"ABBOTT",
"ABOGADO",
"AC",
"ACADEMY",
"ACCENTURE",
"ACCOUNTANT",
"ACCOUNTANTS",
"ACTIVE",
"ACTOR",
"AD",
"ADS",
"ADULT",
"AE",
"AEG",
"AERO",
"AF",
"AFL",
"AG",
"AGENCY",
"AI",
"AIG",
"AIRFORCE",
"AL",
"ALLFINANZ",
"ALSACE",
"AM",
"AMSTERDAM",
"AN",
"ANDROID",
"AO",
"APARTMENTS",
"AQ",
"AQUARELLE",
"AR"... | tlds = ['ABB', 'ABBOTT', 'ABOGADO', 'AC', 'ACADEMY', 'ACCENTURE', 'ACCOUNTANT', 'ACCOUNTANTS', 'ACTIVE', 'ACTOR', 'AD', 'ADS', 'ADULT', 'AE', 'AEG', 'AERO', 'AF', 'AFL', 'AG', 'AGENCY', 'AI', 'AIG', 'AIRFORCE', 'AL', 'ALLFINANZ', 'ALSACE', 'AM', 'AMSTERDAM', 'AN', 'ANDROID', 'AO', 'APARTMENTS', 'AQ', 'AQUARELLE', 'AR',... |
class Bank:
def __init__(self):
self.inf = 0
self._observers = []
def register_observer(self, observer):
self._observers.append(observer)
def notify_observers(self):
print("Inflacja na poziomie: ", format(self.inf, '.2f'))
for observer in self._observers:
... | class Bank:
def __init__(self):
self.inf = 0
self._observers = []
def register_observer(self, observer):
self._observers.append(observer)
def notify_observers(self):
print('Inflacja na poziomie: ', format(self.inf, '.2f'))
for observer in self._observers:
... |
fruta = 'kiwi'
if fruta == 'kiwi':
print("El valor es kiwi")
elif fruta == 'manzana':
print("Es una manzana")
elif fruta == 'manzana2':
pass #si no sabemos que poner y no marque error
else:
print("No son iguales")
mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False
print(mensaje)
| fruta = 'kiwi'
if fruta == 'kiwi':
print('El valor es kiwi')
elif fruta == 'manzana':
print('Es una manzana')
elif fruta == 'manzana2':
pass
else:
print('No son iguales')
mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False
print(mensaje) |
# Status code
API_HANDLER_OK_CODE = 200
API_HANDLER_ERROR_CODE = 400
# REST parameters
SERVICE_HANDLER_POST_ARG_KEY = "key"
SERVICE_HANDLER_POST_BODY_KEY = "body_key"
| api_handler_ok_code = 200
api_handler_error_code = 400
service_handler_post_arg_key = 'key'
service_handler_post_body_key = 'body_key' |
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
------------------------------
15 / 15 test cases passed.
Status: Accepted
Runtime: 72 ms
"""
l, sum, res = 0, 0, len(nums) + 1
... | class Solution:
def min_sub_array_len(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
------------------------------
15 / 15 test cases passed.
Status: Accepted
Runtime: 72 ms
"""
(l, sum, res) = (0, 0, len(nums) + 1... |
def get_paginated_result(query, page, per_page, field, timestamp):
new_query = query
if page != 1 and timestamp != None:
new_query = query.filter(
field < timestamp
)
try:
return new_query.paginate(
per_page=per_page,
page=page
).items, 20... | def get_paginated_result(query, page, per_page, field, timestamp):
new_query = query
if page != 1 and timestamp != None:
new_query = query.filter(field < timestamp)
try:
return (new_query.paginate(per_page=per_page, page=page).items, 200)
except:
response_object = {'status': 'err... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Errors for Invenio-Records module."""
class RecordsError(Exception):
"""Base... | """Errors for Invenio-Records module."""
class Recordserror(Exception):
"""Base class for errors in Invenio-Records module."""
class Missingmodelerror(RecordsError):
"""Error raised when a record has no model.""" |
#!/usr/bin/env python3
# encoding: utf-8
def _subclasses(cls):
try:
return cls.__subclasses__()
except TypeError:
return type.__subclasses__(cls)
class _SubclassNode:
__slots__ = frozenset(('cls', 'children'))
def __init__(self, cls, children=None):
self.cls = cls
self.children = children or []
def __r... | def _subclasses(cls):
try:
return cls.__subclasses__()
except TypeError:
return type.__subclasses__(cls)
class _Subclassnode:
__slots__ = frozenset(('cls', 'children'))
def __init__(self, cls, children=None):
self.cls = cls
self.children = children or []
def __repr... |
def longest_uppercase(input,k):
final_out = 0
for i in input:
test_letters = i
for j in input:
if len(test_letters) == k :
break
if test_letters.find(j) >= 0:
pass
else:
test_letters += j
max = 0
count = 0
for m in input :
if test_letters.find(m) ... | def longest_uppercase(input, k):
final_out = 0
for i in input:
test_letters = i
for j in input:
if len(test_letters) == k:
break
if test_letters.find(j) >= 0:
pass
else:
test_letters += j
max = 0
... |
# The following dependencies were calculated from:
#
# generate_workspace --artifact=io.opencensus:opencensus-api:0.12.2 --artifact=io.opencensus:opencensus-contrib-zpages:0.12.2 --artifact=io.opencensus:opencensus-exporter-trace-logging:0.12.2 --artifact=io.opencensus:opencensus-impl:0.12.2 --repositories=http://repo.... | def opencensus_maven_jars():
native.maven_jar(name='com_google_code_findbugs_jsr305', artifact='com.google.code.findbugs:jsr305:3.0.1', repository='http://repo.maven.apache.org/maven2/', sha1='f7be08ec23c21485b9b5a1cf1654c2ec8c58168d')
native.maven_jar(name='io_grpc_grpc_context', artifact='io.grpc:grpc-context... |
# -- Project information -----------------------------------------------------
project = 'showyourwork'
copyright = '2021, Rodrigo Luger'
author = 'Rodrigo Luger'
release = '1.0.0'
# -- General configuration ---------------------------------------------------
extensions = []
templates_path = ['_templates']
exclude_p... | project = 'showyourwork'
copyright = '2021, Rodrigo Luger'
author = 'Rodrigo Luger'
release = '1.0.0'
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
master_doc = 'index'
html_theme = 'sphinx_book_theme'
html_copy_source = True
html_show_sourcelink = True
html_sou... |
#!/usr/bin/env python3
"""
Bubble Sort Script
"""
def bubble_sort(L):
"""
Sorts a list in increasing order. Because of lists are mutable
this function does not have to return something.
This algorithm uses bubble sort.
@param L: a list (in general unsorted)
"""
for i in... | """
Bubble Sort Script
"""
def bubble_sort(L):
"""
Sorts a list in increasing order. Because of lists are mutable
this function does not have to return something.
This algorithm uses bubble sort.
@param L: a list (in general unsorted)
"""
for i in range(len(L) - 1):
already_sorted... |
class ScriptMessageSent:
""" Triggered when a message is sent using the ScriptConnector
message:str - the message that was sent
index:int - the index into the script (agent.messages) """
def __init__(self, message, index):
self.message = message
self.index = index
def __str... | class Scriptmessagesent:
""" Triggered when a message is sent using the ScriptConnector
message:str - the message that was sent
index:int - the index into the script (agent.messages) """
def __init__(self, message, index):
self.message = message
self.index = index
def __str... |
'''
#3-1
b=0
c=0
while 1 :
a=input("Enthe an integer, the input ends if it is :")
if((a>0)|(a<0)):
if a>0:
b=a
else:
c=-a
if(a==0):
print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c)))
break
'''
'''
#3-2
j = 0
for i in range(15):
s = 10... | """
#3-1
b=0
c=0
while 1 :
a=input("Enthe an integer, the input ends if it is :")
if((a>0)|(a<0)):
if a>0:
b=a
else:
c=-a
if(a==0):
print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c)))
break
"""
'\n#3-2\nj = 0\nfor i in range(15):\n s = 10... |
def mergeSort(myList):
print("Splitting ",myList)
if (len(myList) > 1):
mid = len(myList)//2
leftList = myList[:mid]
rightList = myList[mid:]
mergeSort(leftList)
mergeSort(rightList)
i = 0
j = 0
k = 0
while ((i < len(leftList)) and (j < len(rightList))):
if (leftList[i] < rightList[j]):
... | def merge_sort(myList):
print('Splitting ', myList)
if len(myList) > 1:
mid = len(myList) // 2
left_list = myList[:mid]
right_list = myList[mid:]
merge_sort(leftList)
merge_sort(rightList)
i = 0
j = 0
k = 0
while i < len(leftList) and j < l... |
while True:
relax = master.relax()
relax.optimize()
pi = [c.Pi for c in relax.getConstrs()]
knapsack = Model("KP")
knapsack.ModelSense=-1
y = {}
for i in range(m):
y[i] = knapsack.addVar(ub=q[i], vtype="I", name="y[%d]"%i)
knapsack.update()
knapsack.addConstr(quicksum(w[i]*y[... | while True:
relax = master.relax()
relax.optimize()
pi = [c.Pi for c in relax.getConstrs()]
knapsack = model('KP')
knapsack.ModelSense = -1
y = {}
for i in range(m):
y[i] = knapsack.addVar(ub=q[i], vtype='I', name='y[%d]' % i)
knapsack.update()
knapsack.addConstr(quicksum((w[... |
def hasDoubleDigits(p):
previous = ''
for c in p:
if c == previous:
return True
previous = c
return False
def neverDecreases(p):
previous = -1
for c in p:
current = int(c)
if current < previous:
return False
previous = current
ret... | def has_double_digits(p):
previous = ''
for c in p:
if c == previous:
return True
previous = c
return False
def never_decreases(p):
previous = -1
for c in p:
current = int(c)
if current < previous:
return False
previous = current
r... |
# a red shadow with some blur and a offset
cmykShadow((3, 3), 10, (1, 0, 0, 0))
# draw a rect
rect(100, 100, 30, 30) | cmyk_shadow((3, 3), 10, (1, 0, 0, 0))
rect(100, 100, 30, 30) |
#
# PySNMP MIB module NSLDAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSLDAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:25:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
def deleteDigit(n):
n = str(n)
return max([int(n[:index] + n[index + 1:]) for index in range(len(n))])
print(deleteDigit(152)) | def delete_digit(n):
n = str(n)
return max([int(n[:index] + n[index + 1:]) for index in range(len(n))])
print(delete_digit(152)) |
# SPDX-FileCopyrightText: 2021 Neradoc NeraOnGit@ri1.fr
#
# SPDX-License-Identifier: MIT
"""
Extended list of consumer controls.
"""
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/Neradoc/Circuitpython_Keyboard_Layouts.git"
class ConsumerControlExtended:
UNASSIGNED = 0x00
CONSUMER_CONTROL = 0x01
NUM... | """
Extended list of consumer controls.
"""
__version__ = '0.0.0-auto.0'
__repo__ = 'https://github.com/Neradoc/Circuitpython_Keyboard_Layouts.git'
class Consumercontrolextended:
unassigned = 0
consumer_control = 1
numeric_key_pad = 2
programmable_buttons = 3
plus10 = 32
plus100 = 33
am_pm ... |
'''
Maximum sum with modified positions
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
_ = input()
numbers = list(map(int, input().split()))
unmoved, zero_index = 0, numbers.index(0)
for coeff, i... | """
Maximum sum with modified positions
Status: Accepted
"""
def main():
"""Read input and print output"""
_ = input()
numbers = list(map(int, input().split()))
(unmoved, zero_index) = (0, numbers.index(0))
for (coeff, i) in enumerate(numbers, start=1):
unmoved += coeff * i
(maximal, n... |
name = 'tinymce'
authors = 'Joost Cassee'
version = 'trunk'
release = version
| name = 'tinymce'
authors = 'Joost Cassee'
version = 'trunk'
release = version |
#
# PySNMP MIB module PPVPN-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPVPN-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, constraints_union, single_value_constraint) ... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
cur... | class Solution(object):
def remove_elements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
cur = head
head = tail = None
while cur:
if cur.val != val:
if head:
tail.next =... |
with open('../input.txt','rt') as f:
lst = set(map(int,f.readlines()))
for x in lst:
if 2020-x in lst:
print(x*(2020-x)) | with open('../input.txt', 'rt') as f:
lst = set(map(int, f.readlines()))
for x in lst:
if 2020 - x in lst:
print(x * (2020 - x)) |
print("Calculator has started")
while True:
a = float(input("Enter first number "))
b = float(input("Enter second number "))
chooseop=1
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multipli... | print('Calculator has started')
while True:
a = float(input('Enter first number '))
b = float(input('Enter second number '))
chooseop = 1
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input('Enter 1 for addition, 2 for subtraction, 3 for multiplicati... |
class node:
def __init__(self,value=None):
self.value=value
self.left_child=None
self.right_child=None
self.parent=None # pointer to parent node in tree
self.height=1 # height of node in tree (max dist. to leaf) NEW FOR AVL
class AVLTree:
def __init__(self):
self.root=None
def __repr__(self):
if self... | class Node:
def __init__(self, value=None):
self.value = value
self.left_child = None
self.right_child = None
self.parent = None
self.height = 1
class Avltree:
def __init__(self):
self.root = None
def __repr__(self):
if self.root == None:
... |
class Solution:
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
results = [n for n in range(1, n+1)]
results.sort(key= lambda x: str(x))
return results | class Solution:
def lexical_order(self, n):
"""
:type n: int
:rtype: List[int]
"""
results = [n for n in range(1, n + 1)]
results.sort(key=lambda x: str(x))
return results |
class Boid():
def __init__(self, x,y,width,height):
self.position = Vector(x,y)
| class Boid:
def __init__(self, x, y, width, height):
self.position = vector(x, y) |
class PaginationType:
LIMIT = 'limit'
OFFSET = 'offset'
PAGINATION_LIMIT = 100
class Pagination:
"""
"""
LIMIT = 20
OFFSET = 0
@staticmethod
def validate(pagination_type, value):
"""
:param pagination_type:
:param value:
:return:
"""
t... | class Paginationtype:
limit = 'limit'
offset = 'offset'
pagination_limit = 100
class Pagination:
"""
"""
limit = 20
offset = 0
@staticmethod
def validate(pagination_type, value):
"""
:param pagination_type:
:param value:
:return:
"""
try:... |
# Area of a Triangle
print("Write a function that takes the base and height of a triangle and return its area.")
def area():
base = float(int(input("Enter the Base of the Triangle : ")))
height = float(int(input("Enter the height of the Triangle : ")))
total_area = (base * height)/2
print(total_area)
... | print('Write a function that takes the base and height of a triangle and return its area.')
def area():
base = float(int(input('Enter the Base of the Triangle : ')))
height = float(int(input('Enter the height of the Triangle : ')))
total_area = base * height / 2
print(total_area)
area()
input('Please C... |
"""
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
# Definition for... | """
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ 2 3 <---
\\ 5 4 <---
"""
class Solution(objec... |
def make_pizza(*toppings):
print(toppings)
# for item in toppings:
# print("Add " + item)
| def make_pizza(*toppings):
print(toppings) |
class Solution:
def numSplits(self, s: str) -> int:
answer=0
left=[0]*26
right=[0]*26
for x in s:
right[ord(x)-ord('a')]+=1
leftNum=0
rightNum=sum(x > 0 for x in right)
for x in s:
index=ord(x)-ord('a')
if left[in... | class Solution:
def num_splits(self, s: str) -> int:
answer = 0
left = [0] * 26
right = [0] * 26
for x in s:
right[ord(x) - ord('a')] += 1
left_num = 0
right_num = sum((x > 0 for x in right))
for x in s:
index = ord(x) - ord('a')
... |
#!/usr/bin/python3
# -*- mode: python; coding: utf-8 -*-
VERSION=1
TEMPLATE_KEY_PREFIX = 'jflow.template'
SEPARATOR_KEY = '.'
KEY_VERSION = 'version'
KEY_FORK = 'fork'
KEY_UPSTREAM = 'upstream'
KEY_PUBLIC = 'public'
KEY_DEBUG = 'debug'
KEY_REMOTE = 'remote'
KEY_MERGE_TO = 'merge-to'
KEY_EXTRA = 'extra'
# Template... | version = 1
template_key_prefix = 'jflow.template'
separator_key = '.'
key_version = 'version'
key_fork = 'fork'
key_upstream = 'upstream'
key_public = 'public'
key_debug = 'debug'
key_remote = 'remote'
key_merge_to = 'merge-to'
key_extra = 'extra'
key_public_prefix = 'public-prefix'
key_public_suffix = 'public-suffix'... |
"""
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space
complexity?
"""
__author__ = 'Dan... | """
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space
complexity?
"""
__author__ = 'Dan... |
while True:
print('Who are you?')
name=input()
if name!='Joe':
continue
print('Hello,Joe.What is the password?(it is a fish)')
password=input()
if password=='swordfish':
break
print('Access granted')
| while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello,Joe.What is the password?(it is a fish)')
password = input()
if password == 'swordfish':
break
print('Access granted') |
"""
Dinghy daily digest tool.
"""
__version__ = "0.12.0"
| """
Dinghy daily digest tool.
"""
__version__ = '0.12.0' |
class SearchQuery(dict):
"""
A specialized dict which has helpers for creating and modifying a Search
Query document.
Example usage:
>>> from globus_sdk import SearchClient, SearchQuery
>>> sc = SearchClient(...)
>>> index_id = ...
>>> query = (SearchQuery(q='example query')
>>> ... | class Searchquery(dict):
"""
A specialized dict which has helpers for creating and modifying a Search
Query document.
Example usage:
>>> from globus_sdk import SearchClient, SearchQuery
>>> sc = SearchClient(...)
>>> index_id = ...
>>> query = (SearchQuery(q='example query')
>>> ... |
def GenerateConfig(context):
resources = []
haEnabled = context.properties['num_instances'] > 1
# Enabling services
services = {
'name': 'enable_services',
'type': 'enable_services.py',
'properties': {
'services': context.properties['services']
}
}
# N... | def generate_config(context):
resources = []
ha_enabled = context.properties['num_instances'] > 1
services = {'name': 'enable_services', 'type': 'enable_services.py', 'properties': {'services': context.properties['services']}}
networking = {'name': 'networking', 'type': 'networking.py', 'properties': {'... |
# -*- encoding: utf-8 -*-
class UnWellcomeException(Exception):
"""
Base exception for all exceptions raised by this library.
"""
pass
| class Unwellcomeexception(Exception):
"""
Base exception for all exceptions raised by this library.
"""
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.