content
stringlengths 7
1.05M
|
|---|
# Copyright 2020 Adobe. All rights reserved.
# This file is licensed to you 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 REPRESENTATIONS
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
load("@io_bazel_rules_docker//container:providers.bzl", "PushInfo")
load(
"@io_bazel_rules_docker//skylib:path.bzl",
_get_runfile_path = "runfile",
)
load("//skylib:providers.bzl", "ImagePushesInfo")
load("//skylib/workspace:aspect.bzl", "pushable_aspect")
def _file_to_runfile(ctx, file):
return file.owner.workspace_root or ctx.workspace_name + "/" + file.short_path
def _workspace_impl(ctx):
transitive_executables = []
transitive_runfiles = []
transitive_data = []
for t in ctx.attr.data:
transitive_data.append(t[DefaultInfo].files)
# flatten & 'uniquify' our list of asset files
data = depset(transitive = transitive_data).to_list()
runfiles = depset(transitive = transitive_runfiles).to_list()
files = []
tars = []
for src in ctx.attr.srcs:
tar = src.files.to_list()[0]
tars.append(tar)
rf = ctx.runfiles(files = runfiles + data + tars + ctx.files._bash_runfiles)
trans_img_pushes = []
if ctx.attr.push:
trans_img_pushes = depset(transitive = [
obj[ImagePushesInfo].image_pushes
for obj in ctx.attr.srcs
if ImagePushesInfo in obj
]).to_list()
files += [obj.files_to_run.executable for obj in trans_img_pushes]
for obj in trans_img_pushes:
rf = rf.merge(obj[DefaultInfo].default_runfiles)
ctx.actions.expand_template(
template = ctx.file._template,
substitutions = {
"%{workspace_tar_targets}": " ".join([json.encode(_file_to_runfile(ctx, t)) for t in tars]),
"%{push_targets}": " ".join([json.encode(_file_to_runfile(ctx, exe.files_to_run.executable)) for exe in trans_img_pushes]),
# "async $(rlocation metered/%s)" % exe.files_to_run.executable.short_path
},
output = ctx.outputs.executable,
)
return [
DefaultInfo(
files = depset(files),
runfiles = rf,
),
ImagePushesInfo(
image_pushes = depset(
transitive = [
obj[ImagePushesInfo].image_pushes
for obj in ctx.attr.srcs
if ImagePushesInfo in obj
],
),
),
]
workspace = rule(
implementation = _workspace_impl,
attrs = {
"srcs": attr.label_list(
# cfg = "host",
# allow_files = True,
aspects = [pushable_aspect],
),
"push": attr.bool(default = True),
"data": attr.label_list(
# cfg = "host",
allow_files = True,
),
"_template": attr.label(
default = Label("//skylib/workspace:workspace.sh.tpl"),
allow_single_file = True,
),
"_bash_runfiles": attr.label(
allow_files = True,
default = "@bazel_tools//tools/bash/runfiles",
),
},
executable = True,
)
|
def changecode():
file1=input("Enter your file name1")
file2=input("Enter your file name2")
with open(file1,"r") as a:
data_a = a.read()
with open(file2,"r") as b:
data_b = b.read()
with open(file1,"w") as a:
a.write(data_b)
with open(file2,"w") as b:
b.write(data_a)
changecode()
|
"""
1119. Remove Vowels from a String
Easy
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
Note:
S consists of lowercase English letters only.
1 <= S.length <= 1000
"""
vowels = set(['a', 'e', 'i', 'o', 'u'])
class Solution:
"""
could also assemble a list of characters and join at the end ...
"""
def removeVowels(self, S: str) -> str:
returned = ""
for ch in S:
if ch not in vowels:
returned += ch
return returned
if __name__ == "__main__":
s = Solution()
assert s.removeVowels("leetcodeisacommunityforcoders") == "ltcdscmmntyfrcdrs"
|
ll=range(5, 20, 5)
for i in ll:
print(i)
print (ll)
x = 'Python'
for i in range(len(x)) :
print(x[i])
|
# Function returns nth element of Padovan sequence
def padovan(n):
p = 0
if n > 2:
p = padovan(n-2) + padovan(n-3)
return p
else:
p = 1
return p
def main():
while True:
n = int(input("Enter a number: "))
if n >= 0:
break
print("Invalid number,try again")
print(f"P({n}) = {padovan(n)}")
main()
|
li = []
for x in range (21):
li.append(x)
print(li)
del(li[4])
print(li)
|
CHANGE_PW = {
'tags': ['회원가입 이후'],
'description': '비밀번호 변경',
'parameters': [
{
'name': 'Authorization',
'description': 'JWT Token',
'in': 'header',
'type': 'str'
},
{
'name': 'pw',
'description': '변경할 비밀번호',
'in': 'formData',
'type': 'str'
}
],
'responses': {
'201': {
'description': '비밀번호 변경 완료'
}
}
}
CHANGE_INFO = {
'tags': ['회원가입 이후'],
'description': '사용자 정보 변경',
'parameters': [
{
'name': 'Authorization',
'description': 'JWT Token',
'in': 'header',
'type': 'str'
},
{
'name': 'position',
'description': '변경할 포지션(학생: 0, 운전자: 1, 일반: 2)',
'in': 'formData',
'type': 'int'
},
{
'name': 'sex',
'description': '변경할 성별',
'in': 'formData',
'type': 'str'
},
{
'name': 'age',
'description': '변경할 나이',
'in': 'formData',
'type': 'int'
}
],
'responses': {
'201': {
'description': '사용자 정보 변경 완료'
}
}
}
|
routes = {
'{"command": "stats"}' : {"STATUS":[{"STATUS":"S","When":1553711204,"Code":70,"Msg":"BMMiner stats","Description":"bmminer 1.0.0"}],"STATS":[{"BMMiner":"2.0.0","Miner":"16.8.1.3","CompileTime":"Fri Nov 17 17:37:49 CST 2017","Type":"Antminer S9"},{"STATS":0,"ID":"BC50","Elapsed":248,"Calls":0,"Wait":0.000000,"Max":0.000000,"Min":99999999.000000,"GHS 5s":"13604.84","GHS av":13884.11,"miner_count":3,"frequency":"650","fan_num":2,"fan1":0,"fan2":0,"fan3":5880,"fan4":0,"fan5":0,"fan6":5760,"fan7":0,"fan8":0,"temp_num":3,"temp1":0,"temp2":0,"temp3":0,"temp4":0,"temp5":0,"temp6":62,"temp7":60,"temp8":60,"temp9":0,"temp10":0,"temp11":0,"temp12":0,"temp13":0,"temp14":0,"temp15":0,"temp16":0,"temp2_1":0,"temp2_2":0,"temp2_3":0,"temp2_4":0,"temp2_5":0,"temp2_6":77,"temp2_7":75,"temp2_8":75,"temp2_9":0,"temp2_10":0,"temp2_11":0,"temp2_12":0,"temp2_13":0,"temp2_14":0,"temp2_15":0,"temp2_16":0,"temp3_1":0,"temp3_2":0,"temp3_3":0,"temp3_4":0,"temp3_5":0,"temp3_6":0,"temp3_7":0,"temp3_8":0,"temp3_9":0,"temp3_10":0,"temp3_11":0,"temp3_12":0,"temp3_13":0,"temp3_14":0,"temp3_15":0,"temp3_16":0,"freq_avg1":0.00,"freq_avg2":0.00,"freq_avg3":0.00,"freq_avg4":0.00,"freq_avg5":0.00,"freq_avg6":642.06,"freq_avg7":606.00,"freq_avg8":645.77,"freq_avg9":0.00,"freq_avg10":0.00,"freq_avg11":0.00,"freq_avg12":0.00,"freq_avg13":0.00,"freq_avg14":0.00,"freq_avg15":0.00,"freq_avg16":0.00,"total_rateideal":13501.26,"total_freqavg":631.28,"total_acn":189,"total_rate":13604.84,"chain_rateideal1":0.00,"chain_rateideal2":0.00,"chain_rateideal3":0.00,"chain_rateideal4":0.00,"chain_rateideal5":0.00,"chain_rateideal6":4512.30,"chain_rateideal7":4352.29,"chain_rateideal8":4636.67,"chain_rateideal9":0.00,"chain_rateideal10":0.00,"chain_rateideal11":0.00,"chain_rateideal12":0.00,"chain_rateideal13":0.00,"chain_rateideal14":0.00,"chain_rateideal15":0.00,"chain_rateideal16":0.00,"temp_max":62,"Device Hardware%":0.0000,"no_matching_work":0,"chain_acn1":0,"chain_acn2":0,"chain_acn3":0,"chain_acn4":0,"chain_acn5":0,"chain_acn6":63,"chain_acn7":63,"chain_acn8":63,"chain_acn9":0,"chain_acn10":0,"chain_acn11":0,"chain_acn12":0,"chain_acn13":0,"chain_acn14":0,"chain_acn15":0,"chain_acn16":0,"chain_acs1":"","chain_acs2":"","chain_acs3":"","chain_acs4":"","chain_acs5":"","chain_acs6":" oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo","chain_acs7":" oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo","chain_acs8":" oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo","chain_acs9":"","chain_acs10":"","chain_acs11":"","chain_acs12":"","chain_acs13":"","chain_acs14":"","chain_acs15":"","chain_acs16":"","chain_hw1":0,"chain_hw2":0,"chain_hw3":0,"chain_hw4":0,"chain_hw5":0,"chain_hw6":0,"chain_hw7":0,"chain_hw8":0,"chain_hw9":0,"chain_hw10":0,"chain_hw11":0,"chain_hw12":0,"chain_hw13":0,"chain_hw14":0,"chain_hw15":0,"chain_hw16":0,"chain_rate1":"","chain_rate2":"","chain_rate3":"","chain_rate4":"","chain_rate5":"","chain_rate6":"4631.20","chain_rate7":"4279.31","chain_rate8":"4694.33","chain_rate9":"","chain_rate10":"","chain_rate11":"","chain_rate12":"","chain_rate13":"","chain_rate14":"","chain_rate15":"","chain_rate16":"","chain_xtime6":"{}","chain_xtime7":"{}","chain_xtime8":"{}","chain_offside_6":"0","chain_offside_7":"0","chain_offside_8":"0","chain_opencore_6":"1","chain_opencore_7":"1","chain_opencore_8":"1","miner_version":"16.8.1.3","miner_id":"80108c8c6880881c"}],"id":1},
'{"command": "pools"}' : {"STATUS":[{"STATUS":"S","When":1553711204,"Code":7,"Msg":"3 Pool(s)","Description":"bmminer 1.0.0"}],"POOLS":[{"POOL":0,"URL":"stratum+tcp://sha256.usa.nicehash.com:3334","Status":"Alive","Priority":0,"Quota":1,"Long Poll":"N","Getworks":12,"Accepted":0,"Rejected":0,"Discarded":137,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwAAAA","Last Share Time":"0","Diff":"500K","Diff1 Shares":0,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":True,"Stratum URL":"sha256.usa.nicehash.com","Has GBT":False,"Best Share":845408,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":1,"URL":"stratum+tcp://stratum.antpool.com:3333","Status":"Alive","Priority":1,"Quota":1,"Long Poll":"N","Getworks":1,"Accepted":0,"Rejected":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"antminer_1","Last Share Time":"0","Diff":"","Diff1 Shares":0,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":2,"URL":"stratum+tcp://cn.ss.btc.com:3333","Status":"Dead","Priority":2,"Quota":1,"Long Poll":"N","Getworks":0,"Accepted":0,"Rejected":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"antminer.1","Last Share Time":"0","Diff":"","Diff1 Shares":0,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0,"Pool Rejected%":0.0000,"Pool Stale%":0.0000}],"id":1}
}
|
"""
问题描述: 大家一定玩过“推箱子”这个经典的游戏。具体规则就是在一个N*M的地图上,
有1个玩家、1个箱子、1个目的地以及若干障碍,其余是空地。玩家可以往上下左右4个方
向移动,但是不能移动出地图或者移动到障碍里去。如果往这个方向移动推到了箱子,箱子
也会按这个方向移动一格,当然,箱子也不能被推出地图或推到障碍里。当箱子被推到目的
地以后,游戏目标达成。现在告诉你游戏开始是初始的地图布局,请你求出玩家最少需要移
动多少步才能够将游戏目标达成。
输入描述:
每个测试输入包含1个测试用例
第一行输入两个数字N,M表示地图的大小。其中0<N,M<=8。
接下来有N行,每行包含M个字符表示该行地图。其中 . 表示空地、X表示玩家、*表示箱子、
#表示障碍、@表示目的地。
每个地图必定包含1个玩家、1个箱子、1个目的地。
输出描述:
输出一个数字表示玩家最少需要移动多少步才能将游戏目标达成。当无论如何达成不了的时候,输出-1。
示例1
输入
4 4
....
..*@
....
.X..
6 6
...#..
......
#*##..
..##.#
..X...
.@#...
输出
3
11
"""
start = [-1] * 4 # 前两位表示箱子的起始位置,后两位表示玩家的位置
end = [-1] * 2
n, m = map(int, input().split())
mat = list()
for i in range(n):
line = input()
mat.append(line)
for j in range(len(line)):
# box pos
if line[j] == '*':
start[0], start[1] = i, j
# player pos
if line[j] == 'X':
start[2], start[3] = i, j
# dest pos
if line[j] == '@':
end[0], end[1] = i, j
# 四维表用以记录箱子的x,y及玩家的x,y
reach = [[[[-1 for _ in range(m)] for _ in range(n)] for _ in range(m)] for _ in range(n)]
queue = list()
queue.append(start)
direction = ((0, 1), (1, 0), (0, -1), (-1, 0))
reach[start[0]][start[1]][start[2]][start[3]] = 0
while len(queue):
cur = queue.pop(0)
if cur[0] == end[0] and cur[1] == end[1]:
print(reach[cur[0]][cur[1]][cur[2]][cur[3]])
break
# 可以往四个方向推
for i in range(4):
player_x = cur[2] + direction[i][0]
player_y = cur[3] + direction[i][1]
# 检查箱子和玩家位置是否合法
if 0 <= player_x < n and 0 <= player_y < m and mat[player_x][player_y] != '#':
# 检查玩家和箱子是否重合
if player_x == cur[0] and player_y == cur[1]:
# 重合的时候将箱子往同一个方向推并检查箱子状态是否合法
box_x, box_y = cur[0] + direction[i][0], cur[1] + direction[i][1]
if box_x < 0 or box_x >= n or box_y < 0 or box_y >= m or mat[box_x][box_y] == '#':
continue
else:
# 如果不重合则箱子位置不动
box_x, box_y = cur[0], cur[1]
# 判断该点是否已经遍历过
if reach[box_x][box_y][player_x][player_y] < 0:
queue.append([box_x, box_y, player_x, player_y])
reach[box_x][box_y][player_x][player_y] = reach[cur[0]][cur[1]][cur[2]][cur[3]] + 1
if cur[0] != end[0] or cur[1] != end[1]:
print(-1)
|
class DatabaseNotConnectedException(Exception):
"""This exception is raised when collection is accessed however database is
not connected.
"""
def __init__(self, message: str):
self.message = message
super().__init__(self.message)
|
def folder_to_dict(folder):
return {
'id': folder.folder_id,
'name': folder.name,
'class': folder.folder_class,
'total_count': folder.total_count,
'child_folder_count': folder.child_folder_count,
'unread_count': folder.unread_count
}
def item_to_dict(item, include_body=False):
result = {
'id': item.item_id,
'changekeyid': item.changekey,
'subject': item.subject,
'sensitivity': item.sensitivity,
'text_body': item.text_body,
'body': item.body,
'attachments': len(item.attachments),
'datetime_received': item.datetime_received.ewsformat() if item.datetime_received else None,
'categories': item.categories,
'importance': item.importance,
'is_draft': item.is_draft,
'datetime_sent': item.datetime_sent.ewsformat() if item.datetime_sent else None,
'datetime_created': item.datetime_created.ewsformat() if item.datetime_created else None,
'reminder_is_set': item.reminder_is_set,
'reminder_due_by': item.reminder_due_by.ewsformat() if item.reminder_due_by else None,
'reminder_minutes_before_start': item.reminder_minutes_before_start,
'last_modified_name': item.last_modified_name
}
if not include_body:
del result['body']
del result['text_body']
return result
|
# MVT设计模式,model-view-template
# model负责和数据库交互来获取model数据
# view相当于MVC中的Controller负责处理网络请求http response
# template相当于MVC中的View负责封装html,css,js等内置模板引擎
# 具体流程:客户端发出网页请求 --> View接受网络请求 --> 找mdel去数据库找数据 -->找回的model数据返回给view
# --> view可以直接返回无修饰的model原始数据给客户端 --> 或者找template去美化数据,添加css,html等,动态生成一个html文件返回给View
# --> View将动态生成的html返回给客户端, MVT中的View充当中间人,两头链接M和T
# django安装的时候会默认安装在一个公共的路径下,这样开发不同项目的时候,可能会用到不同版本的django,因为安装在公共陆空
# 这样就会版本覆盖,其他项目可能会产生版本不兼容的异常
# 所以安装django的时候会搭建虚拟环境,一个项目对应一个环境
"""
django的配置,直接使用pycharm专业版,在设置中解释器中使用pip安装django
1- 安装成功后,整体的使用类似于angular的使用方法,关键字django-admin
2- cd到对应的目录下,django-admin startproject 项目名称
_init_.py --> 项目初始化文件,表示该项目可以被当作一个package引入
settings.py --> 项目的整体配置文件,比如在这里关联Book这个app
urls.py --> 项目的url配置文件
wsgi.py --> 项目和WSGI兼容的Web服务器入口
manage.py --> 项目运行的入口,指定配置文件路径,里面包含main函数
3- cd到项目名称下面才可以: python manage.py startapp 应用名称 (创建应用,类似于angular中的模块?)
init.py --> 应用初始化文件,表示该项目可以被当作一个package引入
admin.py --> 后台的站点管理注册文件
apps.py --> 当前app的基本信息
models.py --> 数据模型,里面存放各种bean
tests.py --> 单元测试
views.py --> 处理业务逻辑,MVT中的中间人
migrations --> 模型model迁移的,将model类制作成数据库中的表
4- 配置刚刚创建的app,在项目的settings.py中的installed_apps中添加当前app,进行组装
"""
"""
站点管理: 1- settings.py中设置语言和时区
2- python manage.py createsuperuser 创建管理员
3- 启动服务,到 http://127.0.0.1:8000/admin进行登陆
4- 在admin.py中注册自己的数据models用来在后台显示
"""
"""
ORM: object-relation-mapping 对象关系映射
优点:面向对象编程,不再是面向数据库写代码
实现了数据模型和数据库的解耦,不在关注用的是oracle,mysql还是其他数据库
缺点: object需要花费一点时间转换为sql语句,有性能损失(不过可忽略不计)
"""
|
# 可以模拟魔方逆时针旋转的方法,一直做取出第一行的操作
# 输出并删除第一行后,再进行一次逆时针旋转
# 旋转思路
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
result = []
while matrix:
result.extend(matrix.pop(0)) # result 是一个列表
if not matrix or not matrix[0]: # len([[]]) = 1
break
matrix = self.turn(matrix) # 逆时针翻转矩阵
return result
def turn(self, matrix):
num_r = len(matrix)
num_c = len(matrix[0])
newmat = []
for i in range(num_c - 1, -1, -1):
newmat2 = []
for j in range(num_r):
newmat2.append(matrix[j][i])
newmat.append(newmat2)
return newmat
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
result = []
if matrix:
rows = len(matrix)
columns = len(matrix[0])
start = 0 # 每个循环开始的坐标
while start * 2 < min(rows, columns):
self.PrintMatrixInCircle(matrix, columns, rows, start, result)
start += 1
return result
def PrintMatrixInCircle(self, matrix, columns, rows, start, result):
endX = columns - 1 - start
endY = rows - 1 - start
# 从左到右打印一行
for i in range(start, endX + 1):
#number = matrix[start][i]
result.append(matrix[start][i])
# 从上到下打印一行
if start < endY:
for i in range(start + 1, endY + 1):
#number = matrix[i][endX]
result.append(matrix[i][endX])
# 从右到左打印一行
if start < endX and start < endY:
for i in range(endX - 1, start - 1, -1):
#number = matrix[endY][i]
result.append(matrix[endY][i])
# 从下到上打印一行
if start < endX and start < endY - 1:
for i in range(endY - 1, start, -1):
#number = matrix[i][start]
result.append(matrix[i][start])
|
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
# the names j2, j3, and j4 are the white banks on sweetberry
# Note that here the bank name in the mux position is optional
# as it only gets used to generate a docstring help message
inas = [
('sweetberry', '0x40:3', 'j2_1' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x40:1', 'j2_2' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x40:2', 'j2_3' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x40:0', 'j2_4' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:3', 'j2_5' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:1', 'j2_6' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:2', 'j2_7' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:0', 'j2_8' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:3', 'j2_9' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:1', 'j2_10', 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:2', 'j2_11', 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:0', 'j2_12', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:3', 'j2_13', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:1', 'j2_14', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:2', 'j2_15', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:0', 'j2_16', 5.0, 0.010, 'j2', False),
('sweetberry', '0x44:3', 'j3_1' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x44:1', 'j3_2' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x44:2', 'j3_3' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x44:0', 'j3_4' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:3', 'j3_5' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:1', 'j3_6' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:2', 'j3_7' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:0', 'j3_8' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:3', 'j3_9' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:1', 'j3_10', 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:2', 'j3_11', 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:0', 'j3_12', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:3', 'j3_13', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:1', 'j3_14', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:2', 'j3_15', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:0', 'j3_16', 5.0, 0.010, 'j3', False),
('sweetberry', '0x48:3', 'j4_1' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x48:1', 'j4_2' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x48:2', 'j4_3' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x48:0', 'j4_4' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:3', 'j4_5' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:1', 'j4_6' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:2', 'j4_7' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:0', 'j4_8' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:3', 'j4_9' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:1', 'j4_10', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:2', 'j4_11', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:0', 'j4_12', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:3', 'j4_13', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:1', 'j4_14', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:2', 'j4_15', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:0', 'j4_16', 5.0, 0.010, 'j4', False),
]
|
def leia_int(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\33[31m * ERRO: Digite um número válido.\33[m')
continue
else:
return n
def linha(tam=40, car='-'):
print(car * tam)
def cabecalho(txt):
linha()
print(txt.center(40))
linha()
def menu(lista):
cabecalho('MENU PRINCIPAL')
for i, e in enumerate(lista):
print(f'\33[33m{i+1} - \33[34m{e}\33[m')
linha()
opc = leia_int('\33[32mSua Opção: \33[m')
return opc
|
# Project Euler Problem 4
# Pranav Mital
# function to check if a number is a palindrome
def isPalindrome(n):
flag = 0
str_n = str(n)
for i in range((len(str_n)//2)):
if str_n[i] != str_n[len(str_n)-1-i]:
flag += 1
if flag != 0:
return False
else:
return True
# main script
largest_palindrome = 0
for i in range(100,1000): #nested for loop to try all combinations of 3-digit numbers
for j in range(100,1000):
num_p = i*j
if isPalindrome(num_p):
if num_p>largest_palindrome:
largest_palindrome = num_p
print("The largest palindrome made from the product of two 3-digit numbers is:",largest_palindrome)
|
T = 2000 # Set T to 200 periods
sim_seq_long = log_sequential.simulate(0.5, 0, T)
sHist_long = sim_seq_long[-3]
sim_bel_long = log_bellman.simulate(0.5, 0, T, sHist_long)
titles = ['Consumption', 'Labor Supply', 'Government Debt',
'Tax Rate', 'Government Spending', 'Output']
# Government spending paths
sim_seq_long[4] = log_example.G[sHist_long]
sim_bel_long[4] = log_example.G[sHist_long]
# Output paths
sim_seq_long[5] = log_example.Θ[sHist_long] * sim_seq_long[1]
sim_bel_long[5] = log_example.Θ[sHist_long] * sim_bel_long[1]
fig, axes = plt.subplots(3, 2, figsize=(14, 10))
for ax, title, seq, bel in zip(axes.flatten(), titles, sim_seq_long, sim_bel_long):
ax.plot(seq, '-k', bel, '-.b', alpha=0.5)
ax.set(title=title)
ax.grid()
axes[0, 0].legend(('Complete Markets','Incomplete Markets'))
plt.tight_layout()
pslt.show()
T = 2000 # Set T to 200 periods
titles = ['Government Debt', 'Tax Rate']
fig, axes = plt.subplots(2, 1, figsize=(14, 10))
for ax, title, id in zip(axes.flatten(), titles, [2, 3]):
ax.plot(sim_seq_long[id], '-k', sim_bel_long[id], '-.b', alpha=0.5)
ax.set(title=title)
ax.grid()
axes[0].legend(('Complete Markets', 'Incomplete Markets'))
plt.tight_layout()
# plt.show()
plt.savefig('AMSS_long_sim.png')
|
def f(var=("""
str
""",1)):
pass
anothervar=1
|
class PyFileBuilder:
def __init__(self, name):
self._import_line = None
self._file_funcs = []
self.name = name
def add_imports(self, *modules_names):
import_list = []
for module in modules_names:
import_list.append("import " + module)
if len(import_list) != 0:
self._import_line = "\n".join(import_list)
def add_func(self, str_func):
self._file_funcs.append(str_func)
def get_content(self):
if len(self._file_funcs) == 0:
raise Exception("There are no functions in this file")
content = "\n\n\n".join(self._file_funcs)
if self._import_line is not None:
content = self._import_line + "\n\n\n" + content
return content
|
# Design and implement a TwoSum class. It should support the following operations: add and find.
# add - Add the number to an internal data structure.
# find - Find if there exists any pair of numbers which sum is equal to the value.
# Example 1:
# add(1); add(3); add(5);
# find(4) -> true
# find(7) -> false
# Example 2:
# add(3); add(1); add(2);
# find(3) -> true
# find(6) -> false
class TwoSum(object):
# 哈希表 add:O(1) find:O(n)
# 用哈希表统计每个数的个数。
# add(x) - 直接将 x 插入哈希表;
# find(target) - 枚举集合中的每个数 x,判断与 x 互补的数 target−x 是否也在集合中。
# 这里要注意每个数只能使用一次,所以如果恰好 2x=target 时,集合中需要至少存在2个 x 才可以凑出 target。
# 时间复杂度分析:
# add操作仅有一次哈希表的插入操作,时间复杂度是 O(1),
# find 需要枚举集合中的每个数,时间复杂度是 O(n)。
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = {}
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: None
"""
if number in self.nums:
self.nums[number] += 1
else:
self.nums[number] = 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
for num in self.nums:
if value - num in self.nums:
if value - num != num:
return True
elif value - num == num and self.nums[num] > 1:
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)
|
# Create a program such that when given a non-negative number input, output whether or not if the number is 2 away from a multiple of 10.
# input
num = int(input('Enter a positive number: '))
# processing & output
if (num + 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
elif (num - 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
else:
print(num, 'is not 2 away from a multiple of 10.')
|
#URL:https://www.hackerrank.com/challenges/balanced-brackets/problem?h_r=profile
def check_close(top, ch):
if ch =="(" and top ==")":
return True
if ch =="[" and top =="]":
return True
if ch =="{" and top =="}":
return True
return False
def isBalanced(s):
stack=[]
for ch in s:
#print("stack = ",stack)
if ch == "(" or ch == "[" or ch =="{":
stack.append(ch)
else:
#print("in")
stop = ""
if stack:
stop = stack.pop()
else:
return "NO"
if not check_close(ch, stop):
return "NO"
if stack:
return "NO"
return "YES"
|
class Solution:
"""
@param path: the original path
@return: the simplified path
@ 用 stack
['', 'a', '.', '..', '..', 'c', '']
"""
def simplifyPath(self, path):
# write your code here
path = path.split('/')
stack = []
for i in path:
if i == '..':
if stack:
stack.pop()
elif i != '.' and i != '':
stack.append(i)
return '/' + '/'.join(stack)
|
def tickets(disabled,users):
'''
cheks if disabeld or not
'''
a = input("are you disabled or not: ")
if a == 'disabled':
disabled = 200
return disabled
elif a == 'not':
users = 500
return users
tickets(200,500)
|
#Python Program to take the temperature in Celsius and convert it to Fahrenheit.
while 1:
try:
#a=Celsius= float(input("Enter the temperature in Celcius: "))
print("----------------------------------------------------------------------")
print("* *")
print("* Welcome to the Temperature Converter - המרת טמפרטורה *")
print("* *")
print("----------------------------------------------------------------------")
#b=Fahrenheit = float(input("Enter the temperature in Farenheit: "))
except:
print("Invalid Input")
continue
print("\npress 1 for Converting Celsius to Fahrenheit \npres 2 for Converting Fahrenheit to Celsius ")
option =int(input("\nEnter your option: "))
print("your have selected the option",option)
def Celsius():
#Fahrenheit = float((Celsius * 1.8) + 32)
a=Celsius= float(input("\nEnter the temperature in Celcius: "))
c = float(a *1.8)
Fahrenheit = float(c +32)
return "The given Celsius {0}, in Fahrenheit it is : {1} ".format(a,round(Fahrenheit,4))
def Fahrenheit():
#Celsius = float((Fahrenheit - 32) / 1.8)
b=Fahrenheit = float(input("\nEnter the temperature in Farenheit: "))
c = float( b - 32)
Celsius = float( c / 1.8)
return "The given Fahrenheit {0}, in Celsius is : {1} ".format(b,round(Celsius,4))
def default():
return "Invalid option - default command executed!, Please check again."
switcher = {
1: Celsius,
2: Fahrenheit
}
def switch(option):
return switcher.get(option,default)()
print(switch(option))
choice = input("\nDo you wish to continue if so press y else n: ")
if choice == "y" :
print("-----------------------------------------------------")
continue
elif choice == "n" :
print("\nThank you for using the program, hope you enjoyed it, Pls do visit again.")
print("-----------------------------------------------------------------------")
break
else :
print("\nUnable to determine whether to continue or stop the execution of the program. Hence program aborted ! Restart the program.")
print("-------------------------------------------------------------------------------")
break
|
class Solution:
# 1st solution, Lagrange's four square theorem
# O(sqart(n)) time | O(1) space
def numSquares(self, n: int) -> int:
if int(sqrt(n))**2 == n: return 1
for j in range(int(sqrt(n)) + 1):
if int(sqrt(n - j*j))**2 == n - j*j: return 2
while n % 4 == 0:
n >>= 2
if n % 8 == 7: return 4
return 3
# 2nd solution
# O(n^2) time | O(n^2) space
def numSquares(self, n: int) -> int:
squareSet = set()
k = 1
while k * k <= n:
squareSet.add(k * k)
k += 1
count = 0
stack = set([n])
while stack:
count += 1
newStack = set()
for val in stack:
for sq in squareSet:
if sq < val:
newStack.add(val - sq)
elif sq == val:
return count
stack = newStack
|
#
# PySNMP MIB module CISCO-ATM-SWITCH-FR-RM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SWITCH-FR-RM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
iso, ObjectIdentity, Integer32, IpAddress, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Gauge32, TimeTicks, MibIdentifier, Counter64, Unsigned32, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "ObjectIdentity", "Integer32", "IpAddress", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Gauge32", "TimeTicks", "MibIdentifier", "Counter64", "Unsigned32", "Bits")
DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TruthValue", "TextualConvention")
ciscoAtmSwitchFrRmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 110))
if mibBuilder.loadTexts: ciscoAtmSwitchFrRmMIB.setLastUpdated('9807200000Z')
if mibBuilder.loadTexts: ciscoAtmSwitchFrRmMIB.setOrganization('Cisco Systems')
ciscoAtmSwitchFrRmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1))
cfaAdapter = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1))
cfaInterwork = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2))
class CfaInterworkServiceCategory(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("vbrNrt", 1), ("abr", 2), ("ubr", 3))
cfaAdapterIfVcQThresholdTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1), )
if mibBuilder.loadTexts: cfaAdapterIfVcQThresholdTable.setStatus('current')
cfaAdapterIfVcQThresholdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQService"))
if mibBuilder.loadTexts: cfaAdapterIfVcQThresholdEntry.setStatus('current')
cfaAdapterIfVcQService = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 1), CfaInterworkServiceCategory())
if mibBuilder.loadTexts: cfaAdapterIfVcQService.setStatus('current')
cfaAdapterIfVcQInqDiscThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(87)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQInqDiscThresh.setStatus('current')
cfaAdapterIfVcQOutqDiscThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(87)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQOutqDiscThresh.setStatus('current')
cfaAdapterIfVcQInqMarkThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(75)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQInqMarkThresh.setStatus('current')
cfaAdapterIfVcQOutqMarkThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(75)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQOutqMarkThresh.setStatus('current')
cfaAdapterIfVbrServOflowTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2), )
if mibBuilder.loadTexts: cfaAdapterIfVbrServOflowTable.setStatus('current')
cfaAdapterIfVbrServOflowEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cfaAdapterIfVbrServOflowEntry.setStatus('current')
cfaAdapterIfVbrServOflow = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2, 1, 1), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVbrServOflow.setStatus('current')
cfaAdapterIfFrConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3), )
if mibBuilder.loadTexts: cfaAdapterIfFrConfigTable.setStatus('current')
cfaAdapterIfFrConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cfaAdapterIfFrConfigEntry.setStatus('current')
cfaAdapterIfOverbooking = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 1000)).clone(100)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfOverbooking.setStatus('current')
cfaInterworkIfResourceTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1), )
if mibBuilder.loadTexts: cfaInterworkIfResourceTable.setStatus('current')
cfaInterworkIfResourceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfVcQService"))
if mibBuilder.loadTexts: cfaInterworkIfResourceEntry.setStatus('current')
cfaInterworkIfVcQService = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 1), CfaInterworkServiceCategory())
if mibBuilder.loadTexts: cfaInterworkIfVcQService.setStatus('current')
cfaInterworkIfRxAvailRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 2), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfRxAvailRate.setStatus('current')
cfaInterworkIfTxAvailRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 3), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfTxAvailRate.setStatus('current')
cfaInterworkIfRxAllocRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 4), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfRxAllocRate.setStatus('current')
cfaInterworkIfTxAllocRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 5), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfTxAllocRate.setStatus('current')
ciscoAtmSwitchFrRmMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 2))
ciscoAtmSwitchFrRmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3))
ciscoAtmSwitchFrRmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 1))
ciscoAtmSwitchFrRmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2))
ciscoAtmSwitchFrRmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 1, 1)).setObjects(("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterGroup"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoAtmSwitchFrRmMIBCompliance = ciscoAtmSwitchFrRmMIBCompliance.setStatus('current')
cfaAdapterGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2, 1)).setObjects(("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQInqDiscThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQOutqDiscThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQInqMarkThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQOutqMarkThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVbrServOflow"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfOverbooking"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cfaAdapterGroup = cfaAdapterGroup.setStatus('current')
cfaInterworkGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2, 2)).setObjects(("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfRxAvailRate"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfTxAvailRate"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfRxAllocRate"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfTxAllocRate"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cfaInterworkGroup = cfaInterworkGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-ATM-SWITCH-FR-RM-MIB", cfaAdapterIfVcQOutqDiscThresh=cfaAdapterIfVcQOutqDiscThresh, PYSNMP_MODULE_ID=ciscoAtmSwitchFrRmMIB, cfaAdapterGroup=cfaAdapterGroup, cfaAdapterIfVcQThresholdEntry=cfaAdapterIfVcQThresholdEntry, cfaAdapterIfVbrServOflowEntry=cfaAdapterIfVbrServOflowEntry, cfaInterworkIfTxAvailRate=cfaInterworkIfTxAvailRate, ciscoAtmSwitchFrRmMIBConformance=ciscoAtmSwitchFrRmMIBConformance, cfaAdapterIfVbrServOflowTable=cfaAdapterIfVbrServOflowTable, cfaInterworkGroup=cfaInterworkGroup, ciscoAtmSwitchFrRmMIB=ciscoAtmSwitchFrRmMIB, cfaInterworkIfTxAllocRate=cfaInterworkIfTxAllocRate, cfaInterwork=cfaInterwork, ciscoAtmSwitchFrRmMIBGroups=ciscoAtmSwitchFrRmMIBGroups, cfaInterworkIfResourceTable=cfaInterworkIfResourceTable, ciscoAtmSwitchFrRmMIBCompliance=ciscoAtmSwitchFrRmMIBCompliance, ciscoAtmSwitchFrRmMIBNotifications=ciscoAtmSwitchFrRmMIBNotifications, cfaInterworkIfRxAvailRate=cfaInterworkIfRxAvailRate, ciscoAtmSwitchFrRmMIBCompliances=ciscoAtmSwitchFrRmMIBCompliances, cfaAdapter=cfaAdapter, cfaAdapterIfVcQThresholdTable=cfaAdapterIfVcQThresholdTable, cfaAdapterIfFrConfigEntry=cfaAdapterIfFrConfigEntry, cfaAdapterIfOverbooking=cfaAdapterIfOverbooking, cfaInterworkIfResourceEntry=cfaInterworkIfResourceEntry, cfaAdapterIfVcQInqMarkThresh=cfaAdapterIfVcQInqMarkThresh, cfaAdapterIfFrConfigTable=cfaAdapterIfFrConfigTable, cfaAdapterIfVcQInqDiscThresh=cfaAdapterIfVcQInqDiscThresh, cfaAdapterIfVcQOutqMarkThresh=cfaAdapterIfVcQOutqMarkThresh, ciscoAtmSwitchFrRmMIBObjects=ciscoAtmSwitchFrRmMIBObjects, cfaInterworkIfVcQService=cfaInterworkIfVcQService, cfaInterworkIfRxAllocRate=cfaInterworkIfRxAllocRate, cfaAdapterIfVcQService=cfaAdapterIfVcQService, cfaAdapterIfVbrServOflow=cfaAdapterIfVbrServOflow, CfaInterworkServiceCategory=CfaInterworkServiceCategory)
|
# Credentials for your Twitter bot account
# 1. Sign into Twitter or create new account
# 2. Make sure your mobile number is listed at twitter.com/settings/devices
# 3. Head to apps.twitter.com and select Keys and Access Tokens
CONSUMER_KEY = '6gTma2ITYHEh7MZMRJaflnxK7'
CONSUMER_SECRET = 'a20hHEbN1qudaR6RAdMCHtPKdOjpjiiNKabXjhj52Ajb4uHz2S'
# Create a new Access Token
ACCESS_TOKEN = '1051987549487534081-quzVSEUw33JJiImQ7mSnyvZvdTsmln'
ACCESS_SECRET = 'Uz5w4bC3heTN3efnA5yuh7lOZZMzYzkZYThykqRgnZUtu'
|
numbers=list(range(1,21,2))
for i in range(len(numbers)):
print(numbers[i])
|
#for c in range(2, 52, 2):
#print(c, end=' ')
#print('Acabo')
for c in range(1, 11):
print(c +c)
|
class Table:
def __init__(self, table):
self._table = table
@property
def name(self):
return self._table.__name__
@property
def thead(self):
all_fields = self._table._meta.fields
return [
field.verbose_name for field in all_fields if field.verbose_name != "ID"
]
@property
def tbody_sorted(self):
columns = {}
for row in self._table.objects.all().order_by("time__hour"):
key, data = row.get_record()
columns[key] = data
return columns
@property
def tbody(self):
columns = {}
for row in self._table.objects.all():
key, data = row.get_record()
columns[key] = data
return columns
@property
def inputFields(self):
return self._table.inputFields
|
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_test_examples(self, data_dir, data_file_name, size=-1):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
|
'''
while em python
utilizado para realizar ações enquanto
uma condição for verdadeira.
requisitos: Entender condições e operadores
'''
# while condicao: # enquanto essa condição for verdadeira faça oq ta dentro do codigo
# pass
# while True: # loop infinito. executa infinitamente até achar a expressão falsa (fica preso aqui)
#nome = input('qual o seu nome?: ')
#print(f'olá {nome}!')
# print('não será executada.')
x = 0
while x < 10:
if x == 3:
x = x + 1
continue
print(x)
x = x + 1
print('acabou!') # executado quando o laço anterior terminar
x = 10
while x < 20:
if x == 13:
x = x + 1
break
print(x)
x = x + 1
print('acabou')
|
class AmazonAnsible:
"""Main class to generate Ansible playbooks from Amazon
Args:
debug (bool, optional): debug option. Defaults to False.
from_file (str, optional): Optional file with all data. Defaults to ''.
"""
class AmazonAnsibleCalculation:
"""Class to generate all Ansible playbooks.
Args:
data (dict): Amazon info data to be used to generate the playbooks.
debug (bool, optional): debug option. Defaults to False.
"""
def __init__(self, data, debug=False):
self.debug = debug
self.data = data
class AmazonInfo:
"""Retrieve information about Amazon cloud
Args:
debug (bool, optional): debug option. Defaults to False.
"""
def __init__(self, debug=False):
self.debug = debug
self.data = {}
|
"""
Given an array of size n where all elements are distinct and in range from 0 to n-1,
change contents of arr[] so that arr[i] = j is changed to arr[j] = i.
"""
def rearrange(arr: list) -> list:
"""
Simplest approach would be to create and fill a temp array.
But it would require extra space.
In case there is only one cycle (test case 1), it is easy to do it
in one loop.
In case of multiple cycles(test case 2), the solution becomes more convulated
We can convert the processed values as -ve of the values and use some special value for 0.
We can also increment the values by 1 and save as -ve...
Afterwards we revert them
Time Complexity: O(n)
Space Complexity: O(1)
"""
l, i = len(arr), 0
while i < l: # let's use -l for 0
if arr[i] >= 0: # unprocessed
j = arr[i]
k = i
while j != i:
temp = arr[j]
arr[j] = -(k if k != 0 else l)
j, k = temp, j
arr[i] = -(k if k != 0 else l)
i += 1
for i in range(l):
arr[i] = -arr[i] % l
return arr
if __name__ == "__main__":
assert rearrange([1, 3, 0, 2]) == [2, 0, 3, 1]
assert rearrange([2, 0, 1, 4, 5, 3]) == [1, 2, 0, 5, 3, 4]
|
# http://hg.openjdk.java.net/jdk6/jdk6/jdk/raw-file/tip/src/share/demo/jvmti/hprof/manual.html
path = "/Users/huangjinfu/Downloads/hpr/h1j.hprof"
TYPE_LEN = {
2: 4, # object
4: 1, # boolean
5: 2, # char
6: 4, # float
7: 8, # double
8: 1, # byte
9: 2, # short
10: 4, # int
11: 8 # long
}
TYPE_NAME = {
2: "object",
4: "boolean",
5: "char",
6: "float",
7: "double",
8: "byte",
9: "short",
10: "int",
11: "long"
}
STR_VALUE_TO_ID_DICT = {}
STR_ID_TO_VALUE_DICT = {}
CLASS_NAME_TO_ID_DICT = {}
CLASS_ID_TO_NAME_DICT = {}
INSTANCE_ID = []
INSTANCE_CLASS_OBJECT_ID = []
INSTANCE_ID_TO_CLASS_DICT = {}
THREAD_ID_TO_NAME_DICT = {}
# str value -> str id -> class object id -> filter instance id
def parse_start_thread(data, body_start, body_len, name_to_id_dict):
cur = body_start
cur += 4
thread_object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
cur += 4
thread_name_string_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
THREAD_ID_TO_NAME_DICT[thread_object_ID] = thread_name_string_ID
def parse_load_class(data, body_start, body_len, name_to_id_dict):
cur = body_start
cur += 4
class_object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
cur += 4
class_name_string_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
name_to_id_dict[class_name_string_ID] = class_object_ID
CLASS_ID_TO_NAME_DICT[class_object_ID] = class_name_string_ID
# str 4216398 com.shanbay.words.home.thiz.HomeActivity
# class 318339368 4216398
# 4196292 com.shanbay.words.startup.SplashActivity
# class 315441912 4196292
# class 321121368 4196292
def parse_string(data, body_start, body_len, value_to_id_dict, id_to_value_dict):
# print(f"parse_string {body_start} {body_len} , {len(data)}")
cur = body_start
ID_for_this_string = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
l = body_len - 4
s = str(data[cur:cur + l], encoding="utf-8")
value_to_id_dict[s] = ID_for_this_string
id_to_value_dict[ID_for_this_string] = s
if "com.shanbay" in s:
print(f"{ID_for_this_string} {s}")
def parse_heap_dump_segment_record(data, body_start, body_len):
# print(f"parse_heap_dump_segment_record {body_start} {body_len} , {len(data)}")
cur = body_start
offs = 0
while cur + offs < body_start + body_len:
type = data[cur]
cur += 1
if type == 0xFF:
objid = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
# print(f"{hex(type)} ROOT UNKNOWN {objid}")
elif type == 0x01:
object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
JNI_global_ref_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
# if object_ID == 316467800:
# print(f"{hex(type)} ROOT JNI GLOBAL {object_ID}, {JNI_global_ref_ID}")
elif type == 0x02:
cur += 12
elif type == 0x03:
cur += 4
object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 8
# print(f"{hex(type)} ROOT JAVA FRAME {object_ID}")
elif type == 0x04:
cur += 8
elif type == 0x05:
cur += 4
elif type == 0x06:
cur += 8
elif type == 0x07:
cur += 4
elif type == 0x08:
thread_object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big',
signed=False)
# print(f"ROOT THREAD OBJECT {hex(thread_object_ID)}")
cur += 4
cur += 8
elif type == 0x20: # CLASS DUMP
class_object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big',
signed=False)
cur += 4
cur += 32
size_of_constant_pool_and_number_of_records = int.from_bytes(data[cur:cur + 2], byteorder='big',
signed=False)
cur += 2
i = 0
while i < size_of_constant_pool_and_number_of_records:
i += 1
cur += 2
t = data[cur]
cur += 1
cur += TYPE_LEN[t]
Number_of_static_fields = int.from_bytes(data[cur:cur + 2], byteorder='big', signed=False)
cur += 2
i = 0
while i < Number_of_static_fields:
i += 1
cur += 4
t = data[cur]
cur += 1
cur += TYPE_LEN[t]
Number_of_instance_fields = int.from_bytes(data[cur:cur + 2], byteorder='big', signed=False)
cur += 2
i = 0
while i < Number_of_instance_fields:
i += 1
# cur += 5
if class_object_ID == 316469984:
field_name_string_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
type_of_field = data[cur]
cur += 1
# print(f"{STR_ID_TO_VALUE_DICT[field_name_string_ID]} {TYPE_NAME[type_of_field]}")
# print(f"{TYPE_NAME[type_of_field]}")
else:
cur += 5
elif type == 0x21: # INSTANCE DUMP
object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
# if object_ID == 0x13895dc0:
# print(f"---------------------------------------- {hex(object_ID)}")
INSTANCE_ID.append(object_ID)
# if object_ID == 316467800:
# print(f"----------------------------------------{316467800 in INSTANCE_ID}")
cur += 4
cur += 4
class_object_ID = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
INSTANCE_CLASS_OBJECT_ID.append(class_object_ID)
if class_object_ID == 0x1311ced0:
print(hex(object_ID))
cur += 4
number_of_bytes_that_follow = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
cur += number_of_bytes_that_follow
INSTANCE_ID_TO_CLASS_DICT[object_ID] = class_object_ID
elif type == 0x22:
cur += 8
number_of_elements = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
cur += 4
cur += (number_of_elements * 4)
elif type == 0x23:
cur += 8
number_of_elements = int.from_bytes(data[cur:cur + 4], byteorder='big', signed=False)
cur += 4
t = data[cur]
cur += 1
cur += (number_of_elements * TYPE_LEN[t])
else:
raise RuntimeError(f"unknown type {type}")
fd = open(path, "rb")
content = fd.read()
fd.close()
# parse_heap_dump_segment_record(content, 5484314, 4264)
cursor = 0
offset = 0
# version
while content[cursor + offset] != 0:
offset += 1
version = str(content[cursor:cursor + offset], encoding="utf-8")
cursor = cursor + offset
offset = 0
#
cursor += 1
offset = 4
size_of_identifiers = int.from_bytes(content[cursor:cursor + offset], byteorder='big', signed=False)
cursor = cursor + offset
offset = 0
# skip
cursor += 8
while cursor + offset < len(content):
tag = content[cursor]
cursor += 1
cursor += 4
p = content[cursor:cursor + 4]
record_length = int.from_bytes(p, byteorder='big', signed=False)
cursor += 4
bo_st = cursor
bo_len = record_length
cursor += record_length
# print(f"{tag} - {record_length}")
if tag == 0x1c:
parse_heap_dump_segment_record(content, bo_st, bo_len)
elif tag == 0x01:
parse_string(content, bo_st, bo_len, STR_VALUE_TO_ID_DICT, STR_ID_TO_VALUE_DICT)
elif tag == 0x02:
parse_load_class(content, bo_st, bo_len, CLASS_NAME_TO_ID_DICT)
elif tag == 0x0A:
# print("parse_start_thread")
parse_start_thread(content, bo_st, bo_len)
# print(CLASS_NAME_TO_ID_DICT[4196292])
def get_class_object_id(class_name):
return CLASS_NAME_TO_ID_DICT[STR_VALUE_TO_ID_DICT[class_name]]
def find_instance(class_name):
# 4217296 com.shanbay.biz.web.activity.ShanbayWebPageActivity
# 4203986 com.shanbay.biz.web.activity.ShanbayWebPageActivity$1
# 4203987 com.shanbay.biz.web.activity.ShanbayWebPageActivity$2
# 4225504 com.shanbay.biz.web.activity.ShanbayWebPageActivity$FullscreenHolder
str_id = STR_VALUE_TO_ID_DICT[class_name]
class_object_id = CLASS_NAME_TO_ID_DICT[str_id]
print(f"class_object_id {hex(class_object_id)}")
found = class_object_id in INSTANCE_CLASS_OBJECT_ID
print(f"find instance {class_name} - {found}")
print("---")
# print(get_class_object_id("com.shanbay.words.home.thiz.HomeActivity"))
# print(get_class_object_id("com.shanbay.words.startup.SplashActivity"))
# print(get_class_object_id("com.shanbay.words.startup.InitActivity"))
# print(len(INSTANCE_ID))
# print(314651808 in INSTANCE_ID)
# print(THREAD_ID_TO_NAME_DICT[0x12c13570])
# print(STR_ID_TO_VALUE_DICT[THREAD_ID_TO_NAME_DICT[0x12c13570]])
# print(STR_ID_TO_VALUE_DICT[CLASS_ID_TO_NAME_DICT[INSTANCE_ID_TO_CLASS_DICT[0x12c13570]]])
# find_instance("com.shanbay.words.startup.SplashActivity")
# find_instance("com.shanbay.biz.account.user.bridge.BayLoginMainActivity")
# find_instance("com.shanbay.biz.account.user.bayuser.login.BayLoginActivity")
# find_instance("com.shanbay.words.startup.InitActivity")
# find_instance("com.shanbay.words.home.thiz.HomeActivity")
# find_instance("com.shanbay.biz.message.center.MessageCenterActivity")
# find_instance("com.shanbay.words.setting.SettingActivity")
find_instance("com.shanbay.biz.web.activity.ShanbayWebPageActivity")
# find_instance("")
# find_instance("")
|
in_data = {
u'deliveryOrder': {
u'warehouseCode': u'OTHER',
u'deliveryOrderCode': u'3600120100000',
u'receiverInfo': {
u'detailAddress': u'\u5927\u5382\u680818\u53f7101',
u'city': u'\u4e94\u8fde',
u'province': u'\u5c71\u4e1c',
u'area': u'\u5927\u5382'
},
u'senderInfo': {
u'detailAddress': u'\u6587\u4e09\u8def172\u53f7',
u'city': u'\u676d\u5dde',
},
},
u'orderLines': {
u'orderLine': [
{
u'itemId': u'0192010101',
u'planQty': u'20',
},
{
u'itemId': u'0192010102',
u'planQty': u'30',
}]
}
}
mapping = [
([u'deliveryOrder', u'warehouseCode'], 'warehouse_code'),
([u'deliveryOrder', u'deliveryOrderCode'], 'express_code'),
([u'deliveryOrder', u'receiverInfo', u'area'], 'receiver_area'),
([u'deliveryOrder', u'receiverInfo', u'province'], 'receiver_province'),
([u'deliveryOrder', u'receiverInfo', u'detailAddress'], 'receiver_address'),
([u'deliveryOrder', u'receiverInfo', u'city'], 'receiver_city'),
([u'deliveryOrder', u'senderInfo', u'city'], 'sender_city'),
([u'deliveryOrder', u'senderInfo', u'detailAddress'], 'sender_address'),
([u'orderLines', u'orderLine'], 'lines', [
([u'itemId'], 'item_id'),
([u'planQty'], 'product_qty'),
])
]
|
pkgname = "firmware-ipw2100"
pkgver = "1.3"
pkgrel = 0
pkgdesc = "Firmware for the Intel PRO/Wireless 2100 wifi cards"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:ipw2100"
url = "http://ipw2100.sourceforge.net"
source = f"http://firmware.openbsd.org/firmware-dist/ipw2100-fw-{pkgver}.tgz"
sha256 = "e1107c455e48d324a616b47a622593bc8413dcce72026f72731c0b03dae3a7a2"
options = ["!strip", "foreignelf"]
def do_install(self):
for f in self.cwd.glob("*.fw"):
self.install_file(f, "usr/lib/firmware")
self.install_license("LICENSE")
|
'''Generates a javascript string to display flot graphs.
Please read README_flot_grapher.txt
Eliane Stampfer: eliane.stampfer@gmail.com
April 2009'''
class FlotGraph(object):
#constructor. Accepts an array of data, a title, an array of toggle-able data, and the
#width and height of the graph. All of these values are set to defaults if they are not provided.
def __init__(self, data=[], title='', toggle_data=[], width='600', height='300'):
self.display_title = title
self.title = title.replace(" ", "_")
self.data = data
self.height = height
self.width = width
self.xaxis_options=''
self.toggle_data = toggle_data
self.markings = []
self.enable_zoom = 1
self.zoomable = self.enable_zoom
self.enable_tooltip = 1
self.show_tooltip = self.enable_tooltip
self.xaxis_mode = "null"
self.yaxis_mode = "null"
self.xaxis_min = "null"
self.xaxis_max = "null"
self.yaxis_min = "null"
self.yaxis_max = "null"
self.time_format = "%d/%m/%y"
self.key_outside = 1
self.key_position = self.key_outside
self.javascript_string = ""
#/constructor
#Getters and Setters
#1 sets the key to outside the graph, anything else sets it to inside the graph.
def set_key_position(self, key_position):
self.key_position = key_position
def get_key_position(self):
return self.key_position
#1 enables zoom, anything else disables it
def set_zoomable(self, zoomable):
self.zoomable = zoomable
def get_zoomable(self):
return self.zoomable
#1 enables showing the tooltip, anything else disables it
def set_show_tooltip(self, tooltip):
self.show_tooltip = tooltip
def get_show_tooltip(self):
return self.show_tooltip
def set_markings(self, markings_array):
self.markings = markings_array
def get_markings(self):
return self.markings
def set_display_title(self, display_title):
self.display_title = display_title
def get_display_title(self):
return self.display_title
def set_title(self, title):
self.title = title.replace(" ", "_")
def get_title(self):
return self.title
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_toggle_data(self, toggle_data):
self.toggle_data = toggle_data
def get_toggle_data(self):
return self.toggle_data
def set_height(self, height):
self.height = height
def get_height(self):
return self.height
def set_width(self, width):
self.width = width
def get_width(self):
return self.width
def set_xaxis_min(self, xaxis_min):
self.xaxis_min = xaxis_min
def get_xaxis_min(self):
return self.xaxis_min
def set_xaxis_max(self, xaxis_max):
self.xaxis_max = xaxis_max
def get_xaxis_max(self):
return self.xaxis_max
def set_yaxis_min(self, yaxis_min):
self.yaxis_min = yaxis_min
def get_yaxis_min(self):
return self.yaxis_min
def set_yaxis_max(self, yaxis_max):
self.yaxis_max = yaxis_max
def get_yaxis_max(self):
return self.yaxis_max
def set_xaxis_mode(self, xaxis_mode):
if xaxis_mode == "time":
self.xaxis_mode = "\"" + xaxis_mode + "\""
if xaxis_mode == "null":
self.xaxis_mode = "null"
def get_xaxis_mode(self):
return self.xaxis_mode
def set_yaxis_mode(self, yaxis_mode):
if yaxis_mode == "time":
self.yaxis_mode = "\"" + yaxis_mode + "\""
if yaxis_mode == "null":
self.yaxis_mode = "null"
def get_yaxis_mode(self):
return self.yaxis_mode
def set_time_format(self, time_format):
self.time_format = time_format
def get_time_format(self):
return self.time_format
def get_plot_div(self):
return "plot_" + self.get_title()
#/getters and setters
#Methods that create the javascript string
#called by generate_javascript()
def get_heading_string(self):
string = "<h1>"+self.display_title+"</h1> \n"
string += "<div style=\"float:left\"> \n"
string += "\t<div id=\""+self.get_plot_div()+"\"></div>\n\t<p id=\""+self.get_title()+"_choices\">\n"
string += "<p id=\"message\"></p>"
string += "\t</p>\n"
if(self.get_zoomable() == self.enable_zoom):
string += "\t<p> <span id=\""+self.get_title()+"_xselection\"></span></p>\n"
string += "\t<p> <span id=\""+self.get_title()+"_yselection\"></span></p>\n"
string += "</div> \n"
string += "<div id=\""+self.get_plot_div()+"_miniature\" style=\"float:left;margin-left:20px;margin-top:50px\"> \n"
string += "\t<div id=\""+self.get_plot_div()+"_overview\" style=\"width:166px;height:100px\"></div> \n"
string += "\t<p id=\""+self.get_plot_div()+"_overviewLegend\" style=\"margin-left:10px\"></p>\n </div> \n\
<script id=\"source\" language=\"javascript\" type=\"text/javascript\">\n\
$(function(){\n"
return string;
#called by get_options_string()
def get_markings_string(self):
string = "\t\t\t\t\tmarkings: [\n"
for mark_area in self.markings:
string += "\t\t\t\t\t\t{"
if('xaxis' in mark_area):
xaxis = mark_area['xaxis']
if('from' in xaxis and 'to' in xaxis):
string += "xaxis: {from: "+xaxis['from']+", to: "+xaxis['to']+"}, "
if('yaxis' in mark_area):
yaxis = mark_area['yaxis']
if('from' in yaxis and 'to' in yaxis):
string += "yaxis: {from: "+yaxis['from']+", to: "+yaxis['to']+"}, "
if('color' in mark_area):
string += "color: \""+ mark_area['color']+"\""
if('label' in mark_area):
series_data = self.get_data()
series_data.append({'data': [], 'label': mark_area['label'], 'color': mark_area['color']})
self.set_data(series_data)
string += "},\n"
string += "\t\t\t\t\t],\n"
return string
#called by generate_javascript()
def get_options_string(self):
string = "\n\
var options = {\n\
legend: {\n"
if (self.get_zoomable() == self.enable_zoom):
string += "\t\t\t\t\tshow: false,\n"
string += "\t\t\t\t\tmargin: 5,\n\
backgroundOpacity:.05,\n"
if (not(self.get_zoomable() == self.enable_zoom)):
if (self.get_key_position() == self.key_outside):
string += "\t\t\t\t\tcontainer: $(\"#"+self.get_plot_div()+"_overviewLegend\")\n"
string +="\t\t\t\t},\n\
grid: { \n\
clickable: true,\n\
hoverable: true,\n"
string += self.get_markings_string()
string += "\t\t\t\t},\n\
selection: { \n\
mode: \"xy\"\n\
},\n"
string += self.get_axis_options()
string += "\n\
};\n"
return string
#called by get_options_string()
def get_axis_options(self):
string = "\n\
xaxis: {\n\
mode: "+ self.get_xaxis_mode()+",\n\
timeformat: \""+ self.time_format +"\",\n\
min: "+self.get_xaxis_min()+",\n\
max: "+self.get_xaxis_max()+", \n\
},"
string += "\n\
yaxis: {\n\
mode: "+ self.get_yaxis_mode()+",\n\
timeformat: \""+ self.time_format +"\",\n\
min: "+self.get_yaxis_min()+",\n\
max: "+self.get_yaxis_max()+", \n\
},"
return string
#called by generate_javascript()
def get_toggle_datasets_string(self):
string = "\n\nvar datasets = {"
counter = 0
string += self.get_series_string(self.toggle_data, 1)
#hard-code color indices to prevent them from shifting as
#series are turned on/off
string += "}\n"
string += "var i = "+ str(len(self.data)) + ";\n\
$.each(datasets, function(key, val) {\n\
val.color = i;\n\
++i;\n\
});\n"
return string
#called by generate_javascript()
def get_choice_container_string(self):
return "var choiceContainer = $(\"#"+self.get_title()+"_choices\");\n\
$.each(datasets, function(key, val) {\n\
choiceContainer.append('<br/><input type=\"checkbox\" name=\"' + key +\n\
'\" checked=\"checked\" >' + val.label + '</input>');\n\
});\n\
choiceContainer.find(\"input\").click(plotGraph);\n"
#called by generate_javascript()
def get_plot_area_string(self):
string = "\n\
var plotarea = $(\"#" + self.get_plot_div() + "\");\n\
plotarea.css(\"height\", \"" + str(self.get_height()) + "px\");\n\
plotarea.css(\"width\", \"" + str(self.get_width())+ "px\");\n\n"
return string
#called by get_plot_choices_string() and get_toggle_datasets_string()
def get_series_string(self, data_array, toggle=0):
counter = 1
string = ""
for series in data_array:
if('label' in series):
name = series['label']
else:
name = "series "+str(counter)
counter += 1
if(toggle == 1):
name_internal = name.lower()
string += " \n \t\t\t\"" + name_internal.replace(" ", "_") + "\":"
string += "{\n\
label: \"" + name + "\",\n"
if('lines' in series):
lines_dict = series['lines']
string += "\t\t\t\tlines: {\n\t\t\t\t\tshow: true, \n"
if('lineWidth' in lines_dict and lines_dict['lineWidth'].isdigit()):
string += "\t\t\t\t\tlineWidth: "+ str(lines_dict['lineWidth']) +",\n"
if('fill' in lines_dict):
string += "\t\t\t\t\tfill: "+str(lines_dict['fill']) +",\n"
string += "\t\t\t\t},\n"
if('bars' in series):
bars_dict = series['bars']
string += "\t\t\t\tbars: {\n\t\t\t\t\tshow: true, \n"
if('barWidth' in bars_dict):
string += "\t\t\t\t\tbarWidth: "+str(bars_dict['barWidth']) +",\n"
if('align' in bars_dict and (bars_dict['align'] == "left" or bars_dict['align'] == "center")):
string += "\t\t\t\t\talign: \""+str(bars_dict['align']) +"\",\n"
if('fill' in bars_dict):
string += "\t\t\t\t\tfill: "+str(bars_dict['fill']) +",\n"
string += "\t\t\t\t},\n"
if('points' in series):
points_dict = series['points']
string += "\t\t\t\tpoints: {\n\t\t\t\t\tshow: true, \n"
if('radius' in points_dict and points_dict['radius'].isdigit()):
string += "\t\t\t\t\tradius: "+ str(points_dict['radius']) +",\n"
string += "\t\t\t\t},\n"
if(not('lines' in series) and not('bars' in series) and not ('points' in series)):
string += "\t\t\t\tlines: {\n\t\t\t\t\tshow: true\n\t\t\t\t}, \n\t\t\t\tpoints: {\n\t\t\t\t\tshow: true\n\t\t\t\t},\n"
if('color' in series):
string += "\t\t\t\tcolor: \""+series['color']+"\",\n"
string += "\t\t\t\tdata: [\n\t\t\t\t\t"
for point in series['data']:
string += "[" + str(point[0]) +", " + str(point[1]) + "],"
string += "\n\t\t\t\t]\n\t\t\t},"
return string
#/get_series_string
#called by generate_javascript()
def get_plot_choices_string(self):
string = "function getChoices() {\n\
\n\
var data = ["
string += self.get_series_string(self.data)
string += "];\n\
choiceContainer.find(\"input:checked\").each(function () {\n\
var key = $(this).attr(\"name\");\n\
if (key && datasets[key])\n\
data.push(datasets[key]);\n\
});\n\
\n\
return data;\n\
}\n"
return string
#called by generate_javascript() if the tooltip is enabled.
def get_show_tooltip_string(self):
string = "function showTooltip(x, y, contents) {\n\
$('<div id=\""+self.get_title()+"_tooltip\">' + contents + '</div>').css( {\n\
position: 'absolute',\n\
display: 'none',\n\
top: y + 5,\n\
left: x + 5,\n\
border: '1px solid #fdd',\n\
padding: '2px',\n\
'background-color': '#fee',\n\
opacity: 0.80\n\
}).appendTo(\"body\").fadeIn(200);\n\
}\n"
string += "var previousPoint = null;\n\
$(\"#" + self.get_plot_div() + "\").bind(\"plothover\", function (event, pos, item) {\n\
$(\"#x\").text(pos.x.toFixed(2));\n\
$(\"#y\").text(pos.y.toFixed(2));\n"
string += "if (item) {\n\
if (previousPoint != item.datapoint) {\n\
previousPoint = item.datapoint;\n"
string += "\n $(\"#"+self.get_title()+"_tooltip\").remove();\n\
var x = item.datapoint[0].toFixed(2),\n\
y = item.datapoint[1].toFixed(2);\n\n\
showTooltip(item.pageX, item.pageY, item.series.label + \": (\" + x + \", \" + y+ \")\");\n\
}\n\
}\n\
else {\n\
$(\"#"+self.get_title()+"_tooltip\").remove();\n"
string += "previousPoint = null;\n }\n });"
return string
#called by generate_javascript()
def get_plot_graph_string(self):
string = "var first = 0;\n\
function plotGraph(min_x, max_x, min_y, max_y){\n\
data = getChoices();\n\
if (min_x != null && max_x != null && min_y != null && max_y != null){\n\
$(\"#"+self.get_title()+"_selection\").text(\" \");\n\
graph_obj = $.plot(plotarea, data,\n\
$.extend(true, {}, options, {\n\
xaxis: { min: min_x, max: max_x},\n\
yaxis: { min: min_y, max: max_y},\n\
}));\n\
\n\
}\n\
else\n\
var flot_plot = $.plot(plotarea, data, options);\n\
}\n\
plotGraph();\n\
plotOver();\n"
return string
#called by generate_javascript()
def get_zoom_with_overview(self):
string = "function plotOver(){\nvar data_over = getChoices();\n\
overview = $.plot($(\"#"+self.get_plot_div()+"_overview\"), data_over, {\n\
legend: { show: true, container: $(\"#"+self.get_plot_div()+"_overviewLegend\"), },\n\
shadowSize: 0,\n\
xaxis: { ticks: 4, min: "+self.get_xaxis_min()+", max: "+self.get_xaxis_max()+",},\n\
yaxis: { ticks: 3, min: "+self.get_yaxis_min()+", max: "+self.get_yaxis_max()+",},\n\
grid: {clickable: true, autoHighlight: false, " +self.get_markings_string()+"},\n\
selection: { mode: \"xy\" }\n\
});\n}\n"
string += " $(\"#"+self.get_plot_div()+"\").bind(\"plotselected\", function (event, ranges){ \n"
string += "\n\
// clamp the zooming to prevent eternal zoom \n\
if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)\n\
ranges.xaxis.to = ranges.xaxis.from + 0.00001;\n\
if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)\n\
ranges.yaxis.to = ranges.yaxis.from + 0.00001;\n\
\n\
// do the zooming\n\
plotGraph(ranges.xaxis.from, ranges.xaxis.to, ranges.yaxis.from, ranges.yaxis.to);\n\
$(\"#"+self.get_title()+"_xselection\").text(\"x-axis: \" +ranges.xaxis.from.toFixed(1) + \" to \" +ranges.xaxis.to.toFixed(1))\n"
string += "$(\"#"+self.get_title()+"_yselection\").text(\"y-axis: \" +ranges.yaxis.from.toFixed(1) + \" to \" +ranges.yaxis.to.toFixed(1))\n\
// don't fire event on the overview to prevent eternal loop\n\
overview.setSelection(ranges, true);\n\
});\n"
string += "$(\"#"+self.get_plot_div()+"_overview\").bind(\"plotselected\", function (event, ranges) {\n\
plot.setSelection(ranges);\n\
});\n"
string += "$(\"#"+self.get_plot_div()+"_overview\").bind(\"plotclick\", function (event, pos) {\n\
var axes = overview.getAxes();\n\
var y_min = axes.yaxis.min;\n\
var y_max = axes.yaxis.max;\n\
var x_min = axes.xaxis.min;\n\
var x_max = axes.xaxis.max;\n\
plotGraph(x_min, x_max, y_min, y_max);\n\
});\n"
return string
#called by generate_javascript()
def get_footer_string(self):
return " });\n\
</script>"
#assembles the javascript string
def generate_javascript(self):
javascript_string = self.get_heading_string()
javascript_string += self.get_options_string()
javascript_string += self.get_toggle_datasets_string()
javascript_string += self.get_choice_container_string()
javascript_string += self.get_plot_area_string()
javascript_string += self.get_plot_choices_string()
if(self.get_show_tooltip() == self.enable_tooltip):
javascript_string += self.get_show_tooltip_string()
javascript_string += self.get_plot_graph_string()
if(self.get_zoomable() == self.enable_zoom):
javascript_string += self.get_zoom_with_overview()
javascript_string += self.get_footer_string()
javascript_string.replace("\\n", "\n")
javascript_string.replace("\\t", "\t")
self.javascript_string = javascript_string
return javascript_string
|
def merge(seq, first, mid, last):
(left, right) = (seq[first: mid], seq[mid: last])
(l, r, curr) = (0, 0, first)
(left_size, right_size) = (len(left), len(right))
while l != left_size and r != right_size:
if left[l] < right[r]:
seq[curr] = left[l]
l += 1
else:
seq[curr] = right[r]
r += 1
curr += 1
(x, rest) = (r, right) if (l == left_size) else (l, left)
while x != len(rest):
seq[curr] = rest[x]
(x, curr) = (x+1, curr+1)
def merge_sort(seq, first, last):
if first + 1 < last:
mid = first + (last-first)//2
merge_sort(seq, first, mid)
merge_sort(seq, mid, last)
merge(seq, first, mid, last)
li = [3, 2, 1, 88, 1000, -1]
merge_sort(li, 0, len(li))
print(li)
ls = ["aaa", "1234", "hello", "google", "hi"]
merge_sort(ls, 0, len(ls))
print(ls)
"""
output:
[1, 2, 3, 4]
['1234', 'aaa', 'google', 'hello', 'hi']
"""
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Decode:
def __init__(self, length, K, n, weight):
self.K = K
self.length = length
self.n = n
self.weight = weight
self.solution = [False for i in range(0, n + 1)]
def Search(self):
# Initialize
insert = [[False for k in range(0, self.K + 2)]for i in range(0, self.n + 2)]
score = [[0 for k in range(0, self.K + 2)]for i in range(0, self.n + 2)]
# Loop
for i in range(1, self.n + 1):
for k in range(1, self.K + 1):
if self.length[i] <= k and score[i - 1][k] <= score[i - 1][k - self.length[i]] + self.weight[i]:
insert[i][k] = True
score[i][k] = score[i - 1][k - self.length[i]] + self.weight[i]
else:
score[i][k] = score[i - 1][k]
# Trace
k = self.K
for i in range(self.n, 0, -1):
if insert[i][k] == True:
k = k - self.length[i]
self.solution[i] = True
def GetSolution(self):
return self.solution
if __name__ == '__main__':
pass
|
lines = []
with open('input.txt','r') as INPUT:
lines = INPUT.readlines()
M = int(lines[0])
stack = [None]*M
stack_head = -1
with open('output.txt', 'w') as OUTPUT:
for op in lines[1:]:
if op.startswith('+'):
stack_head += 1
stack[stack_head] = op[2:]
elif op.startswith('-'):
OUTPUT.write(stack[stack_head])
stack_head -= 1
print(op, stack)
|
class BaseScraper:
pass
|
class Board:
def __init__(self, n):
# Размер игры . . .
self.n = n
# Создаем списковое представление пустой доски
self.pieces = [None] * self.n
for i in range(self.n):
self.pieces[i] = [0] * self.n
# Добавляем возможность использования оператора взятия индекса ([] и [][])
def __getitem__(self, index):
return self.pieces[index]
def get_count(self, color):
"""
:param color: <Int>
"цвет" игроков: 1 для крестиков, -1 для ноликов, 0 для незанятых клеток.
:return: count: <Int>
количество фигур типа color.
Подсчитывает количество фигур типа color на доске.
"""
count = 0
for y in range(self.n):
for x in range(self.n):
if self[y][x] == color:
count += 1
return count
def count_diff(self, color):
"""
:param color: <Int>
"цвет" игроков: 1 для крестиков, -1 для ноликов, 0 для незанятых клеток.
:return: count: <Int>
Разница между количеством фигур типа color и -color на доске.
"""
count = 0
for y in range(self.n):
for x in range(self.n):
if self[y][x] == color:
count += 1
if self[y][x] == -color:
count -= 1
return count
def execute_move(self, move, color):
"""
:param move: tuple(<Int>, <Int>), кортеж, представляющий текущий ход
:param color: <Int>, 1 для крестиков, -1 для ноликов
Ставит в клетку с координатами move фигуру color.
"""
(x, y) = move
assert self[x][y] == 0
self[x][y] = color
def has_legal_moves(self):
for y in range(self.n):
for x in range(self.n):
if self[x][y] == 0:
return True
return False
def get_legal_moves(self, color):
moves = set()
for y in range(self.n):
for x in range(self.n):
if self[x][y] == 0:
new_moves = (x,y)
moves.add(new_moves)
return list(moves)
def is_win(self, color):
"""Check whether the given player has collected a triplet in any direction;
@param color (1=white,-1=black)
"""
win = self.n
# check y-strips
for y in range(self.n):
count = 0
for x in range(self.n):
if self[x][y]==color:
count += 1
if count==win:
return True
# check x-strips
for x in range(self.n):
count = 0
for y in range(self.n):
if self[x][y]==color:
count += 1
if count==win:
return True
# check two diagonal strips
count = 0
for d in range(self.n):
if self[d][d]==color:
count += 1
if count==win:
return True
count = 0
for d in range(self.n):
if self[d][self.n-d-1]==color:
count += 1
if count==win:
return True
return False
def print_board(self):
for piece in self.pieces:
print(piece)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 17:12:03 2020
@author: kanukuma
"""
def popularNFeatures(numFeatures, topFeatures, possibleFeatures,
numFeatureRequests, featureRequests):
ngramsList = []
resultList = []
for featureRequest in featureRequests:
ngramsList.append( featureRequest.split())
print(ngramsList)
for feature in possibleFeatures:
for ngrams in ngramsList:
print(feature)
flag = feature in ngrams
print(flag)
if flag ==True:
resultList.append((feature, ngrams.count(feature)))
return resultList;
lst = ["abc","cde","def","efg"]
lst2 = ["abc is good then bcd","bcd is bad then cde, def","cde is good then bcd","def is good then all"]
print(popularNFeatures(4, 2, lst, 4, lst2));
|
def is_sequence(x):
""" Returns whether x is a sequence (tuple, list).
:param x: a value to check
:returns: (boolean)
"""
return (not hasattr(x, 'strip') and
hasattr(x, '__getitem__') or
hasattr(x, '__iter__'))
|
k = int(input())
s = input()
prevlen = 0
ans = 0
for i in range(k, len(s)):
if s[i] == s[i - k]:
prevlen += 1
ans += prevlen
else:
prevlen = 0
print(ans)
|
##########################################################################
# Gene prediction pipeline
#
# $Id: AGP.py 2781 2009-09-10 11:33:14Z andreas $
#
# Copyright (C) 2005 Andreas Heger
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##########################################################################
"""AGP.py - working with AGP files
=====================================================
This module contains a parser for reading from :term:`agp` formatted
files.
Code
----
"""
class ObjectPosition(object):
def map(self, start, end):
if self.mOrientation:
return start + self.start, end + self.start
else:
return end + self.start, start + self.start
class AGP(object):
"""Parser for AGP formatted files."""
def readFromFile(self, infile):
"""read an agp file.
Example line::
scaffold_1 1 1199 1 W contig_13 1 1199 +
This method converts coordinates to zero-based coordinates
using open/closed notation.
In AGP nomenclature
(http://www.ncbi.nlm.nih.gov/genome/guide/Assembly/AGP_Specification.html)
objects (obj) like scaffolds are assembled from components
(com) like contigs.
Component types are
W
WGS sequence
N
gap of specified length.
"""
self.mMapComponent2Object = {}
self.mMapObject2Component = {}
for line in infile:
if line[0] == "#":
continue
data = line[:-1].split("\t")
obj_id, obj_start, obj_end, ncoms, com_type, com_id = data[:6]
if com_type == "N":
continue
com_start, com_end, orientation = data[6:9]
obj_start, obj_end = int(obj_start) - 1, int(obj_end)
com_start, com_end = int(com_start) - 1, int(com_end)
orientation = orientation in ("+", "0", "na")
if com_start != 0:
raise "beware, non zero com_start"
object = ObjectPosition()
object.mId = obj_id
object.start = obj_start
object.end = obj_end
object.mOrientation = orientation
self.mMapComponent2Object[com_id] = object
def mapLocation(self, id, start, end):
"""map a genomic location.
Raises
------
KeyError
If `id` is not present.
"""
if id not in self.mMapComponent2Object:
raise KeyError("id %s is not known" % (id))
pos = self.mMapComponent2Object[id]
return (pos.mId, ) + pos.map(start, end)
|
# Equality checks should behave the same way as assignment
# Variable equality check
bar == {'a': 1, 'b':2}
bar == {
'a': 1,
'b': 2,
}
# Function equality check
foo() == {
'a': 1,
'b': 2,
'c': 3,
}
foo(1, 2, 3) == {
'a': 1,
'b': 2,
'c': 3,
}
|
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0) # here to make sure stack pop off
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans, h * w)
stack.append(i)
heights.pop()
return ans
'''The stack maintain the indexes of buildings with ascending height. Before adding a new building pop the building who is taller than the new one. The building popped out represent the height of a rectangle with the new building as the right boundary and the current stack top as the left boundary. Calculate its area and update ans of maximum area. Boundary is handled using dummy buildings.'''
|
a, b, c, d, e, f, g, h = range(8)
# 邻接集
N1 = [
{b, c, d, e, f},
{c, e},
{d},
{e},
{f},
{c, g, h},
{f, h},
{f, g}
]
# 邻接列表
N2 = [
[b, c, d, e, f],
[c, e],
[d],
[e],
[f],
[c, g, h],
[f, h],
[f, g]
]
# 加权邻接字典
N3 = [
{b: 2, c: 1, d: 3, e: 9, f: 4},
{c: 4, e: 3},
{d: 8},
{e: 7},
{f: 5},
{c: 2, g: 2, h: 2},
{f: 1, h: 6},
{f: 9, g: 8}
]
# 邻接集的字典表示法
N4 = {
'a': set('bcdef'),
'b': set('ce'),
'c': set('d'),
'd': set('e'),
'e': set('f'),
'f': set('cfg'),
'g': set('fh'),
'h': set('fg')
}
# 邻接矩阵
N5 = [
[0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 1, 1, 0]
]
|
class TicTacToe:
def __init__(self):
self.cells = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
self.matrix = [self.cells[0:3], self.cells[3:6], self.cells[6:9]]
# Vertical lines list, to be divided in 3 inner lists:
self.v_lines = []
# Diagonal lines:
self.d1_line = [self.matrix[0][0], self.matrix[1][1],
self.matrix[2][2]]
self.d2_line = [self.matrix[0][2], self.matrix[1][1],
self.matrix[2][0]]
self.x_list = ['X', 'X', 'X']
self.o_list = ['O', 'O', 'O']
self.turn_counter = 0
self.end_game = False
self.coord_input = ''
def vertical_lines_list(self): # Transforming vertical sequences in list.
for c in range(3):
self.v_lines.append([self.matrix[0][c], self.matrix[1][c],
self.matrix[2][c]])
def game_start(self):
self.vertical_lines_list()
self.display()
self.game_mechanism()
def check_input(self, input_):
forbidden = '4567890'
if input_.replace(' ', '').isalpha():
print('You should enter numbers!')
self.game_mechanism() # Start over again, if wrong.
elif len(input_.replace(' ', '')) < 2: # When only one number digited.
print('Coordinates must have 2 numbers!')
self.game_mechanism()
elif input_[0] in forbidden or input_[2] in forbidden:
print('Coordinates should be from 1 to 3!')
self.game_mechanism()
else:
# If input is ok, converted to integer.
self.coord_input = [int(i) for i in input_.replace(' ', '')]
return self.coord_input
def game_mechanism(self):
while not self.end_game:
user = input('Enter coordinates: ')
self.check_input(user)
# Coordinates:
# (1, 3)(2, 3)(3, 3)
# (1, 2)(2, 2)(3, 2)
# (1, 1)(2, 1)(3, 1)
# This following loop works to convert inputs into indexes,
# at the same time it helps to validate results:
for c in range(1, 4):
if not self.end_game: # Used to stop some for loops later,
# that were showing messages 3 times.
if self.coord_input == [c, 3]: # Line 1.
if self.matrix[0][c - 1] == 'X' or \
self.matrix[0][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0: # 'O' is put when
# turn_counter is even.
self.matrix[0][c - 1] = 'O' # Hr. ln. check.
self.v_lines[c - 1][0] = 'O' # Vt. ln. check.
if c == 1:
self.d1_line[0] = 'O'
elif c == 3:
self.d2_line[2] = 'O'
else:
self.matrix[0][c - 1] = 'X'
self.v_lines[c - 1][0] = 'X'
if c == 1:
self.d1_line[0] = 'X'
elif c == 3:
self.d2_line[2] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw() # Verifying results after each vert. line.
elif self.coord_input == [c, 2]: # Line 2.
if self.matrix[1][c - 1] == 'X' or \
self.matrix[1][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0:
self.matrix[1][c - 1] = 'O'
self.v_lines[c - 1][1] = 'O'
if c == 2:
self.d1_line[1] = 'O'
self.d2_line[1] = 'O'
else:
self.matrix[1][c - 1] = 'X'
self.v_lines[c - 1][1] = 'X'
if c == 2:
self.d1_line[1] = 'X'
self.d2_line[1] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw()
elif self.coord_input == [c, 1]: # Line 3.
if self.matrix[2][c - 1] == 'X' or \
self.matrix[2][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0:
self.matrix[2][c - 1] = 'O'
self.v_lines[c - 1][2] = 'O'
if c == 3:
self.d1_line[2] = 'O'
elif c == 1:
self.d2_line[0] = 'O'
else:
self.matrix[2][c - 1] = 'X'
self.v_lines[c - 1][2] = 'X'
if c == 3:
self.d1_line[2] = 'X'
elif c == 1:
self.d2_line[0] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw()
def display(self):
print('-' * 9)
print(f'| {" ".join(self.matrix[0])} |')
print(f'| {" ".join(self.matrix[1])} |')
print(f'| {" ".join(self.matrix[2])} |')
print('-' * 9)
# Results analysis methods:
def x_win(self):
# Diagonal:
if self.d1_line == self.x_list or self.d2_line == self.x_list:
print('X wins')
self.end_game = True
else:
for c in range(3):
if not self.end_game: # Used to stop for loops
# when condition achieved.
if self.matrix[c] == self.x_list or \
self.v_lines[c] == self.x_list:
print('X wins')
self.end_game = True
def o_win(self):
# Diagonal:
if self.d1_line == self.o_list or \
self.d2_line == self.o_list:
print('O wins')
self.end_game = True
else:
for c in range(3):
if not self.end_game: # Used to stop for loops when
# condition achieved.
if self.matrix[c] == self.o_list or \
self.v_lines[c] == self.o_list:
print('O wins')
self.end_game = True
def draw(self):
if not self.end_game:
if self.turn_counter == 9:
print('Draw')
self.end_game = True
tictactoe = TicTacToe()
tictactoe.game_start()
# Have a nice day!
|
#coding=utf-8
'''
Created on 2015-9-24
@author: Devuser
'''
class CITestingTaskPropertyNavBar(object):
'''
classdocs
'''
def __init__(self,request,**args):
self.request=request
self.ci_task=args['ci_task']
if args['property_nav_action'] == 'history':
self.result_active="left_sub_meun_active"
if args['property_nav_action'] == 'config':
self.config_active="left_sub_meun_active"
if args['property_nav_action'] == 'parameter':
self.parameter_active="left_sub_meun_active"
if args['property_nav_action'] == 'build':
self.build_active="left_sub_meun_active"
if args['property_nav_action'] == 'build_clean':
self.build_clean_active="left_sub_meun_active"
class CITaskPropertyNavBar(object):
'''
classdocs
'''
def __init__(self,request,**args):
self.request=request
self.ci_task=args['ci_task']
if args['property_nav_action'] == 'history':
self.history_active="left_sub_meun_active"
if args['property_nav_action'] == 'unittest_history':
self.unittest_active="left_sub_meun_active"
if args['property_nav_action'] == 'config':
self.config_active="left_sub_meun_active"
if args['property_nav_action'] == 'parameter':
self.parameter_active="left_sub_meun_active"
if args['property_nav_action'] == 'build':
self.build_active="left_sub_meun_active"
if args['property_nav_action'] == 'changelog':
self.changelog_active="left_sub_meun_active"
if args['property_nav_action'] == 'build_clean':
self.build_clean_active="left_sub_meun_active"
|
class Solution :
def letterCombinations(self, digits) :
def dfs(index, path) :
if len(path) == len(digits) :
# 한개가 붙는 경우는 마지막 밖에 없으니까 for 문이 의미없이 돌다가 끝남
result.append(path)
return
for i in range(index, len(digits)) :
# 여기서 중요한 것은 digits을 반복하는데, 반복할 때, 이전의 문자를 붙잡아놓고 뒤의 문자를 반복시키는 것 !
for j in graph[digits[i]] :
dfs(i+1, path+j)
graph ={'2' : 'abc', '3' : 'def', '4' : 'ghi', '5' :'jkl', '6' : 'mno', '7' :'pqrs', '8' :'tuv', '9':'wxyz'}
result = []
dfs(0, '')
return result
answer = Solution().letterCombinations(digits= '23')
print(answer)
|
print('='*8,'Dicionário de Palavras','='*8)
d = {}
d['Fato'] = '''Acontecimento acabado; evento, ocorrência: a fiscalização das barracas \nilegais é agora um fato.
\nCoisa cuja realidade pode ser comprovada; verdade, realidade: "contra fatos não há \nargumentos".
\n[Jurídico] O que foi finalizado e não pode ser mudado nem alterado.
\nEtimologia (origem da palavra fato). A palavra fato com esses sentidos deriva do latim \n"factum", com o sentido de "feito, façanha".
\nsubstantivo masculino
\nRebanho de animais, geralmente cabras, em pequeno número.
\n[Zoologia] As entranhas dos animais; miúdos.
\nVestimenta utilizada para uma ocasião específica cujos propósitos já estão determinados: \nfato de mecânico.'''
p = str(input('Qual palavra deseja ver o significado? ')).strip().title()
cont = 0
for k, v in d.items():
if k == p:
print(f'\033[32m{k}\033[m => \033[33m{v}\033[m')
else:
cont += 1
if cont == len(d):
print('\033[36mA palavra desejada não se encontra no dicionário\033[m')
|
msg = str(input('Digite uma mensagem'))
n = 0
n = len(msg)
def escreva():
print('-'*n)
print(msg)
print('-'*n)
escreva()
|
class UVWarpModifier:
axis_u = None
axis_v = None
bone_from = None
bone_to = None
center = None
object_from = None
object_to = None
uv_layer = None
vertex_group = None
|
#
# Copyright Cloudlab URV 2020
#
# 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.
#
_set = set
# General lithops.multiprocessing parameters
LITHOPS_CONFIG = 'LITHOPS_CONFIG'
STREAM_STDOUT = 'STREAM_STDOUT'
# Redis specific parameters
REDIS_EXPIRY_TIME = 'REDIS_EXPIRY_TIME'
REDIS_CONNECTION_TYPE = 'REDIS_CONNECTION_TYPE'
_DEFAULT_CONFIG = {
LITHOPS_CONFIG: {},
STREAM_STDOUT: False,
REDIS_EXPIRY_TIME: 300,
REDIS_CONNECTION_TYPE: 'pubsubconn'
}
_config = _DEFAULT_CONFIG
def set(config_dic=None, **configurations):
if config_dic is None:
config_dic = {}
_config.update(config_dic)
_config.update(configurations)
def set_parameter(key, value):
if key in _config:
_config[key] = value
else:
raise KeyError(key)
def get_parameter(parameter):
return _config[parameter]
|
class NotAllowed(Exception):
"""when change class.id"""
class DatabaseException(Exception):
"""Database error"""
class ColumnTypeUnknown(Exception):
"""Variable type unknown"""
class NoFieldException(Exception):
"""Class has no variables"""
class WhereUsageException(Exception):
"""Detected error when you use class.where"""
|
#オリジナル画像と要素画像の画素値を比較し、最も近い色の要素タイルを選んでいく。
class CompareColors():
def __init__(self, original, material):
self.original = original
self.material = material
def compare(self):
#オリジナル画像の分割数を取得する
original_num = len(self.original)
#素材画像が何枚あるか取得する
material_num = len(self.material)
difference_list = []
#細かく分割したオリジナル画像一枚一枚に対して、素材画像全ての平均画素値を比較する。
for j in range(original_num):
one_image_difference_list = [((self.original[j][0] - self.material[i][0])**2)+((self.original[j][1] - self.material[i][1])**2)+\
((self.original[j][2] - self.material[i][2])**2) for i in range(material_num)]
#比較した数値の差が最も小さい値を求める
min_num = min(one_image_difference_list)
#最も平均画素値の差が小さい画像のファイル名を求める
min_filename = one_image_difference_list.index(min_num)
#最も平均画素値の差が小さい画像のファイル名をリストに格納していく
difference_list.append(min_filename)
return difference_list
|
'''
Vasya the Hipster
red blue socks
simple one
'''
socks = list(map(int, input().split(' ')))
socks.sort()
diff = socks[0]
left = socks[1]-socks[0]
same = left//2
#output format
s = str(diff) + ' ' + str(same)
print(s)
|
def fun(a, b, c, d):
return a + b + c + d
def inc(a):
return a + 1
def add(a, b):
return a + b
|
x_arr = []
y_arr = []
for _ in range(3):
x, y = map(int, input().split())
x_arr.append(x)
y_arr.append(y)
for i in range(3):
if x_arr.count(x_arr[i]) == 1:
x4 = x_arr[i]
if y_arr.count(y_arr[i]) == 1:
y4 = y_arr[i]
print(f'{x4} {y4}')
|
# Methods of Tuple in Python:
# Declaring tuple
tuple = (3, 4, 6, 8, 10, 1, 67)
# Code for printing the length of a tuple
tuple2 = ('Apple', 'Bannana', 'Kiwi')
print('length of tuple2 :', len(tuple2))
# Deleting the tuple
del tuple2
# Printing tuple till 2 index excluding 2
print('tuple[0:2]:', tuple[0:2])
# Displaying tuple in reverse order
print('tuple[::-1]:', tuple[::-1])
# Printing element with maximum value from tuple
print('maximum element in tuple:', max(tuple))
# Printing element with maximum value from tuple
print('minimum element in tuple:', min(tuple))
# printing number of times a specified element
print('Number of times 7 repeated:', tuple.count("7"))
|
encoded_bytes=bytes.fromhex("664B564276757A7274796D477A4D4C7A545057456D47575971566F75585A694F4F454B677771647053544E5452654C6F434C544F6E702E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E3E20284E6F74203C6C6F636B746F6B656E3A7772697465313E29203C687474703A2F2F3139322E3136382E36382E313A38302F666A4D6A62656A4B6352474463557342446B4448784673736A476A6C616B714F78584B4F61616A6A41576E48726D45596D586E6F4B432E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E56565941494149414941494149414941494149414941494149414941494149416A5841514144415A41424152414C41594149415141494151414941684141415A3141494149414A31314149414941424142414251493141495149414951493131314149414A5159415A4241424142414241426B4D4147423975344A42596C486861726D30697049705330753969554D6159307154744B42304E50526B71424C4C426B50524D44626B73426C686C4F77474D7A6D564E516B4F546C6D6C5151716C6C424C6C4D504751566F5A6D6A6146675862496272324E77526B31427A70444B6D7A4F4C744B504C6A7171684A4361387A6138515051744B61496D5049716763744B4D795A786B334D6A6E69526B4D64644B4D3136766E51596F564C6661584F6A6D397175775038577030756C364C43716D39684F4B616D4E44434547746E78426B4F684D544B5156733246744B4C4C504B644B4E784B6C59715A33744B4C44444B59715850644971346E446E446F6B714B53317059314A6231796F4B304F6F314F514A626B5A72486B726D614D62484C734C7259706B504248525772536C72614F314453386E6C62576D566B57396F4855747856304D31497079704B7969344E74623062484E497530306B7970696F49454E704E70505032303130323061306E705338786A4C4F476F6770496F77654637506A6B5553385570773831346E3550684C4269706A71714C72695866715A6C5072366237706833697465616471514B4F77654355457064344A6C596F704E39786255486C30687A50574556425236796F6675306A3970515A6B54714652376F784B52794966686F6F396F4855444B703633515A56704B7148304F6E72626D6C4E324A6D706F784D304E3079704B503051524A697070687058364430536B35696F4765426D445839706B5139704D30723352367050424A4B5030566233423733384B5278594668314F496F4855397155734E4955763165686E514B71496F6D72354F673449594F67784C506B504D307970306B5339524C706C6155543232563255424C44345255716273354C714D624F43314E70316750646A6B4E55704255396B3171386F79706D3139704D304E51794B39726D4C39777359657273504B324C4F6A626B6C6D46344A7A746B5744466A746D4F62684D444977796E3930534537784D61376B4B4E375059726D4C7977635A4E34497753565A744D4F71786C544C4749726E346B6F317A4B646E3750304235497070456D7942556A45614F55734141")
decoded_bytes = bytearray([])
for i in range(len(encoded_bytes)//2):
block=encoded_bytes[i*2:i*2+2]
decoded_byte_low = block[1] & 0x0F
decoded_byte_high = (((block[1]) >> 4) + ((block[0]) & 0x0F)) & 0x0F
decoded_byte=decoded_byte_low + (decoded_byte_high <<4)
decoded_bytes.append(decoded_byte)
with open("decrypted.bin", "wb") as f:
f.write(decoded_bytes)
|
def solve(data):
result = 0
# Iterates through each value of the list and sums it to the result
for number in data:
result += number
# Returns result (total sum)
return result
|
A = int(input())
B = int(input())
PROD = A*B
print("PROD = " + str(PROD))
|
def get_metadata(accessions, metadata_database):
#Quirk - metadata accession has .1 as a part of the accession id
accessions_fixed = []
for accession in accessions:
accessions_fixed.append(accession+'.1')
accessions_data = metadata_database.loc[metadata_database['acc'].isin(accessions_fixed)]
return accessions_data
def calc_sens_spec(start, end, genus_regions, blastdb_regions, genus_blastdb_map, blast_results):
def calc_sensitivity(start, end, genus_regions, amplified_accs):
#For sensitivity calculation:
#1) Determine possible desired genus targets by checking assay start
# and assay end against the genus_regions
#2) Check each possible desired genus target in amplified_accs and record
# which ones were successfully amplified
#3) Sensitivity calculation:
# TP / (TP + FN)
# where
# TP = succesfully amplified accessions
# FN = possible accessions that were not amplified
# TP + FN = total number of possible desired genus targets
def check_within_regions(sequence_regions, start, end):
"""Identify which sequences contain the target region.
Note that the target region is considered continuous from
the specified start and end coordinates.
Parameters:
sequence_regions - dictionary returned from get_sequence_regions
[accession_id]:(seq_start, seq_end)
start - start of target regoin
end - end of target region
Output:
traversed_regions - list of accession IDs that contain
the target region
"""
traversed_regions = []
curr_index = 0
for accession in sequence_regions:
region_start = sequence_regions[accession][0]
region_end = sequence_regions[accession][1]
if (
region_start <= start
and region_end >= end
):
traversed_regions.append(accession)
curr_index = curr_index + 1
if curr_index%1000 == 0:
print(f'Current progress: {curr_index}')
return traversed_regions
amplified_targets = []
possible_genus_targets = check_within_regions(genus_regions, start, end)
for accession in possible_genus_targets:
if accession in amplified_accs:
amplified_targets.append(accession)
sensitivity = len(amplified_targets)/len(possible_genus_targets)
return (sensitivity, amplified_targets)
def calc_specificity(start, end, blastdb_regions, genus_regions, genus_blastdb_map, amplified_accs):
#For specificity calculation
#1) From blastdb_regions.keys(), subtract any accession present in the genus alignment.
# This yields a list of accessions that are only non-target.
#2) From amplified_accessions, subtract any accession present in the genus alignment.
# This yields a list of accessions that are only non-target.
#3) For each non-target accession in blastdb_regions, identify possible non-target accessions
# by checking assay start and assay end against blastdb_regions.
#4) Specificity calculation:
# TN / (TN + FP)
# where
# TN = non-target accessions that were not amplified
# TN = (total non-target) - (amplified non-target)
# FP = amplified non-target
# ((Total non-target) - (amplified non-target)) / total non-target
def check_within_regions(sequence_regions, start, end):
"""Identify which sequences contain the target region.
Note that the target region is considered continuous from
the specified start and end coordinates.
Parameters:
sequence_regions - dictionary returned from get_sequence_regions
[accession_id]:(seq_start, seq_end)
start - start of target regoin
end - end of target region
Output:
traversed_regions - list of accession IDs that contain
the target region
"""
traversed_regions = []
curr_index = 0
for accession in sequence_regions:
region_start = sequence_regions[accession][0]
region_end = sequence_regions[accession][1]
if (
region_start <= start
and region_end >= end
):
traversed_regions.append(accession)
curr_index = curr_index + 1
if curr_index%1000 == 0:
print(f'Current progress: {curr_index}')
return traversed_regions
non_target_blastdb_accs = []
non_target_amplified = amplified_accs.copy()
for accession in blastdb_regions.keys():
non_target_blastdb_accs.append(accession)
#Delete target accessions in blastdb and amplified_accs
for accession in genus_regions.keys():
if accession in non_target_blastdb_accs:
del non_target_blastdb_accs[non_target_blastdb_accs.index(accession)]
if accession in non_target_amplified:
non_target_amplified.remove(accession)
#Identify possible non-target accession
mapped_oligo_start = genus_blastdb_map[start]
mapped_oligo_end = genus_blastdb_map[end]
possible_non_target_blastdb = check_within_regions(blastdb_regions, mapped_oligo_start, mapped_oligo_end)
#Specificity calculation
specificity = (len(possible_non_target_blastdb) - len(non_target_amplified))/(len(possible_non_target_blastdb))
return (specificity, non_target_amplified)
amplified_accessions = set(blast_results.loc[:,'sacc'])
sens, targets = calc_sensitivity(start, end, genus_regions, amplified_accessions)
spec, non_targets = calc_specificity(start, end, blastdb_regions, genus_regions, genus_blastdb_map, amplified_accessions)
return (sens, targets, spec, non_targets)
|
def clean_dict(json):
"""
Remove keys with the value None from the dictionary
"""
for key, value in list(json.items()):
if value is None:
del json[key]
elif isinstance(value, dict):
clean_dict(value)
return json
|
def towerOfHanoi(n, source, auxiliary, destination):
if n == 0:
return 0
# Move n-1 from source to auxiliary using destination
stepCnt1 = towerOfHanoi(n-1, source, destination, auxiliary)
# Move nth disc from source to destination
print(f"{n} {source} -> {destination}")
# move n-1 from auxiliary to destination using source
stepCnt2 = towerOfHanoi(n-1, auxiliary, source, destination)
# Return Total Number of Steps
return 1 + stepCnt1 + stepCnt2
towerOfHanoi(10, "A", "B", "C")
|
# Manas Dash
# 24th July 2020
# the usage of set and max function
# which number is repeated most number of time
numbers = [1, 3, 4, 6, 3, 7, 3, 8, 6, 5, 9, 5, 3, 6, 3, 2, 3]
max_repeated = max(set(numbers), key=numbers.count)
print(f"The number {max_repeated} is repeated maximum number of time in the given list")
# The number 3 is repeated maximum number of time in the given list
|
class ZileanBackuper(object):
def __init__(self):
self._machines = None
self._linked_databases = None
@classmethod
def backup_linked_databases(cls):
pass
@classmethod
def backup_database(cls, db):
pass
|
# Copyright 2020 The Private Cardinality Estimation Framework Authors
#
# 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.
"""Set Generator Base Classes"""
class _SetSizeGenerator(object):
"""Get set_size_list from set_size (fixed for each set) and num_sets."""
def __init__(self, num_sets, set_size):
self.num_sets = num_sets
self.set_size = set_size
def __iter__(self):
for _ in range(self.num_sets):
yield self.set_size
class SetGeneratorBase(object):
"""Base object for generating test sets."""
def __next__(self):
raise NotImplementedError()
@classmethod
def get_generator_factory_with_num_and_size(cls):
"""Returns a function Handle which takes a np.random.RandomState as an arg.
This function handle, when called, will return a fully-formed SetGenerator
object, ready to generate sets.
"""
def f(random_state):
_ = random_state
raise NotImplementedError()
_ = f
# In an implementation, you would return f here
# return f
raise NotImplementedError()
@classmethod
def get_generator_factory_with_set_size_list(cls):
"""Returns a function Handle which takes a np.random.RandomState as an arg.
This function handle, when called, will return a fully-formed SetGenerator
object, ready to generate sets.
"""
def f(random_state):
_ = random_state
raise NotImplementedError()
_ = f
# In an implementation, you would return f here
# return f
raise NotImplementedError()
|
def test_content_create(api_client_authenticated):
response = api_client_authenticated.post(
"/content/",
json={
"title": "hello test",
"text": "this is just a test",
"published": True,
"tags": ["test", "hello"],
},
)
assert response.status_code == 200
result = response.json()
assert result["slug"] == "hello-test"
def test_content_list(api_client_authenticated):
response = api_client_authenticated.get("/content/")
assert response.status_code == 200
result = response.json()
assert result[0]["slug"] == "hello-test"
|
[
[0.26982777, 0.20175242, 0.10614473, 0.17290444, 0.22056401],
[0.18268971, 0.2363915, 0.26958793, 0.29282782, 0.36225248],
[0.31735855, 0.30254544, 0.28661105, 0.33136132, 0.40489719],
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.15203597, 0.32214688, 0.40445594, 0.45318467, 0.44650059],
[0.20070068, 0.31904263, 0.40822282, 0.48738756, 0.46520183],
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.24779961, 0.42250711, 0.49311729, 0.46756128, 0.49151833],
]
|
t=int(input())
for k in range(t):
n=int(input())
a=list(map(int,input().strip().split()))
stack=[]
res={}
for i in a:
res[i]=-1
for j in a:
if len(stack)==0:
stack.append(j)
else:
while len(stack)>0 and stack[-1]<j:
res[stack.pop()]=j
stack.append(j)
for p in a:
print(res[p],end=" ")
print()
|
print(int('3') + 3)
print(float('3.2') + 3.5)
print(str(3) + '2')
|
# Copyright 2019 Eficent Business and IT Consulting Services
# Copyright 2017-2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Stock Picking Return Invoicing",
"summary": "Add an option to refund returned pickings",
"version": "12.0.1.0.1",
"category": "Purchases",
"website": "https://github.com/OCA/account-invoicing",
"author": "Eficent,"
"Tecnativa,"
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"development_status": "Mature",
"depends": [
"purchase_stock",
],
"data": [
"views/account_invoice_view.xml",
"views/purchase_view.xml",
],
"maintainers": [
'pedrobaeza',
],
}
|
def get_regr_coeffs(X, y):
n = X.shape[0]
p = n*(X**2).sum() - X.sum()**2
a = ( n*(X*y).sum() - X.sum()*y.sum() ) / p
b = ( y.sum()*(X**2).sum() - X.sum()*(X*y).sum() ) / p
return a,b
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:
return 0
layer = [root]
res = 0
while layer:
node = layer.pop(0)
left = node.left
right = node.right
if left:
layer.append(left)
if not any([left.left, left.right]):
res += left.val
if right:
layer.append(right)
return res
|
# Binary Search Tree (BST) Implementation
class BSTNode:
def __init__(selfNode, nodeData): # Node Structure
selfNode.nodeData = nodeData
selfNode.left = None
selfNode.right = None
selfNode.parent = None
# Insertion Operation
def insert(selfNode, node):
if selfNode.nodeData > node.nodeData:
if selfNode.left is None:
selfNode.left = node
node.parent = selfNode
else:
selfNode.left.insert(node)
elif selfNode.nodeData < node.nodeData:
if selfNode.right is None:
selfNode.right = node
node.parent = selfNode
else:
selfNode.right.insert(node)
# Removal Operation Functions
def replace_node_of_parent(selfNode, new_node):
if selfNode.parent is not None:
if new_node is not None:
new_node.parent = selfNode.parent
if selfNode.parent.left == selfNode:
selfNode.parent.left = new_node
elif selfNode.parent.right == selfNode:
selfNode.parent.right = new_node
else:
selfNode.nodeData = new_node.nodeData
selfNode.left = new_node.left
selfNode.right = new_node.right
if new_node.left is not None:
new_node.left.parent = selfNode
if new_node.right is not None:
new_node.right.parent = selfNode
def find_min(selfNode):
current = selfNode
while current.left is not None:
current = current.left
return current
def remove(selfNode):
if (selfNode.left is not None and selfNode.right is not None):
successor = selfNode.right.find_min()
selfNode.nodeData = successor.nodeData
successor.remove()
elif selfNode.left is not None:
selfNode.replace_node_of_parent(selfNode.left)
elif selfNode.right is not None:
selfNode.replace_node_of_parent(selfNode.right)
else:
selfNode.replace_node_of_parent(None)
# Search required data within BST
def search(selfNode, nodeData):
if selfNode.nodeData > nodeData:
if selfNode.left is not None:
return selfNode.left.search(nodeData)
else:
return None
elif selfNode.nodeData < nodeData:
if selfNode.right is not None:
return selfNode.right.search(nodeData)
else:
return None
return selfNode
# InOrder Traversal Operation
def inorder(selfNode):
if selfNode.left is not None:
selfNode.left.inorder()
print(selfNode.nodeData, end=' ')
if selfNode.right is not None:
selfNode.right.inorder()
# PostOrder Traversal Operation
def postorder(selfNode):
if selfNode.left is not None:
selfNode.left.inorder()
if selfNode.right is not None:
selfNode.right.inorder()
print(selfNode.nodeData, end=' ')
# PreOrder Traversal Operation
def preorder(selfNode):
print(selfNode.nodeData, end=' ')
if selfNode.left is not None:
selfNode.left.inorder()
if selfNode.right is not None:
selfNode.right.inorder()
class BSTree: # Structure of Binary Search Tree
def __init__(selfNode):
selfNode.root = None
def inorder(selfNode):
if selfNode.root is not None:
selfNode.root.inorder()
def preorder(selfNode):
if selfNode.root is not None:
selfNode.root.preorder()
def postorder(selfNode):
if selfNode.root is not None:
selfNode.root.postorder()
def add(selfNode, nodeData):
new_node = BSTNode(nodeData)
if selfNode.root is None:
selfNode.root = new_node
else:
selfNode.root.insert(new_node)
def remove(selfNode, nodeData):
to_remove = selfNode.search(nodeData)
if (selfNode.root == to_remove and selfNode.root.left is None
and selfNode.root.right is None):
selfNode.root = None
else:
to_remove.remove()
def search(selfNode, nodeData):
if selfNode.root is not None:
return selfNode.root.search(nodeData)
bstree = BSTree() # Object of class BSTree
# Menu of Operations on BST Tree
print('BST Tree Operation Menu')
print('Add <data>')
print('Remove <data>')
print('Inorder')
print('Preorder')
print('Postorder')
print('Quit')
while True:
do = input('Enter your action => ').split()
operation = do[0].strip().lower()
if operation == 'add':
nodeData = int(do[1])
bstree.add(nodeData)
elif operation == 'remove':
nodeData = int(do[1])
bstree.remove(nodeData)
elif operation == 'inorder':
print('Inorder Traversal: ', end='')
bstree.inorder()
print()
elif operation == 'postorder':
print('Postorder Traversal: ', end='')
bstree.postorder()
print()
elif operation == 'preorder':
print('Preorder Traversal: ', end='')
bstree.preorder()
print()
elif operation == 'quit':
print("BST Tree Implementation finished.")
break
|
class Stack:
def __init__(self,size=None,limit=1000):
self.top_item = []
self.size = 0
self.limit = limit
def peek(self):
if not self.is_empty():
return self.value[-1]
else:
print("Stack is empty")
def push(self,value):
#print("Current stack:", self.top_item)
#print("size",len(self.top_item))
if self.has_space():
item = self.top_item.append(value)
self.size += 1
else:
print("No space!")
def set_next_node(self):
item = self.top_item.append(self.value)
item = self.top_item
def pop(self):
if not self.is_empty():
item_to_remove = self.top_item
top_item = self.top_item.pop()
self.size -=1
return top_item
else:
print("Stack is empty")
def has_space(self):
if self.limit > self.size:
return True
def is_empty(self):
return self.top_item == []
myStack = Stack()
print(myStack.push("Seema"))
print(myStack.push("Saharan"))
#print(myStack.pop())
print(myStack.peek())
print("empty",myStack.is_empty())
|
ultimo=10
fila=list(range(1,ultimo+1))#Função Sequenciadora de 1 para ultimo +1
fila2=list(range(1,ultimo+1))
while True:# Sempre dará verdadeiro em loop e só sairá no break
print(f"Existem{len(fila)} clientes na fila\n")
print(f"Existem{len(fila2)} clientes na fila\n")
print(f"Fila atual: {fila}\n")
print(f"Fila atual: {fila2}\n")
print("Digite a Fila que deseja atualizar 1 ou a 2: ")
choice=input("Escolha (1) ou (2): )")
if choice=="1":
print("Digite F para adicionar no final da fila,")
print(f"A para realizar o atendimento ou S para sair")
operacao= input("Operação (F,A ou S): ")
if operacao == "A" or operacao=="a":
if len (fila)>0:
atendido = fila.pop(0)
print(f"Cliente {atendido} atendido")
else:
print("Fila vazia!!!")
elif operacao == "F" or operacao=="f":
ultimo+=1
fila.append(ultimo)
elif operacao =="S" or operacao =="s":
break
else:
print("Operação inválida !")
elif choice=="2":
print("Digite F para adicionar no final da fila,")
print(f"A para realizar o atendimento ou S para sair")
operacao= input("Operação (F,A ou S): ")
if operacao == "A" or operacao=="a":
if len (fila2)>0:
atendido = fila2.pop(0)
print(f"Cliente {atendido} atendido")
else:
print("Fila vazia!!!")
elif operacao == "F" or operacao=="f":
ultimo+=1
fila.append(ultimo)
elif operacao =="S" or operacao =="s":
break
else:
print("Operação inválida !")
|
with open("part1.txt", "r") as file:
checksum = 0
for row in file:
large, small = 0, 9999
for entry in row.split("\t"):
entry = int(entry)
if entry > large:
large = entry
if entry < small:
small = entry
checksum += large - small
print(checksum)
|
# BUILD FILE SYNTAX: SKYLARK
SE_VERSION = '3.141.59-atlassian-1'
|
# Python translation of QuadTree from Risk.Platform.Standard
class QuadTree(object): # in decimal degrees dist from centroid to edge
def __init__(self, latDim, longDim, minLatCentroid, minLongCentroid, baseSize):
self.__longDim = longDim
self.__latDim = latDim
self.__minLong = minLongCentroid
self.__baseSize = baseSize
self.__minLat = minLatCentroid
self.__baseGrid = [[Quad("b" + str(latInx) + "-" + str(longInx) + "-", True, self.__baseSize,
latInx * 2 * self.__baseSize + self.__minLat,
longInx * 2 * self.__baseSize + self.__minLong) for longInx in range(0, longDim)] for
latInx in range(0, latDim)]
def Lookup(self, latitude, longitude):
latInx = self.LatInx(latitude)
longInx = self.LongInx(longitude)
if latInx < 0 or latInx >= self.__latDim or longInx < 0 or longInx >= self.__longDim:
return None
return self.__baseGrid[latInx][longInx].Lookup(latitude, longitude)
def LongInx(self, longitude):
return int((longitude - self.__minLong + self.__baseSize) / (2 * self.__baseSize))
def LatInx(self, latitude):
return int((latitude - self.__minLat + self.__baseSize) / (2 * self.__baseSize))
def Load(self, cellId, latitude, longitude, size):
latInx = self.LatInx(latitude)
longInx = self.LongInx(longitude)
self.__baseGrid[latInx][longInx].Load(cellId, latitude, longitude, size)
def PostLoadTest(self):
return all([y.IsValid() for x in self.__baseGrid for y in self.__baseGrid[x]])
class Quad(object):
def __init__(self, cellID, isLeaf, size, lat, lon):
self.CellID = cellID
self.IsLeaf = isLeaf
self.WasLoaded = False
self.Size = size # dist from centroid to edge (start at 2.56 degrees)
self.Lat = lat # centroid latitude
self.Long = lon # centroid longitude
self.Ne = None # children if not a leaf
self.Nw = None
self.Se = None
self.Sw = None
def Divide(self):
newSize = self.Size / 2
self.IsLeaf = False
self.Ne = Quad(self.CellID + "10", True, newSize, self.Lat + newSize, self.Long + newSize)
self.Nw = Quad(self.CellID + "00", True, newSize, self.Lat + newSize, self.Long - newSize)
self.Se = Quad(self.CellID + "11", True, newSize, self.Lat - newSize, self.Long + newSize)
self.Sw = Quad(self.CellID + "01", True, newSize, self.Lat - newSize, self.Long - newSize)
def Lookup(self, latitude, longitude):
if self.IsLeaf:
return self
if latitude <= self.Lat and longitude <= self.Long:
return self.Sw.Lookup(latitude, longitude)
if latitude > self.Lat and longitude > self.Long:
return self.Ne.Lookup(latitude, longitude)
if latitude > self.Lat and longitude <= self.Long:
return self.Nw.Lookup(latitude, longitude)
return self.Se.Lookup(latitude, longitude)
def Load(self, cellId, latitude, longitude, size):
if abs(size - self.Size) < 0.00001:
self.CellID = cellId
self.WasLoaded = True
return
if self.IsLeaf:
self.Divide()
if latitude <= self.Lat and longitude <= self.Long:
self.Sw.Load(cellId, latitude, longitude, size)
if latitude > self.Lat and longitude > self.Long:
self.Ne.Load(cellId, latitude, longitude, size)
if latitude > self.Lat and longitude <= self.Long:
self.Nw.Load(cellId, latitude, longitude, size)
if latitude <= self.Lat and longitude > self.Long:
self.Se.Load(cellId, latitude, longitude, size)
def IsValid(self):
if self.WasLoaded and self.IsLeaf:
return True
if self.WasLoaded and not self.IsLeaf:
return False
if not self.WasLoaded and self.IsLeaf:
return True
return self.Ne.IsValid() and self.Nw.IsValid() and self.Se.IsValid() and self.Sw.IsValid()
|
class FtpStyleUriParser(UriParser):
"""
A customizable parser based on the File Transfer Protocol (FTP) scheme.
FtpStyleUriParser()
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return FtpStyleUriParser()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
|
""" Tuple"""
names = ("rogers","Joan", "Doreen", "Liz", "Peter" )
print(names)
string_tuple = " ".join(str(name) for name in names)
print(string_tuple)
|
def length(t1, n):
t2=t1*n
l=len(t2)
print("Tuple {} has length: {}", t2, l)
length(('1',(5,3)),2)
#Tuple {} length: ('1',(5,3)'1',(5,3)) 4
#note: here .format is missing
def length(t1, n):
t2=t1*n
l=len(t2)
print("Tuple {} has length: {}". format(t2, l))
length(('1',(5,3)),2)
#Tuple ('1',(5,3)'1',(5,3)) has length: 4
|
def repeat(character: str, counter: int) -> str:
"""Repeat returns character repeated `counter` times."""
word = ""
for counter in range(counter):
word += character
return word
|
__author__ = 'Igor Davydenko <playpauseandstop@gmail.com>'
__description__ = 'Flask-Dropbox test project'
__license__ = 'BSD License'
__version__ = '0.3'
|
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
if media < 5:
print('REPROVADO')
elif 5 <= media < 7:
print('RECUPERAÇÃO')
else:
print('APROVADO')
print('Média: {}'.format(media))
|
# -*- coding: utf-8 -*-
# @Date : 18-4-16 下午8:07
# @Author : hetao
# @Email : 18570367466@163.com
# 正在使用的环境 0: 开发环境, 1: 测试环境, 2: 生产环境
ENVIRONMENT = 0
# ===========================================================
# 本地调试
# ===========================================================
# mongodb
DATABASE_HOST = '192.168.14.240'
# redis
REDIS_HOST = '192.168.14.240'
# ===========================================================
# 通用配置
# ===========================================================
# mongodb
DATABASE_ENGINE = 'mongodb' # 留着备用
DATABASE_PORT = 27017
# redis
REDIS_NAME = 2
REDIS_NAME_PRO = 1
REDIS_PORT = 6379
# wallet_field
# 只和数据库进行交互的dict类型字段
DICT_DB_FIELD = ('master_private_keys', 'master_public_keys', 'addr_history',
'transactions', 'txi', 'txo', 'pruned_txo',
'claimtrie_transactions', 'verified_tx3',
'accounts',
)
# 既和数据库进行交互, 又和内存交互的dict类型字段
DICT_BOTH_FIELD = ()
# 只和数据库进行交互的 list 类型字段
LIST_DB_FIELD = ('addresses',)
# 既和数据库进行交互, 又和内存交互的 list 类型字段
LIST_BOTH_FIELD = ()
# 单个长度字段
NOR_FIELD = ('seed', 'stored_height', 'use_changes')
WALLET_FIELD = DICT_BOTH_FIELD + DICT_DB_FIELD + LIST_DB_FIELD + LIST_BOTH_FIELD + NOR_FIELD
|
# @dependency 001-main/002-createrepository.py
SHA1 = "66f25ae79dcc5e200b136388771b5924a1b5ae56"
with repository.workcopy() as work:
REMOTE_URL = instance.repository_url("alice")
work.run(["checkout", "-b", "008-branch", SHA1])
work.run(["rebase", "--force-rebase", "HEAD~5"])
work.run(["push", REMOTE_URL, "008-branch"])
sha1 = work.run(["rev-parse", "HEAD"]).strip()
try:
instance.unittest("api.branch", ["basic"],
args=["--sha1=" + sha1,
"--name=008-branch"])
finally:
work.run(["push", REMOTE_URL, ":008-branch"])
|
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: h5part.py
#
# Programmer: Gunther Weber
# Date: January, 2009
#
# Modifications:
# Mark C. Miller, Wed Jan 21 09:36:13 PST 2009
# Took Gunther's original code and integrated it with test suite.
#
# ----------------------------------------------------------------------------
RequiredDatabasePlugin("H5Part")
TurnOffAllAnnotations()
OpenDatabase(data_path("h5part_test_data/sample.h5part"), 0)
AddPlot("Pseudocolor", "GaussianField", 1, 0)
DrawPlots()
Test("h5part_01")
ChangeActivePlotsVar("LinearField")
View3DAtts = GetView3D()
View3DAtts.viewNormal = (1.000000, 0.000000, 0.0000000)
View3DAtts.focus = (31.5, 31.5, 31.5)
View3DAtts.viewUp = (0.000000, 1.000000, 0.0000000)
View3DAtts.viewAngle = 30
View3DAtts.parallelScale = 54.5596
View3DAtts.nearPlane = -109.119
View3DAtts.farPlane = 109.119
View3DAtts.imagePan = (0, 0)
View3DAtts.imageZoom = 1
View3DAtts.perspective = 1
View3DAtts.eyeAngle = 2
View3DAtts.centerOfRotationSet = 0
View3DAtts.centerOfRotation = (31.5, 31.5, 31.5)
SetView3D(View3DAtts)
Test("h5part_02")
DeleteActivePlots()
AddPlot("Pseudocolor", "px", 1, 0)
PseudocolorAtts = PseudocolorAttributes()
PseudocolorAtts.pointType = PseudocolorAtts.Sphere
PseudocolorAtts.pointSize = 1.5
SetPlotOptions(PseudocolorAtts)
DrawPlots()
Test("h5part_03")
AddPlot("Pseudocolor", "LinearField", 1, 0)
AddOperator("Slice", 0)
SliceAtts = SliceAttributes()
SliceAtts.originType = SliceAtts.Intercept
SliceAtts.originIntercept = 30
SliceAtts.axisType = SliceAtts.XAxis
SliceAtts.project2d = 0
SliceAtts.meshName = "particles"
SetOperatorOptions(SliceAtts)
DrawPlots()
Test("h5part_04")
Exit()
|
# 题意:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。即蛇形输出
# 题解1:模拟法,主要考虑各种边界情况。。degbug。。
# 题解2: 用python的特性,重复:输出第一行,删掉第一行(加入result),翻转。 matrix是由list中list组成,pop(0)输出第一行,然后将matrix按行zip起来倒序,就等于将矩阵向左翻转90度,再pop删掉,重复操作即可。
class Solution:
def spiralOrder(self, matrix):
# inputs: matrix: List[List[int]]
# outputs: List[int]
if not matrix:
return []
l, r, t, b = 0, len(matrix[0]), 0, len(matrix)
res = []
while True:
# 从左到右
for i in range(l,r):
res.append(matrix[t][i])
t += 1
if t>=b: break
# 从上到下
for j in range(t,b):
res.append(matrix[j][r-1])
r -= 1
if l>=r: break
# 从右到左
for k in range(r-1,l-1,-1):
res.append(matrix[b-1][k])
b -= 1
if t>=b: break
# 从下到上
for q in range(b-1,t-1,-1):
res.append(matrix[q][l])
l += 1
if l>=r: break
return res
class Solution_2:
def spiralOrder(self, matrix):
# inputs: matrix: List[List[int]]
# outputs: List[int]
if not matrix:
return []
res = []
while matrix:
res += matrix.pop(0)
matrix = list(zip(*matrix))[::-1]
return res
|
def artist():
return "The Hardkiss"
def genre():
return "Pop"
def year():
return 2014
def restrictedContent():
return False
def forGeneralAudiences():
return True
|
class TestErrors:
"""Errors"""
pass
|
########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: Funções para:
# ler e criar um cabeçalho;
# criar um rodapé;
# criar linha;
# ler e validar resposta se deseja continuar
# validar recebimento de uma string formada apenas por letras.
########
def ler_cabecalho(msg):
'''
recebe uma string e retorna a mesma em caixa alta com espaçamento de 50 caracteres, incluindo a string passada.
linha pontilhada em baixo e em cima.
'''
print('-'*50)
print(f'{msg.upper():^50}')
print('-'*50)
def criar_rodape():
'''
sem parâmetro
retorna a string FIM com espaçamento de 50 caracteres, incluindo a string.
linha pontilhada em baixo e em cima.
'''
print('-'*50)
print(f'{str.upper("fim"):^50}')
print('-'*50)
def criar_linha(tam=50):
'''
sem parâmetro.
retorna sinais de = repetidos em 50 caracteres.
'''
print()
print('-'*tam)
print()
def ler_resposta(msg):
'''
Aceita que o usuário digite apenas S/SIM ou N/Não
'''
while True:
try:
#[0] captura apenas o primeiro caractere da string
#strip() remove os espaços no começo e no fim
#upper() transforma string em maiúscula
#input() captura o que é digitado
#atribuindo valor à variável 'resposta'
resposta = input(msg).upper().strip()[0]
#verifica se não está contido na string 'SN';
# não há conflito, pois 'resposta' captura apenas a posição inicial da string
if resposta not in 'SN':
#criando exceção
raise Exception('S para sim ou N para não')
#em caso de resposta vazia;
# caso não haja string para pegar a posição inicial
except IndexError:
print(f'Resposta inválida.')
continue
#chama a exceção criada
#variável 'e' retorna a mensagem da exceção
except Exception as erro:
#print(f'') retorna uma string formatada na tela
print(f'Resposta inválida: {erro}')
#volta para o início do laço
continue
#se o 'try' for válido
else:
#retorna o valor da resposta
return resposta
def ler_palavra(msg):
'''
Verifica se o que foi digitado foram apenas letras
'''
while True:
try:
palavra = input(msg).upper().strip()
#retirando espaços
palavras = palavra.split()
palavras = ''.join(palavras)
#isalpha() se possui apenas letras
#verificando se palavra possui caracteres que não sejam letras
if not palavras.isalpha():
raise Exception('Digite apenas letras.')
except Exception as erro:
print(f'Valor inválido: {erro}')
continue
#se o 'try' for válido
else:
return palavra
|
#Exercício Python 010: Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
real = float(input('Digite seu dinheiro em BRL: '))
dolar = real * 0.19
print('Com R${:.2f} você pode comprar U${:.2f}'.format(real, dolar))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.