content
stringlengths 7
1.05M
|
---|
class PaymentAPIError(Exception):
"""
Raised when a payment related action fails.
"""
pass
|
class Meta(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
def bind(self, name, func):
setattr(self.__class__, name, func)
|
# Rain_Water_Trapping
def trappedWater(a, size) :
# left[i] stores height of tallest bar to the to left of it including itself
left = [0] * size
# Right [i] stores height of tallest bar to the to right of it including itself
right = [0] * size
# Initialize result
waterVolume = 0
# filling left (list/array)
left[0] = a[0]
for i in range( 1, size):
left[i] = max(left[i-1], a[i])
# filling right (list/array)
right[size - 1] = a[size - 1]
for i in range(size - 2, - 1, - 1):
right[i] = max(right[i + 1], a[i]);
# Calculating volume of the accumulated water element by element
for i in range(0, size):
waterVolume += min(left[i],right[i]) - a[i]
return waterVolume
# main program
arr =[]
n = int(input()) #input the number of towers
for i in range(n):
arr.append(int(input())) #storing length of each tower in array
print("Maximum water that can be accumulated is ", trappedWater(arr, len(arr)))
#Input:
#12
#0
#1
#0
#2
#1
#0
#1
#3
#2
#1
#2
#1
#Output:
#The maximum water trapped is 6
|
# -*- coding: utf-8 -*-
BOT_NAME = 'spider'
SPIDER_MODULES = ['spiders']
NEWSPIDER_MODULE = 'spiders'
ROBOTSTXT_OBEY = False
# change cookie to yours
#DEFAULT_REQUEST_HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
# 'Cookie': '_T_WM=da71ffa6f7f128ab6e63ff072db80606; SUB=_2A25MgTTBDeRhGeNM6VcX-SrJzjuIHXVvilyJrDV6PUJbkdCOLVTYkW1NTiDEuIdSD9l1__cJQlNUYbZ4BsuX91QV; SCF=ArQVOs0FURqY19hrE2SGFtDk0PfOPJD71jGtPZEhGoMerq3Jyz0ms7PhXAicNQP5JhFT0hT_ob82BdBsVsFhPqQ.'}
#DEFAULT_REQUEST_HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
# 'Cookie': '_T_WM=da71ffa6f7f128ab6e63ff072db80606; WEIBOCN_WM=3349; H5_wentry=H5; backURL=https://passport.sina.cn/; SCF=AttQRDsHb-v6zLir9qtBBIcTXn7d8govOhlAKcT5G1UlfGLJhNrUUBoiFaKjAC6uuVuYVfXwsVdGZ_VtZvnix3U.; SUB=_2A25MgY_MDeRhGeFJ6lsU-S3Fyz6IHXVvjRGErDV6PUJbktB-LW-hkW1NfG6bOCX7HXjOi2Gx6DFCp9WcM_KeXwm5; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5oMQfn.VKjspLb_QEWee-55NHD95QNS024SK.01K5EWs4Dqcjbi--NiK.Xi-2Ri--ciKnRi-zNSo2NeKq01hnfe8Yp1Kn41Btt; SSOLoginState=1636171676'}
DEFAULT_REQUEST_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0',
'Cookie': 'SUB=_2A25MjPT-DeRhGeNM6VcX-SrJzjuIHXVvjpy2rDV6PUJbkdCOLXXzkW1NTiDEuD0Z5qOTeRYpEH6ri8UgbU8C2_bx; SCF=AgEgIi410kgB0i8ZKO3fV-JkJImn736dfQ2fqzzPo5Yk01kdssguluICunFk4fn-C17je7gI48nOuzj4fqGDOmw.; _T_WM=83c8645da16d0fd33b61ddaaecbf1be1'
}
CONCURRENT_REQUESTS = 16
DOWNLOAD_DELAY = 0.5
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': None,
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware': None,
'middlewares.IPProxyMiddleware': 100,
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 101,
}
ITEM_PIPELINES = {
'pipelines.MongoDBPipeline': 300,
}
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017 |
# -*- coding: utf-8 -*-
def consumer():
status = True
while True:
n = yield status
print("我拿到了{}!".format(n))
if n == 3:
status = False
def producer(consumer):
n = 5
while n > 0:
# yield给主程序返回消费者的状态
yield consumer.send(n)
n -= 1
if __name__ == '__main__':
c = consumer()
c.send(None)
p = producer(c)
for status in p:
if status == False:
print("我只要3,4,5就行啦")
break
print("程序结束")
|
# -*- coding: utf-8 -*-
# Copyright (2018) Hewlett Packard Enterprise Development LP
#
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Dict of schemas version used by application.
"""
SCHEMAS = {
"ServiceRoot": "ServiceRoot.v1_3_1.json",
"ChassisCollection": "ChassisCollection.json",
"Chassis": "Chassis.v1_7_0.json",
"CollectionCapabilities": "CollectionCapabilities.v1_0_0.json",
"CompositionService": "CompositionService.v1_0_1.json",
"ComputerSystemCollection": "ComputerSystemCollection.json",
"ComputerSystem": "ComputerSystem.v1_5_0.json",
"Drive": "Drive.v1_4_0.json",
"ManagerCollection": "ManagerCollection.json",
"Manager": "Manager.v1_4_0.json",
"EthernetInterface": "EthernetInterface.v1_4_0.json",
"EthernetInterfaceCollection": "EthernetInterfaceCollection.json",
"EventService": "EventService.v1_1_0.json",
"EventDestination": "EventDestination.v1_3_0.json",
"Event": "Event.v1_2_1.json",
"Thermal": "Thermal.v1_4_0.json",
"StorageCollection": "StorageCollection.json",
"Storage": "Storage.v1_4_0.json",
"Message": "Message.v1_0_5.json",
"NetworkInterfaceCollection": "NetworkInterfaceCollection.json",
"NetworkPortCollection": "NetworkPortCollection.json",
"NetworkDeviceFunctionCollection": "NetworkDeviceFunctionCollection.json",
"NetworkDeviceFunction": "NetworkDeviceFunction.v1_2_1.json",
"NetworkInterface": "NetworkInterface.v1_1_0.json",
"NetworkAdapterCollection": "NetworkAdapterCollection.json",
"NetworkAdapter": "NetworkAdapter.v1_1_0.json",
"NetworkPort": "NetworkPort.v1_1_0.json",
"Processor": "Processor.v1_3_0.json",
"ProcessorCollection": "ProcessorCollection.json",
"ResourceBlockCollection": "ResourceBlockCollection.json",
"ResourceBlock": "ResourceBlock.v1_1_0.json",
"VLanNetworkInterface": "VLanNetworkInterface.v1_1_1.json",
"VLanNetworkInterfaceCollection": "VLanNetworkInterfaceCollection.json",
"ZoneCollection": "ZoneCollection.json",
"Zone": "Zone.v1_2_0.json",
"Session": "Session.v1_1_0.json",
"SessionCollection": "SessionCollection.json",
"EventDestinationCollection": "EventDestinationCollection.json",
"SessionService": "SessionService.v1_1_3.json",
"VolumeCollection": "VolumeCollection.json",
"Volume": "Volume.v1_0_3.json"
}
REGISTRY = {
"Base": "Base.1.1.0.json"
}
|
#Function to remove a given word from a list and strip it at the same time.
def remove_and_split(string, word):
newStr = string.replace(word, "")
return newStr.strip()
this = " Root is a Computer "
n = remove_and_split(this, "Root")
print(n) |
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(table):
colWidth = [0] * len(table) #List of rjust values to be used
for i in range(len(table)): #iterates through the 3 lists
rjustlength = 0
for j in table[i]: #loops each index of list and keeps larger number
if len(j) > rjustlength:
rjustlength = len(j)
colWidth[i] = rjustlength
#formats the columns of print
for y in range(len(table[0])): #iterates through number of strings in sublist
for x in range(len(table)): #for each x
word = table[x][y]
print(word.rjust(colWidth[x]),end = ' ')
print("")
printTable(tableData)
|
N = int(input())
M = int(input())
S = int(input())
for num in range(M, N - 1, - 1):
if num % 2 == 0 and num % 3 == 0:
if num == S:
break
print(num, end=" ") |
# 这是将MNIST中的数据集转换为csv格式的脚本
# 后续代码都会在csv文件的基础上进行编写, 这样大家看代码也能清除很多
# 代码由以下网址提供,表示感谢。
# https://pjreddie.com/projects/mnist-in-csv/
# 该py文件属于一个补充,不使用也不影响后续算法的实践。
# 转换后的CVS文件在Mnist文件夹中
def convert(imgf, labelf, outf, n):
f = open(imgf, "rb")
o = open(outf, "w")
l = open(labelf, "rb")
f.read(16)
l.read(8)
images = []
for i in range(n):
image = [ord(l.read(1))]
for j in range(28*28):
image.append(ord(f.read(1)))
images.append(image)
for image in images:
o.write(",".join(str(pix) for pix in image)+"\n")
f.close()
o.close()
l.close()
if __name__ == '__main__':
convert("transmnist.\Mnist\\t10k-images.idx3-ubyte", "transmnist.\Mnist\\t10k-labels.idx1-ubyte", "transmnist.\Mnist\\mnist_test.csv", 10000)
convert("transmnist.\Mnist\\train-images.idx3-ubyte", "transmnist.\Mnist\\train-labels.idx1-ubyte", "transmnist.\Mnist\mnist_train.csv", 60000) |
f=open('demo1.txt','a')
a=int(input('enter number '))
f.write('hello hi\n')
f.write('world')
f.write(str(a))
f.close()
|
# -*- coding: UTF-8 -*-
# 删除字典中value为空的键值对方法
def deldictNULL(mydict):
for key in list(mydict.keys()):
if not mydict.get(key):
del mydict[key]
return mydict |
ALIEN = {'.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5',
'-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0'}
def morse_converter(s):
return int(''.join(ALIEN[s[a:a + 5]] for a in xrange(0, len(s), 5)))
|
def calculateAverageAge(students):
add_age = 0
for thing in students.values():
age = thing['age']
add_age = add_age + age
return(add_age / len(students.keys()))
students = {
"Peter": {"age": 10, "address": "Lisbon"},
"Isabel": {"age": 11, "address": "Sesimbra"},
"Anna": {"age": 9, "address": "Lisbon"},
"Gibrael": {"age": 10, "address": "Sesimbra"},
"Susan": {"age": 11, "address": "Lisbon"},
"Charles": {"age": 9, "address": "Sesimbra"},
}
print(calculateAverageAge(students)) |
# very old file that isn't very useful but it works with things so I'm keeping it for now
class Rectangle:
current_id = 0
tolerable_distance_to_combine_rectangles = 0.00005 # buildings need to be this (lat/long degrees) away to merge
def __init__(self, init_points, to_id=True):
self.points = init_points # a point is a list, in (lat, long) form
self.deleted_rect_ids = []
if to_id:
Rectangle.current_id += 1
self.id = Rectangle.current_id
def merge_with(self, other_rectangle):
for point in other_rectangle.points:
# if the rectangles overlap
if self.has_point_inside_approx(point):
# get cords for the merged rectangle
top = min(self.get_up_bound(), other_rectangle.get_up_bound())
bot = max(self.get_down_bound(), other_rectangle.get_down_bound())
right = max(self.get_right_bound(), other_rectangle.get_right_bound())
left = min(self.get_left_bound(), other_rectangle.get_left_bound())
# returns the coordinates of the merged rectangles
return [(left, top), (right, top), (right, bot), (left, bot)]
return None
# Checks if a point is inside/on the borders
def has_point_inside(self, point_to_check):
has_up_bound, has_down_bound, has_left_bound, has_right_bound = False, False, False, False
# check all lines in this rectangle -> does the point lay in between 4 lines?
for i in range(0, len(self.points)):
point1 = self.points[i]
point2 = self.points[(i + 1) % len(self.points)]
# if vertical line
if point1[0] == point2[0]:
if point1[1] < point_to_check[1] < point2[1] or point1[1] > point_to_check[1] > point2[1]:
# point_to_check is within the y-range of the line
if point_to_check[0] >= point1[0]:
has_left_bound = True
if point_to_check[0] <= point1[0]:
has_right_bound = True
# if horizontal line
if point1[1] == point2[1]:
if point1[0] < point_to_check[0] < point2[0] or point1[0] > point_to_check[0] > point2[0]:
# point_to_check is within the x-domain of the line
if point_to_check[1] >= point1[1]:
has_down_bound = True
if point_to_check[1] <= point1[1]:
has_up_bound = True
return has_up_bound and has_down_bound and has_left_bound and has_right_bound
# check if point is close enough to be inside by shifting the point up, down, left, right
def has_point_inside_approx(self, point_to_check, tolerable_distance=tolerable_distance_to_combine_rectangles):
if tolerable_distance == 0:
return self.has_point_inside(point_to_check)
slide_right = self.has_point_inside((point_to_check[0] + tolerable_distance, point_to_check[1]))
slide_left = self.has_point_inside((point_to_check[0] - tolerable_distance, point_to_check[1]))
slide_up = self.has_point_inside((point_to_check[0], point_to_check[1] - tolerable_distance))
slide_down = self.has_point_inside((point_to_check[0], point_to_check[1] + tolerable_distance))
stay_put = self.has_point_inside(point_to_check)
return slide_right or slide_left or slide_up or slide_down or stay_put
# returns leftmost x cord
def get_left_bound(self):
left_bound = self.points[0][0]
for point in self.points:
if point[0] < left_bound:
left_bound = point[0]
return left_bound
# returns rightmost x cord
def get_right_bound(self):
right_bound = self.points[0][0]
for point in self.points:
if point[0] > right_bound:
right_bound = point[0]
return right_bound
# returns smallest y cord
def get_up_bound(self):
up_bound = self.points[0][1]
for point in self.points:
if point[1] < up_bound:
up_bound = point[1]
return up_bound
# returns largest y cord
def get_down_bound(self):
down_bound = self.points[0][1]
for point in self.points:
if point[1] > down_bound:
down_bound = point[1]
return down_bound
def get_id(self):
return self.id
def get_points(self):
return self.points
|
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
res = [0] * len(indices)
for i, j in zip(s, indices) :
res[j] = i
return "".join(res)
|
class Move:
def __init__(self, dest_rank_id, from_rank_id):
self.dest_rank_id = dest_rank_id
self.from_rank_id = from_rank_id
def output(self):
out_str = ''
out_str += str(self.from_rank_id)
out_str += ' -> '
out_str += str(self.dest_rank_id)
print(out_str) |
# MatchJoin takes a list of matchers and joins them, to essentially
# make a conjunctive matcher
class MatchJoin:
# @matchers A list of matchers to join into a single match for example
# [
# LiteralMatch("hello ")
# LiteralMatch("world")
# ]
def __init__(self, matchers : list):
self.to_string_call_count = None
self.matchers = matchers
# @body The body to parse and tokenise
# @hard_fail a boolean flag indicating whether or not to throw an error when a match
# doesn't work
def parser(self, body : str, hard_fail = True):
result = []
head = 0
for matcher in self.matchers:
sub_body = body[head:]
out = matcher.parser(sub_body, hard_fail = False)
if not out:
if hard_fail:
raise ValueError(f"MatchJoin: Could not match at {head}")
else:
return False
result.append(out[0])
head += out[1]
return (result, head)
def to_string(self, call_count = 0):
if self.to_string_call_count == call_count:
return "..."
else:
self.to_string_call_count = call_count
return "(" + " ".join([m.to_string(call_count) for m in self.matchers]) + ")"
def __str__(self):
return self.to_string()
|
# Finds the optmial cost
def find_opt_cost(data):
min_cost = data[data.A == -1]['cost'].values[0]
return min_cost
# Finds the energy corresponding to optimal route
def find_opt_energy(data):
opt_energy = data[data.A == -1]['energy'].values[0]
return opt_energy
# Returns true if optimal route is observed
def opt_found(data):
min_cost = find_opt_cost(data)
data_d = data[(data.cost == min_cost) & (data.valid == True) & (data.windows == True) & (data.A != -1)]
return len(data_d) > 0
# Calculates the probability of samples encoding optimal route
def probability(data):
min_cost = find_opt_cost(data)
data_d = data[(data.cost == min_cost) & (data.valid == True) & (data.windows == True) & (data.A != -1)]
return len(data_d) / (len(data) - 1)
# Calculates the probability of samples encoding optimal route, returns 0 if the lowest energy sample is not optimal
def min_prob(data):
min_cost = find_opt_cost(data)
if data.valid.iloc[0] == True & data.windows.iloc[0] == True and data.cost.iloc[0] == min_cost:
return probability(data)
else:
return 0
|
# -*- coding: utf-8 -*-
"""Constant values.
"""
__version__ = '2021.03.27'
# image sizes
RES_TINY = 'TINY'
RES_SMALL = 'SMALL'
RES_MEAN = 'MEAN'
RES_BIG = 'BIG'
RES_HUGE = 'HUGE'
IMAGE_SIZES = {RES_TINY, RES_SMALL, RES_MEAN, RES_BIG, RES_HUGE}
# threshold for sizes
THRESHOLD_TINY = 0.1
THRESHOLD_SMALL = 1.0
THRESHOLD_MEAN = 5.0
THRESHOLD_BIG = 10.0
# duration types
DUR_MOMENT = 'MOMENT'
DUR_SHORT = 'SHORT'
DUR_MEDIUM = 'MEDIUM'
DUR_LONG = 'LONG'
DURATION_TYPES = {DUR_MOMENT, DUR_SHORT, DUR_MEDIUM, DUR_LONG}
# threshold for durations
THRESHOLD_MOMENT = 5
THRESHOLD_SHORT = 300
THRESHOLD_MEDIUM = 2400
# media types
TYPE_IMAGE = 'IMAGE'
TYPE_GIF = 'GIF'
TYPE_VIDEO = 'VIDEO'
TYPE_AUDIO = 'AUDIO'
MEDIA_TYPES = {TYPE_IMAGE, TYPE_GIF, TYPE_VIDEO, TYPE_AUDIO}
# search flags
FLAG_DESC = 'DESC'
FLAG_DEMAND = 'DEMAND'
FLAGS = {FLAG_DESC, FLAG_DEMAND}
KEYWORDS = IMAGE_SIZES | DURATION_TYPES | MEDIA_TYPES | FLAGS
KW_AND = 'AND'
KW_OR = 'OR'
KW_NOT = 'NOT'
KW_INCLUDE = 'INCLUDE'
KW_EXCLUDE = 'EXCLUDE'
OPERATORS = {KW_AND, KW_OR, KW_NOT, KW_INCLUDE, KW_EXCLUDE}
START_MESSAGE = r"""
███╗ ███╗███████╗██████╗ ██╗ █████╗
████╗ ████║██╔════╝██╔══██╗██║██╔══██╗
██╔████╔██║█████╗ ██║ ██║██║███████║
██║╚██╔╝██║██╔══╝ ██║ ██║██║██╔══██║
██║ ╚═╝ ██║███████╗██████╔╝██║██║ ██║
╚═╝ ╚═╝╚══════╝╚═════╝ ╚═╝╚═╝ ╚═╝
███████╗████████╗ ██████╗ ██████╗ █████╗ ██████╗ ███████╗
██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔══██╗██╔════╝ ██╔════╝
███████╗ ██║ ██║ ██║██████╔╝███████║██║ ███╗█████╗
╚════██║ ██║ ██║ ██║██╔══██╗██╔══██║██║ ██║██╔══╝
███████║ ██║ ╚██████╔╝██║ ██║██║ ██║╚██████╔╝███████╗
╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝
███████╗██╗ ██╗███████╗████████╗███████╗███╗ ███╗
██╔════╝╚██╗ ██╔╝██╔════╝╚══██╔══╝██╔════╝████╗ ████║
███████╗ ╚████╔╝ ███████╗ ██║ █████╗ ██╔████╔██║
╚════██║ ╚██╔╝ ╚════██║ ██║ ██╔══╝ ██║╚██╔╝██║
███████║ ██║ ███████║ ██║ ███████╗██║ ╚═╝ ██║
╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
##############################################################
"""
TERMINAL_WIDTH = 79
ALL_THEMES = 'all_themes'
NEVER_FIND_THIS = '?????????????'
UNKNOWN = 'UNKNOWN'
THUMBNAIL_SIZE = (384, 384)
PREVIEW_SIZE = (1024, 1024)
CONFIG_PATH_COMPONENTS = ('.', 'mss', 'config.yaml')
INJECTION_PATH_COMPONENTS = ('.', 'mss', 'injection.html')
SUPPORTED_EXTENSIONS = {
'.jpg',
'.jpeg',
'.png',
}
|
def jogo():
x = 0
while x != 1 and x != 2:
print('1 - para jogar uma partida isolada')
x = int(input('2 - para jogar um campeonato '))
print()
if x == 1:
print('Você escolheu uma partida!')
print()
partida()
else:
print('Você escolheu um campeonato!')
print()
campeonato()
def partida():
n = int(input('Quantas peças? '))
if n <=0:
print('Quantidade de peças deve ser maior do que zero!')
n = int(input('Quantas peças? '))
m = int(input('Limite de peças por jogada? '))
if m == 0:
print('Limite de peças por jogada não pode ser zero!')
m = int(input('Limite de peças por jogada? '))
if m > n:
print('Limite de peças por jogada não pode ser maior que quantidade de peças!')
m = int(input('Limite de peças por jogada? '))
multiplo = n % (m + 1)
qtde_usuario = 0
qtde_computador = 0
print()
if multiplo == 0:
print('Você começa!')
n = n - usuario_escolhe_jogada(n, m)
jogador = True
computador = False
else:
print('Computador começa!')
n = n - computador_escolhe_jogada(n, m)
jogador = False
computador = True
while n >= 1:
if jogador == False:
n = n - usuario_escolhe_jogada(n, m)
jogador = True
computador = False
if computador == False:
n = n - computador_escolhe_jogada(n, m)
jogador = False
computador = True
if jogador == True:
print('Fim do jogo! Você ganhou!')
if computador == True:
print('Fim do jogo! O computador ganhou!')
def computador_escolhe_jogada(n, m):
print()
i = 1
mult = False
while i <= m and mult == False:
k = n - i
if k % (m + 1) == 0:
mult = True
qtde_computador = i
i = i + 1
if mult == False:
qtde_computador = m
if qtde_computador > 1:
print('O computador tirou', qtde_computador, 'peças.')
if qtde_computador == 1:
print('O computador tirou uma peça.')
restantes = n - qtde_computador
if restantes > 1:
print('Agora restam', restantes, 'peças no tabuleiro.')
if restantes == 1:
print('Agora resta apenas uma peça no tabuleiro.')
return qtde_computador
def usuario_escolhe_jogada(n, m):
print()
qtde_usuario = int(input('Quantas peças você vai tirar? '))
while qtde_usuario > m or qtde_usuario <= 0 or qtde_usuario > n:
print()
print('Oops! Jogada inválida! Tente de novo.')
print()
qtde_usuario = int(input('Quantas peças você vai tirar? '))
print()
if qtde_usuario > 1:
print('Você tirou', qtde_usuario, 'peças.')
if qtde_usuario == 1:
print('Você tirou uma peça.')
restantes = n - qtde_usuario
if restantes > 1:
print('Agora restam', restantes, 'peças no tabuleiro.')
if restantes == 1:
print('Agora resta apenas uma peça no tabuleiro.')
return qtde_usuario
def campeonato():
j = 1
while j <= 3:
print()
print('**** Rodada', j, '****')
print()
partida()
j = j + 1
print()
print('**** Final do campeonato! ****')
print()
print('Placar: Você 0 X 3 Computador')
print('Bem-vindo ao jogo do NIM! Escolha:')
print()
jogo()
|
class LayeredStreamReaderBase:
__slots__ = {'upstream'}
def __init__(self, upstream):
self.upstream = upstream
async def read(self, n):
return await self.upstream.read(n)
async def readexactly(self, n):
return await self.upstream.readexactly(n)
|
# class class_name:
# def __init__(self):
#
# def function_name(self):
# return
class Athlete:
def __init__(self, value='Jane'):
self.inner_value = value
print(self.inner_value)
def getInnerValue(self):
return self.inner_value
class InheritanceClass(Athlete):
def __init__(self):
super().__init__()
def setValue(self, first_value):
self.inherit_value = first_value
def getValue(self):
return self.inherit_value
# inherit = InheritanceClass()
#
# print(inherit.getInnerValue())
#
# inherit.setValue(first_value='Sanghun')
#
# print(inherit.getValue())
# athlete = Athlete(value='SangHun') # == Athlete.__init__()
#
# print(athlete.getInnerValue()) |
Import("env")
#
# Add -m32 to the linker (since PlatformIo is not capable directly!)
# (and since we are at it, make everyting statically linked ;-)
#
env.Append(
LINKFLAGS=[
"-m32",
"-static-libgcc",
"-static-libstdc++"
]
)
|
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_like(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.setter
def nome(self, novo_nome):
self._nome = novo_nome.title()
def __str__(self):
return f'nome: {self._nome} - ano: {self.ano} - likes: {self._likes}'
class Filme(Programa):
def __init__(self, nome, ano, duracao):
super().__init__(nome, ano)
self.duracao = duracao
def __str__(self):
return f'nome: {self._nome} - ano: {self.ano} - duracao: {self.duracao} - likes: {self._likes}'
class Serie(Programa):
def __init__(self, nome, ano, temporadas):
super().__init__(nome, ano)
self.temporada = temporadas
def __str__(self):
return f'nome: {self._nome} - ano: {self.ano} - temporada: {self.temporada} - likes: {self._likes}'
vingadores = Filme('vigadores - a guerra', 2020, 160)
vingadores.dar_like()
vingadores.dar_like()
vingadores.dar_like()
senhorDosAneis = Filme('senhor dos aneis', 2010, 320)
[senhorDosAneis.dar_like() for _ in range(10)]
print(f'nome: {vingadores.nome} - ano: {vingadores.ano} - duracao: {vingadores.duracao}')
print(f'likes: {vingadores.likes}')
gameOf = Serie('game of thrones', 2010, 9)
print(f'Nome: {gameOf.nome} - ano: {gameOf.ano} - temporadas: {gameOf.temporada}')
gameOf.dar_like()
print(vingadores.nome)
atlanta = Serie('atlanta', 2018, 2)
atlanta.dar_like()
atlanta.dar_like()
atlanta.dar_like()
print(f'Nome: {atlanta.nome} - Ano: {atlanta.ano}')
print('\n=======================================================================')
filmesESeries = [senhorDosAneis, vingadores, gameOf, atlanta]
for programa in filmesESeries:
# colocando __str__ pode retornar colocando o nome dada da classe: programa
print(programa) |
# -*- coding: utf-8 -*-
{
'name': 'Customer Rating',
'version': '1.0',
'category': 'Productivity',
'description': """
This module allows a customer to give rating.
""",
'depends': [
'mail',
],
'data': [
'views/rating_view.xml',
'views/rating_template.xml',
'security/ir.model.access.csv'
],
'installable': True,
'auto_install': False,
}
|
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# Check edge case
if not intervals:
return []
# Sort the list to make it ascending with respect to the sub-list's first element and then in second element
intervals = sorted(intervals, key = lambda x: (x[0], x[1]))
# Initialize the result list with the first sub-list
res = [intervals[0]]
# Traverse the entire sorted list from the 2nd sub-list
for i in range(1, len(intervals)):
# There is intersection, then update the last sub-list of result
if intervals[i][0] <= res[-1][1]:
res[-1][1] = max(res[-1][1], intervals[i][1])
# There is no intersection, then append the current sub-list to result
else:
res.append(intervals[i])
return res |
__source__ = 'https://leetcode.com/problems/next-greater-element-iii/description/'
# Time: O(n)
# Space: O(n)
#
# Description: same as 556. Next Greater Element III
# //[email protected]
# // Next closest bigger number with the same digits
# // You have to create a function that takes a positive integer number and returns
# the next bigger number formed by the same digits:
#
# // next_bigger(12)==21 //string for permutation
# // next_bigger(513)==531
# // next_bigger(2017)==2071
#
# // If no bigger number can be composed using those digits, return -1:
#
# // next_bigger(9)==-1
# // next_bigger(111)==-1
# // next_bigger(531)==-1
#
Result = '''
IFang Lee ran 238 lines of Java (finished in 11.59s):
getRealNextBiggerInteger():
12-> 21 true
513 -> 531 true
1342-> 1423 true
534976-> 536479 true
9999-> -1 true
11-> -1 true
0-> -1 true
2147483647-> -1 true
getRealNextBiggerIntegerByPermutation():
12-> 21 true
513 -> 531 true
1342-> 1423 true
534976-> 536479 true
9999-> -1 true
11-> -1 true
0-> -1 true
2147483647-> -1 true
'''
my_ans = '''
import java.io.*;
import java.util.*;
// 1. permutation -> worse big O (n!)
// 2. scan from the last digit, swap with the first smaller digit O(n)
public class Solution {
public static void main(String[] args) {
testNextBiggerInteger();
}
public static void testNextBiggerInteger() {
int res1, res2;
System.out.println("getRealNextBiggerInteger(): ");
System.out.println("12-> " + (res2 = getRealNextBiggerInteger(12)) + " "
+ (res2 == 21) + "");
System.out.println("513 -> " + (res2 = getRealNextBiggerInteger(513)) + " "
+ (res2 == 531) + "");
System.out.println("1342-> " + (res2 = getRealNextBiggerInteger(1342)) + " "
+ (res2 == 1423) + "");
System.out.println("534976-> " + (res2 = getRealNextBiggerInteger(534976)) + " "
+ (res2 == 536479) + "");
//negative tests
System.out.println("9999-> " + (res2 = getRealNextBiggerInteger(9999)) + " "
+ (res2 == -1) + "");
System.out.println("11-> " + (res2 = getRealNextBiggerInteger(11)) + " "
+ (res2 == -1) + "");
System.out.println("0-> " + (res2 = getRealNextBiggerInteger(0)) + " "
+ (res2 == -1) + "");
System.out.println("2147483647-> " + (res2 = getRealNextBiggerInteger(Integer.MAX_VALUE))+ " "
+ (res2 == -1) + "");
System.out.println("987654321-> " + (res1 = getRealNextBiggerInteger(987654321)) + " "
+ (res1 == -1) + "");
System.out.println();
System.out.println("getRealNextBiggerIntegerByPermutation(): ");
System.out.println("12-> " + (res1 = getRealNextBiggerIntegerByPermutation(12)) + " "
+ (res1 == 21) + "");
System.out.println("513 -> " + (res1 = getRealNextBiggerIntegerByPermutation(513))+ " "
+ (res1 == 531) + "");
System.out.println("1342-> " + (res1 = getRealNextBiggerIntegerByPermutation(1342)) + " "
+ (res1 == 1423) + "");
System.out.println("534976-> " + (res1 = getRealNextBiggerIntegerByPermutation(534976)) + " "
+ (res1 == 536479) + "");
//negative tests
System.out.println("9999-> " + (res1 = getRealNextBiggerIntegerByPermutation(9999)) + " "
+ (res1 == -1) + "");
System.out.println("11-> " + (res1 = getRealNextBiggerIntegerByPermutation(11)) + " "
+ (res1 == -1) + "");
System.out.println("0-> " + (res1 = getRealNextBiggerIntegerByPermutation(0)) + " "
+ (res1 == -1) + "");
// significant long runtime (10982 milliseconds) for below test cases:
System.out.println("2147483647-> " + (res1 = getRealNextBiggerIntegerByPermutation(Integer.MAX_VALUE))
+ " " + (res1 == -1) + "");
// cannot run below: Stopped: CPU usage beyond threshold!
// System.out.println("9876543210-> " + (res1 = getRealNextBiggerIntegerByPermutation(987654321)) + " "
// + (res1 == -1) + "");
}
/////////////////////////////////////////////////////////////////////////////////////////////
/* Time O(n)
* 1. scan from the right, find the first digit larger than its right neighbor
* 2. Within the range of (1) to right of the number, find a digit larger than(1)
* 3. swap digit at (1) and (2)
* 4. reverse the digit from index at (i) to the end of the digits
* 5. return the result
*/
public static int getRealNextBiggerInteger(int number){
if (number < 0) throw new IllegalArgumentException("input must be positive integer");
char[] num = String.valueOf(number).toCharArray();
int i = num.length - 1, j = num.length - 1;
// find the first digit from right that is smaller the its right digit
while (i > 0 && num[i] <= num[i-1]) i--; //pivot = num[i-1]
// descending order //ex: 54321
if (i == 0) return -1;
// find the smallest digit >= pivot within the range (i, num.length)
while (j > i - 1 && num[j] <= num[i - 1]) j--;
swap(num, i - 1, j);
reverse(num, i, num.length - 1);
try { //check for overflow
return Integer.parseInt(new String(num));
} catch(NumberFormatException noe) {
System.out.println(noe.toString());
return -1;
}
}
private static void swap(char[] num, int i, int j) {
char tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
private static void reverse(char[] num, int start, int end) {
while(start < end) {
swap(num, start, end);
start++;
end--;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
/* Time O(n!)
* 1. Below algo use permutation way to get the next_bigger
* getAllPermutation(): for any given number, it computes all permutation using given number
* getRealNextBiggerIntegerByPermutation(): sort the result return by getAllPermutation() and
* find the next big integer
*/
// return the next big integer of number
// the algo first get all the permutations of that number to a list of integers
// then sort the list and traverse the list to find the next big integer of given number
// return -1 if not found
public static int getRealNextBiggerIntegerByPermutation(int number){
if (number < 0) throw new IllegalArgumentException("input must be positive integer");
List<Integer> permutations;
try{
permutations = getAllPermutation(number);
} catch(NumberFormatException noe) { //overflow case
//System.out.println(noe.toString());
return -1;
}
Collections.sort(permutations);
for (int i = 0; i < permutations.size(); i++) {
if ( i + 1 < permutations.size() && permutations.get(i + 1) > number) {
//System.out.println("ans" + permutations.get(i + 1));
return permutations.get(i+1);
}
}
return -1;
}
// given any number, get a list of all permutations in String type of the given number
// return a list of interger type of the all permutations of that given number
private static List<Integer> getAllPermutation(int number) {
List<String> res = new LinkedList<>();
String num = String.valueOf(number);
getPerm(num.toCharArray(), new boolean[num.length()], new StringBuilder(), res);
List<Integer> numbers = new LinkedList<>();
for (String n : res) {
try{
numbers.add(Integer.parseInt(n));
} catch(NumberFormatException noe) {
throw noe;
}
}
return numbers;
}
// backtrack to get all the permutation of "number" char array
// save the result to a list of string
private static void getPerm(char[] number, boolean[] used, StringBuilder sb, List<String> res) {
if (sb.length() == number.length) {
res.add(sb.toString());
return;
}
for (int i = 0; i < number.length; i++) {
if(!used[i]) {
sb.append(number[i]);
used[i] = true;
getPerm(number, used, sb, res);
sb.setLength(sb.length() - 1);
used[i] = false;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// below not working version
//starts with #2 scan from the last digit, swap with the first smaller digit O(n)
// lets use int think of overflow later (with long)
// the func does not work with 1342 -> returns 2341, but the correct ans = 1423
public static int nextBiggerInteger(int number){ //12
int num = number;
int lastDigit = num % 10; //2
num /= 10; //1
StringBuilder sb = new StringBuilder();
while (num > 0) { //loop throw numbers from last digits
int next = num % 10; //1
if ( next < lastDigit) { //swap next and lastDigit
num = (num / 10) * 10 + lastDigit;
sb.reverse().append(next);
break;
}
sb.append(next);
num /= 10;
}
// add num with sb
String rest = sb.toString();
//System.out.println(rest);
int restInt = 0;
if (rest != null && rest.length() > 0) {
try{
restInt = Integer.parseInt(rest); // none
}catch(NumberFormatException noe) {
System.out.println(noe.toString());
restInt = 0;
}
for (int i = 0; i < rest.length(); i++) {
num *= 10;
}
}
num += restInt;
return num > number ? num : -1;
}
/////////////////////////////////////////////////////////////////////////////////////////////
}
'''
|
def es_vocal(letra):
"""
Decide si una letra es vocal
>>> es_vocal('A')
True
>>> es_vocal('ae')
False
>>> es_vocal('Z')
False
>>> es_vocal('o')
True
:param letra:
:return:
"""
return len(letra) == 1 and letra in 'aeiouAEIOU'
def contar_vocales(texto):
"""
Cuenta cuantas vocales hay en un texto
>>> contar_vocales('')
0
>>> contar_vocales('hola')
2
>>> contar_vocales('qwrtp')
0
>>> contar_vocales('aeiou')
5
:param texto:
:return:
"""
contador = 0
for letra in texto:
if es_vocal(letra):
contador += 1
return contador |
"Ejemplo de implementación con Programación Estructurada"
clientes=[{'Nombre': 'Hector', 'Apellidos':'Costa Guzman', 'dni':'11111111A'},
{'Nombre': 'Juan', 'Apellidos':'González Márquez', 'dni':'22222222B'}]
def mostrar_cliente(clientes, dni):
for cliente in clientes:
if (dni == cliente['dni']):
return '{} {}'.format(cliente['Nombre'],cliente['Apellidos'])
return 'Cliente no encontrado'
def borrar_cliente(clientes, dni):
for cliente in clientes:
if dni == cliente['dni']:
clientes.remove(cliente)
return 'Cliente {} Eliminado'.format(cliente)
return 'Cliente no encontrado'
while True:
dni = input('DNI')
print(mostrar_cliente(clientes, dni))
print(borrar_cliente(clientes,dni))
|
# detector de palindromo
frase = str(input('Digite uma frase: ')).upper().strip()
separado = frase.split()
junto = ''.join(separado)
inverte =''
for letra in range(len(junto)-1,-1,-1):
inverte += junto[letra]
print('O inverso de {} é {}'.format(junto, inverte))
if junto == inverte:
print('A frase é um palíndromo! ')
else:
print('A frase não é um palíndromo')
|
# Portal & Effect for Evan Intro | Dream World: Dream Forest Entrance (900010000)
# Author: Tiger
# "You who are seeking a Pact..."
sm.showEffect("Map/Effect.img/evan/dragonTalk01", 3000)
|
#implement STACK/LIFO using LIST
stack=[]
while True:
choice=int(input("1 push, 2 pop, 3 peek, 4 display, 5 exit "))
if choice == 1:
ele=int(input("enter element to push "))
stack.append(ele)
elif choice == 2:
if len(stack)>0:
pele=stack.pop()
print("poped elemnt ",pele)
else:
print("stack is empty")
elif choice == 3:
if len(stack)>0:
tele=stack[len(stack)-1]
print("topmost elemnt ",tele)
else:
print("stack is empty")
elif choice == 4:
for i in stack:
print(i,end='')
print()
elif choice == 5:
break
else:
print("invalid choice")
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class ErrorCode:
# 数据平台的平台代码--7位错误码的前2位
BKDATA_PLAT_CODE = "15"
# 数据平台子模块代码--7位错误码的3,4位
BKDATA_COMMON = "00"
BKDATA_DATABUS = "06"
BKDATA_DATAAPI_DATABUS = "70"
BKDATA_DATAAPI_STREAM = "71"
BKDATA_DATAAPI_BATCH = "72"
BKDATA_DATAAPI_ADMIN = "73"
BKDATA_DATAAPI_FLOW = "74"
BKDATA_DATAAPI_JOBNAVI = "75"
BKDATA_DATAAPI_ACCESS = "76"
BKDATA_DATAAPI_COLLECTOR = "77"
BKDATA_DATAAPI_STOREKIT = "78"
BKDATA_DATAAPI_MODELFLOW = "79"
BKDATA_DATAAPI_DATALAB = "80"
BKDATA_DATAAPI_UDF = "81"
BKDATA_DATAAPI_DATACUBE = "82"
BKDATA_DATAAPI_RESOURCECENTER = "84"
BKDATA_DATAAPI_CODECHECK = "85"
BKDATA_STREAM = "08"
BKDATA_BATCH = "09"
BKDATA_DMONITOR = "10"
BKDATA_AUTH = "11"
BKDATA_MODELFLOW = "12"
BKDATA_META = "21"
BKDATA_METADATA = "30"
BKDATA_UC = "31"
BKDATA_DATAQUERY = "32"
BKDATA_OLD = "33"
BKDATA_SUPERSET = "34"
BKDATA_DATAAPI_APPS = {
"access": BKDATA_DATAAPI_ACCESS,
"auth": BKDATA_AUTH,
"dataquery": BKDATA_DATAQUERY,
"dataflow": BKDATA_DATAAPI_FLOW,
"storekit": BKDATA_DATAAPI_STOREKIT,
"datamanage": BKDATA_DATAAPI_ADMIN,
"databus": BKDATA_DATAAPI_DATABUS,
"jobnavi": BKDATA_DATAAPI_JOBNAVI,
"datalab": BKDATA_DATAAPI_DATALAB,
"meta": BKDATA_META,
"old": BKDATA_OLD,
"codecheck": BKDATA_DATAAPI_CODECHECK,
}
|
#!/bin/python3
nombre = 3
nombres_premiers = [1, 2]
print(2)
try:
while True:
diviseurs = []
for diviseur in nombres_premiers:
division = nombre / diviseur
if division == int(division):
diviseurs.append(diviseur)
if len(diviseurs) == 1:
print(nombre)
nombres_premiers.append(nombre)
del diviseurs
nombre += 2
except KeyboardInterrupt:
pass
# print(nombre)
|
DIGS = {1: 'F1D', 2: 'F2D', 3: 'F3D', 22: 'SD', -2: 'L2D'}
SEC_ORDER_DIGS = {key: f'{val}_sec' for key, val in DIGS.items()}
REV_DIGS = {'F1D': 1, 'F2D': 2, 'F3D': 3, 'SD': 22, 'L2D': -2}
LEN_TEST = {1: 9, 2: 90, 3: 900, 22: 10, -2: 100}
TEST_NAMES = {'F1D': 'First Digit Test', 'F2D': 'First Two Digits Test',
'F3D': 'First Three Digits Test', 'SD': 'Second Digit Test',
'L2D': 'Last Two Digits Test',
'F1D_sec': 'First Digit Second Order Test',
'F2D_sec': 'First Two Digits Second Order Test',
'F3D_sec': 'First Three Digits Second Order Test',
'SD_sec': 'Second Digit Second Order Test',
'L2D_sec': 'Last Two Digits Second Order Test',
'F1D_Summ': 'First Digit Summation Test',
'F2D_Summ': 'First Two Digits Summation Test',
'F3D_Summ': 'First Three Digits Summation Test',
'Mantissas': 'Mantissas Test'
}
# Critical values for Mean Absolute Deviation
MAD_CONFORM = {1: [0.006, 0.012, 0.015], 2: [0.0012, 0.0018, 0.0022],
3: [0.00036, 0.00044, 0.00050], 22: [0.008, 0.01, 0.012],
-2: None, 'F1D': 'First Digit', 'F2D': 'First Two Digits',
'F3D': 'First Three Digits', 'SD': 'Second Digits'}
# Color for the plotting
COLORS = {'m': '#00798c', 'b': '#E2DCD8', 's': '#9c3848',
'af': '#edae49', 'ab': '#33658a', 'h': '#d1495b',
'h2': '#f64740', 't': '#16DB93'}
# Critical Z-scores according to the confindence levels
CONFS = {None: None, 80: 1.285, 85: 1.435, 90: 1.645, 95: 1.96,
99: 2.576, 99.9: 3.29, 99.99: 3.89, 99.999: 4.417,
99.9999: 4.892, 99.99999: 5.327}
P_VALUES = {None: 'None', 80: '0.2', 85: '0.15', 90: '0.1', 95: '0.05',
99: '0.01', 99.9: '0.001', 99.99: '0.0001', 99.999: '0.00001',
99.9999: '0.000001', 99.99999: '0.0000001'}
# Critical Chi-Square values according to the tests degrees of freedom
# and confidence levels
CRIT_CHI2 = {8: {80: 11.03, 85: 12.027, 90: 13.362, 95: 15.507,
99: 20.090, 99.9: 26.124, 99.99: 31.827, None: None,
99.999: 37.332, 99.9999: 42.701, 99.99999: 47.972},
9: {80: 12.242, 85: 13.288, 90: 14.684, 95: 16.919,
99: 21.666, 99.9: 27.877, 99.99: 33.72, None: None,
99.999: 39.341, 99.9999: 44.811, 99.99999: 50.172},
89: {80: 99.991, 85: 102.826, 90: 106.469, 95: 112.022,
99: 122.942, 99.9: 135.978, 99.99: 147.350,
99.999: 157.702, 99.9999: 167.348, 99.99999: 176.471,
None: None},
99: {80: 110.607, 85: 113.585, 90: 117.407,
95: 123.225, 99: 134.642, 99.9: 148.230,
99.99: 160.056, 99.999: 170.798, 99.9999: 180.792,
99.99999: 190.23, None: None},
899: {80: 934.479, 85: 942.981, 90: 953.752, 95: 969.865,
99: 1000.575, 99.9: 1035.753, 99.99: 1065.314,
99.999: 1091.422, 99.9999: 1115.141,
99.99999: 1137.082, None: None}
}
# Critical Kolmogorov-Smirnov values according to the confidence levels
# These values are yet to be divided by the square root of the sample size
CRIT_KS = {80: 1.075, 85: 1.139, 90: 1.225, 95: 1.36, 99: 1.63,
99.9: 1.95, 99.99: 2.23, 99.999: 2.47,
99.9999: 2.7, 99.99999: 2.9, None: None}
|
# model settings
model = dict(
type='NPID',
neg_num=65536,
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(3,), # no conv-1, x-1: stage-x
norm_cfg=dict(type='SyncBN'),
style='pytorch'),
neck=dict(
type='LinearNeck',
in_channels=2048, out_channels=128,
with_avg_pool=True),
head=dict(type='ContrastiveHead', temperature=0.07),
memory_bank=dict(
type='SimpleMemory', length=1281167, feat_dim=128, momentum=0.5)
)
|
#!/usr/bin/env python3
# coding:utf-8
def estimate_area_from_stock(stock) :
return 10000000000;
|
algo: str = input('Digite algo:')
print('O tipo de primitivo da variável é ', type(algo))
print('É um número? ', algo.isnumeric())
print('É alfabético?', algo.isalpha())
print('É decimal?', algo.isdecimal())
print('Esta em minusculas?',algo.islower())
|
# CFG-RATE (0x06,0x08) packet (without header 0xB5,0x62)
# payload length - 6 (little endian format), update rate 200ms, cycles - 1, reference - UTC (0)
packet = []
packet = input('What is the payload? ')
CK_A,CK_B = 0, 0
for i in range(len(packet)):
CK_A = CK_A + packet[i]
CK_B = CK_B + CK_A
# ensure unsigned byte range
CK_A = CK_A & 0xFF
CK_B = CK_B & 0xFF
print ("UBX packet checksum:", ("0x%02X,0x%02X" % (CK_A,CK_B)))
|
class Course:
def __init__(self, **kw):
self.name = kw.pop('name')
#def full_name(self):
# return self.first_name + " " + self.last_name |
'''Extracts the data from the json content. Outputs results in a dataframe'''
def get_play_df(content):
events = {}
event_num = 0
home = content['gameData']['teams']['home']['id']
away = content['gameData']['teams']['away']['id']
for i in range(len(content['liveData']['plays']['allPlays'])):
temp = {}
if content['liveData']['plays']['allPlays'][i]['result']['event'] == 'Penalty':
temp['event_type'] = 'Penalty'
temp['penalty_minutes'] = content['liveData']['plays']['allPlays'][i]['result']['penaltyMinutes']
temp['time_of_event'] = content['liveData']['plays']['allPlays'][i]['about']['periodTime']
temp['period'] = content['liveData']['plays']['allPlays'][i]['about']['ordinalNum']
temp['current_score'] = content['liveData']['plays']['allPlays'][i]['about']['goals']
if content['liveData']['plays']['allPlays'][i]['team']['id'] == home:
temp['team'] = 'home'
elif content['liveData']['plays']['allPlays'][i]['team']['id'] == away:
temp['team'] = 'away'
else:
temp['team'] = 'error'
events[event_num] = temp
event_num += 1
if content['liveData']['plays']['allPlays'][i]['result']['event'] in ['Blocked Shot', 'Goal', 'Missed Shot', 'Shot']:
temp['event_type'] = content['liveData']['plays']['allPlays'][i]['result']['event']
temp['penalty_minutes'] = 0
temp['time_of_event'] = content['liveData']['plays']['allPlays'][i]['about']['periodTime']
temp['period'] = content['liveData']['plays']['allPlays'][i]['about']['ordinalNum']
temp['current_score'] = content['liveData']['plays']['allPlays'][i]['about']['goals']
if content['liveData']['plays']['allPlays'][i]['team']['id'] == home:
temp['team'] = 'home'
elif content['liveData']['plays']['allPlays'][i]['team']['id'] == away:
temp['team'] = 'away'
else:
temp['team'] = 'error'
events[event_num] = temp
event_num += 1
events_df = pd.DataFrame(events)
events_df_t = events_df.transpose()
return events_df_t
''' Helper function to get time of game events in seconds'''
def get_seconds(time, period):
if period == 'OT':
period = '4th'
elif period == 'SO':
return 3605
seconds = int(time[3:])
minutes = int(time[0:2])
game_period = int(period[0]) -1
timestamp = (20 * 60 * game_period) + (60 * minutes) + seconds
return timestamp
''' Main function that determines shots, and if there are any active penalties (which would negate
the shot being counted towards the advanced stats). The function returns the shot counts for each team'''
def count_all_shots(events_df_t):
home_shots = 0
away_shots = 0
home_blocked_shots = 0
away_blocked_shots = 0
active_penalty = False
home_penalty = False
away_penalty = False
two_man_advtg = False
four_v_four = False
major_penalty = False
shot_types = ['Blocked Shot', 'Goal', 'Missed Shot', 'Shot']
for i in range(len(events_df_t)):
event = events_df_t['event_type'][i]
event_time = events_df_t['timestamp'][i]
if events_df_t['period'][i] == 'SO':
return home_shots, away_shots, home_blocked_shots, away_blocked_shots
if major_penalty == True:
if end_penalty_time <= event_time:
major_penalty = False
if active_penalty == True:
if (event in shot_types) & (end_penalty_time <= event_time):
active_penalty = False
four_v_four = False
elif event == 'Penalty':
if ((events_df_t['team'][i] == 'home') & (home_penalty == True) or ((events_df_t['team'][i] == 'away') & (away_penalty == True))):
added_time = 60 * events_df_t['penalty_minutes'][i]
end_penalty_time = event_time + added_time
two_man_advtg = True
else:
# Currently does not take into account 4v4 as even strength, will fix later
added_time = 60 * events_df_t['penalty_minutes'][i]
end_penalty_time = event_time + added_time
four_v_four = True
if (event in shot_types) & (active_penalty == False):
if events_df_t['team'][i] == 'home':
if event == 'Blocked Shot':
home_blocked_shots += 1
else:
home_shots += 1
else:
if event == 'Blocked Shot':
away_blocked_shots += 1
else:
away_shots += 1
elif (event == 'Penalty') & (active_penalty == False):
active_penalty = True
if events_df_t['penalty_minutes'][i] >= 5:
major_penalty = True
if events_df_t['team'][i] == 'home':
home_penalty = True
else:
away_penalty = True
added_time = 60 * events_df_t['penalty_minutes'][i]
end_penalty_time = event_time + added_time
elif (event == 'Goal') & (active_penalty == True) & (major_penalty == False):
if two_man_advtg == True:
two_man_advtg = False
elif four_v_four == True:
if events_df_t['team'][i] == 'home':
away_penalty = False
elif events_df_t['team'][i] == 'away':
home_penalty = False
four_v_four = False
else:
active_penalty = False
home_penalty = False
away_penalty = False
return home_shots, away_shots, home_blocked_shots, away_blocked_shots
'''Based on the output of the above function, this calculates that actual advanced Corsi and Fenwick stats'''
def calc_advanced_stats(home_shots, away_shots, home_blocked_shots, away_blocked_shots):
corsi_for = home_shots + home_blocked_shots
corsi_against = away_shots + away_blocked_shots
cf_pct = corsi_for/(corsi_for + corsi_against)
ca_pct = corsi_against/(corsi_for + corsi_against)
fenwick_for = home_shots
fenwick_against = away_shots
ff_pct = home_shots/(home_shots + away_shots)
fa_pct = away_shots/(home_shots + away_shots)
return corsi_for, corsi_against, cf_pct, ca_pct, fenwick_for, fenwick_against, ff_pct, fa_pct
'''Performs the API call to the NHL API'''
def get_api_data(game_id):
# Call API
URL = f"https://statsapi.web.nhl.com/api/v1/game/{game_id}/feed/live"
# sending get request and saving the response as response object
r = re.get(url=URL)
content = r.json()
return content
'''Main function to call API. Uses game IDs in the Kaggle dataset to perform the call'''
def get_game_data(game_list):
game_data_dict = {}
i = 0
for game_id in tqdm(game_list):
try:
game_data_dict[game_id] = get_api_data(game_id)
except Exception as e:
print('\n======EXCEPTION=====')
print(e)
game_data_dict[game_id] = 0
continue
# Saving checkpoint
if i % 100 == 0:
print(f"Completed {i} iterations")
#filename = f'game_data_checkpoint_{i}.sav'
#pickle.dump(game_data_dict, open(filename, 'wb'))
i+=1
return game_data_dict |
#APROVANDO EMPRESTIMO
casa = float(input('Valor da casa: R$'))
salario = float(input('Salario do comprador: R$'))
anos = int(input('Quantos anos de financiamento: '))
meses = anos * 12
prestação = casa / meses
print('Para pagar uma casa de R${:.2f} em {} anos a prestação sera de R${:.2f}'.format(casa, anos, prestação))
if prestação >= salario * 30 /100:
print('Emprestimo negado')
else:
print('Emprestimo pode ser CONCEDIDO!')
|
"""
*
* Author: Juarez Paulino(coderemite)
* Email: [email protected]
*
"""
n=int(input())
a,b=map(int,input().split())
c,d=map(int,input().split())
e,f=map(int,input().split())
m=n-a-c-e
x=max(0,min(m,b-a));m-=x
y=max(0,min(m,d-c));m-=y
z=max(0,min(m,f-e));m-=z
print(a+x,c+y,e+z)
|
"""
models/__init__.py
-------------------------------------------------------------------
"""
def init_app(app):
"""
:param app:
:return:
"""
pass
|
"""
Discussion:
As we increase the input firing rate, more synapses move to the extreme values,
either go to zero or to maximal conductance. Using 15Hz, the distribution of the
weights at the end of the simulation is more like a bell-shaped, skewed, with more
synapses to be potentiated. However, increasing the firing rate, in early times,
almost all synapses undergo depression, and then only a few escape and they become
potentiated.
"""; |
# coding: utf8
{
'!langcode!': 'af',
'!langname!': 'Afrikaanse',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'%s %%{row} deleted': '%s rows deleted',
'%s %%{row} updated': '%s rows updated',
'(requires internet access)': '(vereis internet toegang)',
'(something like "it-it")': '(iets soos "it-it")',
'@markmin\x01Searching: **%s** %%{file}': 'Soek: **%s** lêre',
'About': 'oor',
'About application': 'Oor program',
'Additional code for your application': 'Additionele kode vir u application',
'Admin language': 'Admin taal',
'Application name:': 'Program naam:',
'Change admin password': 'verander admin wagwoord',
'Check for upgrades': 'soek vir upgrades',
'Clean': 'maak skoon',
'Compile': 'kompileer',
'Controllers': 'Beheerders',
'Create': 'skep',
'Deploy': 'deploy',
'Deploy on Google App Engine': 'Stuur na Google App Engine toe',
'Edit': 'wysig',
'Edit application': 'Wysig program',
'Errors': 'foute',
'Help': 'hulp',
'Install': 'installeer',
'Installed applications': 'Geinstalleerde apps',
'Languages': 'Tale',
'License for': 'Lisensie vir',
'Logout': 'logout',
'Models': 'Modelle',
'Modules': 'Modules',
'New application wizard': 'Nuwe app wizard',
'New simple application': 'Nuwe eenvoudige app',
'Overwrite installed app': 'skryf oor geinstalleerde program',
'Pack all': 'pack alles',
'Plugins': 'Plugins',
'Powered by': 'Aangedryf deur',
'Site': 'site',
'Start wizard': 'start wizard',
'Static files': 'Static files',
'Sure you want to delete this object?': 'Is jy seker jy will hierde object verwyder?',
'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller',
'The data representation, define database tables and sets': 'The data representation, define database tables and sets',
'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates',
'There are no plugins': 'Daar is geen plugins',
'These files are served without processing, your images go here': 'Hierdie lêre is sonder veranderinge geserved, jou images gaan hier',
'To create a plugin, name a file/folder plugin_[name]': 'Om n plugin te skep, noem n lêer/gids plugin_[name]',
'Translation strings for the application': 'Vertaling woorde vir die program',
'Uninstall': 'verwyder',
'Upload & install packed application': 'Oplaai & install gepakte program',
'Upload a package:': 'Oplaai n package:',
'Use an url:': 'Gebruik n url:',
'Views': 'Views',
'administrative interface': 'administrative interface',
'and rename it:': 'en verander die naam:',
'collapse/expand all': 'collapse/expand all',
'controllers': 'beheerders',
'create file with filename:': 'skep lêer met naam:',
'created by': 'geskep deur',
'crontab': 'crontab',
'currently running': 'loop tans',
'database administration': 'database administration',
'direction: ltr': 'direction: ltr',
'download layouts': 'aflaai layouts',
'download plugins': 'aflaai plugins',
'exposes': 'exposes',
'extends': 'extends',
'filter': 'filter',
'includes': 'includes',
'languages': 'tale',
'loading...': 'laai...',
'models': 'modelle',
'modules': 'modules',
'plugins': 'plugins',
'shell': 'shell',
'static': 'static',
'test': 'toets',
'update all languages': 'update all languages',
'upload': 'oplaai',
'upload file:': 'oplaai lêer:',
'upload plugin file:': 'upload plugin lêer:',
'versioning': 'versioning',
'views': 'views',
'web2py Recent Tweets': 'web2py Onlangse Tweets',
}
|
#!/usr/bin/env python
#-*- coding:utf8 -*-
# @Author: lisnb
# @Date: 2016-04-27T11:05:16+08:00
# @Email: [email protected]
# @Last modified by: lisnb
# @Last modified time: 2016-06-18T22:20:18+08:00
class UnknownError(Exception):
pass
class ImproperlyConfigured(Exception):
"""Wiesler is somehow improperly configured"""
pass
class ImportFailed(ImportError):
"""Import module failed"""
pass
class ImportAppConfigFailed(ImportFailed):
"""Can't import config of app when initialize an App instance"""
pass
class AttributeNotFound(Exception):
"""Necessary attribute is not found"""
pass
class NecessaryVariableIsEmpty(Exception):
"""A variable that is necessary is empty, None or empty list etc."""
pass
class ArguementInvalid(Exception):
"""Attribute is somehow invalid"""
pass
class DBError(Exception):
pass
class MySQLError(DBError):
"""Something happens when using mysql"""
pass
class MySQLConnectionError(MySQLError):
"""Can't establish connection with mysql server"""
pass
class MySQLExecuteError(MySQLError):
"""Error when try to execute SQL statement"""
pass
class MongoDBError(DBError):
pass
class MongoDBConnectionError(MongoDBError):
pass
class MongoDBExecuteError(MongoDBError):
pass
class AppNotFound(ImportFailed):
pass
|
def raio_simplificado(lista_composta):
for elemento in lista_composta:
yield from elemento
lista_composta = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
|
#trying something new
uridine_mods_paths = {'U_to_DDusA' : {'upstream_rxns' : ['U'],
'enzymes' : {20:['DusA_mono'],
'20A':['DusA_mono'],
17:['DusA_mono'],
16:['DusA_mono']}},
'U_to_DDusgen' : {'upstream_rxns' : ['U'],
'enzymes' : {20:['generic_Dus'],
'20A':['generic_Dus'],
17:['generic_Dus'],
16:['generic_Dus']}},
'U_to_Um' : {'upstream_rxns' : ['U'],
'enzymes' : {2552:['RrmJ_mono'],
32 : ['TrmJ_dim'],
34 :['trmL_dim' ]}},
'U_to_Y' : {'upstream_rxns' : ['U'],
'enzymes' : {32:['RluA_mono'],
746 : ['RluA_mono'],
2605:['RluB_mono'],
2504 :['RluC_mono'],
2580:['RluC_mono'],
995 :[ 'RluC_mono'],
1915:['RluD_mono_mod_1:mg2'],
1911:['RluD_mono_mod_1:mg2'],
1917:['RluD_mono_mod_1:mg2'],
2457 :['YmfC_mono'],
2604 :[ 'YjbC_mono'],
13 :[ 'TruD_mono'],
65 :[ 'YqcB_mono'],
55 : ['TruB_mono'],
38 : ['TruA_dim'],
39 :[ 'TruA_dim'],
40 : ['TruA_dim'],
516 :['RsuA_mono']}
},
'U_to_acp3U' : {'upstream_rxns' : ['U'],
'enzymes' : {47:['enzyme_unknown']}},
'U_to_cmnm5U' : {'upstream_rxns' : ['U'],
'enzymes' : {34:['MnmEG_cplx_mod_fad_mod_2:k']}},
'U_to_ho5U' : {'upstream_rxns' : ['U'],
'enzymes' : {34:['enzyme_unknown2']}},
'U_to_m3U' : {'upstream_rxns' : ['U'],
'enzymes' : {1498:['YggJ_dim']}},
'U_to_m5U' : {'upstream_rxns' : ['U'],
'enzymes' : {747:['RumB_mono_mod_1:4fe4s'],
1939:['RumA_mono_mod_1:4fe4s'],
54 :['TrmA_mono']
}},
'U_to_nm5U' : {'upstream_rxns' : ['U'],
'enzymes' : {34:['MnmEG_cplx_mod_fad_mod_2:k']}},
'U_to_s2U' : {'upstream_rxns' : ['U'],
'enzymes' : {34:['TrmU_mono']}},
'U_to_s4U' : {'upstream_rxns' : ['U'],
'enzymes' : {8:['ThiI_mono']}},
'ho5U_to_mo5U' : {'upstream_rxns' : ['U_to_ho5U'],
'enzymes' : {34:['YecP_mono']}},
's2U_to_nm5s2U' : {'upstream_rxns' : ['U_to_s2U'],
'enzymes' : {34:['MnmEG_cplx_mod_fad_mod_2:k']}},
'cmnm5U_to_cmnm5s2U' : {'upstream_rxns' : ['U_to_cmnm5U'],
'enzymes' : {34:['TrmU_mono']}},
's2U_to_ges2U' : {'upstream_rxns' : ['U_to_s2U'],
'enzymes' : {34:['YbbB_dim']}},
's2U_to_se2U' : {'upstream_rxns' : ['U_to_s2U'],
'enzymes' : {34:['YbbB_dim']}}, # this is a guess!
's2U_to_cmnm5s2U' : {'upstream_rxns' : ['U_to_s2U'],
'enzymes' : {34:['MnmEG_cplx_mod_fad_mod_2:k']}},
'cmnm5s2U_to_cmnm5se2U' : {'upstream_rxns' : ['s2U_to_cmnm5s2U','cmnm5U_to_cmnm5s2U'],
'enzymes' : {34:['YbbB_dim']}},
'mnm5s2U_to_mnm5ges2U' : {'upstream_rxns' : ['nm5s2U_to_mnm5s2U','mnm5U_to_mnm5s2U'],
'enzymes' : {34:['YbbB_dim']}},
'cmnm5se2U_to_nm5se2U' : {'upstream_rxns' : ['se2U_to_cmnm5se2U','cmnm5s2U_to_cmnm5se2U'],
'enzymes' : {34:['MnmC_mono_mod_fad']}},
'Y_to_m3Y' : {'upstream_rxns' : ['U_to_Y'],
'enzymes' : {1915:['RlmH_dim']}},
'se2U_to_cmnm5se2U' : {'upstream_rxns' : ['s2U_to_se2U'],
'enzymes' : {34:['MnmEG_cplx_mod_fad_mod_2:k']}},
'cmnm5s2U_to_nm5s2U' : {'upstream_rxns' : ['s2U_to_cmnm5s2U','cmnm5U_to_cmnm5s2U'],
'enzymes' : {34:['MnmC_mono_mod_fad']}},
'nm5se2U_to_mnm5se2U' : {'upstream_rxns' : ['cmnm5se2U_to_nm5se2U', 'se2U_to_nm5se2U' ,'nm5s2U_to_nm5se2U'],
'enzymes' : {34:['MnmC_mono_mod_fad']}},
'mnm5s2U_to_mnm5se2U' : {'upstream_rxns' : ['nm5s2U_to_mnm5s2U','mnm5U_to_mnm5s2U'],
'enzymes' : {34:['YbbB_dim']}},
'mnm5U_to_mnm5s2U' : {'upstream_rxns' : ['nm5U_to_mnm5U'],
'enzymes' : {34:['TrmU_mono']}},
'nm5s2U_to_nm5se2U' : {'upstream_rxns' : ['s2U_to_nm5s2U','cmnm5s2U_to_nm5s2U'],
'enzymes' : {34:['YbbB_dim']}},
'nm5s2U_to_mnm5s2U' : {'upstream_rxns' : ['s2U_to_nm5s2U','cmnm5s2U_to_nm5s2U'],
'enzymes' : {34:['MnmC_mono_mod_fad']}},
'se2U_to_nm5se2U' : {'upstream_rxns' : ['s2U_to_se2U'],
'enzymes' : {34:['MnmEG_cplx_mod_fad_mod_2:k']}},
'cmnm5U_to_nm5U' : {'upstream_rxns' : ['U_to_cmnm5U'],
'enzymes' : {34:['MnmC_mono_mod_fad']}},
'cmnm5U_to_cmnm5Um' : {'upstream_rxns' : ['U_to_cmnm5U'],
'enzymes' : {34:['trmL_dim']}},
'Um_to_cmnm5Um' : {'upstream_rxns' : ['U_to_Um'],
'enzymes' : {34:['MnmEG_cplx_mod_fad_mod_2:k']}},
'nm5U_to_mnm5U' : {'upstream_rxns' : ['U_to_nm5U', 'cmnm5U_to_nm5U'],
'enzymes' : {34:['MnmC_mono_mod_fad']}},
'ho5U_to_cmo5U' : {'upstream_rxns' : ['U_to_ho5U'],
'enzymes' : {34:['YecP_mono']}
}}
cytidine_mods_paths = {'C_to_s2C' : {'upstream_rxns' : ['C'],
'enzymes' : {32:['YdaO_mono']}},
'C_to_m5C' : {'upstream_rxns' : ['C'],
'enzymes' : {1962:['RlmI_dim'],
967 : ['RsmB_mono'],
1407 : ['RsmF_mono']}},
'C_to_Cm' : {'upstream_rxns' : ['C'],
'enzymes' : {2498:['RlmM_mono'],
1402:['RsmI_mono'],
32:['TrmJ_dim'],
34 : ['trmL_dim']}},
'C_to_ac4C' : {'upstream_rxns' : ['C'],
'enzymes' : {34:['TmcA_mono']}},
'Cm_to_m4Cm' : {'upstream_rxns' : ['C_to_Cm'],
'enzymes' : {1402:['RsmH_mono']}},
'm4Cm_to_m44Cm' : {'upstream_rxns' : ['Cm_to_m4Cm','m4C_to_m4Cm'],
'enzymes' : {1402:['RsmH_mono']}},
'C_to_m4C' : {'upstream_rxns' : ['C'],
'enzymes' : {1402:['RsmH_mono']}},
'm4C_to_m44C' : {'upstream_rxns' : ['C_to_m4C'],
'enzymes' : {1402:['RsmI_mono']}},
'm4C_to_m4Cm' : {'upstream_rxns' : ['C_to_m4C'],
'enzymes' : {1402:['RsmH_mono']}},
'C_to_k2C' : {'upstream_rxns' : ['C'],
'enzymes' : {34:['TilS_mono']}}
}
adenine_mods_paths ={'A_to_m2A' : {'upstream_rxns' : ['A'],
'enzymes' : {37:['RlmN_mono_mod_1:4fe4s'],
2503:['RlmN_mono_mod_1:4fe4s']}},
'A_to_m6A' : {'upstream_rxns' : ['A'],
'enzymes' : {2058:['enzyme_new_ErmBC'],
1618:['RlmF_mono'],
2030:['enzyme_new_RlmJ'],
1518:['KsgA_mono'],
1519:['KsgA_mono'],
37:['YfiC_mono']}},
'm6A_to_m66A' : {'upstream_rxns' : ['A_to_m6A'],
'enzymes' : { 1518:['KsgA_mono'],
1519:['KsgA_mono']}},
'A_to_I' : {'upstream_rxns' : ['A'],
'enzymes' : {34:['TadA_dim_mod_2:zn2']}},
'A_to_m1A' : {'upstream_rxns' : ['A'],
'enzymes' : {1408:['enzyme_new_NpmA']}},
'A_to_i6A' : {'upstream_rxns' : ['A'],
'enzymes' : {37:['MiaA_dim_mod_2:mg2']}},
'i6A_to_ms2i6A' : {'upstream_rxns' : ['A_to_i6A'],
'enzymes' : {37:['MiaB_mono_mod_1:4fe4s']}},
'A_to_t6A' : {'upstream_rxns' : ['A'],
'enzymes' : {37:['TsaBCDE']}},
't6A_to_m6t6A' : {'upstream_rxns' : ['A_to_t6A'],
'enzymes' : {37:['EG11503_MONOMER']}},
't6A_to_ct6A' : {'upstream_rxns' : ['A_to_t6A'],
'enzymes' : {37:['TcdA_dim']}}
}
guanine_mods_paths={'G_to_m7G' : {'upstream_rxns' : ['G'],
'enzymes' : {2069:['RlmL_dim'],
1405:['enzyme_new_RmtB'],
527:['RsmG_mono'],
46:['YggH_mono']}},
'G_to_m2G' : {'upstream_rxns' : ['G'],
'enzymes' : {1835:['RlmG_mono'],
2445:['RlmL_dim'],
1207:['RsmC_mono'],
966:['RsmD_mono'],
1516:['enzyme_new_RsmJ']
}},
'G_to_Gm' : {'upstream_rxns' : ['G'],
'enzymes' : {2251:['RlmB_dim'],
18:['TrmH_dim']}},
'G_to_m1G' : {'upstream_rxns' : ['G'],
'enzymes' : {745:['RrmA_dim_mod_2:zn2'],
37:['TrmD_dim']}},
'G_to_preq1tRNA' : {'upstream_rxns' : ['G'],
'enzymes' : {34:['Tgt_hexa_mod_6:zn2']}},
'preq1tRNA_to_oQtRNA' : {'upstream_rxns' : ['G_to_preq1tRNA'],
'enzymes' : {34:['QueA_mono']}},
'oQtRNA_to_QtRNA' : {'upstream_rxns' : ['preq1tRNA_to_oQtRNA'],
'enzymes' : {34:['QueG_mono_mod_adocbl']}},
'QtRNA_to_gluQtRNA' : {'upstream_rxns' : ['oQtRNA_to_QtRNA'],
'enzymes' : {34:['YadB_mono']}}
} |
#The casefold() method is an aggressive lower() method which convert strings to casefolded strings for caseless matching.
string = "PYTHON IS AWESOME"
# print lowercase string
print("Lowercase string:", string.casefold())
firstString = "der Fluß"
secondString = "der Fluss"
# ß is equivalent to ss in german
if firstString.casefold() == secondString.casefold():
print('The strings are equal.')
else:
print('The strings are not equal.')
|
class Pessoa:
olhos = 2 # atributo Default ou atributo de classe
def __init__(self, *filhos, nome=None, idade=59):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
@staticmethod
def metodo_estatico():
return 59
@classmethod
def nome_e_atributos_de_classe(cls):
return f'{cls} - olhos {cls.olhos}'
def cumprimentar(self):
return f'Olá {id(self)}'
if __name__ == '__main__':
felipe = Pessoa(nome='Felipe')
lucia = Pessoa(felipe, nome='Lucia')
print(Pessoa.cumprimentar(lucia))
print(id(lucia))
print(lucia.cumprimentar())
print(lucia.nome)
print(lucia.idade)
for filho in lucia.filhos:
print("A ", lucia, "tem um filho chamado ", filho.nome)
## criando atributo dinamicoamente (sobrenome)
lucia.sobrenome = 'Franco'
print(lucia.nome +' '+ lucia.sobrenome)
print(lucia.__dict__)
print(felipe.__dict__)
print(Pessoa.olhos)
print(lucia.olhos)
print(felipe.olhos)
########## Todos os objetos da classe pessoa tem 2 olhos e o mesmo ( id de olhos)
print(id(Pessoa.olhos), id(lucia.olhos), id(felipe.olhos))
################
print(Pessoa.metodo_estatico(), lucia.metodo_estatico())
print(Pessoa.nome_e_atributos_de_classe(), lucia.nome_e_atributos_de_classe())
|
def run():
# Range can receive a first value that defines start value of range: range(1, 1000)
for i in range(1000):
print('Value ' + str(i))
if __name__ == '__main__':
run()
|
def biggerIsGreater(w):
w = list(w)
x = len(w)-1
while x > 0 and w[x-1] >= w[x]:
x -= 1
if x <= 0:
return 'no answer'
j = len(w) - 1
while w[j] <= w[x - 1]:
j -= 1
w[x-1], w[j] = w[j], w[x-1]
w[x:] = w[len(w)-1:x-1:-1]
return ''.join(w) |
# Add support for multiple event queues
def upgrader(cpt):
cpt.set('Globals', 'numMainEventQueues', '1')
legacy_version = 12
|
class Solution(object):
def moveZeroes(self, nums):
totalZeros = 0
for i in range(len(nums)):
if nums[i] == 0 :
totalZeros += 1
continue
nums[i - totalZeros] = nums[i]
if(totalZeros) : nums[i] = 0
|
# This file is created by generate_build_files.py. Do not edit manually.
ssl_headers = [
"src/include/openssl/dtls1.h",
"src/include/openssl/srtp.h",
"src/include/openssl/ssl.h",
"src/include/openssl/ssl3.h",
"src/include/openssl/tls1.h",
]
fips_fragments = [
"src/crypto/fipsmodule/aes/aes.c",
"src/crypto/fipsmodule/aes/aes_nohw.c",
"src/crypto/fipsmodule/aes/key_wrap.c",
"src/crypto/fipsmodule/aes/mode_wrappers.c",
"src/crypto/fipsmodule/bn/add.c",
"src/crypto/fipsmodule/bn/asm/x86_64-gcc.c",
"src/crypto/fipsmodule/bn/bn.c",
"src/crypto/fipsmodule/bn/bytes.c",
"src/crypto/fipsmodule/bn/cmp.c",
"src/crypto/fipsmodule/bn/ctx.c",
"src/crypto/fipsmodule/bn/div.c",
"src/crypto/fipsmodule/bn/div_extra.c",
"src/crypto/fipsmodule/bn/exponentiation.c",
"src/crypto/fipsmodule/bn/gcd.c",
"src/crypto/fipsmodule/bn/gcd_extra.c",
"src/crypto/fipsmodule/bn/generic.c",
"src/crypto/fipsmodule/bn/jacobi.c",
"src/crypto/fipsmodule/bn/montgomery.c",
"src/crypto/fipsmodule/bn/montgomery_inv.c",
"src/crypto/fipsmodule/bn/mul.c",
"src/crypto/fipsmodule/bn/prime.c",
"src/crypto/fipsmodule/bn/random.c",
"src/crypto/fipsmodule/bn/rsaz_exp.c",
"src/crypto/fipsmodule/bn/shift.c",
"src/crypto/fipsmodule/bn/sqrt.c",
"src/crypto/fipsmodule/cipher/aead.c",
"src/crypto/fipsmodule/cipher/cipher.c",
"src/crypto/fipsmodule/cipher/e_aes.c",
"src/crypto/fipsmodule/cipher/e_des.c",
"src/crypto/fipsmodule/des/des.c",
"src/crypto/fipsmodule/digest/digest.c",
"src/crypto/fipsmodule/digest/digests.c",
"src/crypto/fipsmodule/ec/ec.c",
"src/crypto/fipsmodule/ec/ec_key.c",
"src/crypto/fipsmodule/ec/ec_montgomery.c",
"src/crypto/fipsmodule/ec/felem.c",
"src/crypto/fipsmodule/ec/oct.c",
"src/crypto/fipsmodule/ec/p224-64.c",
"src/crypto/fipsmodule/ec/p256-x86_64.c",
"src/crypto/fipsmodule/ec/scalar.c",
"src/crypto/fipsmodule/ec/simple.c",
"src/crypto/fipsmodule/ec/simple_mul.c",
"src/crypto/fipsmodule/ec/util.c",
"src/crypto/fipsmodule/ec/wnaf.c",
"src/crypto/fipsmodule/ecdh/ecdh.c",
"src/crypto/fipsmodule/ecdsa/ecdsa.c",
"src/crypto/fipsmodule/hmac/hmac.c",
"src/crypto/fipsmodule/md4/md4.c",
"src/crypto/fipsmodule/md5/md5.c",
"src/crypto/fipsmodule/modes/cbc.c",
"src/crypto/fipsmodule/modes/cfb.c",
"src/crypto/fipsmodule/modes/ctr.c",
"src/crypto/fipsmodule/modes/gcm.c",
"src/crypto/fipsmodule/modes/gcm_nohw.c",
"src/crypto/fipsmodule/modes/ofb.c",
"src/crypto/fipsmodule/modes/polyval.c",
"src/crypto/fipsmodule/rand/ctrdrbg.c",
"src/crypto/fipsmodule/rand/rand.c",
"src/crypto/fipsmodule/rand/urandom.c",
"src/crypto/fipsmodule/rsa/blinding.c",
"src/crypto/fipsmodule/rsa/padding.c",
"src/crypto/fipsmodule/rsa/rsa.c",
"src/crypto/fipsmodule/rsa/rsa_impl.c",
"src/crypto/fipsmodule/self_check/self_check.c",
"src/crypto/fipsmodule/sha/sha1-altivec.c",
"src/crypto/fipsmodule/sha/sha1.c",
"src/crypto/fipsmodule/sha/sha256.c",
"src/crypto/fipsmodule/sha/sha512.c",
"src/crypto/fipsmodule/tls/kdf.c",
"src/third_party/fiat/p256.c",
]
ssl_internal_headers = [
"src/ssl/internal.h",
]
ssl_sources = [
"src/ssl/bio_ssl.cc",
"src/ssl/d1_both.cc",
"src/ssl/d1_lib.cc",
"src/ssl/d1_pkt.cc",
"src/ssl/d1_srtp.cc",
"src/ssl/dtls_method.cc",
"src/ssl/dtls_record.cc",
"src/ssl/handoff.cc",
"src/ssl/handshake.cc",
"src/ssl/handshake_client.cc",
"src/ssl/handshake_server.cc",
"src/ssl/s3_both.cc",
"src/ssl/s3_lib.cc",
"src/ssl/s3_pkt.cc",
"src/ssl/ssl_aead_ctx.cc",
"src/ssl/ssl_asn1.cc",
"src/ssl/ssl_buffer.cc",
"src/ssl/ssl_cert.cc",
"src/ssl/ssl_cipher.cc",
"src/ssl/ssl_file.cc",
"src/ssl/ssl_key_share.cc",
"src/ssl/ssl_lib.cc",
"src/ssl/ssl_privkey.cc",
"src/ssl/ssl_session.cc",
"src/ssl/ssl_stat.cc",
"src/ssl/ssl_transcript.cc",
"src/ssl/ssl_versions.cc",
"src/ssl/ssl_x509.cc",
"src/ssl/t1_enc.cc",
"src/ssl/t1_lib.cc",
"src/ssl/tls13_both.cc",
"src/ssl/tls13_client.cc",
"src/ssl/tls13_enc.cc",
"src/ssl/tls13_server.cc",
"src/ssl/tls_method.cc",
"src/ssl/tls_record.cc",
]
crypto_headers = [
"src/include/openssl/aead.h",
"src/include/openssl/aes.h",
"src/include/openssl/arm_arch.h",
"src/include/openssl/asn1.h",
"src/include/openssl/asn1_mac.h",
"src/include/openssl/asn1t.h",
"src/include/openssl/base.h",
"src/include/openssl/base64.h",
"src/include/openssl/bio.h",
"src/include/openssl/blowfish.h",
"src/include/openssl/bn.h",
"src/include/openssl/buf.h",
"src/include/openssl/buffer.h",
"src/include/openssl/bytestring.h",
"src/include/openssl/cast.h",
"src/include/openssl/chacha.h",
"src/include/openssl/cipher.h",
"src/include/openssl/cmac.h",
"src/include/openssl/conf.h",
"src/include/openssl/cpu.h",
"src/include/openssl/crypto.h",
"src/include/openssl/curve25519.h",
"src/include/openssl/des.h",
"src/include/openssl/dh.h",
"src/include/openssl/digest.h",
"src/include/openssl/dsa.h",
"src/include/openssl/e_os2.h",
"src/include/openssl/ec.h",
"src/include/openssl/ec_key.h",
"src/include/openssl/ecdh.h",
"src/include/openssl/ecdsa.h",
"src/include/openssl/engine.h",
"src/include/openssl/err.h",
"src/include/openssl/evp.h",
"src/include/openssl/ex_data.h",
"src/include/openssl/hkdf.h",
"src/include/openssl/hmac.h",
"src/include/openssl/hrss.h",
"src/include/openssl/is_boringssl.h",
"src/include/openssl/lhash.h",
"src/include/openssl/md4.h",
"src/include/openssl/md5.h",
"src/include/openssl/mem.h",
"src/include/openssl/nid.h",
"src/include/openssl/obj.h",
"src/include/openssl/obj_mac.h",
"src/include/openssl/objects.h",
"src/include/openssl/opensslconf.h",
"src/include/openssl/opensslv.h",
"src/include/openssl/ossl_typ.h",
"src/include/openssl/pem.h",
"src/include/openssl/pkcs12.h",
"src/include/openssl/pkcs7.h",
"src/include/openssl/pkcs8.h",
"src/include/openssl/poly1305.h",
"src/include/openssl/pool.h",
"src/include/openssl/rand.h",
"src/include/openssl/rc4.h",
"src/include/openssl/ripemd.h",
"src/include/openssl/rsa.h",
"src/include/openssl/safestack.h",
"src/include/openssl/sha.h",
"src/include/openssl/siphash.h",
"src/include/openssl/span.h",
"src/include/openssl/stack.h",
"src/include/openssl/thread.h",
"src/include/openssl/type_check.h",
"src/include/openssl/x509.h",
"src/include/openssl/x509_vfy.h",
"src/include/openssl/x509v3.h",
]
crypto_internal_headers = [
"src/crypto/asn1/asn1_locl.h",
"src/crypto/bio/internal.h",
"src/crypto/bytestring/internal.h",
"src/crypto/chacha/internal.h",
"src/crypto/cipher_extra/internal.h",
"src/crypto/conf/conf_def.h",
"src/crypto/conf/internal.h",
"src/crypto/cpu-arm-linux.h",
"src/crypto/err/internal.h",
"src/crypto/evp/internal.h",
"src/crypto/fipsmodule/aes/internal.h",
"src/crypto/fipsmodule/bn/internal.h",
"src/crypto/fipsmodule/bn/rsaz_exp.h",
"src/crypto/fipsmodule/cipher/internal.h",
"src/crypto/fipsmodule/delocate.h",
"src/crypto/fipsmodule/des/internal.h",
"src/crypto/fipsmodule/digest/internal.h",
"src/crypto/fipsmodule/digest/md32_common.h",
"src/crypto/fipsmodule/ec/internal.h",
"src/crypto/fipsmodule/ec/p256-x86_64-table.h",
"src/crypto/fipsmodule/ec/p256-x86_64.h",
"src/crypto/fipsmodule/md5/internal.h",
"src/crypto/fipsmodule/modes/internal.h",
"src/crypto/fipsmodule/rand/internal.h",
"src/crypto/fipsmodule/rsa/internal.h",
"src/crypto/fipsmodule/sha/internal.h",
"src/crypto/fipsmodule/tls/internal.h",
"src/crypto/hrss/internal.h",
"src/crypto/internal.h",
"src/crypto/obj/obj_dat.h",
"src/crypto/pkcs7/internal.h",
"src/crypto/pkcs8/internal.h",
"src/crypto/poly1305/internal.h",
"src/crypto/pool/internal.h",
"src/crypto/x509/charmap.h",
"src/crypto/x509/internal.h",
"src/crypto/x509/vpm_int.h",
"src/crypto/x509v3/ext_dat.h",
"src/crypto/x509v3/internal.h",
"src/crypto/x509v3/pcy_int.h",
"src/third_party/fiat/curve25519_32.h",
"src/third_party/fiat/curve25519_64.h",
"src/third_party/fiat/curve25519_tables.h",
"src/third_party/fiat/internal.h",
"src/third_party/fiat/p256_32.h",
"src/third_party/fiat/p256_64.h",
]
crypto_sources = [
"err_data.c",
"src/crypto/asn1/a_bitstr.c",
"src/crypto/asn1/a_bool.c",
"src/crypto/asn1/a_d2i_fp.c",
"src/crypto/asn1/a_dup.c",
"src/crypto/asn1/a_enum.c",
"src/crypto/asn1/a_gentm.c",
"src/crypto/asn1/a_i2d_fp.c",
"src/crypto/asn1/a_int.c",
"src/crypto/asn1/a_mbstr.c",
"src/crypto/asn1/a_object.c",
"src/crypto/asn1/a_octet.c",
"src/crypto/asn1/a_print.c",
"src/crypto/asn1/a_strnid.c",
"src/crypto/asn1/a_time.c",
"src/crypto/asn1/a_type.c",
"src/crypto/asn1/a_utctm.c",
"src/crypto/asn1/a_utf8.c",
"src/crypto/asn1/asn1_lib.c",
"src/crypto/asn1/asn1_par.c",
"src/crypto/asn1/asn_pack.c",
"src/crypto/asn1/f_enum.c",
"src/crypto/asn1/f_int.c",
"src/crypto/asn1/f_string.c",
"src/crypto/asn1/tasn_dec.c",
"src/crypto/asn1/tasn_enc.c",
"src/crypto/asn1/tasn_fre.c",
"src/crypto/asn1/tasn_new.c",
"src/crypto/asn1/tasn_typ.c",
"src/crypto/asn1/tasn_utl.c",
"src/crypto/asn1/time_support.c",
"src/crypto/base64/base64.c",
"src/crypto/bio/bio.c",
"src/crypto/bio/bio_mem.c",
"src/crypto/bio/connect.c",
"src/crypto/bio/fd.c",
"src/crypto/bio/file.c",
"src/crypto/bio/hexdump.c",
"src/crypto/bio/pair.c",
"src/crypto/bio/printf.c",
"src/crypto/bio/socket.c",
"src/crypto/bio/socket_helper.c",
"src/crypto/bn_extra/bn_asn1.c",
"src/crypto/bn_extra/convert.c",
"src/crypto/buf/buf.c",
"src/crypto/bytestring/asn1_compat.c",
"src/crypto/bytestring/ber.c",
"src/crypto/bytestring/cbb.c",
"src/crypto/bytestring/cbs.c",
"src/crypto/bytestring/unicode.c",
"src/crypto/chacha/chacha.c",
"src/crypto/cipher_extra/cipher_extra.c",
"src/crypto/cipher_extra/derive_key.c",
"src/crypto/cipher_extra/e_aesccm.c",
"src/crypto/cipher_extra/e_aesctrhmac.c",
"src/crypto/cipher_extra/e_aesgcmsiv.c",
"src/crypto/cipher_extra/e_chacha20poly1305.c",
"src/crypto/cipher_extra/e_null.c",
"src/crypto/cipher_extra/e_rc2.c",
"src/crypto/cipher_extra/e_rc4.c",
"src/crypto/cipher_extra/e_tls.c",
"src/crypto/cipher_extra/tls_cbc.c",
"src/crypto/cmac/cmac.c",
"src/crypto/conf/conf.c",
"src/crypto/cpu-aarch64-fuchsia.c",
"src/crypto/cpu-aarch64-linux.c",
"src/crypto/cpu-arm-linux.c",
"src/crypto/cpu-arm.c",
"src/crypto/cpu-intel.c",
"src/crypto/cpu-ppc64le.c",
"src/crypto/crypto.c",
"src/crypto/curve25519/spake25519.c",
"src/crypto/dh/check.c",
"src/crypto/dh/dh.c",
"src/crypto/dh/dh_asn1.c",
"src/crypto/dh/params.c",
"src/crypto/digest_extra/digest_extra.c",
"src/crypto/dsa/dsa.c",
"src/crypto/dsa/dsa_asn1.c",
"src/crypto/ec_extra/ec_asn1.c",
"src/crypto/ec_extra/ec_derive.c",
"src/crypto/ecdh_extra/ecdh_extra.c",
"src/crypto/ecdsa_extra/ecdsa_asn1.c",
"src/crypto/engine/engine.c",
"src/crypto/err/err.c",
"src/crypto/evp/digestsign.c",
"src/crypto/evp/evp.c",
"src/crypto/evp/evp_asn1.c",
"src/crypto/evp/evp_ctx.c",
"src/crypto/evp/p_dsa_asn1.c",
"src/crypto/evp/p_ec.c",
"src/crypto/evp/p_ec_asn1.c",
"src/crypto/evp/p_ed25519.c",
"src/crypto/evp/p_ed25519_asn1.c",
"src/crypto/evp/p_rsa.c",
"src/crypto/evp/p_rsa_asn1.c",
"src/crypto/evp/p_x25519.c",
"src/crypto/evp/p_x25519_asn1.c",
"src/crypto/evp/pbkdf.c",
"src/crypto/evp/print.c",
"src/crypto/evp/scrypt.c",
"src/crypto/evp/sign.c",
"src/crypto/ex_data.c",
"src/crypto/fipsmodule/bcm.c",
"src/crypto/fipsmodule/fips_shared_support.c",
"src/crypto/fipsmodule/is_fips.c",
"src/crypto/hkdf/hkdf.c",
"src/crypto/hrss/hrss.c",
"src/crypto/lhash/lhash.c",
"src/crypto/mem.c",
"src/crypto/obj/obj.c",
"src/crypto/obj/obj_xref.c",
"src/crypto/pem/pem_all.c",
"src/crypto/pem/pem_info.c",
"src/crypto/pem/pem_lib.c",
"src/crypto/pem/pem_oth.c",
"src/crypto/pem/pem_pk8.c",
"src/crypto/pem/pem_pkey.c",
"src/crypto/pem/pem_x509.c",
"src/crypto/pem/pem_xaux.c",
"src/crypto/pkcs7/pkcs7.c",
"src/crypto/pkcs7/pkcs7_x509.c",
"src/crypto/pkcs8/p5_pbev2.c",
"src/crypto/pkcs8/pkcs8.c",
"src/crypto/pkcs8/pkcs8_x509.c",
"src/crypto/poly1305/poly1305.c",
"src/crypto/poly1305/poly1305_arm.c",
"src/crypto/poly1305/poly1305_vec.c",
"src/crypto/pool/pool.c",
"src/crypto/rand_extra/deterministic.c",
"src/crypto/rand_extra/forkunsafe.c",
"src/crypto/rand_extra/fuchsia.c",
"src/crypto/rand_extra/rand_extra.c",
"src/crypto/rand_extra/windows.c",
"src/crypto/rc4/rc4.c",
"src/crypto/refcount_c11.c",
"src/crypto/refcount_lock.c",
"src/crypto/rsa_extra/rsa_asn1.c",
"src/crypto/rsa_extra/rsa_print.c",
"src/crypto/siphash/siphash.c",
"src/crypto/stack/stack.c",
"src/crypto/thread.c",
"src/crypto/thread_none.c",
"src/crypto/thread_pthread.c",
"src/crypto/thread_win.c",
"src/crypto/x509/a_digest.c",
"src/crypto/x509/a_sign.c",
"src/crypto/x509/a_strex.c",
"src/crypto/x509/a_verify.c",
"src/crypto/x509/algorithm.c",
"src/crypto/x509/asn1_gen.c",
"src/crypto/x509/by_dir.c",
"src/crypto/x509/by_file.c",
"src/crypto/x509/i2d_pr.c",
"src/crypto/x509/rsa_pss.c",
"src/crypto/x509/t_crl.c",
"src/crypto/x509/t_req.c",
"src/crypto/x509/t_x509.c",
"src/crypto/x509/t_x509a.c",
"src/crypto/x509/x509.c",
"src/crypto/x509/x509_att.c",
"src/crypto/x509/x509_cmp.c",
"src/crypto/x509/x509_d2.c",
"src/crypto/x509/x509_def.c",
"src/crypto/x509/x509_ext.c",
"src/crypto/x509/x509_lu.c",
"src/crypto/x509/x509_obj.c",
"src/crypto/x509/x509_r2x.c",
"src/crypto/x509/x509_req.c",
"src/crypto/x509/x509_set.c",
"src/crypto/x509/x509_trs.c",
"src/crypto/x509/x509_txt.c",
"src/crypto/x509/x509_v3.c",
"src/crypto/x509/x509_vfy.c",
"src/crypto/x509/x509_vpm.c",
"src/crypto/x509/x509cset.c",
"src/crypto/x509/x509name.c",
"src/crypto/x509/x509rset.c",
"src/crypto/x509/x509spki.c",
"src/crypto/x509/x_algor.c",
"src/crypto/x509/x_all.c",
"src/crypto/x509/x_attrib.c",
"src/crypto/x509/x_crl.c",
"src/crypto/x509/x_exten.c",
"src/crypto/x509/x_info.c",
"src/crypto/x509/x_name.c",
"src/crypto/x509/x_pkey.c",
"src/crypto/x509/x_pubkey.c",
"src/crypto/x509/x_req.c",
"src/crypto/x509/x_sig.c",
"src/crypto/x509/x_spki.c",
"src/crypto/x509/x_val.c",
"src/crypto/x509/x_x509.c",
"src/crypto/x509/x_x509a.c",
"src/crypto/x509v3/pcy_cache.c",
"src/crypto/x509v3/pcy_data.c",
"src/crypto/x509v3/pcy_lib.c",
"src/crypto/x509v3/pcy_map.c",
"src/crypto/x509v3/pcy_node.c",
"src/crypto/x509v3/pcy_tree.c",
"src/crypto/x509v3/v3_akey.c",
"src/crypto/x509v3/v3_akeya.c",
"src/crypto/x509v3/v3_alt.c",
"src/crypto/x509v3/v3_bcons.c",
"src/crypto/x509v3/v3_bitst.c",
"src/crypto/x509v3/v3_conf.c",
"src/crypto/x509v3/v3_cpols.c",
"src/crypto/x509v3/v3_crld.c",
"src/crypto/x509v3/v3_enum.c",
"src/crypto/x509v3/v3_extku.c",
"src/crypto/x509v3/v3_genn.c",
"src/crypto/x509v3/v3_ia5.c",
"src/crypto/x509v3/v3_info.c",
"src/crypto/x509v3/v3_int.c",
"src/crypto/x509v3/v3_lib.c",
"src/crypto/x509v3/v3_ncons.c",
"src/crypto/x509v3/v3_ocsp.c",
"src/crypto/x509v3/v3_pci.c",
"src/crypto/x509v3/v3_pcia.c",
"src/crypto/x509v3/v3_pcons.c",
"src/crypto/x509v3/v3_pku.c",
"src/crypto/x509v3/v3_pmaps.c",
"src/crypto/x509v3/v3_prn.c",
"src/crypto/x509v3/v3_purp.c",
"src/crypto/x509v3/v3_skey.c",
"src/crypto/x509v3/v3_sxnet.c",
"src/crypto/x509v3/v3_utl.c",
"src/third_party/fiat/curve25519.c",
]
tool_sources = [
"src/tool/args.cc",
"src/tool/ciphers.cc",
"src/tool/client.cc",
"src/tool/const.cc",
"src/tool/digest.cc",
"src/tool/file.cc",
"src/tool/generate_ed25519.cc",
"src/tool/genrsa.cc",
"src/tool/pkcs12.cc",
"src/tool/rand.cc",
"src/tool/server.cc",
"src/tool/sign.cc",
"src/tool/speed.cc",
"src/tool/tool.cc",
"src/tool/transport_common.cc",
]
tool_headers = [
"src/tool/internal.h",
"src/tool/transport_common.h",
]
crypto_sources_ios_aarch64 = [
"ios-aarch64/crypto/chacha/chacha-armv8.S",
"ios-aarch64/crypto/fipsmodule/aesv8-armx64.S",
"ios-aarch64/crypto/fipsmodule/armv8-mont.S",
"ios-aarch64/crypto/fipsmodule/ghash-neon-armv8.S",
"ios-aarch64/crypto/fipsmodule/ghashv8-armx64.S",
"ios-aarch64/crypto/fipsmodule/sha1-armv8.S",
"ios-aarch64/crypto/fipsmodule/sha256-armv8.S",
"ios-aarch64/crypto/fipsmodule/sha512-armv8.S",
"ios-aarch64/crypto/fipsmodule/vpaes-armv8.S",
"ios-aarch64/crypto/test/trampoline-armv8.S",
]
crypto_sources_ios_arm = [
"ios-arm/crypto/chacha/chacha-armv4.S",
"ios-arm/crypto/fipsmodule/aesv8-armx32.S",
"ios-arm/crypto/fipsmodule/armv4-mont.S",
"ios-arm/crypto/fipsmodule/bsaes-armv7.S",
"ios-arm/crypto/fipsmodule/ghash-armv4.S",
"ios-arm/crypto/fipsmodule/ghashv8-armx32.S",
"ios-arm/crypto/fipsmodule/sha1-armv4-large.S",
"ios-arm/crypto/fipsmodule/sha256-armv4.S",
"ios-arm/crypto/fipsmodule/sha512-armv4.S",
"ios-arm/crypto/fipsmodule/vpaes-armv7.S",
"ios-arm/crypto/test/trampoline-armv4.S",
]
crypto_sources_linux_aarch64 = [
"linux-aarch64/crypto/chacha/chacha-armv8.S",
"linux-aarch64/crypto/fipsmodule/aesv8-armx64.S",
"linux-aarch64/crypto/fipsmodule/armv8-mont.S",
"linux-aarch64/crypto/fipsmodule/ghash-neon-armv8.S",
"linux-aarch64/crypto/fipsmodule/ghashv8-armx64.S",
"linux-aarch64/crypto/fipsmodule/sha1-armv8.S",
"linux-aarch64/crypto/fipsmodule/sha256-armv8.S",
"linux-aarch64/crypto/fipsmodule/sha512-armv8.S",
"linux-aarch64/crypto/fipsmodule/vpaes-armv8.S",
"linux-aarch64/crypto/test/trampoline-armv8.S",
]
crypto_sources_linux_arm = [
"linux-arm/crypto/chacha/chacha-armv4.S",
"linux-arm/crypto/fipsmodule/aesv8-armx32.S",
"linux-arm/crypto/fipsmodule/armv4-mont.S",
"linux-arm/crypto/fipsmodule/bsaes-armv7.S",
"linux-arm/crypto/fipsmodule/ghash-armv4.S",
"linux-arm/crypto/fipsmodule/ghashv8-armx32.S",
"linux-arm/crypto/fipsmodule/sha1-armv4-large.S",
"linux-arm/crypto/fipsmodule/sha256-armv4.S",
"linux-arm/crypto/fipsmodule/sha512-armv4.S",
"linux-arm/crypto/fipsmodule/vpaes-armv7.S",
"linux-arm/crypto/test/trampoline-armv4.S",
"src/crypto/curve25519/asm/x25519-asm-arm.S",
"src/crypto/poly1305/poly1305_arm_asm.S",
]
crypto_sources_linux_ppc64le = [
"linux-ppc64le/crypto/fipsmodule/aesp8-ppc.S",
"linux-ppc64le/crypto/fipsmodule/ghashp8-ppc.S",
"linux-ppc64le/crypto/test/trampoline-ppc.S",
]
crypto_sources_linux_x86 = [
"linux-x86/crypto/chacha/chacha-x86.S",
"linux-x86/crypto/fipsmodule/aesni-x86.S",
"linux-x86/crypto/fipsmodule/bn-586.S",
"linux-x86/crypto/fipsmodule/co-586.S",
"linux-x86/crypto/fipsmodule/ghash-ssse3-x86.S",
"linux-x86/crypto/fipsmodule/ghash-x86.S",
"linux-x86/crypto/fipsmodule/md5-586.S",
"linux-x86/crypto/fipsmodule/sha1-586.S",
"linux-x86/crypto/fipsmodule/sha256-586.S",
"linux-x86/crypto/fipsmodule/sha512-586.S",
"linux-x86/crypto/fipsmodule/vpaes-x86.S",
"linux-x86/crypto/fipsmodule/x86-mont.S",
"linux-x86/crypto/test/trampoline-x86.S",
]
crypto_sources_linux_x86_64 = [
"linux-x86_64/crypto/chacha/chacha-x86_64.S",
"linux-x86_64/crypto/cipher_extra/aes128gcmsiv-x86_64.S",
"linux-x86_64/crypto/cipher_extra/chacha20_poly1305_x86_64.S",
"linux-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S",
"linux-x86_64/crypto/fipsmodule/aesni-x86_64.S",
"linux-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S",
"linux-x86_64/crypto/fipsmodule/ghash-x86_64.S",
"linux-x86_64/crypto/fipsmodule/md5-x86_64.S",
"linux-x86_64/crypto/fipsmodule/p256-x86_64-asm.S",
"linux-x86_64/crypto/fipsmodule/p256_beeu-x86_64-asm.S",
"linux-x86_64/crypto/fipsmodule/rdrand-x86_64.S",
"linux-x86_64/crypto/fipsmodule/rsaz-avx2.S",
"linux-x86_64/crypto/fipsmodule/sha1-x86_64.S",
"linux-x86_64/crypto/fipsmodule/sha256-x86_64.S",
"linux-x86_64/crypto/fipsmodule/sha512-x86_64.S",
"linux-x86_64/crypto/fipsmodule/vpaes-x86_64.S",
"linux-x86_64/crypto/fipsmodule/x86_64-mont.S",
"linux-x86_64/crypto/fipsmodule/x86_64-mont5.S",
"linux-x86_64/crypto/test/trampoline-x86_64.S",
"src/crypto/hrss/asm/poly_rq_mul.S",
]
crypto_sources_mac_x86 = [
"mac-x86/crypto/chacha/chacha-x86.S",
"mac-x86/crypto/fipsmodule/aesni-x86.S",
"mac-x86/crypto/fipsmodule/bn-586.S",
"mac-x86/crypto/fipsmodule/co-586.S",
"mac-x86/crypto/fipsmodule/ghash-ssse3-x86.S",
"mac-x86/crypto/fipsmodule/ghash-x86.S",
"mac-x86/crypto/fipsmodule/md5-586.S",
"mac-x86/crypto/fipsmodule/sha1-586.S",
"mac-x86/crypto/fipsmodule/sha256-586.S",
"mac-x86/crypto/fipsmodule/sha512-586.S",
"mac-x86/crypto/fipsmodule/vpaes-x86.S",
"mac-x86/crypto/fipsmodule/x86-mont.S",
"mac-x86/crypto/test/trampoline-x86.S",
]
crypto_sources_mac_x86_64 = [
"mac-x86_64/crypto/chacha/chacha-x86_64.S",
"mac-x86_64/crypto/cipher_extra/aes128gcmsiv-x86_64.S",
"mac-x86_64/crypto/cipher_extra/chacha20_poly1305_x86_64.S",
"mac-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S",
"mac-x86_64/crypto/fipsmodule/aesni-x86_64.S",
"mac-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S",
"mac-x86_64/crypto/fipsmodule/ghash-x86_64.S",
"mac-x86_64/crypto/fipsmodule/md5-x86_64.S",
"mac-x86_64/crypto/fipsmodule/p256-x86_64-asm.S",
"mac-x86_64/crypto/fipsmodule/p256_beeu-x86_64-asm.S",
"mac-x86_64/crypto/fipsmodule/rdrand-x86_64.S",
"mac-x86_64/crypto/fipsmodule/rsaz-avx2.S",
"mac-x86_64/crypto/fipsmodule/sha1-x86_64.S",
"mac-x86_64/crypto/fipsmodule/sha256-x86_64.S",
"mac-x86_64/crypto/fipsmodule/sha512-x86_64.S",
"mac-x86_64/crypto/fipsmodule/vpaes-x86_64.S",
"mac-x86_64/crypto/fipsmodule/x86_64-mont.S",
"mac-x86_64/crypto/fipsmodule/x86_64-mont5.S",
"mac-x86_64/crypto/test/trampoline-x86_64.S",
]
crypto_sources_win_x86 = [
"win-x86/crypto/chacha/chacha-x86.asm",
"win-x86/crypto/fipsmodule/aesni-x86.asm",
"win-x86/crypto/fipsmodule/bn-586.asm",
"win-x86/crypto/fipsmodule/co-586.asm",
"win-x86/crypto/fipsmodule/ghash-ssse3-x86.asm",
"win-x86/crypto/fipsmodule/ghash-x86.asm",
"win-x86/crypto/fipsmodule/md5-586.asm",
"win-x86/crypto/fipsmodule/sha1-586.asm",
"win-x86/crypto/fipsmodule/sha256-586.asm",
"win-x86/crypto/fipsmodule/sha512-586.asm",
"win-x86/crypto/fipsmodule/vpaes-x86.asm",
"win-x86/crypto/fipsmodule/x86-mont.asm",
"win-x86/crypto/test/trampoline-x86.asm",
]
crypto_sources_win_x86_64 = [
"win-x86_64/crypto/chacha/chacha-x86_64.asm",
"win-x86_64/crypto/cipher_extra/aes128gcmsiv-x86_64.asm",
"win-x86_64/crypto/cipher_extra/chacha20_poly1305_x86_64.asm",
"win-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.asm",
"win-x86_64/crypto/fipsmodule/aesni-x86_64.asm",
"win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm",
"win-x86_64/crypto/fipsmodule/ghash-x86_64.asm",
"win-x86_64/crypto/fipsmodule/md5-x86_64.asm",
"win-x86_64/crypto/fipsmodule/p256-x86_64-asm.asm",
"win-x86_64/crypto/fipsmodule/p256_beeu-x86_64-asm.asm",
"win-x86_64/crypto/fipsmodule/rdrand-x86_64.asm",
"win-x86_64/crypto/fipsmodule/rsaz-avx2.asm",
"win-x86_64/crypto/fipsmodule/sha1-x86_64.asm",
"win-x86_64/crypto/fipsmodule/sha256-x86_64.asm",
"win-x86_64/crypto/fipsmodule/sha512-x86_64.asm",
"win-x86_64/crypto/fipsmodule/vpaes-x86_64.asm",
"win-x86_64/crypto/fipsmodule/x86_64-mont.asm",
"win-x86_64/crypto/fipsmodule/x86_64-mont5.asm",
"win-x86_64/crypto/test/trampoline-x86_64.asm",
]
|
def possible_combination(string):
n = len(string)
count = [0] * (n + 1);
count[0] = 1;
count[1] = 1;
for i in range(2, n + 1):
count[i] = 0;
if (string[i - 1] > '0'):
count[i] = count[i - 1];
if (string[i - 2] == '1' or (string[i - 2] == '2' and string[i - 1] < '7')):
count[i] += count[i - 2];
return count[n];
print(possible_combination(input()))
|
'''
Description:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Input: root node of binary tree
Output: convert binary tree to right-skewed linked list
"""
cur_node = root
while cur_node:
if cur_node.left:
# locate the rightmost anchor node of left sub-tree
rihgtmost_of_left_subtree = cur_node.left
while rihgtmost_of_left_subtree.right:
rihgtmost_of_left_subtree = rihgtmost_of_left_subtree.right
# flatten the right sub-tree to linked lsit and append to anchor node
rihgtmost_of_left_subtree.right = cur_node.right
# flatten the left sub-tree to right-skewed linked list
cur_node.right = cur_node.left
cur_node.left = None
cur_node = cur_node.right
# n : the number of node in binary tree
## Time Compleity: O( n )
#
# The overhead in time is the cost of DFS traverdal, which is of O( n ).
## Space Complexity: O( n )
#
# The overhead in space is the dpeth of recursion call stack, which is of O( n ).
def print_right_skewed_linked_list( node:TreeNode ):
if node:
print( f'{node.val} ', end = '')
print_right_skewed_linked_list( node.right )
def test_bench():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(6)
Solution().flatten(root)
# expected output:
'''
1 2 3 4 5 6
'''
print_right_skewed_linked_list( root )
return
if __name__ == '__main__':
test_bench() |
"""Constants for the Template Platform Components."""
CONF_AVAILABILITY_TEMPLATE = "availability_template"
DOMAIN = "template"
PLATFORM_STORAGE_KEY = "template_platforms"
PLATFORMS = [
"alarm_control_panel",
"binary_sensor",
"cover",
"fan",
"light",
"lock",
"sensor",
"switch",
"vacuum",
"weather",
]
|
###############################################################################
# Copyright (c) 2019, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory
# Written by the Merlin dev team, listed in the CONTRIBUTORS file.
# <[email protected]>
#
# LLNL-CODE-797170
# All rights reserved.
# This file is part of Merlin, Version: 1.5.1.
#
# For details, see https://github.com/LLNL/merlin.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
###############################################################################
DESCRIPTION = {"description": {}}
BATCH = {"batch": {"type": "local", "dry_run": False, "shell": "/bin/bash"}}
ENV = {"env": {"variables": {}}}
STUDY_STEP_RUN = {"task_queue": "merlin", "shell": "/bin/bash", "max_retries": 30}
PARAMETER = {"global.parameters": {}}
MERLIN = {
"merlin": {
"resources": {"task_server": "celery", "overlap": False, "workers": None},
"samples": None,
}
}
WORKER = {"steps": ["all"], "nodes": None, "batch": None}
SAMPLES = {
"generate": {"cmd": "echo 'Insert sample-generating command here'"},
"level_max_dirs": 25,
}
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 20:20:20 2020
@authors: Amal Htait and Leif Azzopardi
For license information, see LICENSE.TXT
"""
class SentimentIntensityAggregator:
"""
Apply an aggregation to a list of similarity scores.
"""
def __init__(self):
pass
def agg_score(self, pos_dists, neg_dists):
"""
Return a float as a score of aggregated similarity scores with positive and negative seeds lists.
:param pos_dists: a list of similarity scores with pos seeds
:param neg_dists: a list of similarity scores with neg seeds
:return: a score (float)
"""
pass
class SumSentimentIntensityAggregator(SentimentIntensityAggregator):
"""
Apply an sum aggregation to a list of similarity scores.
"""
def agg_score(self, pos_dists, neg_dists):
pos_score=0.0
neg_score=0.0
dists_size = len(pos_dists)
for i in range(dists_size):
pos_score=pos_score + (1.0-pos_dists[i])
neg_score=neg_score + (1.0-neg_dists[i])
score=pos_score - neg_score
return score
class AvgSentimentIntensityAggregator(SentimentIntensityAggregator):
"""
Apply an average aggregation to a list of similarity scores.
"""
def agg_score(self, pos_dists, neg_dists):
pos_sum = 0.0
neg_sum = 0.0
dists_size = len(pos_dists)
for i in range(dists_size):
pos_sum = pos_sum + (1.0-pos_dists[i])
neg_sum = neg_sum + (1.0-neg_dists[i])
pos_score = pos_sum/dists_size
neg_score = neg_sum/dists_size
score = pos_score - neg_score
return score
class MaxSentimentIntensityAggregator(SentimentIntensityAggregator):
"""
Selecting the maximum value in a list of similarity scores.
"""
def agg_score(self, pos_dists, neg_dists):
pos_score = (1.0-(min(pos_dists)))
neg_score = (1.0-(min(neg_dists)))
score = pos_score - neg_score
return score
|
# Metadata Create Tests
def test0_metadata_create():
return
# Metadata Getters Tests
def test0_metadata_name():
return
def test0_metadata_ename():
return
def test0_metadata_season():
return
def test0_metadata_episode():
return
def test0_metadata_quality():
return
def test0_metadata_extension():
return
def test0_metadata_year():
return
def tets0_metadata_fflag():
return
# ExtendendMetadata Create Tests
def test0_extendedmetadata_create():
return
# ExtendendMetadata Getters Tests
def test0_extendedmetadata_genre():
return |
#
# @lc app=leetcode.cn id=374 lang=python3
#
# [374] 猜数字大小
#
# https://leetcode-cn.com/problems/guess-number-higher-or-lower/description/
#
# algorithms
# Easy (50.55%)
# Likes: 145
# Dislikes: 0
# Total Accepted: 65.9K
# Total Submissions: 130.4K
# Testcase Example: '10\n6'
#
# 猜数字游戏的规则如下:
#
#
# 每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
# 如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。
#
#
# 你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或 0):
#
#
# -1:我选出的数字比你猜的数字小 pick < num
# 1:我选出的数字比你猜的数字大 pick > num
# 0:我选出的数字和你猜的数字一样。恭喜!你猜对了!pick == num
#
#
# 返回我选出的数字。
#
#
#
# 示例 1:
#
#
# 输入:n = 10, pick = 6
# 输出:6
#
#
# 示例 2:
#
#
# 输入:n = 1, pick = 1
# 输出:1
#
#
# 示例 3:
#
#
# 输入:n = 2, pick = 1
# 输出:1
#
#
# 示例 4:
#
#
# 输入:n = 2, pick = 2
# 输出:2
#
#
#
#
# 提示:
#
#
# 1
# 1
#
#
#
# @lc code=start
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
left, right = 1, n
while left < right:
mid = (right + left) >> 1
if guess(mid) <= 0:
right = mid
else:
left = mid + 1
return left
# @lc code=end
|
# coding: utf-8
# Author: zhao-zh10
# The function localize takes the following arguments:
#
# colors:
# 2D list, each entry either 'R' (for red cell) or 'G' (for green cell). The environment is cyclic.
#
# measurements:
# list of measurements taken by the robot, each entry either 'R' or 'G'
#
# motions:
# list of actions taken by the robot, each entry of the form [dy,dx],
# where dx refers to the change in the x-direction (positive meaning
# movement to the right) and dy refers to the change in the y-direction
# (positive meaning movement downward)
# NOTE: the *first* coordinate is change in y; the *second* coordinate is
# change in x
#
# sensor_right:
# float between 0 and 1, giving the probability that any given
# measurement is correct; the probability that the measurement is
# incorrect is 1-sensor_right
#
# p_move:
# float between 0 and 1, giving the probability that any given movement
# command takes place; the probability that the movement command fails
# (and the robot remains still) is 1-p_move; the robot will NOT overshoot
# its destination in this exercise
#
# The function should RETURN (not just show or print) a 2D list (of the same
# dimensions as colors) that gives the probabilities that the robot occupies
# each cell in the world.
#
# Compute the probabilities by assuming the robot initially has a uniform
# probability of being in any cell.
#
# Also assume that at each step, the robot:
# 1) first makes a movement,
# 2) then takes a measurement.
#
# Motion:
# [0,0] - stay
# [0,1] - right
# [0,-1] - left
# [1,0] - down
# [-1,0] - up
# For the purpose of this homework assume that the robot can move only left, right, up, or down. It cannot move diagonally.
# Also, for this assignment, the robot will never overshoot its destination square; it will either make the movement or it will remain stationary.
def localize(colors,measurements,motions,sensor_right,p_move):
# initializes p to a uniform distribution over a grid of the same dimensions as colors
pinit = 1.0 / float(len(colors)) / float(len(colors[0]))
p = [[pinit for col in range(len(colors[0]))] for row in range(len(colors))]
assert(len(motions) == len(measurements))
for i in range(len(motions)):
p = move(p, motions[i], p_move)
p = sense(p, colors, measurements[i], sensor_right)
return p
def show(p):
rows = ['[' + ','.join(map(lambda x: '{0:.5f}'.format(x),r)) + ']' for r in p]
print('[' + ',\n '.join(rows) + ']')
def sense(probability, colors, measurement, sensor_right):
prob = [[0.0 for col in range(len(colors[0]))] for row in range(len(colors))]
sum_prob = 0.0
sensor_wrong = 1.0 - sensor_right
for i in range(len(colors)):
for j in range(len(colors[0])):
hit = (measurement == colors[i][j])
prob[i][j] = probability[i][j] * (hit * sensor_right + (1 - hit) * sensor_wrong)
sum_prob += prob[i][j]
for i in range(len(colors)):
for j in range(len(colors[0])):
prob[i][j] /= sum_prob
return prob
def move(probability, motion, p_move):
dy, dx = motion[0], motion[1]
prob = [[0.0 for col in range(len(colors[0]))] for row in range(len(colors))]
p_stay = 1.0 - p_move
for i in range(len(colors)):
for j in range(len(colors[0])):
prob[i][j] = probability[i][j] * p_stay + probability[(i-dy)%len(colors)][(j-dx)%len(colors[0])] * p_move
return prob
if __name__ == '__main__':
#################################################################################
#Test Case
# # test 1
# colors = [['G', 'G', 'G'],
# ['G', 'R', 'G'],
# ['G', 'G', 'G']]
# measurements = ['R']
# motions = [[0,0]]
# sensor_right = 1.0
# p_move = 1.0
# p = localize(colors,measurements,motions,sensor_right,p_move)
# correct_answer = (
# [[0.0, 0.0, 0.0],
# [0.0, 1.0, 0.0],
# [0.0, 0.0, 0.0]])
# show(p)
# # test 2
# colors = [['G', 'G', 'G'],
# ['G', 'R', 'R'],
# ['G', 'G', 'G']]
# measurements = ['R']
# motions = [[0,0]]
# sensor_right = 1.0
# p_move = 1.0
# p = localize(colors,measurements,motions,sensor_right,p_move)
# correct_answer = (
# [[0.0, 0.0, 0.0],
# [0.0, 0.5, 0.5],
# [0.0, 0.0, 0.0]])
# show(p)
# # test 3
# colors = [['G', 'G', 'G'],
# ['G', 'R', 'R'],
# ['G', 'G', 'G']]
# measurements = ['R']
# motions = [[0,0]]
# sensor_right = 0.8
# p_move = 1.0
# p = localize(colors,measurements,motions,sensor_right,p_move)
# correct_answer = (
# [[0.06666666666, 0.06666666666, 0.06666666666],
# [0.06666666666, 0.26666666666, 0.26666666666],
# [0.06666666666, 0.06666666666, 0.06666666666]])
# show(p)
# # test 4
# colors = [['G', 'G', 'G'],
# ['G', 'R', 'R'],
# ['G', 'G', 'G']]
# measurements = ['R', 'R']
# motions = [[0,0], [0,1]]
# sensor_right = 0.8
# p_move = 1.0
# p = localize(colors,measurements,motions,sensor_right,p_move)
# correct_answer = (
# [[0.03333333333, 0.03333333333, 0.03333333333],
# [0.13333333333, 0.13333333333, 0.53333333333],
# [0.03333333333, 0.03333333333, 0.03333333333]])
# show(p)
# # test 5
# colors = [['G', 'G', 'G'],
# ['G', 'R', 'R'],
# ['G', 'G', 'G']]
# measurements = ['R', 'R']
# motions = [[0,0], [0,1]]
# sensor_right = 1.0
# p_move = 1.0
# p = localize(colors,measurements,motions,sensor_right,p_move)
# correct_answer = (
# [[0.0, 0.0, 0.0],
# [0.0, 0.0, 1.0],
# [0.0, 0.0, 0.0]])
# show(p)
# # test 6
# colors = [['G', 'G', 'G'],
# ['G', 'R', 'R'],
# ['G', 'G', 'G']]
# measurements = ['R', 'R']
# motions = [[0,0], [0,1]]
# sensor_right = 0.8
# p_move = 0.5
# p = localize(colors,measurements,motions,sensor_right,p_move)
# correct_answer = (
# [[0.0289855072, 0.0289855072, 0.0289855072],
# [0.0724637681, 0.2898550724, 0.4637681159],
# [0.0289855072, 0.0289855072, 0.0289855072]])
# show(p)
# # test 7
# colors = [['G', 'G', 'G'],
# ['G', 'R', 'R'],
# ['G', 'G', 'G']]
# measurements = ['R', 'R']
# motions = [[0,0], [0,1]]
# sensor_right = 1.0
# p_move = 0.5
# p = localize(colors,measurements,motions,sensor_right,p_move)
# correct_answer = (
# [[0.0, 0.0, 0.0],
# [0.0, 0.33333333, 0.66666666],
# [0.0, 0.0, 0.0]])
# show(p)
#############################################################
# For the following test case, your output should be
# [[0.01105, 0.02464, 0.06799, 0.04472, 0.02465],
# [0.00715, 0.01017, 0.08696, 0.07988, 0.00935],
# [0.00739, 0.00894, 0.11272, 0.35350, 0.04065],
# [0.00910, 0.00715, 0.01434, 0.04313, 0.03642]]
# (within a tolerance of +/- 0.001 for each entry)
colors = [['R','G','G','R','R'],['R','R','G','R','R'],['R','R','G','G','R'],['R','R','R','R','R']]
measurements = ['G','G','G','G','G']
motions = [[0,0],[0,1],[1,0],[1,0],[0,1]]
p = localize(colors,measurements,motions,sensor_right = 0.7, p_move = 0.8)
show(p) # displays your answer
|
def foo():
print("In utility.py ==> foo()")
if __name__=='__main__':
foo()
|
count=0
def permute(s,l,pos,n):
if pos>=n:
global count
count+=1
print(l)
for k in l:
print(s[k],end="")
print()
return
for i in range(n):
if i not in l[:pos]:
l[pos] = i
permute(s,l,pos+1,n)
s="shivank"
n=len(s)
l=[]
for i in range(n):
l.append(0)
permute(s,l,0,n)
print(count) |
# https://leetcode.com/problems/divide-two-integers/
#
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend == divisor:
return 1
isPositive = (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0)
dividend = dividend if dividend > 0 else -dividend
divisor = divisor if divisor > 0 else -divisor
ans = 0
divisors = {0: 0, 1: divisor}
divIdx = 1
while divisors[divIdx] < dividend:
i = divIdx
divIdx += divIdx
divisors[divIdx] = divisors[i] + divisors[i]
divisorsKeys = sorted(list(divisors.keys()))
divisorsIdx = len(divisorsKeys)-1
while divisorsIdx > 0 and dividend > 0:
while divisors[divisorsKeys[divisorsIdx]] > dividend:
divisorsIdx -= 1
dividend -= divisors[divisorsKeys[divisorsIdx]]
ans += divisorsKeys[divisorsIdx]
return ans if isPositive else -ans
s = Solution()
# print(s.divide(10,3))
print(s.divide(10,-2))
print(s.divide(100000000000,-2)) |
class DataClassFile():
def functionName1(self, parameter1):
""" One Function (takes a parameter) with one test function
(with single line comments) where outdated documentation
exists.
************************************************************
####UnitTest Specifications
- Given: Old specifications Given: line
When : Old specifications When: line
Then : Old specifications Then: line
`test_functionName1_test_case_3()`
************************************************************
@param string $parameter1 a String
@return string a String
"""
say = "say"
fu = "fu"
return say + " " + fu |
#!/usr/bin/env python3
def linearSearch(lst,item):
isFound = False
for x in range(0,len(lst)):
if item == lst[x]:
isFound = True
return "Item found at index " + str(x)
elif (x == len(lst)-1) and (isFound == False):
return "Item not found"
if __name__ == '__main__':
numLst = [11,45,6,8,1,2,9,45,32]
print(linearSearch(numLst,22))
|
line = input()
if line == 's3cr3t!P@ssw0rd':
print("Welcome")
else:
print("Wrong password!")
|
# Η εργασία που είχε μπεί στο τέλος, για το πρώτο τμήμα
my_list = []
# Λίστα με στοιχεία από το 1 μέχρι το 25
for i in range(25):
my_list.append(i)
# Αφαίρεση ζυγών αριθμών
for i in range(25):
if i % 2 == 0:
my_list.remove(i)
print(my_list)
|
#%%
def generate_range(min: int, max: int, step: int) -> None:
for i in range(min, max + 1, step):
print(i)
generate_range(2, 10, 2)
# %%
# %%
def generate_range(min: int, max: int, step: int) -> None:
i = min
while i <= max:
print(i)
i = i + step
generate_range(2, 10, 2)
|
begin_unit
comment|'# Copyright 2015 Red Hat Inc'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# http://www.apache.org/licenses/LICENSE-2.0'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Unless required by applicable law or agreed to in writing, software'
nl|'\n'
comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT'
nl|'\n'
comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the'
nl|'\n'
comment|'# License for the specific language governing permissions and limitations'
nl|'\n'
comment|'# under the License.'
nl|'\n'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# See blueprint backportable-db-migrations-icehouse'
nl|'\n'
comment|'# http://lists.openstack.org/pipermail/openstack-dev/2013-March/006827.html'
nl|'\n'
nl|'\n'
name|'from'
name|'sqlalchemy'
name|'import'
name|'MetaData'
op|','
name|'Table'
op|','
name|'Column'
op|','
name|'String'
op|','
name|'Index'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|upgrade
name|'def'
name|'upgrade'
op|'('
name|'migrate_engine'
op|')'
op|':'
newline|'\n'
indent|' '
name|'meta'
op|'='
name|'MetaData'
op|'('
name|'bind'
op|'='
name|'migrate_engine'
op|')'
newline|'\n'
nl|'\n'
comment|'# Add a new column to store PCI device parent address'
nl|'\n'
name|'pci_devices'
op|'='
name|'Table'
op|'('
string|"'pci_devices'"
op|','
name|'meta'
op|','
name|'autoload'
op|'='
name|'True'
op|')'
newline|'\n'
name|'shadow_pci_devices'
op|'='
name|'Table'
op|'('
string|"'shadow_pci_devices'"
op|','
name|'meta'
op|','
name|'autoload'
op|'='
name|'True'
op|')'
newline|'\n'
nl|'\n'
name|'parent_addr'
op|'='
name|'Column'
op|'('
string|"'parent_addr'"
op|','
name|'String'
op|'('
number|'12'
op|')'
op|','
name|'nullable'
op|'='
name|'True'
op|')'
newline|'\n'
nl|'\n'
name|'if'
name|'not'
name|'hasattr'
op|'('
name|'pci_devices'
op|'.'
name|'c'
op|','
string|"'parent_addr'"
op|')'
op|':'
newline|'\n'
indent|' '
name|'pci_devices'
op|'.'
name|'create_column'
op|'('
name|'parent_addr'
op|')'
newline|'\n'
dedent|''
name|'if'
name|'not'
name|'hasattr'
op|'('
name|'shadow_pci_devices'
op|'.'
name|'c'
op|','
string|"'parent_addr'"
op|')'
op|':'
newline|'\n'
indent|' '
name|'shadow_pci_devices'
op|'.'
name|'create_column'
op|'('
name|'parent_addr'
op|'.'
name|'copy'
op|'('
op|')'
op|')'
newline|'\n'
nl|'\n'
comment|'# Create index'
nl|'\n'
dedent|''
name|'parent_index'
op|'='
name|'Index'
op|'('
string|"'ix_pci_devices_compute_node_id_parent_addr_deleted'"
op|','
nl|'\n'
name|'pci_devices'
op|'.'
name|'c'
op|'.'
name|'compute_node_id'
op|','
nl|'\n'
name|'pci_devices'
op|'.'
name|'c'
op|'.'
name|'parent_addr'
op|','
nl|'\n'
name|'pci_devices'
op|'.'
name|'c'
op|'.'
name|'deleted'
op|')'
newline|'\n'
name|'parent_index'
op|'.'
name|'create'
op|'('
name|'migrate_engine'
op|')'
newline|'\n'
dedent|''
endmarker|''
end_unit
|
while True:
entrada = input()
if entrada == '0':
break
entrada = input()
joao = entrada.count('1')
maria = entrada.count('0')
print(f'Mary won {maria} times and John won {joao} times')
|
# Age avergage with floating points
# Var declarations
# Code
age1 = 10.0
age2 = 11.0
age3 = 13.0
age4 = 9.0
age5 = 12.0
result = (age1+age2+age3+age4+age5)/5.0
# Result
print(result)
|
'''
编辑距离
给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
示例 1:
输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
示例 2:
输入:word1 = "intention", word2 = "execution"
输出:5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')
提示:
0 <= word1.length, word2.length <= 500
word1 和 word2 由小写英文字母组成
'''
'''
思路:动态规划
设二维动态规划数组dp[m][n],
对于元素dp[i][j]的意思是截止word1的第i个字符和word2的第j字符,所用的最少编辑次数
有3种编辑方式:替换、删除、插入,根据3种编辑方式写出状态转移方程
如果word1[i]==word2[j],dp[i][j] = dp[i-1][j-1]
否则:dp[i][j] = min(dp[i-1][j-1]+1, dp[i-1][j]+1, dp[i][j-1]+1)
在上面的min里面,3个最优子结构的意思是替换1个字符,删除1个字符,添加1个字符
时间复杂度:O(mn)
空间复杂度:O(mn)
'''
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1): # 初始化边界初始值,j为0,如果要变换成word1,编辑次数就是字符串长度
dp[i][0] = i
for j in range(n + 1): # 初始化边界初始值,i为0,如果要变换成word2,编辑次数就是字符串长度
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
return dp[m][n]
s = Solution()
print(s.minDistance("horse", "ros"))
print(s.minDistance("intention", "execution"))
|
class Word:
def __init__(self, cells):
if not cells:
raise ValueError("word cannot contain 0 cells")
self.cell = cells[0]
self.rest = Word(cells[1:]) if cells[1:] else None
def _clear(self):
self.cell |= 0
if self.rest:
self.rest.clear()
def _succ(self):
self.cell += 1
if self.rest:
for if_ in (~self.cell).not_():
self.rest._succ()
def _pred(self):
if self.rest:
for if_ in (~self.cell).not_():
self.rest._pred()
self.cell -= 1
def _if(self):
if self.rest:
for if_ in self.cell | self.rest:
self.rest.clear()
yield
else:
for if_ in self.cell:
yield
def _while(self):
...
|
'''6. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already
ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged.
Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringly' '''
def add_string(str1):
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
#Reference: w3resource |
# basic tuple functionality
x = (1, 2, 3 * 4)
print(x)
try:
x[0] = 4
except TypeError:
print("TypeError")
print(x)
try:
x.append(5)
except AttributeError:
print("AttributeError")
print(x[1:])
print(x[:-1])
print(x[2:3])
print(x + (10, 100, 10000))
|
# from util.stack import Stack
"""
Given a array of number find the next greater no in the right of each element
Example- Input 12 15 22 09 07 02 18 23 27
Output 15 22 23 18 18 18 23 27 -1
"""
'''prints element and NGE pair for all elements of arr[] '''
def find_next_greater_ele_in_array(array):
"""
complexity O(n2)
:param array:
:return:
"""
temp_arr = []
for i in range(0, len(array)):
# if i == len(array) - 1:
# temp_arr.append(-1)
nxt = -1
for j in range(i + 1, len(array)):
if array[i] < array[j]:
nxt = array[j]
break
temp_arr.append(nxt)
print(array)
print(temp_arr)
class Stack(object):
@staticmethod
def create_stack():
stack = []
return stack
@staticmethod
def is_empty(stack):
return len(stack) == 0
@staticmethod
def push(stack, x):
stack.append(x)
@staticmethod
def pop(stack):
if Stack.is_empty(stack):
print("Error : stack underflow")
else:
return stack.pop()
def find_next_greater_ele_in_array_using_stack(array):
"""
complexity O(n)
:param array:
:return:
"""
stack = Stack.create_stack()
ele = 0
nxt = 0
temp = []
# push the first element to stack
Stack.push(stack, array[0])
# iterate for rest of the elements
for i in range(1, len(array), 1):
nxt = array[i]
if not Stack.is_empty(stack):
# if stack is not empty, then pop an element from stack
ele = Stack.pop(stack)
'''
If the popped element is smaller than next, then
keep popping while elements are smaller and stack is not empty
'''
while ele < nxt:
temp.append(nxt)
if Stack.is_empty(stack):
break
ele = Stack.pop(stack)
'''If element is greater than next, then push the element back '''
if ele > nxt:
Stack.push(stack, ele)
'''push next to stack so that we can find next greater for it '''
Stack.push(stack, nxt)
'''
After iterating over the loop, the remaining
elements in stack do not have the next greater
element, so print -1 for them
'''
while not Stack.is_empty(stack):
ele = Stack.pop(stack)
nxt = -1
temp.append(nxt)
print(array)
print(temp)
if __name__ == '__main__':
arr = [12, 15, 22, 9, 7, 2, 18, 23, 27]
find_next_greater_ele_in_array(arr)
find_next_greater_ele_in_array_using_stack(arr)
|
N = int(input())
list = []
for _ in range(N):
command = input().rstrip().split()
if "insert" in command:
i = int(command[1])
e = int(command[2])
list.insert(i, e)
elif "print" in command:
print(list)
elif "remove" in command:
i = int(command[1])
list.remove(i)
elif "append" in command:
i = int(command[1])
list.append(i)
elif "sort" in command:
list = sorted(list)
elif "pop" in command:
list.pop()
elif "reverse" in command:
reversed = []
for _ in range(len(list)):
reversed.append(list.pop())
list = reversed
else:
None
|
# Store all kinds of lookup table.
# # generate rsPoly lookup table.
# from qrcode import base
# def create_bytes(rs_blocks):
# for r in range(len(rs_blocks)):
# dcCount = rs_blocks[r].data_count
# ecCount = rs_blocks[r].total_count - dcCount
# rsPoly = base.Polynomial([1], 0)
# for i in range(ecCount):
# rsPoly = rsPoly * base.Polynomial([1, base.gexp(i)], 0)
# return ecCount, rsPoly
# rsPoly_LUT = {}
# for version in range(1,41):
# for error_correction in range(4):
# rs_blocks_list = base.rs_blocks(version, error_correction)
# ecCount, rsPoly = create_bytes(rs_blocks_list)
# rsPoly_LUT[ecCount]=rsPoly.num
# print(rsPoly_LUT)
# Result. Usage: input: ecCount, output: Polynomial.num
# e.g. rsPoly = base.Polynomial(LUT.rsPoly_LUT[ecCount], 0)
rsPoly_LUT = {
7: [1, 127, 122, 154, 164, 11, 68, 117],
10: [1, 216, 194, 159, 111, 199, 94, 95, 113, 157, 193],
13: [1, 137, 73, 227, 17, 177, 17, 52, 13, 46, 43, 83, 132, 120],
15: [1, 29, 196, 111, 163, 112, 74, 10, 105, 105, 139, 132, 151,
32, 134, 26],
16: [1, 59, 13, 104, 189, 68, 209, 30, 8, 163, 65, 41, 229, 98, 50, 36, 59],
17: [1, 119, 66, 83, 120, 119, 22, 197, 83, 249, 41, 143, 134, 85, 53, 125,
99, 79],
18: [1, 239, 251, 183, 113, 149, 175, 199, 215, 240, 220, 73, 82, 173, 75,
32, 67, 217, 146],
20: [1, 152, 185, 240, 5, 111, 99, 6, 220, 112, 150, 69, 36, 187, 22, 228,
198, 121, 121, 165, 174],
22: [1, 89, 179, 131, 176, 182, 244, 19, 189, 69, 40, 28, 137, 29, 123, 67,
253, 86, 218, 230, 26, 145, 245],
24: [1, 122, 118, 169, 70, 178, 237, 216, 102, 115, 150, 229, 73, 130, 72,
61, 43, 206, 1, 237, 247, 127, 217, 144, 117],
26: [1, 246, 51, 183, 4, 136, 98, 199, 152, 77, 56, 206, 24, 145, 40, 209,
117, 233, 42, 135, 68, 70, 144, 146, 77, 43, 94],
28: [1, 252, 9, 28, 13, 18, 251, 208, 150, 103, 174, 100, 41, 167, 12, 247,
56, 117, 119, 233, 127, 181, 100, 121, 147, 176, 74, 58, 197],
30: [1, 212, 246, 77, 73, 195, 192, 75, 98, 5, 70, 103, 177, 22, 217, 138,
51, 181, 246, 72, 25, 18, 46, 228, 74, 216, 195, 11, 106, 130, 150]
}
|
#!/bin/python3
# coding: utf-8
print ('input name: ')
name = input()
print ('input passwd: ')
passwd = input()
if name == 'A':
print('A')
if passwd == 'BB':
print('BB')
else:
print('Other!')
|
# Created by MechAviv
# Map ID :: 940001050
# Hidden Street : East Pantheon
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
OBJECT_1 = sm.sendNpcController(3000107, -2000, 20)
sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0)
sm.setSpeakerID(3000107)
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("There are Specters here as well?")
sm.setSpeakerID(3000107)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendSay("The situation might be more serious than I expected.")
sm.forcedInput(1)
sm.sendDelay(30)
sm.forcedInput(0)
sm.setSpeakerID(3000107)
sm.removeEscapeButton()
sm.setPlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("This isn't good. Go back and activate the shield as soon as possible.")
sm.setSpeakerID(3000107)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendSay("This is precisely when you need the most help. Even if you are Kaiser, you can't make it by yourself...")
sm.setSpeakerID(3000107)
sm.removeEscapeButton()
sm.setPlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendSay("Cartalion, you are a knight of Nova. Your first duty is always to the people of Nova. You must protect them, not me. As Kaiser, I fight for others, not the other way around.")
sm.setSpeakerID(3000107)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendSay("As you wish. Good luck out there.")
sm.sendDelay(1000)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(False, True, False, False)
sm.warp(940001100, 0)
|
subreddit = "quackers987" #CHANGE THIS
#Multiple subreddits can be specified by joining them with pluses, for example AskReddit+NoStupidQuestions.
fileLog = "imageRemoveLog.txt"
neededModPermissions = ['posts', 'flair']
removeSubmission = False
logFullInfo = False
checkResolution = True
minHeight = 800
minWidth = 800
lowResReply = f"Your submission has been removed as it was deemed to be low resolution (less than {minWidth} x {minHeight})."
lowResPostFlairID = "90320684-d8c4-11eb-8b59-0e83c0f77ef7" #CHANGE THIS
checkImgDomain = False
acceptedDomain = ["i.redd.it", "i.imgur.com"]
wrongDomainReply = f"Your submission has been removed as it was deemed to be posted to a disallowed domain. Allowed domains are {acceptedDomain}"
wrongDomainPostFlairID = "4f78c98a-d8d2-11eb-bf32-0e0b42d5cc2b" #CHANGE THIS |
# In Islandora 8 maps to Repository Item Content Type -> field_resource_type field
# The field_resource_type field is a pointer to the Resource Types taxonomy
#
class Genre:
def __init__(self):
self.drupal_fieldname = 'field_genre'
self.islandora_taxonomy = ['tags','genre']
self.mods_xpath = 'mods/genre'
self.dc_designator = 'type'
self.genre = ''
def set_genre(self, genre):
if isinstance(genre, str) and genre != '':
self.genre = genre
def get_genre(self):
return self.genre
def get_genre_fieldname(self):
return self.drupal_fieldname
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup ------------------------------------------------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information ---------------------------------------------------------------------------------------------
project = 'nRF Asset Tracker'
copyright = '2019-2021, Nordic Semiconductor ASA | nordicsemi.no'
author = 'Nordic Semiconductor ASA | nordicsemi.no'
# -- General configuration -------------------------------------------------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx_rtd_theme',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# These folders are copied to the documentation's HTML output
html_static_path = ['_static']
# These paths are either relative to html_static_path
# or fully qualified paths (eg. https://...)
html_css_files = [
'common.css',
]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -----------------------------------------------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
'logo_only': True
}
# Enable the "Edit in GitHub link within the header of each page.
html_context = {
'display_github': True,
'github_user': 'NordicSemiconductor',
'github_repo': 'asset-tracker-cloud-docs',
'github_version': 'saga'
}
master_doc = 'index'
suppress_warnings = ['ref.ref'] |
# 띄어쓰기, 들여쓰기 꼭 확인하세요!
list1 = ["갈비탕", "비빔밥", "냉면"]
list2 = ["짜장", "짬뽕", "꿔바로우", "깐풍기"]
list3 = ["파스타", "스테이크", "감바스"]
food = input("음식을 입력해주세요: ")
# 여기서부터 음식이 한식, 중식, 양식 중 어느 곳에 속하는지 판단하는 코드를 작성해주세요.
# 단, 조건식으로 list1, list2, list3에 포함되는지 여부를 이용하셔야 합니다!
if food in list1:
print("한식입니다.")
elif food in list2:
print("중식입니다.")
elif food in list3:
print("양식입니다.") |
# Problem: Missing Number
# Difficulty: Easy
# Category: Array
# Leetcode 268:https://leetcode.com/problems/missing-number/#/description
# Description:
"""
Given an sorted array containing n distinct numbers taken from 0, 1, 2, ..., n,
find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity.
Could you implement it using only constant extra space complexity?
"""
class Solution(object):
def bit_manipulation(self, nums):
missing = 0
i = 0
while i < len(nums):
missing = missing ^ i ^ nums[i]
i += 1
return missing ^ i
obj = Solution()
nums1 = [7, 5, 3, 4, 1, 0, 2]
nums2 = [3, 0, 1, 2]
print(obj.bit_manipulation(nums1))
print(obj.bit_manipulation(nums2)) |
'''Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
A) Quantos números foram digitados
B) A lista de valores, ordenada de forma decrescente
C) Se o valor 5 foi digitado e está ou não na lista.'''
lista = []
print('\033[1;33m-=\033[m' * 20)
while True:
lista.append(int(input('\033[36mDigite um valor:\033[m ')))
sair = ' '
while sair not in 'SN':
continuar = str(input('\033[37mContinuar [S/N]: \033[m')).upper().strip()[0]
sair = continuar
print('\033[1;33m-=\033[m' * 20)
if sair == 'N':
break
lista.sort(reverse=True)
print(f'\033[35mVocê digitou {len(lista)} elementos\033[m')
print(f'\033[34mOs valores em ordem decrescente são {lista}\033[m')
if 5 in lista:
print(f'\033[31mSim, o valor 5 esta na lista\033[m')
else:
print('\033[31mO valor 5 não faz parte da lista\033[m')
print('\033[1;33m-=\033[m' * 20)
print('\033[1;32mFIM\033[m')
|
while True:
num = int(input("Enter an even number: "))
if num % 2 == 0:
break
print("Thanks for following directions.")
|
#Tuple is a collection of ordered items. A tuple is immutable in nature.
#Refer https://docs.python.org/3/library/stdtypes.html?#tuples for more information
person= ("Susan","Christopher","Bill","Susan")
print(person)
print(person[1])
x= person.count("Susan")
print("Occurrence of 'Susan' in tuple is:" + str(x))
l=['apple','oranges']
print(tuple(l))
|
def get_sdm_query(query,lambda_t=0.8,lambda_o=0.1,lambda_u=0.1):
words = query.split()
if len(words)==1:
return f"#combine( {query} )"
terms = " ".join(words)
ordered = "".join([" #1({}) ".format(" ".join(bigram)) for bigram in zip(words,words[1:])])
unordered = "".join([" #uw8({}) ".format(" ".join(bigram)) for bigram in zip(words,words[1:])])
indri_query = f"#weight({lambda_t} #combine( {terms} ) {lambda_o} #combine({ordered}) {lambda_u} #combine({unordered}))"
return indri_query
if __name__ == "__main__":
query = "greta thunberg cross atlantic"
print(get_sdm_query(query))
|
"""Define common constants"""
JOB_COMMAND_START = "start"
JOB_COMMAND_CANCEL = "cancel"
JOB_COMMAND_RESTART = "restart"
JOB_COMMAND_PAUSE = "pause"
JOB_COMMAND_PAUSE_PAUSE = "pause"
JOB_COMMAND_PAUSE_RESUME = "resume"
JOB_COMMAND_PAUSE_TOGGLE = "toggle"
JOB_STATE_OPERATIONAL="Operational"
JOB_STATE_PRINTING="Printing"
JOB_STATE_PAUSING="Pausing"
JOB_STATE_PAUSED="Paused"
JOB_STATE_CANCELLING="Cancelling"
JOB_STATE_ERROR="Error"
JOB_STATE_OFFLINE="Offline" |
def encode_structure_fold(fold, tree):
def encode_node(node):
if node.is_leaf():
return fold.add('boxEncoder', node.box)
elif node.is_adj():
left = encode_node(node.left)
right = encode_node(node.right)
return fold.add('adjEncoder', left, right)
elif node.is_sym():
feature = encode_node(node.left)
sym = node.sym
return fold.add('symEncoder', feature, sym)
encoding = encode_node(tree.root)
return fold.add('sampleEncoder', encoding)
def decode_structure_fold(fold, feature, tree):
def decode_node_box(node, feature):
if node.is_leaf():
box = fold.add('boxDecoder', feature)
recon_loss = fold.add('boxLossEstimator', box, node.box)
label = fold.add('nodeClassifier', feature)
label_loss = fold.add('classifyLossEstimator', label, node.label)
return fold.add('vectorAdder', recon_loss, label_loss)
elif node.is_adj():
left, right = fold.add('adjDecoder', feature).split(2)
left_loss = decode_node_box(node.left, left)
right_loss = decode_node_box(node.right, right)
label = fold.add('nodeClassifier', feature)
label_loss = fold.add('classifyLossEstimator', label, node.label)
loss = fold.add('vectorAdder', left_loss, right_loss)
return fold.add('vectorAdder', loss, label_loss)
elif node.is_sym():
sym_gen, sym_param = fold.add('symDecoder', feature).split(2)
sym_param_loss = fold.add('symLossEstimator', sym_param, node.sym)
sym_gen_loss = decode_node_box(node.left, sym_gen)
label = fold.add('nodeClassifier', feature)
label_loss = fold.add('classifyLossEstimator', label, node.label)
loss = fold.add('vectorAdder', sym_gen_loss, sym_param_loss)
return fold.add('vectorAdder', loss, label_loss)
feature = fold.add('sampleDecoder', feature)
loss = decode_node_box(tree.root, feature)
return loss
|
# -*- coding: utf-8 -*-
class TrieNode:
def __init__(self):
self.children = {}
self.leaf = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
current = self.root
for char in word:
if char not in current.children:
current.children[char] = TrieNode()
current = current.children[char]
current.leaf = True
def minimumLengthEncoding(self):
result = 0
for child in self.root.children:
result += self.depthOfLeaves(self.root.children[child], 1)
return result
def depthOfLeaves(self, current, length):
if not current.children:
return length + 1
result = 0
for child in current.children:
result += self.depthOfLeaves(current.children[child], length + 1)
return result
class Solution:
def minimumLengthEncoding(self, words):
trie = Trie()
for word in words:
trie.insert(word[::-1])
return trie.minimumLengthEncoding()
if __name__ == '__main__':
solution = Solution()
assert 10 == solution.minimumLengthEncoding(['time', 'me', 'bell'])
assert 12 == solution.minimumLengthEncoding(['time', 'atime', 'btime'])
|
# Introduction to Computation and Programming Using Python (2021)
# Chapter 2, Finger Exercise 1
# Finger exercise: Write a program that examines three variables—
# x, y, and z—and prints the largest odd number among them. If none
# of them are odd, it should print the smallest value of the three.
x = 10 # largest, not odd
y = 5 # largest odd
z = 1 # smallest odd
numbers = [x, y, z]
numbers.sort()
biggestOdd = None # so anything is bigger
smallest = None # so anything is smaller
for n in numbers:
if n%2 == 1 and (biggestOdd == None or n > biggestOdd): #both biggest and odd
biggestOdd = n
if smallest == None or n < smallest: # the first number is the smallest, then it compares
smallest = n
if biggestOdd != None:
print("The largest odd number is", biggestOdd)
else:
print("There is no odd number. The smallest number is", smallest)
|
class PID:
"""PID controller."""
def __init__(self, Kp, Ti, Td, Imax):
self.Kp = Kp
self.Ti = Ti
self.Td = Td
self.Imax = Imax
self.clear()
def clear(self):
self.Cp = 0.0
self.Ci = 0.0
self.Cd = 0.0
self.previous_error = 0.0
def update(self, error, dt):
de = error - self.previous_error
self.previous_error = error
self.Cp = self.Kp * error
self.Ci += self.Kp * error * dt / self.Ti
self.Ci = min(self.Ci, self.Imax)
self.Ci = max(self.Ci, -self.Imax)
self.Cd = self.Kp * self.Td * de / dt
return self.Cp + self.Ci + self.Cd
|
class DecimalPointFloatConverter:
"""
Custom Django converter for URLs.
Parses floats with a decimal point (not with a comma!)
Allows for integers too, parses values in this or similar form:
- 100.0
- 100
Will NOT work for these forms:
- 100.000.000
- 100,0
"""
regex = "[0-9]*[.]?[0-9]*"
def to_python(self, value):
return float(value)
def to_url(self, value):
return str(value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.