content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/python3
"""Alta3 Research | RZFeeser
Review of Lists and Dictionaries"""
# define a short data set (in real world, we want to read this from a file or API)
munsters = {'endDate': 1966, 'startDate': 1964,\
'names':['Lily', 'Herman', 'Grandpa', 'Eddie', 'Marilyn']} # {} creates dict
# Your solut... | """Alta3 Research | RZFeeser
Review of Lists and Dictionaries"""
munsters = {'endDate': 1966, 'startDate': 1964, 'names': ['Lily', 'Herman', 'Grandpa', 'Eddie', 'Marilyn']}
names = munsters['names']
for i in range(len(names)):
print(names[i])
print(munsters['endDate'])
print(munsters['startDate'])
munsters['epis... |
with open('assets/day09.txt', 'r') as file:
lines = [line for line in file.read().splitlines()]
depths = [[9] + [int(d) for d in line] + [9] for line in lines]
depths = [[9] * len(depths[0])] + depths + [[9] * len(depths[0])]
minimums = []
for y in range(1, len(depths) - 1):
for x in range(1, len(depths[y]) ... | with open('assets/day09.txt', 'r') as file:
lines = [line for line in file.read().splitlines()]
depths = [[9] + [int(d) for d in line] + [9] for line in lines]
depths = [[9] * len(depths[0])] + depths + [[9] * len(depths[0])]
minimums = []
for y in range(1, len(depths) - 1):
for x in range(1, len(depths[y]) - 1... |
CONTENT = """huc basin
<!--10n 60s-->
01 New England
0101 St. John
010100 St. John
01010001 Upper St. John
01010002 Allagash
01010003 Fish
01010004 Aroostook
01010005 Meduxnekeag
0102 Penobscot
010200 Penobscot
01020001 West Branch Penobscot
01020002 East Branch Penobscot
01020003 Mattawamkeag
01020004 Piscataquis
0102... | content = 'huc\tbasin\n<!--10n\t60s-->\n01\tNew England\n0101\tSt. John\n010100\tSt. John\n01010001\tUpper St. John\n01010002\tAllagash\n01010003\tFish\n01010004\tAroostook\n01010005\tMeduxnekeag\n0102\tPenobscot\n010200\tPenobscot\n01020001\tWest Branch Penobscot\n01020002\tEast Branch Penobscot\n01020003\tMattawamkea... |
# Copyright 2020 Joshua Laniado and Todd O. Yeates.
__author__ = "Joshua Laniado and Todd O. Yeates"
__copyright__ = "Copyright 2020, Nanohedra"
__version__ = "1.0"
# SYMMETRY COMBINATION MATERIAL TABLE (T.O.Y and J.L, 2020)
sym_comb_dict = {
1: [1, 'C2', 1, ['r:<0,0,1,a>', 't:<0,0,b>'], 2, '<0,0,0>', 'C2', 1, ['r... | __author__ = 'Joshua Laniado and Todd O. Yeates'
__copyright__ = 'Copyright 2020, Nanohedra'
__version__ = '1.0'
sym_comb_dict = {1: [1, 'C2', 1, ['r:<0,0,1,a>', 't:<0,0,b>'], 2, '<0,0,0>', 'C2', 1, ['r:<0,0,1,c>', 't:<0,0,d>'], 1, '<0,0,0>', 'D2', 'D2', 0, 'N/A', 4, 2], 2: [2, 'C2', 1, ['r:<0,0,1,a>', 't:<0,0,b>'], 1,... |
n, k = map(int, input().split())
y = sorted(map(int, input().split()))
sol = 0
for i in y:
if k <= (5-i):
sol += 1
print(sol//3)
| (n, k) = map(int, input().split())
y = sorted(map(int, input().split()))
sol = 0
for i in y:
if k <= 5 - i:
sol += 1
print(sol // 3) |
# Enter your code here. Read input from STDIN. Print output to STDOUT
#with name and number input, divide both and enter into dict
phonebook = {}
number = int(input())
for _ in range(0, number):
item = str(input()).split(" ")
name = item[0]
phonenumber = int(item[1])
phonebook[name] = phonenumber
#... | phonebook = {}
number = int(input())
for _ in range(0, number):
item = str(input()).split(' ')
name = item[0]
phonenumber = int(item[1])
phonebook[name] = phonenumber
for i in range(0, number):
name = input()
if name in phonebook:
print(name + '=' + str(phonebook[name]))
else:
... |
{
"targets":[
{
"target_name":"pcap_addon",
"sources":[
"./src/winpcap/pcap_addon.cc",
"./src/winpcap/pcapObjFactory.cc",
"./src/winpcap/commLib.cc"],
"include_dirs": [
"<!(node -e \"require('nan')\")",
... | {'targets': [{'target_name': 'pcap_addon', 'sources': ['./src/winpcap/pcap_addon.cc', './src/winpcap/pcapObjFactory.cc', './src/winpcap/commLib.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")', 'lib/winpcap/include', 'lib/winpcap/include/pcap', 'src/winpcap/include'], 'defines': ['HAVE_REMOTE'], 'conditions': [[... |
# coding: utf-8
# file generated by setuptools_scm
# don't change, don't track in version control
version = '1.9.0'
version_tuple = (1, 9, 0)
| version = '1.9.0'
version_tuple = (1, 9, 0) |
# -*- coding: utf-8 -*-
"""
Generate features from pandas dataframe, with columns statistics.
-------------------
Return dataframe, columns=[by, col]
"""
def get_count(df, by):
return df.groupby(by=by).count().iloc[:,0]
def get_sum(df, col, by):
return df.groupby(by=by).sum()[col]
def get_mean(df, col, ... | """
Generate features from pandas dataframe, with columns statistics.
-------------------
Return dataframe, columns=[by, col]
"""
def get_count(df, by):
return df.groupby(by=by).count().iloc[:, 0]
def get_sum(df, col, by):
return df.groupby(by=by).sum()[col]
def get_mean(df, col, by):
return df.groupby... |
LINKING_PROPERTY = "Transaction/generated/LinkedTransactionId"
INPUT_TXN_FILTER = "type in 'Buy','Purchase','Sell','FwdFxSell', 'FwdFxBuy','FxBuy','FxSell','StockIn'"
ENTITY_PROPERTY = "Portfolio/test/Entity"
BROKER_PROPERTY = "Portfolio/test/Broker"
COUNTRY_PROPERTY = "Instrument/test/Country"
PROPERTIES_REQUIRED = [... | linking_property = 'Transaction/generated/LinkedTransactionId'
input_txn_filter = "type in 'Buy','Purchase','Sell','FwdFxSell', 'FwdFxBuy','FxBuy','FxSell','StockIn'"
entity_property = 'Portfolio/test/Entity'
broker_property = 'Portfolio/test/Broker'
country_property = 'Instrument/test/Country'
properties_required = [E... |
"""
Given a lowercase string, s, return the index fo the first character that appears just once in a string.
If every character appears more than once, return -1
Example input:
s: "Who wants hot watermelon?"
Example Output:
8
Explanation:
"who wants hot watermelon?"
^
012345678
The first charactter ... | """
Given a lowercase string, s, return the index fo the first character that appears just once in a string.
If every character appears more than once, return -1
Example input:
s: "Who wants hot watermelon?"
Example Output:
8
Explanation:
"who wants hot watermelon?"
^
012345678
The first charactter ... |
class Solution:
def reformatNumber(self, number: str) -> str:
number = number.replace(' ','')
number = number.replace('-','')
output = ''
count = len(number)
remain = count % 3
print(remain)
if remain == 0:
last = number[len(numbe... | class Solution:
def reformat_number(self, number: str) -> str:
number = number.replace(' ', '')
number = number.replace('-', '')
output = ''
count = len(number)
remain = count % 3
print(remain)
if remain == 0:
last = number[len(number) - 3:]
... |
numero = int(input('digite um numero: '))
u = numero // 1 % 10
d = numero // 10 % 10
c = numero // 100 % 10
m = numero // 1000 % 10
print('analisando numero {}'.format(numero))
print('unidades: {}'.format(u))
print('dezenas: {}'.format(d))
print('centenas: {}'.format(c))
print('milhares: {}'.format(m))
| numero = int(input('digite um numero: '))
u = numero // 1 % 10
d = numero // 10 % 10
c = numero // 100 % 10
m = numero // 1000 % 10
print('analisando numero {}'.format(numero))
print('unidades: {}'.format(u))
print('dezenas: {}'.format(d))
print('centenas: {}'.format(c))
print('milhares: {}'.format(m)) |
SOURCE = "http://tabinstore.fr"
HEADER = "User-Agent: Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
MAX_IMG_SIZE = 71680 # In Bytes
| source = 'http://tabinstore.fr'
header = 'User-Agent: Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'
max_img_size = 71680 |
li = []
inp = input()
li = inp.split(' ' , 5)
print(1-int(li[0]),' ',1-int(li[1]),' ',2-int(li[2]),' ',2-int(li[3]),' ',2-int(li[4]),' ',8-int(li[5]), end = '')
| li = []
inp = input()
li = inp.split(' ', 5)
print(1 - int(li[0]), ' ', 1 - int(li[1]), ' ', 2 - int(li[2]), ' ', 2 - int(li[3]), ' ', 2 - int(li[4]), ' ', 8 - int(li[5]), end='') |
x,y = 8, 4
if x > y:
print("x es mayor que y")
print("x es el doble de y")
if x > y:
print("x es mayor que y")
else:
print("x es menor o igual que y")
if x < y:
print("x es menor que y")
elif x == y:
print("x es igual a y")
else:
print("x es mayor que y") | (x, y) = (8, 4)
if x > y:
print('x es mayor que y')
print('x es el doble de y')
if x > y:
print('x es mayor que y')
else:
print('x es menor o igual que y')
if x < y:
print('x es menor que y')
elif x == y:
print('x es igual a y')
else:
print('x es mayor que y') |
set_name(0x8012EA14, "GameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x8012EA1C, "vecleny__Fii", SN_NOWARN)
set_name(0x8012EA40, "veclenx__Fii", SN_NOWARN)
set_name(0x8012EA6C, "GetDamageAmt__FiPiT1", SN_NOWARN)
set_name(0x8012F0DC, "CheckBlock__Fiiii", SN_NOWARN)
set_name(0x8012F22C, "FindClosest__Fiii", SN_NOWARN)
set... | set_name(2148723220, 'GameOnlyTestRoutine__Fv', SN_NOWARN)
set_name(2148723228, 'vecleny__Fii', SN_NOWARN)
set_name(2148723264, 'veclenx__Fii', SN_NOWARN)
set_name(2148723308, 'GetDamageAmt__FiPiT1', SN_NOWARN)
set_name(2148724956, 'CheckBlock__Fiiii', SN_NOWARN)
set_name(2148725292, 'FindClosest__Fiii', SN_NOWARN)
set... |
""" Third party dependencies for this project. """
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def zola_deps():
""" Fetches the dependencies for the zola project. """
if "zola-v0-14-1-x86-64-unknown-linux-gnu" not in native.existing_rules():
http_archive(
name = "z... | """ Third party dependencies for this project. """
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def zola_deps():
""" Fetches the dependencies for the zola project. """
if 'zola-v0-14-1-x86-64-unknown-linux-gnu' not in native.existing_rules():
http_archive(name='zola-v0-14-1-x86-... |
#Printing stars in 'W' shape!
'''
* * *
* * * *
** **
* *
'''
i=0
j=3
for row in range(4):
for col in range(7):
if(col==0 or col==6) or (col==4 and row==1) or (col==5 and row==2):
print('*',end='')
elif row==i and col==j:
print('*', end='')
i+=1
... | """
* * *
* * * *
** **
* *
"""
i = 0
j = 3
for row in range(4):
for col in range(7):
if (col == 0 or col == 6) or (col == 4 and row == 1) or (col == 5 and row == 2):
print('*', end='')
elif row == i and col == j:
print('*', end='')
i += 1
j -=... |
def get():
return [
'const',
'var',
'import',
'require',
'using',
'load',
'from',
'as'
] | def get():
return ['const', 'var', 'import', 'require', 'using', 'load', 'from', 'as'] |
def inlookuptable(value: str, lookuptable: str):
with open(lookuptable, "r") as lookuptablestream:
for table in lookuptablestream:
if table.strip("\n") == value:
return True
return False
| def inlookuptable(value: str, lookuptable: str):
with open(lookuptable, 'r') as lookuptablestream:
for table in lookuptablestream:
if table.strip('\n') == value:
return True
return False |
# Labels for Nodes and Relationships
BOT_LABEL = "Bot"
USER_LABEL = "User"
TWEET_LABEL = "Tweet"
WROTE_LABEL = "WROTE"
RETWEET_LABEL = "RETWEETED"
QUOTE_LABEL = "QUOTED"
REPLY_LABEL = "REPLIED"
FOLLOW_LABEL = "FOLLOWS"
QUERY = "match (b:Bot) - [r] - (t:Tweet) - [r2] - (t2:Tweet)" \
"call apoc.cypher.run('with `t` as ... | bot_label = 'Bot'
user_label = 'User'
tweet_label = 'Tweet'
wrote_label = 'WROTE'
retweet_label = 'RETWEETED'
quote_label = 'QUOTED'
reply_label = 'REPLIED'
follow_label = 'FOLLOWS'
query = "match (b:Bot) - [r] - (t:Tweet) - [r2] - (t2:Tweet)call apoc.cypher.run('with `t` as t match (u:User) -[]-(t) return u, t limit 5... |
def my_first_module_func():
print('you are using my first created module')
def console_log(message):
print(message)
| def my_first_module_func():
print('you are using my first created module')
def console_log(message):
print(message) |
def cuadrado1(num1):
return num1**2
cuadrado2 = lambda num1: num1 ** 2
print(cuadrado1(5))
print(cuadrado2(5)) | def cuadrado1(num1):
return num1 ** 2
cuadrado2 = lambda num1: num1 ** 2
print(cuadrado1(5))
print(cuadrado2(5)) |
MODE_5X11 = 0b00000011
class I2cConstants:
def __init__(self):
self.I2C_ADDR = 0x60
self.CMD_SET_MODE = 0x00
self.CMD_SET_BRIGHTNESS = 0x19
self.MODE_5X11 = 0b00000011
class IS31FL3730:
def __init__(self, smbus, font):
self.bus = smbus
self.font = font
s... | mode_5_x11 = 3
class I2Cconstants:
def __init__(self):
self.I2C_ADDR = 96
self.CMD_SET_MODE = 0
self.CMD_SET_BRIGHTNESS = 25
self.MODE_5X11 = 3
class Is31Fl3730:
def __init__(self, smbus, font):
self.bus = smbus
self.font = font
self.i2cConstants = i2c... |
def sum_list(numbers):
total = 0
for i in numbers:
total += i
return total
print(sum_list([1, 2, -8]))
"""
Write a Python program to sum all the items in a list
"""
| def sum_list(numbers):
total = 0
for i in numbers:
total += i
return total
print(sum_list([1, 2, -8]))
'\n\n Write a Python program to sum all the items in a list\n \n' |
#Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.
#Given a string containing just the characters '(', ')', '{', '}', '[' and ']'... | class Solution:
def close_para(self, s):
if s == '(':
return (')', False)
elif s == '{':
return ('}', False)
elif s == '[':
return (']', False)
else:
return (s, True)
def append_stack(self, c, paraStack):
paraStack.append(... |
# -*- coding:utf-8 -*-
"""
@author: leonardo
@created time: 2020-11-03
@last modified time:2020-11-03
"""
def select(engine, backtesting_id):
"""
:param engine:
:param backtesting_id:
:return:
"""
sql = 'SELECT * from strategy_backtesting where backtesting_id="{}"'.format(backtesting_id)
... | """
@author: leonardo
@created time: 2020-11-03
@last modified time:2020-11-03
"""
def select(engine, backtesting_id):
"""
:param engine:
:param backtesting_id:
:return:
"""
sql = 'SELECT * from strategy_backtesting where backtesting_id="{}"'.format(backtesting_id)
return list(engine.execu... |
if type(Query.target) is IfStatement:
parent = Query.target.parent
parent.beginModification('If to while')
condition = Query.target.condition
thenBranch = Query.target.thenBranch
Query.target.replaceChild(condition, Node.createNewNode('Expression', None))
Query.target.replaceChild(thenBranch, Node.createNewNode... | if type(Query.target) is IfStatement:
parent = Query.target.parent
parent.beginModification('If to while')
condition = Query.target.condition
then_branch = Query.target.thenBranch
Query.target.replaceChild(condition, Node.createNewNode('Expression', None))
Query.target.replaceChild(thenBranch, N... |
# -*- coding:utf-8 -*-
class CocoException(Exception):
pass
class CoCoRuntimeError(RuntimeError):
pass | class Cocoexception(Exception):
pass
class Cocoruntimeerror(RuntimeError):
pass |
#!/usr/bin/env python3
def exam_grade(score):
"""Students in a class receive their grades as Pass/Fail. Scores of 60 or more
(out of 100) mean that the grade is "Pass". For lower scores, the grade is
"Fail". In addition, scores above 95 (not included) are graded as "Top Score".
This function receives the score and... | def exam_grade(score):
"""Students in a class receive their grades as Pass/Fail. Scores of 60 or more
(out of 100) mean that the grade is "Pass". For lower scores, the grade is
"Fail". In addition, scores above 95 (not included) are graded as "Top Score".
This function receives the score and returns the proper g... |
sampleJson = {
"id": 3,
"pin": "700014",
"cgst": 3241.53,
"date": "2021-04-16",
"igst": 0,
"name": "Subhajit Paul",
"sgst": 3241.53,
"type": "S",
"email": 'nulestu@gmail.com',
"gstin": 'KKHUU654343KL8',
"phone": 9165799976,
"mobile": "7059403006",
"ref_no": "GKUS/30/2... | sample_json = {'id': 3, 'pin': '700014', 'cgst': 3241.53, 'date': '2021-04-16', 'igst': 0, 'name': 'Subhajit Paul', 'sgst': 3241.53, 'type': 'S', 'email': 'nulestu@gmail.com', 'gstin': 'KKHUU654343KL8', 'phone': 9165799976, 'mobile': '7059403006', 'ref_no': 'GKUS/30/21', 'address': '7 Dr Suresh Sarkar road Kolkata', 'p... |
def dot(data, compile_to=None):
notation_list = data.split('.')
compiling = ""
compiling += notation_list[0]
beginning_string = compile_to.split('{1}')[0]
compiling = beginning_string + compiling
dot_split = compile_to.replace(beginning_string + '{1}', '').split('{.}')
if any(len(x) > 1 for... | def dot(data, compile_to=None):
notation_list = data.split('.')
compiling = ''
compiling += notation_list[0]
beginning_string = compile_to.split('{1}')[0]
compiling = beginning_string + compiling
dot_split = compile_to.replace(beginning_string + '{1}', '').split('{.}')
if any((len(x) > 1 for... |
"""Functions relating to grokking_algorithms qucksort chapter."""
def euclid_algorithm(area):
"""Return the largest square to subdivide area by."""
height = area[0]
width = area[1]
maxdim = max(height, width)
mindim = min(height, width)
remainder = maxdim % mindim
if remainder == 0:
... | """Functions relating to grokking_algorithms qucksort chapter."""
def euclid_algorithm(area):
"""Return the largest square to subdivide area by."""
height = area[0]
width = area[1]
maxdim = max(height, width)
mindim = min(height, width)
remainder = maxdim % mindim
if remainder == 0:
... |
expected_output = {
"tag": {
"test": {
"system_id": {
"R2_xr": {
"type": {
"L1L2": {
"area_address": ["49.0001"],
"circuit_id": "R1_xe.01",
"format": "P... | expected_output = {'tag': {'test': {'system_id': {'R2_xr': {'type': {'L1L2': {'area_address': ['49.0001'], 'circuit_id': 'R1_xe.01', 'format': 'Phase V', 'interface': 'GigabitEthernet2.115', 'ip_address': ['10.12.115.2*'], 'ipv6_address': ['FE80::F816:3EFF:FE67:2452'], 'nsf': 'capable', 'priority': 64, 'state': 'up', '... |
class CliArgs(object):
def __init__(self):
self.search = []
self.all = False
self.slim = False
self.include = False
self.order = False
self.reverse = False
self.json = False
self.version = False
| class Cliargs(object):
def __init__(self):
self.search = []
self.all = False
self.slim = False
self.include = False
self.order = False
self.reverse = False
self.json = False
self.version = False |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
# https://projecteuler.net/problem=1
# 1, 5, 10, 15, 20, ...
# 3, 6, 9, 12, 15, 18, 21, ...
limit = 1000
print( sum( set(range(... | limit = 1000
print(sum(set(range(5, limit, 5)).union(set(range(3, limit, 3))))) |
def circ_supply(height: int, nano: bool = False) -> int:
"""
Circulating supply at given height, in ERG (or nanoERG).
"""
# Emission settings
initial_rate = 75
fixed_rate_blocks = 525600 - 1
epoch_length = 64800
step = 3
# At current height
completed_epochs = max(0, h... | def circ_supply(height: int, nano: bool=False) -> int:
"""
Circulating supply at given height, in ERG (or nanoERG).
"""
initial_rate = 75
fixed_rate_blocks = 525600 - 1
epoch_length = 64800
step = 3
completed_epochs = max(0, height - fixed_rate_blocks) // epoch_length
current_epoch =... |
# Resources for an MPMCT with n controls
def mpmct_depth(n):
return 28*n - 60
def mpmct_t_c(n):
return 12*n - 20
def mpmct_t_d(n):
return 4*(n-2)
def mpmct_h_c(n):
return 4*n - 6
def mpmct_cnot_c(n):
return 24*n - 40
| def mpmct_depth(n):
return 28 * n - 60
def mpmct_t_c(n):
return 12 * n - 20
def mpmct_t_d(n):
return 4 * (n - 2)
def mpmct_h_c(n):
return 4 * n - 6
def mpmct_cnot_c(n):
return 24 * n - 40 |
class Equip():
def __init__(self, name, attribute, action):
self.name = name
self.attribute = attribute
self.action = action
class Item():
def __init__(self, name, attribute, buff):
self.name = name
self.attribute = attribute
self.buff = buff
class Attribute(dic... | class Equip:
def __init__(self, name, attribute, action):
self.name = name
self.attribute = attribute
self.action = action
class Item:
def __init__(self, name, attribute, buff):
self.name = name
self.attribute = attribute
self.buff = buff
class Attribute(dict)... |
class ProxyException(Exception):
"""Proxy returned an error."""
def __init__(self, message='Proxy returned an error.'):
# Call the base class constructor with the parameters it needs
super(ProxyException, self).__init__(message)
| class Proxyexception(Exception):
"""Proxy returned an error."""
def __init__(self, message='Proxy returned an error.'):
super(ProxyException, self).__init__(message) |
H, W, N = map(int, input().split())
berry = [tuple(int(x) for x in input().split()) for _ in range(N)]
ans = []
for i in range(1, W+1):
up = 0
for x, y in berry:
if i * y == H * x:
break
elif i * y > H * x:
up += 1
else:
if up * 2 == N:
ans.append(... | (h, w, n) = map(int, input().split())
berry = [tuple((int(x) for x in input().split())) for _ in range(N)]
ans = []
for i in range(1, W + 1):
up = 0
for (x, y) in berry:
if i * y == H * x:
break
elif i * y > H * x:
up += 1
else:
if up * 2 == N:
ans... |
__author__ = 'lg'
a = raw_input()
if a > 0:
print('positive number')
elif a < 0:
print('negative number')
else:
print('the number is zero') | __author__ = 'lg'
a = raw_input()
if a > 0:
print('positive number')
elif a < 0:
print('negative number')
else:
print('the number is zero') |
# Advent of Code - Day 7 - Part One
def parse(input):
return [int(n) for n in input[0].split(",")]
def result(input):
positions = parse(input)
fuel_cost_options = []
for i in range(min(positions), max(positions) + 1):
movements = [abs(n - i) for n in positions]
fuel_cost_options.appe... | def parse(input):
return [int(n) for n in input[0].split(',')]
def result(input):
positions = parse(input)
fuel_cost_options = []
for i in range(min(positions), max(positions) + 1):
movements = [abs(n - i) for n in positions]
fuel_cost_options.append(sum(movements))
return min(fuel_... |
'''
6. Write a Python program to create a histogram from a given list of integers.
'''
def histogram(values):
for n in values:
output = ''
x = n
while(x > 0):
output += '*'
x = x - 1
print(output)
histogram([1,2,3,4,5,6]) | """
6. Write a Python program to create a histogram from a given list of integers.
"""
def histogram(values):
for n in values:
output = ''
x = n
while x > 0:
output += '*'
x = x - 1
print(output)
histogram([1, 2, 3, 4, 5, 6]) |
print("#######################################")
print("## AVERAGE STUDENT HEIGHT CALCULATOR ##")
print("#######################################")
#test heights: 123 149 175 183 166 179 125
student_heights = input(" Input a list of student heights:\n>> ").split()
for n in range(0, len(student_heights)):
student_hei... | print('#######################################')
print('## AVERAGE STUDENT HEIGHT CALCULATOR ##')
print('#######################################')
student_heights = input(' Input a list of student heights:\n>> ').split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total =... |
i = 1
while True:
print(i)
i += 1
if i > 10:
break
| i = 1
while True:
print(i)
i += 1
if i > 10:
break |
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
c = (a, b)
d = {e: 1, f: 2}
fun(a, b, *c, **d)
# EXPECTED:
[
...,
BUILD_TUPLE(2),
...,
BUILD_TUPLE_UNPACK_WITH_CALL(2),
...,
CALL_FUNCTION_EX(1),
...,
]
| c = (a, b)
d = {e: 1, f: 2}
fun(a, b, *c, **d)
[..., build_tuple(2), ..., build_tuple_unpack_with_call(2), ..., call_function_ex(1), ...] |
#A program that counts the number of characters up to the first $ in a text file.
file = open("poem.txt","r")
data = file.readlines()
for index in range(len(data)):
for secondIndex in range(len(data[index])):
if data[index][secondIndex] == "$":
break
print( "Total number of chara... | file = open('poem.txt', 'r')
data = file.readlines()
for index in range(len(data)):
for second_index in range(len(data[index])):
if data[index][secondIndex] == '$':
break
print('Total number of characters up to the first $ are = ', index + secondIndex)
file.close() |
def metade(valor = 0, format = False):
resp = valor/2
return resp if format is False else money(resp)
def dobro(valor = 0, format = False):
resp = valor*2
return resp if format is False else money(resp)
def dez_porcento(valor = 0, format = False):
resp = valor + (valor*10)/100
return resp i... | def metade(valor=0, format=False):
resp = valor / 2
return resp if format is False else money(resp)
def dobro(valor=0, format=False):
resp = valor * 2
return resp if format is False else money(resp)
def dez_porcento(valor=0, format=False):
resp = valor + valor * 10 / 100
return resp if format ... |
'''
Created on 2020-04-15 14:50:02
Last modified on 2020-05-07 21:21:10
Python 2.7.16
v0.1
@author: L. F. Pereira (lfpereira@fe.up.pt)
Main goal
---------
Develop functions to get data from odb files.
'''
#%% history outputs
def get_xydata_from_nodes_history_output(odb, nodes, variable,
... | """
Created on 2020-04-15 14:50:02
Last modified on 2020-05-07 21:21:10
Python 2.7.16
v0.1
@author: L. F. Pereira (lfpereira@fe.up.pt)
Main goal
---------
Develop functions to get data from odb files.
"""
def get_xydata_from_nodes_history_output(odb, nodes, variable, directions=(1, 2, 3), step_name=None):
"""
... |
P = {}
# Imputers
P['mean imp'] = {'strategy': 'mean'}
P['median imp'] = {'strategy': 'median'}
P['most freq imp'] = {'strategy': 'most_frequent'}
P['constant imp'] = {'strategy': 'constant'}
P['iterative imp'] = {'initial_strategy': 'mean',
'skip_complete': True}
| p = {}
P['mean imp'] = {'strategy': 'mean'}
P['median imp'] = {'strategy': 'median'}
P['most freq imp'] = {'strategy': 'most_frequent'}
P['constant imp'] = {'strategy': 'constant'}
P['iterative imp'] = {'initial_strategy': 'mean', 'skip_complete': True} |
#23212 | Contract with Mastema
isDS = chr.getJob() == 3100
sm.setSpeakerID(2450017)
if not sm.canHold(1142342):
sm.sendSayOkay("Please make space in your equip inventory.")
sm.dispose()
if sm.sendAskYesNo("Everything is ready. Let us begin the contract ritual. Focus on your mind."):
sm.jobAdvance(isDS a... | is_ds = chr.getJob() == 3100
sm.setSpeakerID(2450017)
if not sm.canHold(1142342):
sm.sendSayOkay('Please make space in your equip inventory.')
sm.dispose()
if sm.sendAskYesNo('Everything is ready. Let us begin the contract ritual. Focus on your mind.'):
sm.jobAdvance(isDS and 3110 or 3120)
sm.giveItem(i... |
#prob:lem statement: Make the below pattern. Here, n =4
#4 4 4 4 4 4 4
#4 3 3 3 3 3 4
#4 3 2 2 2 3 4
#4 3 2 1 2 3 4
#4 3 2 2 2 3 4
#4 3 3 3 3 3 4
#4 4 4 4 4 4 4
n=int(input("enter any number: "))
#n is the number for the outermost lines and val is the value to be printed in row i column j
#for first left quadrant
for i... | n = int(input('enter any number: '))
for i in range(1, n + 1):
for j in range(1, n + 1):
if i < j:
val = i
else:
val = j
print(n - val + 1, end='')
for j in range(n - 1, 0, -1):
if i < j:
val = i
else:
val = j
print(... |
# train-project/train_schedule/views/formatters.py
"""Helper functions to format data for display."""
def format_station(station, show_id=False):
"""Format station data for display"""
if station is None:
return "Unknown"
else:
fmt_str = "{city}, {country} ({code})"
if show_id:
... | """Helper functions to format data for display."""
def format_station(station, show_id=False):
"""Format station data for display"""
if station is None:
return 'Unknown'
else:
fmt_str = '{city}, {country} ({code})'
if show_id:
fmt_str = '{id}: ' + fmt_str
return ... |
def index_settings(table_name):
"""
Return the Elasticsearch mapping for a given table in the database.
:param table_name: The name of the table in the upstream database.
:return:
"""
settings = {
"index": {
"number_of_shards": 18,
"number_of_replicas": 0,
... | def index_settings(table_name):
"""
Return the Elasticsearch mapping for a given table in the database.
:param table_name: The name of the table in the upstream database.
:return:
"""
settings = {'index': {'number_of_shards': 18, 'number_of_replicas': 0, 'refresh_interval': '-1'}, 'analysis': {... |
class IntegralCalculator:
def __init__(self):
self.value = 0
self.last_time = 0
def get_current_integral(self) -> float:
return self.value
def get_and_update_integral(self, new_x, new_time) -> float:
self.update_integral(new_x, new_time)
return self.get_current_inte... | class Integralcalculator:
def __init__(self):
self.value = 0
self.last_time = 0
def get_current_integral(self) -> float:
return self.value
def get_and_update_integral(self, new_x, new_time) -> float:
self.update_integral(new_x, new_time)
return self.get_current_int... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
ADMINS = (
('Joe Admin', 'joe@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'EN... | debug = True
template_debug = DEBUG
allowed_hosts = []
admins = (('Joe Admin', 'joe@example.com'),)
managers = ADMINS
databases = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'chain', 'USER': 'yoda', 'PASSWORD': '123', 'HOST': 'localhost', 'PORT': '', 'CONN_MAX_AGE': 600}}
collector_auth = (... |
def countApplesAndOranges(s, t, a, b, apples, oranges):
# Write your code here
fallen_apples = 0
fallen_oranges = 0
for apple in apples:
if a + apple >= s and a + apple <= t:
fallen_apples += 1
for orange in oranges:
if b + orange >= s and b + orange <= t:
f... | def count_apples_and_oranges(s, t, a, b, apples, oranges):
fallen_apples = 0
fallen_oranges = 0
for apple in apples:
if a + apple >= s and a + apple <= t:
fallen_apples += 1
for orange in oranges:
if b + orange >= s and b + orange <= t:
fallen_oranges += 1
pri... |
# Create a set and check if element already exists.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums)) | class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums)) |
i = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2 | i = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2 |
vector_collection = {
'none': None,
'empty': [],
'numerals': [1, 1, 2, 3, 5, 8, 13, 21],
'strings': ['foo', 'bar', 'zen'],
'cities': ['san fransisco', 'buenos aires', 'bern', 'kinshasa-brazzaville', 'nairobi']
}
| vector_collection = {'none': None, 'empty': [], 'numerals': [1, 1, 2, 3, 5, 8, 13, 21], 'strings': ['foo', 'bar', 'zen'], 'cities': ['san fransisco', 'buenos aires', 'bern', 'kinshasa-brazzaville', 'nairobi']} |
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l=nums
j=0
for i in range(len(l)):
if l[i]!=0:
nums[j]=l[i]
j+=1
fo... | class Solution:
def move_zeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = nums
j = 0
for i in range(len(l)):
if l[i] != 0:
nums[j] = l[i]
j += ... |
# list in python and follow indexing rule, start from 0
thisList = ["pooya","mohammad","Mahdi","Alireza"]
print(thisList)
thisList[1] = "Eshghe Man"
print(thisList)
# The list() constructor include add item to list and delete the item
listTwo = list(("apple","melon","orange"))
print(listTwo)
# append() use to add ... | this_list = ['pooya', 'mohammad', 'Mahdi', 'Alireza']
print(thisList)
thisList[1] = 'Eshghe Man'
print(thisList)
list_two = list(('apple', 'melon', 'orange'))
print(listTwo)
listTwo.append('mandarin')
print(listTwo)
listTwo.remove(listTwo[2])
print(listTwo)
print(len(listTwo))
print(thisList)
print(thisList.clear())
x ... |
'''
Key points:
- recognize that this is very similar to merging intervals (https://leetcode.com/problems/merge-intervals/description/)
- it doesn't matter which employee an interval belongs to, so just flatten
- can build result array while merging, don't have to do afterward (and don't need full merged arr)
'''
def... | """
Key points:
- recognize that this is very similar to merging intervals (https://leetcode.com/problems/merge-intervals/description/)
- it doesn't matter which employee an interval belongs to, so just flatten
- can build result array while merging, don't have to do afterward (and don't need full merged arr)
"""
def... |
ligne_vide = ['o','o','o','o','o','o','o','o','o']
ligne_courte = ['o','o','.','.','.','.','.','o','o']
ligne_longue = ['o','.','.','.','.','.','.','.','o']
arche_vide = [ligne_vide,ligne_courte,ligne_longue,ligne_longue,ligne_courte,ligne_vide]
#print(arche_vide)
def affiche_ligne (l) :
s=''
for c i... | ligne_vide = ['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o']
ligne_courte = ['o', 'o', '.', '.', '.', '.', '.', 'o', 'o']
ligne_longue = ['o', '.', '.', '.', '.', '.', '.', '.', 'o']
arche_vide = [ligne_vide, ligne_courte, ligne_longue, ligne_longue, ligne_courte, ligne_vide]
def affiche_ligne(l):
s = ''
for c i... |
class TalkMessage:
def __init__(self, messageId, timeStamp, body, senderAvatarId, senderAvatarName, senderAccountId, senderAccountName, receiverAvatarId, receiverAvatarName, receiverAccountId, receiverAccountName, talkType, extraInfo=None):
self.timeStamp = timeStamp
self.body = body
self... | class Talkmessage:
def __init__(self, messageId, timeStamp, body, senderAvatarId, senderAvatarName, senderAccountId, senderAccountName, receiverAvatarId, receiverAvatarName, receiverAccountId, receiverAccountName, talkType, extraInfo=None):
self.timeStamp = timeStamp
self.body = body
self.s... |
''' While Loops
Used to execute a set of statements(code) continuously as long as a condition is True.
The while loop needs to be setup in a way that as long as a condition is True, Then stop when the condition becomes False.
While loop can have optional else clause.
'''
i = 1
| """ While Loops
Used to execute a set of statements(code) continuously as long as a condition is True.
The while loop needs to be setup in a way that as long as a condition is True, Then stop when the condition becomes False.
While loop can have optional else clause.
"""
i = 1 |
def get_f(f, i, mode):
try:
if mode == 0:
return f[f[i]]
if mode == 1:
return f[i]
except KeyError:
return 0
raise NotImplementedError
def set_f(f, value, i, mode):
if mode == 0:
f[f[i]] = value
return
if mode == 1:
f[i] = val... | def get_f(f, i, mode):
try:
if mode == 0:
return f[f[i]]
if mode == 1:
return f[i]
except KeyError:
return 0
raise NotImplementedError
def set_f(f, value, i, mode):
if mode == 0:
f[f[i]] = value
return
if mode == 1:
f[i] = valu... |
"""
Provides hard-coded values used in this package. No imports are allowed
since many other modules import this one
"""
__copyright__ = "Copyright 2020, Datera, Inc."
VERSION = "1.2.26"
VERSION_HISTORY = """
Version History:
1.1.0 -- Initial Version
1.1.1 -- Metadata Endpoint, Pep8 cleanup, Logging revamp
... | """
Provides hard-coded values used in this package. No imports are allowed
since many other modules import this one
"""
__copyright__ = 'Copyright 2020, Datera, Inc.'
version = '1.2.26'
version_history = "\nVersion History:\n 1.1.0 -- Initial Version\n 1.1.1 -- Metadata Endpoint, Pep8 cleanup, Logging revamp\n ... |
USER = "__DUMMY_TRANSFORMERS_USER__"
FULL_NAME = "Dummy User"
PASS = "__DUMMY_TRANSFORMERS_PASS__"
# Not critical, only usable on the sandboxed CI instance.
TOKEN = "hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLL"
ENDPOINT_PRODUCTION = "https://huggingface.co"
ENDPOINT_STAGING = "https://hub-ci.huggingface.co"
ENDPOINT_STAGIN... | user = '__DUMMY_TRANSFORMERS_USER__'
full_name = 'Dummy User'
pass = '__DUMMY_TRANSFORMERS_PASS__'
token = 'hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLL'
endpoint_production = 'https://huggingface.co'
endpoint_staging = 'https://hub-ci.huggingface.co'
endpoint_staging_basic_auth = f'https://{USER}:{PASS}@hub-ci.huggingface.co... |
print("copy content from auto created ex23_sample_05.txt to ex23_sample_06.txt using 1 line only")
input('In powershell: echo "This is a unicode Test." > ex23_sample_05.txt ')
in_file = open('c:\\users\\roy\\ex23_sample_05.txt', encoding = 'utf-16').read()
out_file = open('c:\\users\\roy\\ex23_sample_06.txt', 'w', enc... | print('copy content from auto created ex23_sample_05.txt to ex23_sample_06.txt using 1 line only')
input('In powershell: echo "This is a unicode Test." > ex23_sample_05.txt ')
in_file = open('c:\\users\\roy\\ex23_sample_05.txt', encoding='utf-16').read()
out_file = open('c:\\users\\roy\\ex23_sample_06.txt', 'w', encodi... |
sum = 0
count = 0
while True:
try:
name = input()
distance = int(input())
sum += distance
count += 1
except EOFError:
break
print("{:.1f}".format(sum/count)) | sum = 0
count = 0
while True:
try:
name = input()
distance = int(input())
sum += distance
count += 1
except EOFError:
break
print('{:.1f}'.format(sum / count)) |
# -*- coding: utf-8 -*-
#from scrapy.settings.default_settings import DOWNLOAD_DELAY
#from scrapy.settings.default_settings import ITEM_PIPELINES
# Scrapy settings for fbo_scraper project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#... | bot_name = 'packard_scraper'
spider_modules = ['packard_scraper.spiders']
item_pipelines = {'packard_scraper.pipelines.FboScraperExcelPipeline': 0}
newspider_module = 'packard_scraper.spiders'
robotstxt_obey = True
randomize_download_delay = True
download_delay = 5.0
user_agent = 'packard_scraper (+http://research.umd.... |
#Factorial de un numero, usar recursividad.
def factorial(number):
if number == 0:
return 1
return number * factorial(number - 1)
if __name__ == '__main__':
number = int(input('Ingrese numero a convertir en factorial: '))
result = factorial(number)
print('El resultado es:... | def factorial(number):
if number == 0:
return 1
return number * factorial(number - 1)
if __name__ == '__main__':
number = int(input('Ingrese numero a convertir en factorial: '))
result = factorial(number)
print('El resultado es: {}'.format(result)) |
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def go_to_school(self):
return "I'm going to {}".format(self.school)
anna = Student("Anna", "Oxford")... | class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def go_to_school(self):
return "I'm going to {}".format(self.school)
anna = student('Anna', 'Oxford')
... |
"""Top-level package for fdf."""
__author__ = """Ledenel Intelli"""
__email__ = 'ledenelintelli@gmail.com'
__version__ = '0.1.9'
| """Top-level package for fdf."""
__author__ = 'Ledenel Intelli'
__email__ = 'ledenelintelli@gmail.com'
__version__ = '0.1.9' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Andy Wilson, Michael Darling, David Stracuzzi, Shelley Leger
Sandia National Laboratories
February 25, 2020
Defines set of test sudoku problems to use to test the sudoku infrastructure
"""
puzzles = {
'test2-i24e40': '30000070000000100000006000000070001540030000... | """
Andy Wilson, Michael Darling, David Stracuzzi, Shelley Leger
Sandia National Laboratories
February 25, 2020
Defines set of test sudoku problems to use to test the sudoku infrastructure
"""
puzzles = {'test2-i24e40': '300000700000001000000060000000700015400300000000000020610000800000540900002000000', 'test3-i29e35'... |
# Part 2 on day 2 on advent of code
#
# Tyler Stuessi
def get_bathroom_code():
# get input
code = ""
keypaths = []
try:
while True:
raw = input()
keypaths.append(raw)
except EOFError:
pass
# hard code the grid
grid = [["0", "0", "1", "0", "0"],
... | def get_bathroom_code():
code = ''
keypaths = []
try:
while True:
raw = input()
keypaths.append(raw)
except EOFError:
pass
grid = [['0', '0', '1', '0', '0'], ['0', '2', '3', '4', '0'], ['5', '6', '7', '8', '9'], ['0', 'A', 'B', 'C', '0'], ['0', '0', 'D', '0', ... |
def fizz_buzz(input):
result = []
for x in range(1, input + 1):
value = ''
if x % 3 == 0:
value += 'Fizz'
if x % 5 == 0:
value += 'Buzz'
value = value or x
result.append(value)
return result
| def fizz_buzz(input):
result = []
for x in range(1, input + 1):
value = ''
if x % 3 == 0:
value += 'Fizz'
if x % 5 == 0:
value += 'Buzz'
value = value or x
result.append(value)
return result |
# This sample tests annotated types on global variables.
# This should generate an error because the declared
# type below does not match the assigned type.
glob_var1 = 4
# This should generate an error because the declared
# type doesn't match the later declared type.
glob_var1 = Exception() # type: str
glob_var1 ... | glob_var1 = 4
glob_var1 = exception()
glob_var1 = exception()
glob_var1 = 'hello'
glob_var2 = 5
def func1():
global glob_var1
global glob_var2
glob_var1 = 3
glob_var2 = 'hello' |
"""
Mock for the figures.permissions model.
"""
def is_active_staff_or_superuser(request):
"""
Exact copy of Figures=0.4.x `figures.permissions.is_active_staff_or_superuser` helper.
"""
return request.user and request.user.is_active and (
request.user.is_staff or request.user.is_superuser)
| """
Mock for the figures.permissions model.
"""
def is_active_staff_or_superuser(request):
"""
Exact copy of Figures=0.4.x `figures.permissions.is_active_staff_or_superuser` helper.
"""
return request.user and request.user.is_active and (request.user.is_staff or request.user.is_superuser) |
"""ssd_classes.py
This file was modified from:
http://github.com/AastaNV/TRT_object_detection/blob/master/coco.py
"""
COCO_CLASSES_LIST = [
'background', # was 'unlabeled'
'person',
'bicycle',
'car',
'motorcycle',
'airplane',
'bus',
'train',
'truck',
'boat',
'traffic light... | """ssd_classes.py
This file was modified from:
http://github.com/AastaNV/TRT_object_detection/blob/master/coco.py
"""
coco_classes_list = ['background', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'street sign', 'stop sign', 'parking meter', '... |
"""Write a HashTable class that stores strings
in a hash table, where keys are calculated
using the first two letters of the string."""
class HashTable(object):
def __init__(self):
self.table = [None] * 10000
def store(self, string):
"""Input a string that's stored in
the table."""
... | """Write a HashTable class that stores strings
in a hash table, where keys are calculated
using the first two letters of the string."""
class Hashtable(object):
def __init__(self):
self.table = [None] * 10000
def store(self, string):
"""Input a string that's stored in
the table."""
... |
N = int(input())
for i in range(1, N):
print(' ' * (N - i) + '*' * ((i * 2) - 1))
for i in range(N, 0, -1):
print(' ' * (N - i) + '*' * ((i * 2) - 1)) | n = int(input())
for i in range(1, N):
print(' ' * (N - i) + '*' * (i * 2 - 1))
for i in range(N, 0, -1):
print(' ' * (N - i) + '*' * (i * 2 - 1)) |
#!/usr/bin/env python
__all__ = [
"test_misc",
"test_dictarray",
"test_table",
"test_transform",
"test_recode_alignment",
"test_union_dict",
]
__author__ = ""
__copyright__ = "Copyright 2007-2022, The Cogent Project"
__credits__ = [
"Jeremy Widmann",
"Sandra Smit",
"Gavin Huttley",
... | __all__ = ['test_misc', 'test_dictarray', 'test_table', 'test_transform', 'test_recode_alignment', 'test_union_dict']
__author__ = ''
__copyright__ = 'Copyright 2007-2022, The Cogent Project'
__credits__ = ['Jeremy Widmann', 'Sandra Smit', 'Gavin Huttley', 'Rob Knight', 'Zongzhi Liu', 'Amanda Birmingham', 'Greg Caporas... |
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = "B\xb2?.\xdf\x9f\xa7m\xf8\x8a%,\xf7\xc4\xfa\x91"
MONGO_URI="mongodb://localhost:27017/test"
IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads"
SESSION_COOKIE_SECURE = False
class ProductionConfig(Config):
... | class Config(object):
debug = False
testing = False
secret_key = 'B²?.ß\x9f§mø\x8a%,÷Äú\x91'
mongo_uri = 'mongodb://localhost:27017/test'
image_uploads = '/home/username/projects/my_app/app/static/images/uploads'
session_cookie_secure = False
class Productionconfig(Config):
debug = False
... |
# Real part of spherical harmonic Y_(4,2)(theta,phi)
def Y(l,m):
def g(theta,phi):
R = abs(fp.re(fp.spherharm(l,m,theta,phi)))
x = R*fp.cos(phi)*fp.sin(theta)
y = R*fp.sin(phi)*fp.sin(theta)
z = R*fp.cos(theta)
return [x,y,z]
return g
fp.splot(Y(4,2), [0,fp.pi], [0,2*fp.... | def y(l, m):
def g(theta, phi):
r = abs(fp.re(fp.spherharm(l, m, theta, phi)))
x = R * fp.cos(phi) * fp.sin(theta)
y = R * fp.sin(phi) * fp.sin(theta)
z = R * fp.cos(theta)
return [x, y, z]
return g
fp.splot(y(4, 2), [0, fp.pi], [0, 2 * fp.pi], points=300) |
number = int(input())
if number % 2 == 1 or 6 <= number <= 20:
print('Weird')
elif 2 <= number <= 5 or number > 20:
print('Not Weird')
| number = int(input())
if number % 2 == 1 or 6 <= number <= 20:
print('Weird')
elif 2 <= number <= 5 or number > 20:
print('Not Weird') |
'''
Exercise 5:
Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string\
after the colon character and then use the float function to
convert the extracted string into a floating point number... | """
Exercise 5:
Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string after the colon character and then use the float function to
convert the extracted string into a floating point number.
... |
#$Id$
class Category:
"""This class is used to create object for category."""
def __init__(self):
"""Initialize parameters for Category."""
self.id = ""
self.name = ""
def set_id(self, id):
"""Set id.
Args:
id(str): Id.
"""
se... | class Category:
"""This class is used to create object for category."""
def __init__(self):
"""Initialize parameters for Category."""
self.id = ''
self.name = ''
def set_id(self, id):
"""Set id.
Args:
id(str): Id.
"""
self.id = id
... |
class Song:
def __init__(self, name, length, single):
self.name = name
self.length = length
self.single = single
def get_info(self):
return f"{self.name} - {self.length}"
#Test code
# song = Song("Running in the 90s", 3.45, False)
# print(song.get_info()) | class Song:
def __init__(self, name, length, single):
self.name = name
self.length = length
self.single = single
def get_info(self):
return f'{self.name} - {self.length}' |
class MyCircularQueue:
def __init__(self, k: int):
self.q = [None] * k
self.maxlen = k
self.front = 0
self.rear = 0
def enQueue(self, value: int) -> bool:
if self.q[self.rear] is None:
self.q[self.rear] = value
self.rear = (self.rear + 1... | class Mycircularqueue:
def __init__(self, k: int):
self.q = [None] * k
self.maxlen = k
self.front = 0
self.rear = 0
def en_queue(self, value: int) -> bool:
if self.q[self.rear] is None:
self.q[self.rear] = value
self.rear = (self.rear + 1) % self... |
load("//tools:defaults.bzl", "protractor_web_test_suite")
"""
Macro that can be used to define a e2e test in `modules/benchmarks`. Targets created through
this macro differentiate from a "benchmark_test" as they will run on CI and do not run
with `@angular/benchpress`.
"""
def e2e_test(name, server, **kwargs):
... | load('//tools:defaults.bzl', 'protractor_web_test_suite')
'\n Macro that can be used to define a e2e test in `modules/benchmarks`. Targets created through\n this macro differentiate from a "benchmark_test" as they will run on CI and do not run\n with `@angular/benchpress`.\n'
def e2e_test(name, server, **kwargs):
... |
_base_ = [
'../_base_/models/lxmert/lxmert_pretrain_config.py',
'../_base_/datasets/lxmert/lxmert_pretrain.py',
'../_base_/default_runtime.py',
]
| _base_ = ['../_base_/models/lxmert/lxmert_pretrain_config.py', '../_base_/datasets/lxmert/lxmert_pretrain.py', '../_base_/default_runtime.py'] |
def print_all_binary_strings(n):
helper(n, "")
print("-------------------")
def helper(n, s, lvl = 0):
space = (" " * lvl) + s
print(space)
if(len(s) == n):
print(s)
else:
helper(n, s + "0", lvl + 1)
helper(n, s + "1", lvl + 1)
print_all_binary_strings(1)
print_all_binary_str... | def print_all_binary_strings(n):
helper(n, '')
print('-------------------')
def helper(n, s, lvl=0):
space = ' ' * lvl + s
print(space)
if len(s) == n:
print(s)
else:
helper(n, s + '0', lvl + 1)
helper(n, s + '1', lvl + 1)
print_all_binary_strings(1)
print_all_binary_s... |
# DEBUG FLAGS
TRAIN_JUST_ONE_BATCH = False
TRAIN_JUST_ONE_ROUND = False
PROFILE = False
CHECK_GRADS = False
# Basic
LEARNING_RATE_DEFAULT = 1e-2 # 0.01
MAX_EPOCHS_DEFAULT = 100
EVAL_FREQ_DEFAULT = 5
BATCH_SIZE_DEFAULT = 5
WORKERS_DEFAULT = 4
OPTIMIZER_DEFAULT = 'ADAM'
WEIGHT_DECAY_DEFAULT = 0.01
DATA_DIR_DEFAULT ... | train_just_one_batch = False
train_just_one_round = False
profile = False
check_grads = False
learning_rate_default = 0.01
max_epochs_default = 100
eval_freq_default = 5
batch_size_default = 5
workers_default = 4
optimizer_default = 'ADAM'
weight_decay_default = 0.01
data_dir_default = 'data/EEG_age_data/'
log_dir_defa... |
# The contents of this file has been derived code from the Twisted project
# (http://twistedmatrix.com/). The original author is Jp Calderone.
# Twisted project license follows:
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# ... | class Foldernameerror(ValueError):
pass
def encode(s):
if isinstance(s, str) and sum((n for n in (ord(c) for c in s) if n > 127)):
raise folder_name_error('%r contains characters not valid in a str folder name. Convert to unicode first?' % s)
r = []
_in = []
for c in s:
if ord(c) in... |
# debug
DEBUG = False
| debug = False |
'''1. Write a Python function that takes a sequence of numbers and determines whether
all the numbers are different from each other.'''
def unique(string):
if len(string) == len(set(string)):
ans = 'True'
else:
ans = 'False'
return ans
print(unique((1, 2, 3, 4)))
print(unique((1, 3, 3, 4)... | """1. Write a Python function that takes a sequence of numbers and determines whether
all the numbers are different from each other."""
def unique(string):
if len(string) == len(set(string)):
ans = 'True'
else:
ans = 'False'
return ans
print(unique((1, 2, 3, 4)))
print(unique((1, 3, 3, 4))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.