content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def fibonacci(n):
if n == 0:
return (0, 1)
else:
a, b = fibonacci(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
x = 0
y = 0
num = 1
while len(str(x)) < 1000:
x, y = fib... | def fibonacci(n):
if n == 0:
return (0, 1)
else:
(a, b) = fibonacci(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
x = 0
y = 0
num = 1
while len(str(x)) < 1000:
(x, y) = fibonacci(num)... |
def add(x, y):
return x + y
print(add(5, 7))
# -- Written as a lambda --
add = lambda x, y: x + y
print(add(5, 7))
# Four parts
# lambda
# parameters
# :
# return value
# Lambdas are meant to be short functions, often used without giving them a name.
# For example, in conjunction with built-in function map
# ... | def add(x, y):
return x + y
print(add(5, 7))
add = lambda x, y: x + y
print(add(5, 7))
def double(x):
return x * 2
sequence = [1, 3, 5, 9]
doubled = [double(x) for x in sequence]
doubled = map(double, sequence)
print(list(doubled))
sequence = [1, 3, 5, 9]
doubled = map(lambda x: x * 2, sequence)
print(list(dou... |
"""
atpthings.util
--------------
Utilities
"""
| """
atpthings.util
--------------
Utilities
""" |
def test_3_5_15(n):
if (n % 15 == 0) and n != 0 :
return 'FizzBuzz'
elif n % 3 ==0 and n != 0:
return 'Fizz'
elif n % 5 == 0 and n != 0:
return 'Buzz'
else:
return n
def coundown():
for x in range (0,101):
print(test_3_5_15(x))
coundown() | def test_3_5_15(n):
if n % 15 == 0 and n != 0:
return 'FizzBuzz'
elif n % 3 == 0 and n != 0:
return 'Fizz'
elif n % 5 == 0 and n != 0:
return 'Buzz'
else:
return n
def coundown():
for x in range(0, 101):
print(test_3_5_15(x))
coundown() |
def average(data):
if isinstance(data[0], int):
return sum(data) / len(data)
else:
raw_data = list(map(lambda r: r.value, data))
return sum(raw_data) / len(raw_data)
def minimum(data, index=0):
if index == 0:
data_slice = data
else:
data_slice = data[index:]
return min(data_slice)
def maximum(data, i... | def average(data):
if isinstance(data[0], int):
return sum(data) / len(data)
else:
raw_data = list(map(lambda r: r.value, data))
return sum(raw_data) / len(raw_data)
def minimum(data, index=0):
if index == 0:
data_slice = data
else:
data_slice = data[index:]
... |
EXCHANGE_MAX_NAME_LENGTH = 100
EXCHANGE_MAX_DESCRIPTION_LENGTH = 1000
FOLDER_FORBIDDEN_CHARS = {'/', '\\', ':', '*', '"', '<', '>', '?', '|'}
FOLDER_MAX_NAME_LENGTH = 60
def validate_folder(folder):
if 'name' not in folder:
raise Exception('No name')
for c in VALIDATE_FOLDER_FORBIDDEN_CHARS:
... | exchange_max_name_length = 100
exchange_max_description_length = 1000
folder_forbidden_chars = {'/', '\\', ':', '*', '"', '<', '>', '?', '|'}
folder_max_name_length = 60
def validate_folder(folder):
if 'name' not in folder:
raise exception('No name')
for c in VALIDATE_FOLDER_FORBIDDEN_CHARS:
if... |
class OperationStaResult(object):
def __init__(self):
self.total = None
self.wait = None
self.processing = None
self.success = None
self.fail = None
self.stop = None
self.timeout = None
def getTotal(self):
return self.total
def setTotal(self... | class Operationstaresult(object):
def __init__(self):
self.total = None
self.wait = None
self.processing = None
self.success = None
self.fail = None
self.stop = None
self.timeout = None
def get_total(self):
return self.total
def set_total(se... |
"""
This very high-level module determines/implements the specific behavior of the "standard" Necrobot running on the Crypt
of the Necrobot server.
Package Requirements
--------------------
botbase
util
daily
race
stats
user
Dependencies
------------
mainchannel
botbase/
... | """
This very high-level module determines/implements the specific behavior of the "standard" Necrobot running on the Crypt
of the Necrobot server.
Package Requirements
--------------------
botbase
util
daily
race
stats
user
Dependencies
------------
mainchannel
botbase/
... |
# Copyright 2018 Google LLC
#
# 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, s... | """Common configs for compatibility_lib."""
ignored_dependencies = ['pip', 'setuptools', 'wheel']
pkg_list = ['google-api-core', 'google-api-python-client', 'google-auth', 'google-cloud-bigquery', 'google-cloud-bigquery-datatransfer', 'google-cloud-bigtable', 'google-cloud-container', 'google-cloud-core', 'google-cloud... |
"""
Project: algorithms-exercises-using-python
Created by robin1885@github on 17-2-20.
"""
def anagram_solution3(s1, s2):
"""
@rtype : bool
@param s1: str1
@param s2: str2
@return: True or False
"""
pass | """
Project: algorithms-exercises-using-python
Created by robin1885@github on 17-2-20.
"""
def anagram_solution3(s1, s2):
"""
@rtype : bool
@param s1: str1
@param s2: str2
@return: True or False
"""
pass |
# Medium
# https://leetcode.com/problems/next-greater-element-ii/
# TC: O(N)
# SC: O(N)
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
nums = nums + nums
stack = []
out = [-1 for _ in nums]
for index, num in enumerate(nums):
while len(stack) ... | class Solution:
def next_greater_elements(self, nums: List[int]) -> List[int]:
nums = nums + nums
stack = []
out = [-1 for _ in nums]
for (index, num) in enumerate(nums):
while len(stack) and num > nums[stack[-1]]:
out[stack.pop()] = num
stack... |
days = ["Mon", "Thu", "Wed", "Thur", "Fri"] # list(mutable sequence)
print(days)
days.append("Sat")
days.reverse()
print(days)
| days = ['Mon', 'Thu', 'Wed', 'Thur', 'Fri']
print(days)
days.append('Sat')
days.reverse()
print(days) |
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
n = len(nums)
ans = []
for i in range(0, n-2):
if i > 0 and nums[i] == nums[i-1]:
continue
j,k ... | class Solution(object):
def three_sum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
n = len(nums)
ans = []
for i in range(0, n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
... |
"""Custom exceptions for money operations"""
# pylint: disable=missing-docstring
class InvalidAmountError(ValueError):
def __init__(self):
super().__init__("Invalid amount for currency")
class CurrencyMismatchError(ValueError):
def __init__(self):
super().__init__("Currencies must match")
... | """Custom exceptions for money operations"""
class Invalidamounterror(ValueError):
def __init__(self):
super().__init__('Invalid amount for currency')
class Currencymismatcherror(ValueError):
def __init__(self):
super().__init__('Currencies must match')
class Invalidoperanderror(ValueError)... |
# -*- coding: utf-8 -*-
"""
file: gromacs_ti.py
Functions for setting up a Gromacs based Thermodynamic Integration (TI)
calculation.
"""
| """
file: gromacs_ti.py
Functions for setting up a Gromacs based Thermodynamic Integration (TI)
calculation.
""" |
class StreamPredictorConsumer(object):
def __init__(self, name, algorithm=None, **kw):
self.algorithm = algorithm
self.name = name
self.run_count = 0
self.runs = []
async def handle(self, payload):
self.run_count += 1
try:
results, err = await self.a... | class Streampredictorconsumer(object):
def __init__(self, name, algorithm=None, **kw):
self.algorithm = algorithm
self.name = name
self.run_count = 0
self.runs = []
async def handle(self, payload):
self.run_count += 1
try:
(results, err) = await self... |
group_template_tag_prefix = 'DRKNS_GROUP_TEMPLATE_' # BEGIN / END
unit_template_tag_prefix = 'DRKNS_UNIT_TEMPLATE_' # BEGIN / END
groups_tag = 'DRKNS_GROUPS'
group_units_tag = 'DRKNS_GROUP_UNITS'
group_name_tag = 'DRKNS_GROUP_NAME'
unit_name_tag = 'DRKNS_UNIT_NAME'
dependency_groups_names_tag = 'DRKNS_DEPENDENCY_G... | group_template_tag_prefix = 'DRKNS_GROUP_TEMPLATE_'
unit_template_tag_prefix = 'DRKNS_UNIT_TEMPLATE_'
groups_tag = 'DRKNS_GROUPS'
group_units_tag = 'DRKNS_GROUP_UNITS'
group_name_tag = 'DRKNS_GROUP_NAME'
unit_name_tag = 'DRKNS_UNIT_NAME'
dependency_groups_names_tag = 'DRKNS_DEPENDENCY_GROUPS_NAMES'
all_group_names_tag ... |
#!/usr/bin/env python3
def main():
for i in range(1,11):
for j in range(1,11):
if(j==10):
print(i*j)
else:
print(i*j, end=" ")
if __name__ == "__main__":
main()
| def main():
for i in range(1, 11):
for j in range(1, 11):
if j == 10:
print(i * j)
else:
print(i * j, end=' ')
if __name__ == '__main__':
main() |
def require(*types):
'''
Return a decorator function that requires specified types.
types -- tuple each element of which is a type or class or a tuple of
several types or classes.
Example to require a string then a numeric argument
@require(str, (int, long, float))
will do the tric... | def require(*types):
"""
Return a decorator function that requires specified types.
types -- tuple each element of which is a type or class or a tuple of
several types or classes.
Example to require a string then a numeric argument
@require(str, (int, long, float))
will do the tric... |
def try_if(l):
ret = 0
for x in l:
if x == 1:
ret += 2
elif x == 0:
ret += 4
else:
ret -= 2
return ret
try_if([0, 1, 0, 1, 2, 3])
| def try_if(l):
ret = 0
for x in l:
if x == 1:
ret += 2
elif x == 0:
ret += 4
else:
ret -= 2
return ret
try_if([0, 1, 0, 1, 2, 3]) |
class Solution(object):
def XXX(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
i, j, k = 0, len(nums) - 1, 0
while k < len(nums):
if nums[k] == 0 and k > i:
nums[k], nums[i] = n... | class Solution(object):
def xxx(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
(i, j, k) = (0, len(nums) - 1, 0)
while k < len(nums):
if nums[k] == 0 and k > i:
(nums[k], nums[... |
class World:
def __init__(self):
pass
def get_state(self):
pass
def execute_action(self,a):
pass
class GameTree:
class GameNode:
def __init__(self, state, action, par):
self.state = state
self.action = action
self.... | class World:
def __init__(self):
pass
def get_state(self):
pass
def execute_action(self, a):
pass
class Gametree:
class Gamenode:
def __init__(self, state, action, par):
self.state = state
self.action = action
self.visited = 0.0
... |
namespace = '/map'
routes = {
'getAllObjectDest': '/',
}
| namespace = '/map'
routes = {'getAllObjectDest': '/'} |
"""
Exercise 1
Many of the built-in functions use variable-length argument
tuples. For example, max and min can take any number of
arguments:
>>> max(1,2,3)
3
But sum does not.
>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
Write a function called sumall that takes any number
of argu... | """
Exercise 1
Many of the built-in functions use variable-length argument
tuples. For example, max and min can take any number of
arguments:
>>> max(1,2,3)
3
But sum does not.
>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
Write a function called sumall that takes any number
of arguments and ret... |
# Validar uma string
def valida_str(texto, min, max):
tam = len(texto)
if tam < min or tam > max:
return False
else:
return True
# Programa Principal
texto = input('Digite um string (3-15 caracteres): ')
while valida_str(texto, 3, 15):
texto = input('Digite uma string (3-15 caracteres)... | def valida_str(texto, min, max):
tam = len(texto)
if tam < min or tam > max:
return False
else:
return True
texto = input('Digite um string (3-15 caracteres): ')
while valida_str(texto, 3, 15):
texto = input('Digite uma string (3-15 caracteres): ')
print(texto) |
#
# PySNMP MIB module HH3C-STACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-STACK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:29:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint) ... |
l1=[1,2,3,4,5,6,7,8,9,10]
l2=list(map(lambda n:n*n,l1))
print('l2:',l2)
l3=list((map(lambda n,m:n*m,l1,l2)))#map function can take more than one sequence argument
print('l3:',l3)
#if the length of the sequence is not equal then function will perform till same length
l3.pop()
print('popped l3:',l3)
l4=list(map(lambda n,... | l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l2 = list(map(lambda n: n * n, l1))
print('l2:', l2)
l3 = list(map(lambda n, m: n * m, l1, l2))
print('l3:', l3)
l3.pop()
print('popped l3:', l3)
l4 = list(map(lambda n, m, o: n + m + o, l1, l2, l3))
print('l4:', l4) |
{
'targets': [
{
'target_name': 'gpiobcm2835nodejs',
'sources': [
'src/gpiobcm2835nodejs.cc'
],
"cflags" : [ "-lrt -lbcm2835" ],
'conditions': [
['OS=="linux"', {
'cflags!': [
'-lrt -lbcm2835',
],
... | {'targets': [{'target_name': 'gpiobcm2835nodejs', 'sources': ['src/gpiobcm2835nodejs.cc'], 'cflags': ['-lrt -lbcm2835'], 'conditions': [['OS=="linux"', {'cflags!': ['-lrt -lbcm2835']}]], 'include_dirs': ['src/gpio_functions'], 'libraries': ['-lbcm2835']}]} |
class SpekulatioError(Exception):
pass
class FrontmatterError(SpekulatioError):
pass
| class Spekulatioerror(Exception):
pass
class Frontmattererror(SpekulatioError):
pass |
class Sql:
make_itemdb = '''
CREATE TABLE IF NOT EXISTS ITEMDB (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT,
PRICE REAL,
REGDATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
'''
insert_itemdb = '''
INSERT INTO ITEMDB (NAME, PRICE) VALUES ... | class Sql:
make_itemdb = '\n CREATE TABLE IF NOT EXISTS ITEMDB (\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\n NAME TEXT,\n PRICE REAL,\n REGDATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n )\n '
insert_itemdb = '\n INSERT INTO ITEMDB (NAME, PRICE) VALUE... |
def getbounds(img):
return tuple([min((si[i] for si in img)) for i in range(2)]), \
tuple([max((si[i] for si in img)) for i in range(2)])
def enhance(img, setval, algo):
bounds = getbounds(img)
offsets = ((1, 1), (0, 1), (-1, 1), (1, 0), (0, 0), (-1, 0), (1, -1), (0, -1), (-1, -1))
overhang... | def getbounds(img):
return (tuple([min((si[i] for si in img)) for i in range(2)]), tuple([max((si[i] for si in img)) for i in range(2)]))
def enhance(img, setval, algo):
bounds = getbounds(img)
offsets = ((1, 1), (0, 1), (-1, 1), (1, 0), (0, 0), (-1, 0), (1, -1), (0, -1), (-1, -1))
overhang = 2
n_i... |
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.is_word = False
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
root = TrieNode()
for word in words:
cur = root
for ch i... | class Trienode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.is_word = False
class Solution:
def find_words(self, board: List[List[str]], words: List[str]) -> List[str]:
root = trie_node()
for word in words:
cur = root
for ... |
def rotate(matrix):
#code here
for i in range(len(matrix)):
listt = list(reversed(matrix[i]))
for j in range(len(matrix[i])):
matrix[i][j] = listt[j]
# print(matrix)
for i in range(len(matrix)):
for j in range(i, len(matrix[i])):
matrix[i][j], matrix... | def rotate(matrix):
for i in range(len(matrix)):
listt = list(reversed(matrix[i]))
for j in range(len(matrix[i])):
matrix[i][j] = listt[j]
for i in range(len(matrix)):
for j in range(i, len(matrix[i])):
(matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j])
i... |
# Like list we can have set and dict comprehensions.
# Set comprehensions.
# The below set is not ordered.
square_set = {num * num for num in range(11)}
print(square_set)
# Dict Comprehension
dict_square = {num: num * num for num in range(11)}
print(dict_square)
# Use f"string to create a set and dict
f_string_squar... | square_set = {num * num for num in range(11)}
print(square_set)
dict_square = {num: num * num for num in range(11)}
print(dict_square)
f_string_square_set = {f'The square of {num} is {num * num}' for num in range(5)}
for x in f_string_square_set:
print(x)
f_string_square_dict = {num: f'the square is {num * num}' fo... |
## -*- encoding: utf-8 -*-
"""
This file (./sol/linalg_doctest.sage) was *autogenerated* from ./sol/linalg.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./sol/linalg_doctest.sage
It is a... | """
This file (./sol/linalg_doctest.sage) was *autogenerated* from ./sol/linalg.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./sol/linalg_doctest.sage
It is always safe to delete this f... |
#ANSI Foreground colors
black = u"\u001b[30m"
red = u"\u001b[31m"
green = u"\u001b[32m"
yellow = u"\u001b[33m"
blue = u"\u001b[34m"
magneta = u"\u001b[35m"
magenta = magneta
cyan = u"\u001b[36m"
white = u"\u001b[37m"
#ANSI Background colors
blackB = u"\u001b[40m"
redB = u"\u001b[41m"
greenB = u"\u001b[42m"
yellowB = u"... | black = u'\x1b[30m'
red = u'\x1b[31m'
green = u'\x1b[32m'
yellow = u'\x1b[33m'
blue = u'\x1b[34m'
magneta = u'\x1b[35m'
magenta = magneta
cyan = u'\x1b[36m'
white = u'\x1b[37m'
black_b = u'\x1b[40m'
red_b = u'\x1b[41m'
green_b = u'\x1b[42m'
yellow_b = u'\x1b[43m'
blue_b = u'\x1b[44m'
magneta_b = u'\x1b[45m'
magenta_b =... |
LAB_STYLE = """
body {
--jp-layout-color0: transparent;
--jp-layout-color1: transparent;
--jp-layout-color2: transparent;
--jp-layout-color3: transparent;
--jp-cell-editor-background: transparent;
--jp-border-width: 0;
--jp-border-color0: transparent;
... | lab_style = '\n body {\n --jp-layout-color0: transparent;\n --jp-layout-color1: transparent;\n --jp-layout-color2: transparent;\n --jp-layout-color3: transparent;\n --jp-cell-editor-background: transparent;\n --jp-border-width: 0;\n --jp-border-color0: transparent;\n ... |
#!/usr/bin/env python
"""
Find the greatest product of five consecutive digits in the 1000-digit number
"""
num = '\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
125406987471585238630507156932909632952274430... | """
Find the greatest product of five consecutive digits in the 1000-digit number
"""
num = '73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318... |
athlete_1 = int(input())
athlete_2 = int(input())
athlete_3 = int(input())
podium = []
if (athlete_1 < athlete_2 and athlete_1 < athlete_3):
podium.append(1)
if(athlete_2 < athlete_3):
podium.append(2)
podium.append(3)
else:
podium.append(3)
podium.append(2)
elif (athlete... | athlete_1 = int(input())
athlete_2 = int(input())
athlete_3 = int(input())
podium = []
if athlete_1 < athlete_2 and athlete_1 < athlete_3:
podium.append(1)
if athlete_2 < athlete_3:
podium.append(2)
podium.append(3)
else:
podium.append(3)
podium.append(2)
elif athlete_2 < ath... |
Number = int(input("\nPlease Enter the Range Number: "))
First_Value = 0
Second_Value = 1
for Num in range(0, Number):
if (Num <= 1):
Next = Num
else:
Next = First_Value + Second_Value
First_Value = Second_Value
Second_Value = Next
print(Next) | number = int(input('\nPlease Enter the Range Number: '))
first__value = 0
second__value = 1
for num in range(0, Number):
if Num <= 1:
next = Num
else:
next = First_Value + Second_Value
first__value = Second_Value
second__value = Next
print(Next) |
def Spell_0_10(n):
refTuple = ("zero","one","two","three","four","five",
"six","seven","eight","nine","ten")
return refTuple[n]
print(1, " is spelt as ", Spell_0_10(1))
for i in range(11):
print("{} is spelt as {}".format(i,Spell_0_10(i)))
for i in range (-9,0,1):
print("{} i... | def spell_0_10(n):
ref_tuple = ('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten')
return refTuple[n]
print(1, ' is spelt as ', spell_0_10(1))
for i in range(11):
print('{} is spelt as {}'.format(i, spell_0_10(i)))
for i in range(-9, 0, 1):
print('{} is spelt as {}'.f... |
"""Registry for behavior configurables."""
_BEHAVIOR_LIST = []
def behaviors():
"""Yields the currently registered behaviors in the order in which they
were defined."""
for name, cls, brief, level in _BEHAVIOR_LIST:
yield name, cls, brief, level
def behavior(name, brief, level=0):
"""Decorato... | """Registry for behavior configurables."""
_behavior_list = []
def behaviors():
"""Yields the currently registered behaviors in the order in which they
were defined."""
for (name, cls, brief, level) in _BEHAVIOR_LIST:
yield (name, cls, brief, level)
def behavior(name, brief, level=0):
"""Decor... |
"""excpetions.py"""
class GTMManagerException(Exception):
"""GTMManagerException"""
pass
class AuthError(GTMManagerException):
pass
class VariableNotFound(GTMManagerException):
"""VariableNotFound"""
def __init__(self, variable_name, parent):
super(VariableNotFound, self).__init__()
... | """excpetions.py"""
class Gtmmanagerexception(Exception):
"""GTMManagerException"""
pass
class Autherror(GTMManagerException):
pass
class Variablenotfound(GTMManagerException):
"""VariableNotFound"""
def __init__(self, variable_name, parent):
super(VariableNotFound, self).__init__()
... |
#Plugin to handle dialogues for men and women
#Written by Owain for Runefate
#31/01/18
#I want to give every spawned NPC a use, and not do what most servers have with useless non functioning NPCs.
#Even small things such as NPC dialogues can help make Runefate more rounded and enjoyable.
npc_ids = [3078, 3079]
dialo... | npc_ids = [3078, 3079]
dialogue_ids = [7502, 7504, 7506, 7508]
def first_click_npc_3078(player):
player.getDH().sendDialogues(7500)
def chat_7500(player):
player.getDH().sendPlayerChat('Hi there.', 591)
dialogue = random.choice(dialogue_ids)
player.nextDialogue = dialogue
def chat_7502(player):
p... |
class ReferenceDummy():
def __init__(self, *args):
return
def _to_dict(self, *args):
return "dummy"
| class Referencedummy:
def __init__(self, *args):
return
def _to_dict(self, *args):
return 'dummy' |
# #1
# def make_negative( number ):
# return number if number < 0 else - number
# #2
def make_negative( number ):
return -abs(number) | def make_negative(number):
return -abs(number) |
# This class parses a gtfs text file
class Reader:
def __init__(self, file):
self.fields = []
self.fp = open(file, "r")
self.fields.extend(self.fp.readline().rstrip().split(","))
def get_line(self):
data = {}
line = self.fp.readline().rstrip().split(",")
for e... | class Reader:
def __init__(self, file):
self.fields = []
self.fp = open(file, 'r')
self.fields.extend(self.fp.readline().rstrip().split(','))
def get_line(self):
data = {}
line = self.fp.readline().rstrip().split(',')
for (el, field) in zip(line, self.fields):
... |
# Cajones es una aplicacion que calcula el listado de partes
# de una cajonera
# unidad de medida en mm
# constantes
hol_lado = 13
# variables
h = 900
a = 600
prof_c = 400
h_c = 120
a_c = 200
hol_sup = 20
hol_inf = 10
hol_int = 40
hol_lateral = 2
esp_lado = 18
esp_sup = 18
esp_inf = 18
esp... | hol_lado = 13
h = 900
a = 600
prof_c = 400
h_c = 120
a_c = 200
hol_sup = 20
hol_inf = 10
hol_int = 40
hol_lateral = 2
esp_lado = 18
esp_sup = 18
esp_inf = 18
esp_c = 15
cubre_der_total = True
cubre_iz_total = True
def calcular_lado_cajon(prof_c, esp_c):
lado_cajon = prof_c - 2 * esp_c
return lado_cajon
def ca... |
#!/usr/bin/env python
class TwitterError(Exception):
"""Base class for Twitter errors"""
@property
def message(self):
'''Returns the first argument used to construct this error.'''
return self.args[0]
class PythonTwitterDeprecationWarning(DeprecationWarning):
"""Base class for pytho... | class Twittererror(Exception):
"""Base class for Twitter errors"""
@property
def message(self):
"""Returns the first argument used to construct this error."""
return self.args[0]
class Pythontwitterdeprecationwarning(DeprecationWarning):
"""Base class for python-twitter deprecation war... |
def middle(t):
'''Write a function called middle that takes a list and returns a new list that contains
all but the first and last elements'''
return t[1: -1]
if __name__ == '__main__':
t = [1, 2, 30, 400, 5000]
print(t)
print(middle(t))
| def middle(t):
"""Write a function called middle that takes a list and returns a new list that contains
all but the first and last elements"""
return t[1:-1]
if __name__ == '__main__':
t = [1, 2, 30, 400, 5000]
print(t)
print(middle(t)) |
"""
File: hailstone.py
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, as defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
This program will... | """
File: hailstone.py
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, as defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
This program will ... |
print("Size of list");
list1 = [1,23,5,2,42,526,52];
print(list1);
print(len(list1));
| print('Size of list')
list1 = [1, 23, 5, 2, 42, 526, 52]
print(list1)
print(len(list1)) |
#!/usr/bin/env python
#
# Copyright 2015 British Broadcasting Corporation
#
# 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 requ... | """
This module provides functions to analyses the timings of the detected
beep/flashes and compare them against expected timings of beep/flashes to
determine which observed ones correspond to which expected ones.
So for any given light sensor or audio input we have a set of observed timings
of beeps/flashes and a set... |
FANARTTV_PROJECTKEY = ''
TADB_PROJECTKEY = ''
TMDB_PROJECTKEY = ''
THETVDB_PROJECTKEY = ''
| fanarttv_projectkey = ''
tadb_projectkey = ''
tmdb_projectkey = ''
thetvdb_projectkey = '' |
# Regards, Takeda Shingen (Sengoku Era) Questline | Near Momiji Hills 1 (811000001)
# Author: Tiger
TAKEDA = 9000427
if "1" in sm.getQRValue(58901): # Regards, Takeda Shingen
sm.setSpeakerID(TAKEDA)
sm.flipDialogue()
sm.sendNext("Good, you're here! I was about to pick another fight")
sm.flipDialogue... | takeda = 9000427
if '1' in sm.getQRValue(58901):
sm.setSpeakerID(TAKEDA)
sm.flipDialogue()
sm.sendNext("Good, you're here! I was about to pick another fight")
sm.flipDialogue()
sm.sendSay("We have a problem, and it's not a lack of conditioner. I'll tell ya that!")
sm.flipDialogue()
sm.sendSa... |
array = [3,5,-4,8,11,-1,6]
targetSum = 10
def twoNumberSum(array, targetSum):
#for loop to iterate the array
for i in range(len(array) - 1):
firstNum = array[i]
for j in range(i + 1, len(array)):
secondNum = array[j]
if firstNum + secondNum == targetSum:
r... | array = [3, 5, -4, 8, 11, -1, 6]
target_sum = 10
def two_number_sum(array, targetSum):
for i in range(len(array) - 1):
first_num = array[i]
for j in range(i + 1, len(array)):
second_num = array[j]
if firstNum + secondNum == targetSum:
return [firstNum, second... |
def can_create_a_Fibonacci_number(int_1, int_2):
"""
This function checks to see if the sum, difference, product, or module
of the two inputs product a Fibonacci number.
1, 1, 2, 3, 5, 8, 13, 21, 34 ...
The two inputs are assumed to be integers
"""
sum = int_1 + int_2
product = int_1 ... | def can_create_a__fibonacci_number(int_1, int_2):
"""
This function checks to see if the sum, difference, product, or module
of the two inputs product a Fibonacci number.
1, 1, 2, 3, 5, 8, 13, 21, 34 ...
The two inputs are assumed to be integers
"""
sum = int_1 + int_2
product = int_1... |
"""
The constants module contains some numerical constants for use
in the module.
Note that modifying these may yield unpredictable results.
"""
# Force zero values to this amount, for numerical stability
MIN_SITE_FRACTION = 1e-12
MIN_PHASE_FRACTION = 1e-12
# Phases with mole fractions less than COMP_DIFFERENCE_TOL apa... | """
The constants module contains some numerical constants for use
in the module.
Note that modifying these may yield unpredictable results.
"""
min_site_fraction = 1e-12
min_phase_fraction = 1e-12
comp_difference_tol = 0.01
bignum = 1e+60 |
#!/usr/bin/env python
major_version = 0
minor_version = 0
patch_version = 10
def format_version():
return "{0}.{1}.{2}".format(major_version, minor_version, patch_version)
| major_version = 0
minor_version = 0
patch_version = 10
def format_version():
return '{0}.{1}.{2}'.format(major_version, minor_version, patch_version) |
# BIP39 Wordlist Validator - A tool to validate BIP39 wordlists in Latin
# languages.
# bip39validator/data_structs.py: Program data structures.
# Copyright 2020 Ali Sherief
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softw... | class Wordandlinearray:
def __init__(self, args):
self.word_list = args[0]
self.line_numbers = args[1]
class Levdist:
def __init__(self, **kwargs):
self.dist = kwargs['dist']
self.line_numbers = kwargs['line_numbers']
self.words = kwargs['words']
class Levdistarray:
... |
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
"""
Ideas:
1. Count the frequencies, sort and take top k -> O(N) + O(N log N)
2. heapq.nlargest -> O(N) + O(N log N)
3. Count the frequencies and keep only top k elements in the heap -> ... | class Solution:
def top_k_frequent(self, nums: List[int], k: int) -> List[int]:
"""
Ideas:
1. Count the frequencies, sort and take top k -> O(N) + O(N log N)
2. heapq.nlargest -> O(N) + O(N log N)
3. Count the frequencies and keep only top k elements in the heap ... |
#!/bin/python3
FAVORITE_NUMBER = 1362
GRID = [[0 for j in range(50)] for i in range(50)]
TARGET = (31, 39)
def check_wall(coordinates):
x, y = coordinates
if x < 0 or y < 0 or x >= 50 or y >= 50:
return False
elif GRID[x][y] != 0:
return False
current = x * x + 3 * x + 2 * x * y + ... | favorite_number = 1362
grid = [[0 for j in range(50)] for i in range(50)]
target = (31, 39)
def check_wall(coordinates):
(x, y) = coordinates
if x < 0 or y < 0 or x >= 50 or (y >= 50):
return False
elif GRID[x][y] != 0:
return False
current = x * x + 3 * x + 2 * x * y + y + y * y
cu... |
# coding: utf-8
# author: Fei Gao
#
# Search A 2d Matrix Ii
# Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
# Integers in each row are sorted in ascending from left to right.
# Integers in each column are sorted in ascending from top to bottom.
# ... | class Solution(object):
def search_matrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
def search(row1, row2, col1, col2):
"""Search target in sub matrix[row1:row2][col1:col2]"""
if row1 >= row2 ... |
""" https://www.hackerrank.com/challenges/dynamic-array/problem """
def dynamicArray(n, queries):
seqList = [[] for x in range(n)]
lastAnswer = 0
result = []
for q in queries:
[qType, seqIndex, number] = q
index = (seqIndex ^ lastAnswer) % n
seq = seqList[index]
if q... | """ https://www.hackerrank.com/challenges/dynamic-array/problem """
def dynamic_array(n, queries):
seq_list = [[] for x in range(n)]
last_answer = 0
result = []
for q in queries:
[q_type, seq_index, number] = q
index = (seqIndex ^ lastAnswer) % n
seq = seqList[index]
if ... |
_title = 'KleenExtractor'
_description = 'Clean extract system to export folder content and sub content.'
_version = '0.1.2'
_author = 'Edenskull'
_license = 'MIT'
| _title = 'KleenExtractor'
_description = 'Clean extract system to export folder content and sub content.'
_version = '0.1.2'
_author = 'Edenskull'
_license = 'MIT' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 1 10:46:16 2020
@author: AzureD
Useful tools to splitting and cleaning up input text.
"""
def cleanly(text: str):
"""
Splits the text into words at spaces, removing excess spaces.
"""
segmented = text.split(' ')
clean = [s for... | """
Created on Sat Aug 1 10:46:16 2020
@author: AzureD
Useful tools to splitting and cleaning up input text.
"""
def cleanly(text: str):
"""
Splits the text into words at spaces, removing excess spaces.
"""
segmented = text.split(' ')
clean = [s for s in segmented if not s == '']
return clea... |
q = int(input())
for _ in range(q):
n = int(input())
m = []
for _ in range(n*2):
m.append(list(map(int, input().split(' '))))
# Sorcery here...
bigMax = 0
for i in range(n):
for j in range(n):
try:
bigMax += max(m[i][j], m[i][2*... | q = int(input())
for _ in range(q):
n = int(input())
m = []
for _ in range(n * 2):
m.append(list(map(int, input().split(' '))))
big_max = 0
for i in range(n):
for j in range(n):
try:
big_max += max(m[i][j], m[i][2 * n - 1 - j], m[2 * n - 1 - i][j], m[2 * n... |
secret = 'BEEF0123456789a'
skipped_sequential_false_positive = '0123456789a'
print('second line')
var = 'third line'
| secret = 'BEEF0123456789a'
skipped_sequential_false_positive = '0123456789a'
print('second line')
var = 'third line' |
#http://www.pythonchallenge.com/pc/def/ocr.html
s = ""
with open("3.html") as f:
for line in f.readlines():
s += line
for el in s:
if el >= 'a' and el <= 'z':
print(el),
| s = ''
with open('3.html') as f:
for line in f.readlines():
s += line
for el in s:
if el >= 'a' and el <= 'z':
(print(el),) |
# feel free to change these settings
APP_NAME = 'Deep Vision' # any string: The application title (desktop and web).
ABOUT_TITLE = "Deep Vision" # any string: The about box title (desktop and web).
ABOUT_MESSAGE = "Created By : FastAI Student" # any string: The about box contents (desktop and web).
APP_TYPE = 'deskt... | app_name = 'Deep Vision'
about_title = 'Deep Vision'
about_message = 'Created By : FastAI Student'
app_type = 'desktop'
show_media = True
save_media = False
save_media_path = None
save_media_file = None
show_logs = False
camera_id = 0
images_types = ['*.jpg', '*.jpeg', '*.jpe', '*.png', '*.bmp']
videos_types = ['*.mp4'... |
# coding=utf-8
# Author: Jianghan LI
# Question: 114.Flatten_Binary_Tree_to_Linked_List
# Date: 2017-04-19 9:15 - 9:21
# 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):
... | class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root:
return
queue = [root]
if root.right:
queue.append(root.right)
if root... |
ch=input(('Enter any alphabet or digit '))
if ch in 'aeiouAEIOU':
print(ch,'is a vowel.')
elif ch in '0123456789':
print(ch,'is a digit.')
else:
print(ch,'is a consonant.')
| ch = input('Enter any alphabet or digit ')
if ch in 'aeiouAEIOU':
print(ch, 'is a vowel.')
elif ch in '0123456789':
print(ch, 'is a digit.')
else:
print(ch, 'is a consonant.') |
class MessageWriter:
"""
This class allows a "message" to be sent to an external recipient.
"""
def __init__(self, *args, **kwargs):
pass
def send_message(self, message):
"""
Sends a message to an external recipient.
Usually, this involves creating a connection to a... | class Messagewriter:
"""
This class allows a "message" to be sent to an external recipient.
"""
def __init__(self, *args, **kwargs):
pass
def send_message(self, message):
"""
Sends a message to an external recipient.
Usually, this involves creating a connection to a... |
LOCAL_STATE_PATH = "/state"
DEFAULT_INSTANCE_TYPE_TRAINING = "ml.m5.large"
DEFAULT_INSTANCE_TYPE_PROCESSING = "ml.t3.medium"
DEFAULT_INSTANCE_COUNT = 1
DEFAULT_VOLUME_SIZE = 30 # GB
DEFAULT_USE_SPOT = True
DEFAULT_MAX_RUN = 24 * 60
DEFAULT_MAX_WAIT = 0
DEFAULT_IAM_ROLE = "SageMakerIAMRole"
DEFAULT_IAM_BUCKET_POLICY_... | local_state_path = '/state'
default_instance_type_training = 'ml.m5.large'
default_instance_type_processing = 'ml.t3.medium'
default_instance_count = 1
default_volume_size = 30
default_use_spot = True
default_max_run = 24 * 60
default_max_wait = 0
default_iam_role = 'SageMakerIAMRole'
default_iam_bucket_policy_suffix =... |
"""
*Coarsen*
"""
__all__ = ["Coarsen"]
class Coarsen(
TensorOperator,
):
pass
| """
*Coarsen*
"""
__all__ = ['Coarsen']
class Coarsen(TensorOperator):
pass |
def avg(values):
return sum(values) / len(values)
def input_to_list(count):
lines = []
for _ in range(count):
lines.append(input())
return lines
n = int(input())
students_grades_lines = input_to_list(n)
students_grades = {}
for line in students_grades_lines:
student, grade = line.spl... | def avg(values):
return sum(values) / len(values)
def input_to_list(count):
lines = []
for _ in range(count):
lines.append(input())
return lines
n = int(input())
students_grades_lines = input_to_list(n)
students_grades = {}
for line in students_grades_lines:
(student, grade) = line.split(' ... |
"""
## OSBot-Utils
Project with multiple Util classes (to streamline development)
Main GitHub repo: https://github.com/owasp-sbot/OSBot-Utils
[](https://coveralls.io/github/owasp-sbot/OSBot-Utils?branch=master)
""" | """
## OSBot-Utils
Project with multiple Util classes (to streamline development)
Main GitHub repo: https://github.com/owasp-sbot/OSBot-Utils
[](https://coveralls.io/github/owasp-sbot/OSBot-Utils?branch=master)
""" |
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
weight = dict()
for x in people:
if x in weight:
weight[x] += 1
else:
weight[x] = 1
ans = 0
for x in people:
if weight[x] > 0:
... | class Solution:
def num_rescue_boats(self, people: List[int], limit: int) -> int:
weight = dict()
for x in people:
if x in weight:
weight[x] += 1
else:
weight[x] = 1
ans = 0
for x in people:
if weight[x] > 0:
... |
n=int(input())
l=[]
k=[]
e=[]
for i in range (n):
t=input()
l.append(t)
print(l)
for j in l:
if j not in k:
k.append(j)
print(k)
print(len(k))
for m in range(len(k)):
c=0
for d in l:
if( k[m]==d):
c=c+1
e.append(c)
print(e)
for i in e:
... | n = int(input())
l = []
k = []
e = []
for i in range(n):
t = input()
l.append(t)
print(l)
for j in l:
if j not in k:
k.append(j)
print(k)
print(len(k))
for m in range(len(k)):
c = 0
for d in l:
if k[m] == d:
c = c + 1
e.append(c)
print(e)
for i in e:
print(i, end=... |
"""
format:
def request(login, password):
return bool(...)
""" | """
format:
def request(login, password):
return bool(...)
""" |
class Shop:
_small_shop_capacity = 10
def __init__(self, name, shop_type, capacity):
self.name = name
self.type = shop_type
self.capacity = capacity
self.items_count = 0
self.items = {}
@classmethod
def small_shop(cls, name, shop_type):
return cls(name, ... | class Shop:
_small_shop_capacity = 10
def __init__(self, name, shop_type, capacity):
self.name = name
self.type = shop_type
self.capacity = capacity
self.items_count = 0
self.items = {}
@classmethod
def small_shop(cls, name, shop_type):
return cls(name, ... |
for row in range(5,0):
for col in range(1,row+1):
print(col,end=" ")
print()
| for row in range(5, 0):
for col in range(1, row + 1):
print(col, end=' ')
print() |
IDENTIFIED_COMMANDS = {
'NS STATUS %s': ['STATUS {username} (\d)', '3'],
'PRIVMSG NickServ ACC %s': ['{username} ACC (\d)', '3'],
}
IRC_AUTHS = {
# 'localhost': {'username': 'Botname', 'realname': 'Bot Real Name'},
}
IRC_GROUPCHATS = [
# 'groupchat@localhost',
]
IRC_PERMISSIONS = {
# 'nekmo@loca... | identified_commands = {'NS STATUS %s': ['STATUS {username} (\\d)', '3'], 'PRIVMSG NickServ ACC %s': ['{username} ACC (\\d)', '3']}
irc_auths = {}
irc_groupchats = []
irc_permissions = {} |
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
result = []
for i in range(0, len(nums), 2):
freq, val = nums[i:i+2]
for n in range(freq):
result.append(val)
return result
| class Solution:
def decompress_rl_elist(self, nums: List[int]) -> List[int]:
result = []
for i in range(0, len(nums), 2):
(freq, val) = nums[i:i + 2]
for n in range(freq):
result.append(val)
return result |
filename = "myFile1.py"
with open(filename, "r") as f:
for line in f:
print(f)
| filename = 'myFile1.py'
with open(filename, 'r') as f:
for line in f:
print(f) |
"""
domonic.constants
====================================
"""
namespaces = {'xml': 'http://www.w3.org/XML/1998/namespace', 'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink',
'xmlns': 'http://www.w3.org/2000/xmlns/', 'xm': 'http://www.w3.org/2001/xml-events', 'xh': 'ht... | """
domonic.constants
====================================
"""
namespaces = {'xml': 'http://www.w3.org/XML/1998/namespace', 'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink', 'xmlns': 'http://www.w3.org/2000/xmlns/', 'xm': 'http://www.w3.org/2001/xml-events', 'xh': 'http://www.w3.org... |
m = 35.0 / 8.0
n = int(35/8)
print(m)
print(n)
| m = 35.0 / 8.0
n = int(35 / 8)
print(m)
print(n) |
class Dealer:
def __init__(self):
self.__hand = None
def select_action(self):
if self.hand_total() < 17:
return 1
else:
return 0
def give_card(self, card):
self.__hand.add_card(card)
def revealed_card(self):
cards = self.__hand.cards()
return cards[0]
def is_busted(... | class Dealer:
def __init__(self):
self.__hand = None
def select_action(self):
if self.hand_total() < 17:
return 1
else:
return 0
def give_card(self, card):
self.__hand.add_card(card)
def revealed_card(self):
cards = self.__hand.cards()
... |
# https://cses.fi/problemset/task/1083
d = [False for _ in range(int(input()))]
for i in input().split(' '):
d[int(i) - 1] = True
for i, b in enumerate(d):
if not b:
print(i + 1)
exit()
| d = [False for _ in range(int(input()))]
for i in input().split(' '):
d[int(i) - 1] = True
for (i, b) in enumerate(d):
if not b:
print(i + 1)
exit() |
{
"targets": [
{
"target_name": "lib/daemon",
"sources": [ "src/daemon.cc" ]
}
]
} | {'targets': [{'target_name': 'lib/daemon', 'sources': ['src/daemon.cc']}]} |
class CommandTools:
@staticmethod
def get_token():
""" Simple helper that will return the token stored in the text file.
:return: Your Robinhood API token
"""
robinhood_token_file = open('robinhood_token.txt')
current_token = robinhood_token_file.read()
return... | class Commandtools:
@staticmethod
def get_token():
""" Simple helper that will return the token stored in the text file.
:return: Your Robinhood API token
"""
robinhood_token_file = open('robinhood_token.txt')
current_token = robinhood_token_file.read()
return c... |
def main():
st = input("")
print(st[0])
print(end="")
main()
| def main():
st = input('')
print(st[0])
print(end='')
main() |
# This program demonstrates how to use the remove
# method to remove an item from a list.
def main():
# Create a list with some items.
food = ['Pizza', 'Burgers', 'Chips']
# Display the list.
print('Here are the items in the food list:')
print(food)
# Get the item to change.
i... | def main():
food = ['Pizza', 'Burgers', 'Chips']
print('Here are the items in the food list:')
print(food)
item = input('Which item should I remove? ')
try:
food.remove(item)
print('Here is the revised list:')
print(food)
except ValueError:
print('That item was no... |
class TeamNotFound(Exception):
"""Raise when the team is not found in the database"""
class NoMatchData(Exception):
"""Raise when data for match cant be created"""
| class Teamnotfound(Exception):
"""Raise when the team is not found in the database"""
class Nomatchdata(Exception):
"""Raise when data for match cant be created""" |
def computepay(h, r):
print("In computepay")
if h>40:
pay = 40 * r + (h - 40) * 1.5 * r
else:
pay = h * r
return pay
hrs = input("Enter Hours:")
h = float(hrs)
rate = input("Enter Rate:")
r = float(rate)
pay = computepay(h,r)
print(pay)
| def computepay(h, r):
print('In computepay')
if h > 40:
pay = 40 * r + (h - 40) * 1.5 * r
else:
pay = h * r
return pay
hrs = input('Enter Hours:')
h = float(hrs)
rate = input('Enter Rate:')
r = float(rate)
pay = computepay(h, r)
print(pay) |
"""Scheduling errors."""
class AssignmentError(Exception):
"""Raised for errors when generating assignments."""
def __init__(self, message: str):
self.message = message
| """Scheduling errors."""
class Assignmenterror(Exception):
"""Raised for errors when generating assignments."""
def __init__(self, message: str):
self.message = message |
'''
MIT License
Name cs225sp20_env Python Package
URL https://github.com/Xiwei-Wang/cs225sp20_env
Version 1.0
Creation Date 26 April 2020
Copyright(c) 2020 Instructors, TAs and Some Students of UIUC CS 225 SP20 ZJUI Course
Instructorts: Prof. Dr. Klaus-Dieter Schewe
TAs: Tingou Liang, Run Zhang, Enyi Jiang, Xiang Li... | """
MIT License
Name cs225sp20_env Python Package
URL https://github.com/Xiwei-Wang/cs225sp20_env
Version 1.0
Creation Date 26 April 2020
Copyright(c) 2020 Instructors, TAs and Some Students of UIUC CS 225 SP20 ZJUI Course
Instructorts: Prof. Dr. Klaus-Dieter Schewe
TAs: Tingou Liang, Run Zhang, Enyi Jiang, Xiang Li... |
def merge(list0,list1):
result = []
while len(list1) and len(list0):
if list0[0]<list1[0]:
result.append(list0.pop(0))
else:
result.append(list1.pop(0))
result.extend(list0)
result.extend(list1)
return result
def mergesort(item):
if len(item)<=1:
... | def merge(list0, list1):
result = []
while len(list1) and len(list0):
if list0[0] < list1[0]:
result.append(list0.pop(0))
else:
result.append(list1.pop(0))
result.extend(list0)
result.extend(list1)
return result
def mergesort(item):
if len(item) <= 1:
... |
# Link - https://leetcode.com/problems/unique-morse-code-words/
'''
Runtime: 28 ms, faster than 95.58% of Python3 online submissions for Unique Morse Code Words.
Memory Usage: 13.6 MB, less than 99.77% of Python3 online submissions for Unique Morse Code Words.
'''
class Solution:
def uniqueMorseRepresentations(se... | """
Runtime: 28 ms, faster than 95.58% of Python3 online submissions for Unique Morse Code Words.
Memory Usage: 13.6 MB, less than 99.77% of Python3 online submissions for Unique Morse Code Words.
"""
class Solution:
def unique_morse_representations(self, words: List[str]) -> int:
morse = ['.-', '-...', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# services - Waqas Bhatti (wbhatti@astro.princeton.edu) - Oct 2017
# License: MIT. See the LICENSE file for more details.
'''This contains various modules to query online data services. These are not
exhaustive and are meant to support other astrobase modules.
- :py:mod:`... | """This contains various modules to query online data services. These are not
exhaustive and are meant to support other astrobase modules.
- :py:mod:`astrobase.services.dust`: interface to the 2MASS DUST
extinction/emission service.
- :py:mod:`astrobase.services.gaia`: interface to the GAIA TAP+ ADQL query
servic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.