content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
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(... |
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']} |
'''
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... |
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')
... |
# 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' |
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.
... |
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... |
_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))... |
try:
var1 += 1
except:
var1 = 1
def __quick_unload_script():
print("Unloaded: %s" % str(var1))
print(f"Just edit and save! {var1}")
| try:
var1 += 1
except:
var1 = 1
def __quick_unload_script():
print('Unloaded: %s' % str(var1))
print(f'Just edit and save! {var1}') |
class MissingKeyError(Exception):
pass
class NoneError(Exception):
pass
| class Missingkeyerror(Exception):
pass
class Noneerror(Exception):
pass |
#Also called as Circular Queue
class Queue:
def __init__(self, maxSize):
self.items = maxSize * [None] # To initialize a list with a limit set make a list with the size u want and make all the elements None
self.maxSize = maxSize
self.start = -1
self.top = -1
def __str__(self)... | class Queue:
def __init__(self, maxSize):
self.items = maxSize * [None]
self.maxSize = maxSize
self.start = -1
self.top = -1
def __str__(self):
values = [str(x) for x in self.items]
return ' '.join(values)
def is_full(self):
if self.top + 1 == self.... |
def checkorders(orders: [str]) -> [bool]:
results = []
for i in orders:
flag = True
stock = []
for j in i:
if j in '([{':
stock.append(j)
else:
if stock == []:
flag = False
break
... | def checkorders(orders: [str]) -> [bool]:
results = []
for i in orders:
flag = True
stock = []
for j in i:
if j in '([{':
stock.append(j)
else:
if stock == []:
flag = False
break
... |
a = int(input())
b = int(input())
if a > b:
print(a)
else:
print(b)
| a = int(input())
b = int(input())
if a > b:
print(a)
else:
print(b) |
a,b = map(int,input().split())
ans=0
k=1
while a or b:
ans+=k*(((b%3)-(a%3))%3)
a//=3
b//=3
k*=3
print(ans) | (a, b) = map(int, input().split())
ans = 0
k = 1
while a or b:
ans += k * ((b % 3 - a % 3) % 3)
a //= 3
b //= 3
k *= 3
print(ans) |
# Minimum Remove to Make Valid Parentheses: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
# Given a string s of '(' , ')' and lowercase English characters.
# Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is ... | class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
stack = []
for index in range(len(s)):
char = s[index]
if char == ')':
if len(stack) == 0:
stack.append(index)
elif s[stack[-1]] == '(':
... |
app_name = "users"
urlpatterns = [
]
| app_name = 'users'
urlpatterns = [] |
#def divisor is from:
#https://www.w3resource.com/python-exercises/basic/python-basic-1-exercise-24.php
def divisor(n):
for i in range(n):
x = len([i for i in range(1, n+1) if not n % i])
return x
nums = []
i = 0
while i < 20:
preNum = int(input())
if(preNum > 0):
nums.append([diviso... | def divisor(n):
for i in range(n):
x = len([i for i in range(1, n + 1) if not n % i])
return x
nums = []
i = 0
while i < 20:
pre_num = int(input())
if preNum > 0:
nums.append([divisor(preNum), preNum])
i += 1
nums.sort()
f = nums[len(nums) - 1]
x = f.copy()
y = x[::-1]
print(*y, ... |
s, t = 7, 11
a, b = 5, 15
m, n = 3, 2
apple = [-2, 2, 1]
orange = [5, -6]
a_score, b_score = 0, 0
''' too slow
for i in apple:
if (a + i) in list(range(s, t+1)):
a_score +=1
for i in orange:
if (b + i) in list(range(s, t+1)):
b_score +=1
'''
for i in apple:
if (a+i >= s) and (a+i <= t):
... | (s, t) = (7, 11)
(a, b) = (5, 15)
(m, n) = (3, 2)
apple = [-2, 2, 1]
orange = [5, -6]
(a_score, b_score) = (0, 0)
' too slow\nfor i in apple:\n if (a + i) in list(range(s, t+1)):\n a_score +=1\n\nfor i in orange:\n if (b + i) in list(range(s, t+1)):\n b_score +=1\n\n'
for i in apple:
if a + i >=... |
class Customer:
id = 1
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
self.id = Customer.id
Customer.id += 1
def __repr__(self):
return f"Customer <{self.id}> {self.name}; Address: {self.address}; Email: ... | class Customer:
id = 1
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
self.id = Customer.id
Customer.id += 1
def __repr__(self):
return f'Customer <{self.id}> {self.name}; Address: {self.address}; Email: ... |
SECRET_KEY = "abc"
FILEUPLOAD_ALLOWED_EXTENSIONS = ["png"]
# FILEUPLOAD_PREFIX = "/cool/upload"
# FILEUPLOAD_LOCALSTORAGE_IMG_FOLDER = "images/boring/"
FILEUPLOAD_RANDOM_FILE_APPENDIX = True
FILEUPLOAD_CONVERT_TO_SNAKE_CASE = True
| secret_key = 'abc'
fileupload_allowed_extensions = ['png']
fileupload_random_file_appendix = True
fileupload_convert_to_snake_case = True |
# 6. Math Power
def math_power(n, p):
power_output = n ** p
print(power_output)
number = float(input())
power = float(input())
math_power(number, power) | def math_power(n, p):
power_output = n ** p
print(power_output)
number = float(input())
power = float(input())
math_power(number, power) |
# https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_bj
n = int(input())
xx = [0] * n
yy = [0] * n
for i in range(n):
xx[i], yy[i] = map(int, input().split())
xx.sort()
yy.sort()
ax = 0
ay = 0
cx = 0
cy = 0
for i in range(n):
ax += xx[i] * i - cx
cx += xx[i]
ay += yy[i] * i - cy
... | n = int(input())
xx = [0] * n
yy = [0] * n
for i in range(n):
(xx[i], yy[i]) = map(int, input().split())
xx.sort()
yy.sort()
ax = 0
ay = 0
cx = 0
cy = 0
for i in range(n):
ax += xx[i] * i - cx
cx += xx[i]
ay += yy[i] * i - cy
cy += yy[i]
print(ax + ay) |
_version_major = 0
_version_minor = 1
_version_micro = 0
__version__ = "{0:d}.{1:d}.{2:d}".format(
_version_major, _version_minor, _version_micro)
| _version_major = 0
_version_minor = 1
_version_micro = 0
__version__ = '{0:d}.{1:d}.{2:d}'.format(_version_major, _version_minor, _version_micro) |
def troca(i,j,lista):
if (i >= 0 and j >= 0) and (i <= (len(lista) - 1) and j <= (len(lista) - 1)):
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
def main():
n = int(input())
lista = []
for k in range(n):
lista.append(int(input()))
i = int(input(... | def troca(i, j, lista):
if (i >= 0 and j >= 0) and (i <= len(lista) - 1 and j <= len(lista) - 1):
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
def main():
n = int(input())
lista = []
for k in range(n):
lista.append(int(input()))
i = int(input())... |
# test
def addTwoNumbers(a, b):
sum = a + b
return sum
def addList(l1):
sum = 0
for i in l1:
sum += i
return sum
add = lambda x, y : x + y
num1 = 1
num2 = 2
print("The sum is ", addTwoNumbers(num1, num2))
numlist = (1, 2, 3)
print(add(10, 20))
print("The sum is ", addList(numlist)... | def add_two_numbers(a, b):
sum = a + b
return sum
def add_list(l1):
sum = 0
for i in l1:
sum += i
return sum
add = lambda x, y: x + y
num1 = 1
num2 = 2
print('The sum is ', add_two_numbers(num1, num2))
numlist = (1, 2, 3)
print(add(10, 20))
print('The sum is ', add_list(numlist))
for i in r... |
#
# PySNMP MIB module MITEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
"prints a matrix of integers"
row_len = len(matrix)
col_len = len(matrix[0])
for i in range(row_len):
for j in range(col_len):
if j != col_len - 1:
print("{:d}".format(matrix[i][j]), end=' ')
else... | def print_matrix_integer(matrix=[[]]):
"""prints a matrix of integers"""
row_len = len(matrix)
col_len = len(matrix[0])
for i in range(row_len):
for j in range(col_len):
if j != col_len - 1:
print('{:d}'.format(matrix[i][j]), end=' ')
else:
... |
def sum_of_squares(n):
total = 0
for i in range(n):
if i * i < n:
total += i * i
else:
break
return total
| def sum_of_squares(n):
total = 0
for i in range(n):
if i * i < n:
total += i * i
else:
break
return total |
_base_ = [
'../_base_/models/fcn_r50-d8.py', '../_base_/datasets/pascal_context.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py'
]
model = dict(
decode_head=dict(num_classes=60),
auxiliary_head=dict(num_classes=60),
test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(... | _base_ = ['../_base_/models/fcn_r50-d8.py', '../_base_/datasets/pascal_context.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py']
model = dict(decode_head=dict(num_classes=60), auxiliary_head=dict(num_classes=60), test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(320, 320)))
optimizer =... |
_base_ = [
'../_base_/models/irrpwc.py',
'../_base_/datasets/flyingthings3d_subset_bi_with_occ_384x768.py',
'../_base_/schedules/schedule_s_fine_half.py',
'../_base_/default_runtime.py'
]
custom_hooks = [dict(type='EMAHook')]
data = dict(
train_dataloader=dict(
samples_per_gpu=1, workers_p... | _base_ = ['../_base_/models/irrpwc.py', '../_base_/datasets/flyingthings3d_subset_bi_with_occ_384x768.py', '../_base_/schedules/schedule_s_fine_half.py', '../_base_/default_runtime.py']
custom_hooks = [dict(type='EMAHook')]
data = dict(train_dataloader=dict(samples_per_gpu=1, workers_per_gpu=5, drop_last=True), val_dat... |
class Solution:
def isAlienSorted(self, words, order):
lookup = {c: i for i, c in enumerate(order)}
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
... | class Solution:
def is_alien_sorted(self, words, order):
lookup = {c: i for (i, c) in enumerate(order)}
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
... |
#!/usr/bin/python
# sorting.py
items = { "coins": 7, "pens": 3, "cups": 2,
"bags": 1, "bottles": 4, "books": 5 }
for key in sorted(items.keys()):
print ("%s: %s" % (key, items[key]))
print ("####### #######")
for key in sorted(items.keys(), reverse=True):
print ("%s: %s" % (key, items[key]))
| items = {'coins': 7, 'pens': 3, 'cups': 2, 'bags': 1, 'bottles': 4, 'books': 5}
for key in sorted(items.keys()):
print('%s: %s' % (key, items[key]))
print('####### #######')
for key in sorted(items.keys(), reverse=True):
print('%s: %s' % (key, items[key])) |
# variants
model_type = 'SepDisc'
runner = 'SepDiscRunner01'
lambda_img = 0.001
lambda_lidar = 0.001
src_acc_threshold = 0.6
tgt_acc_threshold = 0.6
img_disc = dict(type='FCDiscriminatorCE', in_dim=64)
img_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
lidar_disc = dict(type='FCDiscriminatorCE', in_dim=64)
lid... | model_type = 'SepDisc'
runner = 'SepDiscRunner01'
lambda_img = 0.001
lambda_lidar = 0.001
src_acc_threshold = 0.6
tgt_acc_threshold = 0.6
img_disc = dict(type='FCDiscriminatorCE', in_dim=64)
img_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
lidar_disc = dict(type='FCDiscriminatorCE', in_dim=64)
lidar_opt = dic... |
def debug(x):
print(x)
### Notebook Magics
# %matplotlib inline
def juptyerConfig(pd, max_columns=500, max_rows = 500, float_format = '{:,.6f}', max_info_rows = 1000, max_categories = 500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.options.display.float_format = float_f... | def debug(x):
print(x)
def juptyer_config(pd, max_columns=500, max_rows=500, float_format='{:,.6f}', max_info_rows=1000, max_categories=500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.options.display.float_format = float_format.format
pd.options.display.max_info_rows... |
n = [ 1 ] + [ 50 ] * 10 + [ 1 ]
with open('8.in', 'r') as f:
totn, m, k, op = [ int(x) for x in f.readline().split() ]
for i in range(m):
f.readline()
for i, v in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
... | n = [1] + [50] * 10 + [1]
with open('8.in', 'r') as f:
(totn, m, k, op) = [int(x) for x in f.readline().split()]
for i in range(m):
f.readline()
for (i, v) in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
... |
# Configuration file for ipython-console.
c = get_config()
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp configuration
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp will inherit config from: TerminalIP... | c = get_config() |
def fib(n):
'''Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,...'''
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
| def fib(n):
"""Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,..."""
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2) |
class Column(object):
def __init__(self, name, dataType):
self._number = 0
self._name = name
self._dataType = dataType
self._length = None
self._default = None
self._notNull = False
self._unique = False
self._constraint = None
self._check = []
... | class Column(object):
def __init__(self, name, dataType):
self._number = 0
self._name = name
self._dataType = dataType
self._length = None
self._default = None
self._notNull = False
self._unique = False
self._constraint = None
self._check = []... |
# Definisikan class Karyawan
class Karyawan:
def __init__(self, nama, usia, pendapatan, insentif_lembur):
self.nama = nama
self.usia = usia
self.pendapatan = pendapatan
self.pendapatan_tambahan = 0
self.insentif_lembur = insentif_lembur
def lembur(self):
self.pend... | class Karyawan:
def __init__(self, nama, usia, pendapatan, insentif_lembur):
self.nama = nama
self.usia = usia
self.pendapatan = pendapatan
self.pendapatan_tambahan = 0
self.insentif_lembur = insentif_lembur
def lembur(self):
self.pendapatan_tambahan += self.ins... |
def permutations(arr):
arr1 = arr.copy()
print(" ".join(arr1), end=" ")
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
p... | def permutations(arr):
arr1 = arr.copy()
print(' '.join(arr1), end=' ')
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
print(' '.join... |
class AvailableCashError(Exception):
def __init__(self, available_amount, requested_amount):
error_message = (
'There is not enough available cash in the account. ' +
'Amount available is {available_amount}, amount requested is {requested_amount}. ' +
'\nPlease add funds ... | class Availablecasherror(Exception):
def __init__(self, available_amount, requested_amount):
error_message = ('There is not enough available cash in the account. ' + 'Amount available is {available_amount}, amount requested is {requested_amount}. ' + '\nPlease add funds or reduce the requested amount.').fo... |
# --------------
##File path for the file
file_path
#Code starts here
def read_file(path):
f=open(path,'r')
sentence=f.readline()
f.close()
return sentence
sample_message=read_file(file_path)
print(sample_message)
# --------------
#Code starts here
file_path_1
file_path_2
def fus... | file_path
def read_file(path):
f = open(path, 'r')
sentence = f.readline()
f.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
file_path_1
file_path_2
def fuse_msg(message_a, message_b):
a = int(message_a)
b = int(message_b)
quotient = b // a
return st... |
#
# Copyright SAS Institute
#
# 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... | class Sasconfignotfounderror(Exception):
def __init__(self, path: str):
self.path = path
def __str__(self):
return 'Configuration path {} does not exist.'.format(self.path)
class Sasconfignotvaliderror(Exception):
def __init__(self, defn: str, msg: str=None):
self.defn = defn if ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
## Onera M6 configuration module for geoGen
#
# Adrien Crovato
def getParams():
p = {}
# Wing parameters (nP planforms for half-wing)
p['airfPath'] = '../airfoils' # path pointing the airfoils directory (relative to this config file)
p['airfName'] = ['one... | def get_params():
p = {}
p['airfPath'] = '../airfoils'
p['airfName'] = ['oneraM6.dat', 'oneraM6.dat']
p['span'] = [1.196]
p['taper'] = [0.562]
p['sweep'] = [30]
p['dihedral'] = [0]
p['twist'] = [0, 0]
p['rootChord'] = 0.8059
p['offset'] = [0.0, 0.0]
p['coWingtip'] = True
... |
# A function is a block of organized, reusable code that is used to perform a single, related action.
# Define a function.
def fun():
print("What's a Funtion ?")
# Functions with Arguments.
def funArg(arg1,arg2):
print(arg1," ",arg2)
# return(arg1," ",arg2)
#Functions that returns a value... | def fun():
print("What's a Funtion ?")
def fun_arg(arg1, arg2):
print(arg1, ' ', arg2)
def fun_x(a):
return a + a
fun()
fun_arg(50, 50)
print(fun_arg(50, 50))
print(fun_x(50)) |
# Frames Per Second
FPS = 60
# SCREEN
SCREEN_COLUMNS_NUMBER = 6
SCREEN_ROWS_NUMBER = 7
SCREEN_COLUMN_SIZE = 96
SCREEN_ROW_SIZE = 96
SCREEN_WIDTH = SCREEN_COLUMNS_NUMBER * SCREEN_COLUMN_SIZE
SCREEN_HEIGHT = SCREEN_ROWS_NUMBER * SCREEN_ROW_SIZE
# Colors for display.
COLOR_WHITE = (255, 255, 255)
CO... | fps = 60
screen_columns_number = 6
screen_rows_number = 7
screen_column_size = 96
screen_row_size = 96
screen_width = SCREEN_COLUMNS_NUMBER * SCREEN_COLUMN_SIZE
screen_height = SCREEN_ROWS_NUMBER * SCREEN_ROW_SIZE
color_white = (255, 255, 255)
color_black = (0, 0, 0)
color_green = (0, 128, 0)
color_blue = (0, 0, 128)
c... |
class Linked_List():
def __init__(self, head):
self.head = head
class Node():
def __init__(self, data):
self.data = data
self.next = None
# O(N) space and O(N) time
def partition_linked_list(linked_list, partition):
less_than = []
greater_than_or_equal = []
next_one = linke... | class Linked_List:
def __init__(self, head):
self.head = head
class Node:
def __init__(self, data):
self.data = data
self.next = None
def partition_linked_list(linked_list, partition):
less_than = []
greater_than_or_equal = []
next_one = linked_list.head
while next_on... |
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# External libraries
# Markdown
'markdownx',
# Bootstrap
'bootstrap4',
# Our apps
'... | installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdownx', 'bootstrap4', 'apps.blocks', 'apps.bot', 'apps.custom_admin', 'apps.lp', 'apps.results', 'apps.services', 'apps.tags', 'apps.qu... |
class Sorting:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
curr = arr[i]
j = i - 1
while j >= 0 and curr < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr
return arr
if __name__ == "__m... | class Sorting:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
curr = arr[i]
j = i - 1
while j >= 0 and curr < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr
return arr
if __name__ == '__ma... |
HERO = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'}
OUTPUT = '{}: {}'.format
class BatmanQuotes(object):
@staticmethod
def get_quote(quotes, hero):
for i, a in enumerate(hero):
if i == 0:
hero = HERO[a]
elif a.isdigit():
quotes = quotes[int(a)]
... | hero = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'}
output = '{}: {}'.format
class Batmanquotes(object):
@staticmethod
def get_quote(quotes, hero):
for (i, a) in enumerate(hero):
if i == 0:
hero = HERO[a]
elif a.isdigit():
quotes = quotes[int(a)]
... |
numBlanks = 0
golden = ["Emptiness", "fear", "mountain"]
newLines = []
with open('fill-blanks.txt', 'r') as f:
for line in f:
if '...' in line:
blank = input("Fill the blank in " + line)
if blank == golden[numBlanks]:
newLine = line.replace("...", blank)
e... | num_blanks = 0
golden = ['Emptiness', 'fear', 'mountain']
new_lines = []
with open('fill-blanks.txt', 'r') as f:
for line in f:
if '...' in line:
blank = input('Fill the blank in ' + line)
if blank == golden[numBlanks]:
new_line = line.replace('...', blank)
... |
array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
SENTINEL = 10**12
def merge(array, left, mid, right):
L = array[left:mid]
R = array[mid:right]
L.append(SENTINEL)
R.append(SENTINEL)
i = j = 0
for k in range(left, right):
if L[i] <= R[j]:
arr... | array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
sentinel = 10 ** 12
def merge(array, left, mid, right):
l = array[left:mid]
r = array[mid:right]
L.append(SENTINEL)
R.append(SENTINEL)
i = j = 0
for k in range(left, right):
if L[i] <= R[j]:
arra... |
ACTIONS = ["Attribution", "CommericalUse", "DerivativeWorks", "Distribution", "Notice", "Reproduction", "ShareAlike", "Sharing", "SourceCode", "acceptTracking", "adHocShare", "aggregate", "annotate", "anonymize", "append", "appendTo", "archive", "attachPolicy", "attachSource", "attribute", "commercialize", "compensate"... | actions = ['Attribution', 'CommericalUse', 'DerivativeWorks', 'Distribution', 'Notice', 'Reproduction', 'ShareAlike', 'Sharing', 'SourceCode', 'acceptTracking', 'adHocShare', 'aggregate', 'annotate', 'anonymize', 'append', 'appendTo', 'archive', 'attachPolicy', 'attachSource', 'attribute', 'commercialize', 'compensate'... |
_base_ = [
'../_base_/models/regnet/regnetx_400mf.py',
'../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs1024_coslr.py',
'../_base_/default_runtime.py'
]
# Precise BN hook will update the bn stats, so this hook should be executed
# before CheckpointHook, which has priority of 'NORM... | _base_ = ['../_base_/models/regnet/regnetx_400mf.py', '../_base_/datasets/imagenet_bs32.py', '../_base_/schedules/imagenet_bs1024_coslr.py', '../_base_/default_runtime.py']
custom_hooks = [dict(type='PreciseBNHook', num_samples=8192, interval=1, priority='ABOVE_NORMAL')]
optimizer = dict(lr=0.8, nesterov=True)
dataset_... |
###########################################################################
#
# Copyright 2020 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
#
# https://www.apache.org/l... | conversion_status__schema = [[{'name': 'childDirectedTreatment', 'type': 'BOOLEAN', 'mode': 'NULLABLE'}, {'name': 'customVariables', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{'description': '', 'name': 'kind', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': 'U1, U10, U100, U11, U12, U13, U14, U15, U16, U... |
with open("input") as file:
lines = [line.split(" ") for line in file.read().strip().split("\n")]
register_names = set([line[0] for line in lines])
registers = {}
for name in register_names:
registers[name] = 0
operations = {
"dec": lambda r,v: r-v,
"inc": lambda r,v: r+v }
... | with open('input') as file:
lines = [line.split(' ') for line in file.read().strip().split('\n')]
register_names = set([line[0] for line in lines])
registers = {}
for name in register_names:
registers[name] = 0
operations = {'dec': lambda r, v: r - v, 'inc': lambda r, v: r + v}
compariso... |
# Source: https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/mean.py
def get_mean(norm_value=255, dataset='activitynet'):
# Below values are in RGB order
assert dataset in ['activitynet', 'kinetics', 'ucf101']
if dataset == 'activitynet':
return [114.7748/norm_value, 107.7354/norm_value... | def get_mean(norm_value=255, dataset='activitynet'):
assert dataset in ['activitynet', 'kinetics', 'ucf101']
if dataset == 'activitynet':
return [114.7748 / norm_value, 107.7354 / norm_value, 99.475 / norm_value]
elif dataset == 'kinetics':
return [110.63666788 / norm_value, 103.16065604 / n... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"say_hello": "00_core.ipynb",
"say_bye": "00_core.ipynb",
"optimize_bayes_param": "01_bayes_opt.ipynb",
"ReadTabBatchIdentity": "02_tab_ae.ipynb",
"TabularPandasIdentity": ... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'say_hello': '00_core.ipynb', 'say_bye': '00_core.ipynb', 'optimize_bayes_param': '01_bayes_opt.ipynb', 'ReadTabBatchIdentity': '02_tab_ae.ipynb', 'TabularPandasIdentity': '02_tab_ae.ipynb', 'TabDataLoaderIdentity': '02_tab_ae.ipynb', 'RecreatedLoss... |
list_of_numbers_as_strings = input().split(", ")
for index in range(len(list_of_numbers_as_strings)):
number = int(list_of_numbers_as_strings[index])
if number == 0:
list_of_numbers_as_strings.remove(str(0))
list_of_numbers_as_strings.append(str(0))
print(list_of_numbers_as_strings)
| list_of_numbers_as_strings = input().split(', ')
for index in range(len(list_of_numbers_as_strings)):
number = int(list_of_numbers_as_strings[index])
if number == 0:
list_of_numbers_as_strings.remove(str(0))
list_of_numbers_as_strings.append(str(0))
print(list_of_numbers_as_strings) |
##Config file for lifetime_spyrelet.py in spyre/spyre/spyrelet/
# Device List
devices = {
'vna':[
'lantz.drivers.VNA_Keysight.E5071B',
['TCPIP0::A-E5071B-03400::inst0::INSTR'],
{}
],
'source':[
'lantz.drivers.mwsource.SynthNVPro',
['ASRL16::INSTR'],
{}
]
... | devices = {'vna': ['lantz.drivers.VNA_Keysight.E5071B', ['TCPIP0::A-E5071B-03400::inst0::INSTR'], {}], 'source': ['lantz.drivers.mwsource.SynthNVPro', ['ASRL16::INSTR'], {}]}
spyrelets = {'freqSweep_Keysight': ['spyre.spyrelets.freqSweep_VNA_Keysight_spyrelet.Sweep', {'vna': 'vna', 'source': 'source'}, {}]} |
height = int(input())
for i in range(1, height + 1):
for j in range(1,i+1):
if(i == height or j == 1 or i == j):
print(i,end=" ")
else:
print(end=" ")
print()
# Sample Input :- 5
# Output :-
# 1
# 2 2
# 3 3
# 4 4
# 5 5 5 5 5
| height = int(input())
for i in range(1, height + 1):
for j in range(1, i + 1):
if i == height or j == 1 or i == j:
print(i, end=' ')
else:
print(end=' ')
print() |
# -*- coding:utf-8-*-
name = ["gyj","dzj","why","zz","wwb","zke","ljx","syb","yxd"]
print(name)
name.reverse()
print(name)
print(len(name))
| name = ['gyj', 'dzj', 'why', 'zz', 'wwb', 'zke', 'ljx', 'syb', 'yxd']
print(name)
name.reverse()
print(name)
print(len(name)) |
def flatten(seq):
r = []
for x in seq:
if type(x) == list:
r += flatten(x)
else:
r.append(x)
return r
seq = [1,[2,3],4]
seq = [1,[2,[5,6],3],4]
print(seq, '-->', flatten(seq))
| def flatten(seq):
r = []
for x in seq:
if type(x) == list:
r += flatten(x)
else:
r.append(x)
return r
seq = [1, [2, 3], 4]
seq = [1, [2, [5, 6], 3], 4]
print(seq, '-->', flatten(seq)) |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'nonassocLESSMOREEQUALSTOMOREEQUALLESSEQUALNOTEQUALleftPLUSMINUSleftTIMESDIVIDEleftANDORrightUMINUSINT FLOAT PLUS MINUS TIMES DIVIDE EQUALS LPAREN RPAREN LCURLBRACKET RCURLBRACKET ID COMMENT ST... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'nonassocLESSMOREEQUALSTOMOREEQUALLESSEQUALNOTEQUALleftPLUSMINUSleftTIMESDIVIDEleftANDORrightUMINUSINT FLOAT PLUS MINUS TIMES DIVIDE EQUALS LPAREN RPAREN LCURLBRACKET RCURLBRACKET ID COMMENT STRING ASSIGN SEMICOLON COMMA POINT NOT EQUALSTO MORE LESS MOREEQUAL LES... |
class Level:
def __init__(self, current_level=1, current_xp=0, level_up_base=30, level_up_factor=30):
#Original (self, current_level=1, current_xp=0, level_up_base=200, level_up_factor=150)
self.current_level = current_level
self.current_xp = current_xp
self.level_up_base = level_up_... | class Level:
def __init__(self, current_level=1, current_xp=0, level_up_base=30, level_up_factor=30):
self.current_level = current_level
self.current_xp = current_xp
self.level_up_base = level_up_base
self.level_up_factor = level_up_factor
@property
def experience_to_next_l... |
version = 1
disable_existing_loggers = False
loggers = {
'sanic.root': {
'level': 'DEBUG',
'handlers': ['console', 'root_file'],
'propagate': True
},
'sanic.error': {
'level': 'ERROR',
'handlers': ['error_file'],
'propagate': True
},
'sanic.access': {... | version = 1
disable_existing_loggers = False
loggers = {'sanic.root': {'level': 'DEBUG', 'handlers': ['console', 'root_file'], 'propagate': True}, 'sanic.error': {'level': 'ERROR', 'handlers': ['error_file'], 'propagate': True}, 'sanic.access': {'level': 'INFO', 'handlers': ['access_file'], 'propagate': True}}
handlers... |
#Printing Stars in 'C' Shape !
'''
****
*
*
*
*
*
****
'''
for row in range(7):
for col in range(5):
if (col==0 and (row!=0 and row!=6)) or (row==0 or row==6) and (col>0):
print('*',end='')
else:
print(end=' ')
print() | """
****
*
*
*
*
*
****
"""
for row in range(7):
for col in range(5):
if col == 0 and (row != 0 and row != 6) or ((row == 0 or row == 6) and col > 0):
print('*', end='')
else:
print(end=' ')
print() |
def Main():
a = 1
b = 2
c = 3
e = 4
d = a + b - c * e
return d
| def main():
a = 1
b = 2
c = 3
e = 4
d = a + b - c * e
return d |
# Parameters:
# MON_PERIOD : Number of seconds the temperature is read.
# MON_INTERVAL : Number of seconds the temperature is checked.
# TEMP_HIGH : Value in Celsius degree on that a warning e-mail is sent if temperature is above it.
# TEMP_CRITICAL : Value in Celsius degree on that the device is shutted down ... | mon_period = 1
mon_interval = 600
temp_high = 85.0
temp_critical = 90.0 |
material = []
for i in range(int(input())):
material.append(int(input()))
srted = sorted(material)
if srted == material:
print("YES")
else:
print("NO") | material = []
for i in range(int(input())):
material.append(int(input()))
srted = sorted(material)
if srted == material:
print('YES')
else:
print('NO') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.