blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
sequencelengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
683d159a37abb8fcabc1893bcb298c151da97ec0 | 1cd5275832f8af8d0550fc0539836a3baf95ea7c | /MouseEvent.py | d26a14a2d5a4bab2773920e77f3884a3d4029d2a | [] | no_license | NyangUk/AutoSoldering | b10a67a0812ee90c1758972cc44ec6db2e2d80ea | 29d21572ad534c8a97243bb4211485e05f20b8df | refs/heads/master | 2023-02-25T20:32:30.808231 | 2021-01-29T04:19:14 | 2021-01-29T04:19:14 | 269,067,416 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,014 | py | import cv2
import numpy as np
# 클릭 이벤트 선언
ROIevents = [i for i in dir(cv2) if 'EVENT' in i]
# SelectEvents = [j for j in dir(cv2) if 'EVENT' in j]
# 클릭이 되었을때 드래그 할것 이므로 Click flag 넘기기
OriginalImg = cv2.imread('PCB(0).jpg')
H,W,C =OriginalImg.shape[:]
RoiImg = np.zeros((H,W,C),np.uint8)
mask = np.zeros((H,W,C),np.uint8)
# H,W,C = oriSP.shape
SelectPointImg = np.zeros((H,W,C),np.uint8)
click = False
# click = False
x1,y1,x2,y2 = -1,-1,-1,-1
def CallROIMouse(event ,x,y,flags,param):
global x1,y1,x2,y2,RoiImg,mask#,click
RoiImg = OriginalImg
if event == cv2.EVENT_LBUTTONDOWN: # 마우스 누를때
# click = True
x1,y1 =x,y
elif event == cv2.EVENT_LBUTTONUP: # 마우스 땔때
# click =False
x2,y2 =x,y
cv2.rectangle(RoiImg,(x1,y1),(x2,y2),(0,0,0),-1)
def CropRoi():
global RoiImg
while True:
cv2.imshow('img',OriginalImg)
cv2.namedWindow('img')
cv2.setMouseCallback('img',CallROIMouse)
if cv2.waitKey(1)&0xFF == 27:
print("roi 선택을 그만두셨습니다.")
break
elif cv2.waitKey(1)&0xFF == ord('s'):
cv2.imwrite('AppliedROI.jpg',RoiImg)
print("roi 선택 완료")
break
elif cv2.waitKey(1)&0xFF == ord('r'):
RoiImg = OriginalImg
cv2.imshow('img',OriginalImg)
print("roi 선택을 다시합니다.")
def CallPointMouse(event ,x,y,flags,param):
global x1,y1,x2,y2,click,SelectPointImg
# SelectPointImg = oriSP
if event == cv2.EVENT_LBUTTONDOWN: # 마우스 누를때
click = True
cv2.circle(SelectPointImg,(x,y),7,(0,255,0),-1)
elif event == cv2.EVENT_MOUSEMOVE: # 그냥 움직일때도 인식할수 있으므로 Click flag로 관리한다.
if click:
cv2.circle(SelectPointImg,(x,y),7,(0,255,0),-1)
# break
elif event == cv2.EVENT_LBUTTONUP: # 마우스 땔때
click =False
def Point():
while True:
cv2.imshow('simg',oriSP)
cv2.namedWindow('simg')
cv2.setMouseCallback('simg',CallPointMouse)
cv2.imshow('result',SelectPointImg)
# elif k ==ord('f'):
if cv2.waitKey(1) & 0xFF == ord('s'):
print("납땜 활성화 포인트 저장완료")
break
cv2.imwrite('SelectPoint.jpg',SelectPointImg)
def Cvt(holeImg,selectedholeImg):
mask = cv2.imread("SelectPoint.jpg",cv2.IMREAD_GRAYSCALE)
img = cv2.imread("Hole(Checking).jpg",cv2.IMREAD_GRAYSCALE)
ret, mask = cv2.threshold(mask ,10, 255, cv2.THRESH_BINARY)
result=cv2.bitwise_and(img,mask,mask =mask)
cv2.imwrite('result.jpg',result)
cv2.imshow('re',result)
cv2.waitKey(0)
CropRoi()
oriSP = cv2.imread("AppliedROI.jpg")
Point()
Cvt(oriSP,SelectPointImg)
| [
"[email protected]"
] | |
2a75e8b776adf77118adf0d54f42f84b2551c522 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/303/usersdata/303/113604/submittedfiles/testes.py | b38cb9db11ad8f8582188be5061ca9df68f86486 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 536 | py | nome=str(input('DIGITE O NOME DO USUÁRIO:'))
n=int(input('DIGITE A QUANTIDADE DE CARACTERES:'))
senha=[]
for i in range(0,n,1):
senha.append(int(input('DIGITE UM NUMERO P SENHA:')))
cont=0
for i in range(0,n-1,1):
if senha[i] == senha[i+1]:
cont+=1
while cont != 0:
print('SENHA INVÁLIDA')
for i in range(0,n,1):
senha.append(int(input('DIGITE UM NUMERO P SENHA:')))
cont=0
for i in range(0,n-1,1):
if senha[i] == senha [i+1]:
cont +=1
else:
print('SENHA VALIDA') | [
"[email protected]"
] | |
b83e8a6ee60459e5d14a6c88488c71a87a39bf03 | bb150497a05203a718fb3630941231be9e3b6a32 | /models/PaddleHub/hub_all_func/test_hrnet18_imagenet.py | fe47da5a17a9ed230afe2c30b89ac3851267324b | [] | no_license | PaddlePaddle/PaddleTest | 4fb3dec677f0f13f7f1003fd30df748bf0b5940d | bd3790ce72a2a26611b5eda3901651b5a809348f | refs/heads/develop | 2023-09-06T04:23:39.181903 | 2023-09-04T11:17:50 | 2023-09-04T11:17:50 | 383,138,186 | 42 | 312 | null | 2023-09-13T11:13:35 | 2021-07-05T12:44:59 | Python | UTF-8 | Python | false | false | 490 | py | """hrnet18_imagenet"""
import os
import paddle
import paddlehub as hub
if paddle.is_compiled_with_cuda():
paddle.set_device("gpu")
use_gpu = True
else:
paddle.set_device("cpu")
use_gpu = False
def test_hrnet18_imagenet_predict():
"""hrnet18_imagenet predict"""
os.system("hub install hrnet18_imagenet")
model = hub.Module(name="hrnet18_imagenet")
result = model.predict(["doc_img.jpeg"])
print(result)
os.system("hub uninstall hrnet18_imagenet")
| [
"[email protected]"
] | |
02c4dcd07823de17baa8b4d8aab9220976d3e480 | 338dbd8788b019ab88f3c525cddc792dae45036b | /bin/jupyter-trust | 61083c1cbdc70c3a63711f834326a32daebbb528 | [] | permissive | KshitizSharmaV/Quant_Platform_Python | 9b8b8557f13a0dde2a17de0e3352de6fa9b67ce3 | d784aa0604d8de5ba5ca0c3a171e3556c0cd6b39 | refs/heads/master | 2022-12-10T11:37:19.212916 | 2019-07-09T20:05:39 | 2019-07-09T20:05:39 | 196,073,658 | 1 | 2 | BSD-3-Clause | 2022-11-27T18:30:16 | 2019-07-09T19:48:26 | Python | UTF-8 | Python | false | false | 284 | #!/Users/kshitizsharma/Desktop/Ktz2/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from nbformat.sign import TrustNotebookApp
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(TrustNotebookApp.launch_instance())
| [
"[email protected]"
] | ||
3b7117eaffa82e3a6acc038157c672635cab47e5 | bfaf64c553eb43684970fb3916eedaafbecf0506 | /Hunter/set3/as2.py | a20bf7a7d5f61c0501ab86d7d268d2d9fd64b8fd | [] | no_license | santhoshbabu4546/GUVI-9 | 879e65df0df6fafcc07166b2eaecf676ba9807a2 | b9bfa4b0fa768e70c8d3f40b11dd1bcc23692a49 | refs/heads/master | 2022-01-24T15:22:34.457564 | 2019-07-21T14:20:35 | 2019-07-21T14:20:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 127 | py | b=int(input())
lst1=list(map(int,input().split()))
re1=1
len=[]
for i in lst1:
re1=re1*i
for i in lst1:
len.append(re1//i)
| [
"[email protected]"
] | |
61fde716fc9aa18c597e13bf6a75fae4f5e24a20 | dde0d75db42c19390f2625a7888586e4d2a14fd7 | /devel/lib/python2.7/dist-packages/cob_object_detection_msgs/msg/_DetectObjectsFeedback.py | 0b38ddd2ccca9d736873f4fb3f3af80c934bc709 | [] | no_license | dhemp09/uml-robotics | 16460efe8195a3f9a6a8296047f4fd4d9df0de80 | 862132e00e221b0a86bc283e7568efa984be673f | refs/heads/master | 2020-03-26T09:44:04.033762 | 2018-08-15T18:11:18 | 2018-08-15T18:11:18 | 144,762,178 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 141 | py | /home/dan/dan_ws/devel/.private/cob_object_detection_msgs/lib/python2.7/dist-packages/cob_object_detection_msgs/msg/_DetectObjectsFeedback.py | [
"[email protected]"
] | |
67b29bf7daa0c0b0ce6c52fe5c85eb82b14b1151 | bd72c02af0bbd8e3fc0d0b131e3fb9a2aaa93e75 | /Math/reverse_integer.py | 3530292157d2d2c928ffdf80db8d13c8f43c9475 | [] | no_license | harvi7/Leetcode-Problems-Python | d3a5e8898aceb11abc4cae12e1da50061c1d352c | 73adc00f6853e821592c68f5dddf0a823cce5d87 | refs/heads/master | 2023-05-11T09:03:03.181590 | 2023-04-29T22:03:41 | 2023-04-29T22:03:41 | 222,657,838 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 261 | py | class Solution:
def reverse(self, x: int) -> int:
res, remains = 0, abs(x)
while remains:
res, remains = res * 10 + remains % 10, remains // 10
if x < 0: res *= -1
return res if abs(res) < 0x7fffffff else 0 | [
"[email protected]"
] | |
c28fb8fc2a4334556b948b4b105d41221be43ad9 | 4b72cfb730e9d967ecc9ece7a5dcdff03242ce7a | /7 კლასი/7_3/ფეიქრიშვილი თამარ/ციფრთა_ჯამი.py | b84fcd3aec12120e492bd3a5755e719354dbfd7f | [] | no_license | sc-199/2018-2019 | 20945a0aaf7a998e6038e3fd3310c8be2296e54f | 578d7aad254dc566cf5f8502f1a82c1eb267cbc2 | refs/heads/master | 2020-04-26T02:59:26.560166 | 2019-05-03T13:32:30 | 2019-05-03T13:32:30 | 168,499,541 | 4 | 0 | null | 2019-02-14T17:17:25 | 2019-01-31T09:36:13 | Python | UTF-8 | Python | false | false | 157 | py | n1=input ("რიცხვი :")
n1=int(n1)
n2=n1
ans=0
while (n1>0):
ans+=n1%10
n1//=10
print (n2,"ის ციფრთა ჯამია",ans)
| [
"[email protected]"
] | |
43c200e5d7084e82f82da331ad9eca1cb8cf1156 | 6d48a1f8d4243ddffad0b0fc9d035baf7a9ca87b | /citibike.py | 250539533bac1970c5dad98d2aaef407386a2155 | [] | no_license | scstu/GCNTrafficPrediction | 38027cc437555f59b90f79070e24dce3a8b44b4e | 4eae5b1515fec1b39e0483710de998deec72bbce | refs/heads/master | 2022-11-14T21:47:52.972377 | 2020-07-02T03:54:17 | 2020-07-02T03:54:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,633 | py | import os
import argparse
import numpy as np
import tensorflow as tf
#from gensim.models import Word2Vec
from model.FC_LSTM import FC_LSTM
from model.FC_GRU import FC_GRU
from model.GCN import GCN
from model.Coupled_GCN import Coupled_GCN
from model.flow_GCN import flow_GCN
from solver import ModelSolver
from preprocessing import *
from utils import *
from dataloader import *
# import scipy.io as sio
def main():
parse = argparse.ArgumentParser()
# ---------- environment setting: which gpu -------
parse.add_argument('-gpu', '--gpu', type=str, default='0', help='which gpu to use: 0 or 1')
parse.add_argument('-folder_name', '--folder_name', type=str, default='datasets/citibike-data/data/')
parse.add_argument('-output_folder_name', '--output_folder_name', type=str, default='output/citibike-data/data/')
# ---------- input/output settings -------
parse.add_argument('-input_steps', '--input_steps', type=int, default=6,
help='number of input steps')
# ---------- model ----------
parse.add_argument('-model', '--model', type=str, default='GCN', help='model: DyST, GCN, AttGCN')
parse.add_argument('-num_layers', '--num_layers', type=int, default=2, help='number of layers in model')
parse.add_argument('-num_units', '--num_units', type=int, default=64, help='dim of hidden states')
parse.add_argument('-trained_adj_mx', '--trained_adj_mx', type=int, default=0, help='if training adjacent matrix')
parse.add_argument('-filter_type', '--filter_type', type=str, default='dual_random_walk', help='laplacian, random_walk, or dual_random_walk')
parse.add_argument('-delta', '--delta', type=int, default=1e7, help='delta to calculate rescaled weighted matrix')
parse.add_argument('-epsilon', '--epsilon', type=float, default=0.8, help='epsilon to calculate rescaled weighted matrix')
parse.add_argument('-dy_adj', '--dy_adj', type=int, default=1,
help='whether to use dynamic adjacent matrix for lower feature extraction layer')
parse.add_argument('-dy_filter', '--dy_filter', type=int, default=0,
help='whether to use dynamic filter generate region-specific filter ')
#parse.add_argument('-att_dynamic_adj', '--att_dynamic_adj', type=int, default=1, help='whether to use dynamic adjacent matrix in attention parts')
parse.add_argument('-model_save', '--model_save', type=str, default='gcn', help='folder name to save model')
parse.add_argument('-pretrained_model', '--pretrained_model_path', type=str, default=None,
help='path to the pretrained model')
# ---------- params for CNN ------------
parse.add_argument('-num_filters', '--num_filters', type=int,
default=32, help='number of filters in CNN')
parse.add_argument('-pooling_units', '--pooling_units', type=int,
default=64, help='number of pooling units')
parse.add_argument('-dropout_keep_prob', '--dropout_keep_prob', type=float,
default=0.5, help='keep probability in dropout layer')
# ---------- training parameters --------
parse.add_argument('-n_epochs', '--n_epochs', type=int, default=20, help='number of epochs')
parse.add_argument('-batch_size', '--batch_size', type=int, default=8, help='batch size for training')
parse.add_argument('-show_batches', '--show_batches', type=int,
default=100, help='show how many batches have been processed.')
parse.add_argument('-lr', '--learning_rate', type=float, default=0.0002, help='learning rate')
parse.add_argument('-update_rule', '--update_rule', type=str, default='adam', help='update rule')
# ---------- train or predict -------
parse.add_argument('-train', '--train', type=int, default=1, help='whether to train')
parse.add_argument('-test', '--test', type=int, default=0, help='if test')
#
args = parse.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
print('load train, test data...')
# train: 20140401 - 20140831
# validate: 20140901 - 20140910
# test: 20140911 - 20140930
split = [3672, 240, 480]
#split = [3912, 480]
data, train_data, val_data, test_data = load_npy_data(
filename=[args.folder_name+'d_station.npy', args.folder_name+'p_station.npy'], split=split)
# data: [num, station_num, 2]
#f_data, train_f_data, val_f_data, test_f_data = load_pkl_data(args.folder_name + 'f_data_list.pkl', split=split)
f_data, train_f_data, val_f_data, test_f_data = load_npy_data(filename=[args.folder_name + 'citibike_flow_data.npy'], split=split)
print(len(f_data))
print('preprocess train/val/test flow data...')
#f_preprocessing = StandardScaler()
f_preprocessing = MinMaxNormalization01()
f_preprocessing.fit(train_f_data)
train_f_data = f_preprocessing.transform(train_f_data)
if val_f_data is not None:
val_f_data = f_preprocessing.transform(val_f_data)
test_f_data = f_preprocessing.transform(test_f_data)
print('preprocess train/val/test data...')
pre_process = MinMaxNormalization01()
#pre_process = StandardScaler()
pre_process.fit(train_data)
train_data = pre_process.transform(train_data)
if val_data is not None:
val_data = pre_process.transform(val_data)
test_data = pre_process.transform(test_data)
#
num_station = data.shape[1]
print('number of station: %d' % num_station)
#
train_loader = DataLoader_graph(train_data, train_f_data,
args.input_steps, flow_format='identity')
if val_data is not None:
val_loader = DataLoader_graph(val_data, val_f_data,
args.input_steps, flow_format='identity')
else:
val_loader = None
test_loader = DataLoader_graph(test_data, test_f_data,
args.input_steps, flow_format='identity')
# f_adj_mx = None
if os.path.isfile(args.folder_name + 'f_adj_mx.npy'):
f_adj_mx = np.load(args.folder_name + 'f_adj_mx.npy')
else:
f_adj_mx = train_loader.get_flow_adj_mx()
np.save(args.folder_name + 'f_adj_mx.npy', f_adj_mx)
#
#
if args.filter_type == 'laplacian':
w = np.load(args.folder_name + 'w.npy')
# w = np.array(w, dtype=np.float32)
W = get_rescaled_W(w, delta=args.delta, epsilon=args.epsilon)
# Calculate graph kernel
L = scaled_laplacian(W)
#
f_adj_mx = L
if args.model == 'FC_LSTM':
model = FC_LSTM(num_station, args.input_steps,
num_layers=args.num_layers, num_units=args.num_units,
batch_size=args.batch_size)
if args.model == 'FC_GRU':
model = FC_GRU(num_station, args.input_steps,
num_layers=args.num_layers, num_units=args.num_units,
batch_size=args.batch_size)
if args.model == 'GCN':
model = GCN(num_station, args.input_steps,
num_layers=args.num_layers, num_units=args.num_units,
dy_adj=args.dy_adj, dy_filter=args.dy_filter,
f_adj_mx=f_adj_mx, trained_adj_mx=args.trained_adj_mx,
filter_type=args.filter_type,
batch_size=args.batch_size)
if args.model == 'flow_GCN':
model = flow_GCN(num_station, args.input_steps,
num_layers=args.num_layers, num_units=args.num_units,
f_adj_mx=f_adj_mx, trained_adj_mx=args.trained_adj_mx,
filter_type=args.filter_type,
batch_size=args.batch_size)
if args.model == 'Coupled_GCN':
model = Coupled_GCN(num_station, args.input_steps,
num_layers=args.num_layers, num_units=args.num_units,
f_adj_mx=f_adj_mx, trained_adj_mx=args.trained_adj_mx,
filter_type=args.filter_type,
batch_size=args.batch_size)
#
model_path = os.path.join(args.output_folder_name, 'model_save', args.model_save)
if not os.path.exists(model_path):
os.makedirs(model_path)
#model_path = os.path.join(args.folder_name, 'model_save', args.model_save)
solver = ModelSolver(model, train_loader, val_loader, test_loader, pre_process,
batch_size=args.batch_size,
show_batches=args.show_batches,
n_epochs=args.n_epochs,
pretrained_model=args.pretrained_model_path,
update_rule=args.update_rule,
learning_rate=args.learning_rate,
model_path=model_path,
)
results_path = os.path.join(model_path, 'results')
if not os.path.exists(results_path):
os.makedirs(results_path)
if args.train:
print('==================== begin training ======================')
test_target, test_prediction = solver.train(os.path.join(model_path, 'out'))
np.save(os.path.join(results_path, 'test_target.npy'), test_target)
np.save(os.path.join(results_path, 'test_prediction.npy'), test_prediction)
if args.test:
print('==================== begin test ==========================')
test_target, test_prediction = solver.test()
np.save(os.path.join(results_path, 'test_target.npy'), test_target)
np.save(os.path.join(results_path, 'test_prediction.npy'), test_prediction)
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
a2b0c359f4da196842f99948a3ee61a1f4d744ca | 3fbd28e72606e5358328bfe4b99eb0349ca6a54f | /.history/a_lucky_number_20210606191954.py | b041fa21188bdd03b0ad2ed3d85af6f7cb3e4810 | [] | no_license | Tarun1001/codeforces | f0a2ef618fbd45e3cdda3fa961e249248ca56fdb | 576b505d4b8b8652a3f116f32d8d7cda4a6644a1 | refs/heads/master | 2023-05-13T04:50:01.780931 | 2021-06-07T21:35:26 | 2021-06-07T21:35:26 | 374,399,423 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 132 | py | n= int(input())
count= 0
while n!=0:
if n%10==4 or n%10==7:
count+=1
n=n/10
if count ==4 or count==7:
| [
"[email protected]"
] | |
dad8cf8c89082d71ba12771c42b06974bbf8d0aa | 509823ea14f04d5791486b56a592d7e7499d7d51 | /parte18/demo50_dibujo.py | 11b11c4fa76b7a6c4582464be00e4da3e8ffbbd7 | [] | no_license | Fhernd/Python-CursoV2 | 7613144cbed0410501b68bedd289a4d7fbefe291 | 1ce30162d4335945227f7cbb875f99bc5f682b98 | refs/heads/master | 2023-08-08T05:09:44.167755 | 2023-08-05T19:59:38 | 2023-08-05T19:59:38 | 239,033,656 | 64 | 38 | null | null | null | null | UTF-8 | Python | false | false | 1,643 | py | from tkinter import Canvas, Tk
class Dibujo(object):
def __init__(self, master):
self.master = master
self.inicializar_gui()
def inicializar_gui(self):
self.canvas = Canvas(bg='white', height=300, width=300)
self.canvas.pack()
self.canvas.bind('<ButtonPress-1>', self.iniciar_dibujo)
self.canvas.bind('<B1-Motion>', self.dibujar)
self.canvas.bind('<Double-1>', self.limpiar)
self.canvas.bind('<ButtonPress-3>', self.mover)
self.tipos_figuras = [self.canvas.create_oval, self.canvas.create_rectangle]
self.dibujo = None
def iniciar_dibujo(self, evento):
self.figura = self.tipos_figuras[0]
self.tipos_figuras = self.tipos_figuras[1:] + self.tipos_figuras[:1]
self.inicio = evento
self.dibujo = None
def dibujar(self, evento):
canvas = evento.widget
if self.dibujo:
self.canvas.delete(self.dibujo)
id_figura = self.figura(self.inicio.x, self.inicio.y, evento.x, evento.y)
self.dibujo = id_figura
def limpiar(self, evento):
evento.widget.delete('all')
def mover(self, evento):
if self.dibujo:
canvas = evento.widget
diferencia_x = evento.x - self.inicio.x
diferencia_y = evento.y - self.inicio.y
canvas.move(self.dibujo, diferencia_x, diferencia_y)
self.inicio = evento
def main():
master = Tk()
master.title('Dibujo')
master.geometry('300x300')
ventana = Dibujo(master)
master.mainloop()
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
758a78f2514e8832a8e26e6989826523e8f71918 | 8be5929368bd987caf744c92f234884bf49d3d42 | /services/web/apps/main/messageroute/views.py | cff0d7e546d5ec40804fdad5750c0b3a05d585a6 | [
"BSD-3-Clause"
] | permissive | oleg-soroka-lt/noc | 9b670d67495f414d78c7080ad75f013ab1bf4dfb | c39422743f52bface39b54d5d915dcd621f83856 | refs/heads/master | 2023-08-21T03:06:32.235570 | 2021-10-20T10:22:02 | 2021-10-20T10:22:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 716 | py | # ----------------------------------------------------------------------
# main.messageroute application
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC modules
from noc.lib.app.extdocapplication import ExtDocApplication
from noc.main.models.messageroute import MessageRoute
from noc.core.translation import ugettext as _
class MessageRouteApplication(ExtDocApplication):
"""
MessageRoute application
"""
title = "Message Route"
menu = [_("Setup"), _("Message Routes")]
model = MessageRoute
glyph = "arrows-alt"
| [
"[email protected]"
] | |
8acebdf1f210641c6ca8b6e7b089a55c784932ea | 7dc240e587213e4b420676c60aa1b24905b1b2e4 | /src/diplomas/services/diploma_generator.py | 12a3fca9d83d34bd91583ed496ca192eb36fe208 | [
"MIT"
] | permissive | denokenya/education-backend | 834d22280717f15f93407108846e2eea767421c8 | 3b43ba0cc54c6a2fc2f1716170393f943323a29b | refs/heads/master | 2023-08-27T09:07:48.257108 | 2021-11-03T00:19:04 | 2021-11-03T00:19:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,932 | py | import requests
from dataclasses import dataclass
from django.conf import settings
from django.core.files.base import ContentFile
from urllib.parse import urljoin
from diplomas.models import Diploma, DiplomaTemplate
from products.models import Course
from studying.models import Study
from users.models import User
class WrongDiplomaServiceResponse(requests.exceptions.HTTPError):
pass
@dataclass
class DiplomaGenerator:
course: Course
student: User
language: str
def __call__(self) -> Diploma:
image = self.fetch_image()
diploma = self.create_diploma()
diploma.image.save(name='diploma.png', content=image)
return diploma
@property
def study(self) -> Study:
return Study.objects.get(student=self.student, course=self.course)
@property
def template(self) -> DiplomaTemplate:
return DiplomaTemplate.objects.get(
course=self.course,
language=self.language,
)
def create_diploma(self) -> Diploma:
return Diploma.objects.get_or_create(
study=self.study,
language=self.language,
)[0]
def fetch_image(self) -> ContentFile:
response = requests.get(
url=self.get_external_service_url(),
params=self.get_template_context(),
headers={
'Authorization': f'Bearer {settings.DIPLOMA_GENERATOR_TOKEN}',
},
)
if response.status_code != 200:
raise WrongDiplomaServiceResponse(f'Got {response.status_code} status code: {response.text}')
return ContentFile(response.content)
def get_external_service_url(self) -> str:
return urljoin(settings.DIPLOMA_GENERATOR_HOST, f'/{self.template.slug}.png')
def get_template_context(self) -> dict:
return {
'name': str(self.student),
'sex': self.student.gender[:1],
}
| [
"[email protected]"
] | |
84fa237b31973a55a76d7db0c5c59e4a408aa9d0 | a40950330ea44c2721f35aeeab8f3a0a11846b68 | /Django/Django.py | 4224dc68380a1c0e32675dc55a56ce3ce59e7ead | [] | no_license | huang443765159/kai | 7726bcad4e204629edb453aeabcc97242af7132b | 0d66ae4da5a6973e24e1e512fd0df32335e710c5 | refs/heads/master | 2023-03-06T23:13:59.600011 | 2023-03-04T06:14:12 | 2023-03-04T06:14:12 | 233,500,005 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 274 | py | """
https://www.djangoproject.com/start/ 学习网址:例子什么都有
pip3 -m install django
python3 -m django startproject 项目名称(非存在)会建立一个项目
python3 -m django help --commands 列出所有指令
python -m django <command> [options]
""" | [
"[email protected]"
] | |
0d4fa822d511761432ee7ba760c62f146b04cf69 | a8b29cc5a2ecd8a1434fc8e1c9ad8f106b75f8dc | /setup.py | f39fb9091bfb84ac5fbee9e713450527b9672b67 | [
"MIT"
] | permissive | ipalindromi/notion-py | 7a2df43dd1eedb7279e6df16f0055f497ebb978e | 573cf67a4ab7ce10558c6a666b7c77b5728de93c | refs/heads/master | 2020-05-22T09:40:00.553506 | 2019-05-11T16:11:49 | 2019-05-11T16:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,000 | py | import setuptools
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
with open("README.md", "r") as fh:
long_description = fh.read()
reqs = parse_requirements("requirements.txt", session=False)
install_requires = [str(ir.req) for ir in reqs]
setuptools.setup(
name="notion",
version="0.0.21",
author="Jamie Alexandre",
author_email="[email protected]",
description="Unofficial Python API client for Notion.so",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/jamalex/notion-py",
install_requires=install_requires,
include_package_data=True,
packages=setuptools.find_packages(),
python_requires='>=3.4',
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
) | [
"[email protected]"
] | |
024fddd4f9e6fcd1ef11b8229f5dee8d71fe2ca0 | 27d982d2b1d7d70b6d2589a182b272c0afd15016 | /zx_module/ppt_v12.py | b731b82131f6e2f9865f1a3552ae53914ce75b62 | [] | no_license | zXpp/hw_easy_ppt_kits | d5c494f71a03e7ddc973154fb858cd296f11c38a | ec0014a4de380da1639fd5cafe7a0ca1c3213ed6 | refs/heads/master | 2021-06-27T04:31:39.694137 | 2017-09-19T10:41:27 | 2017-09-19T10:41:27 | 104,061,957 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,698 | py | # -*- coding: utf-8 -*-
"""
"""
import os
import win32com.client
#sys.path= pyrealpath.append(os.path.split(os.path.realpath(__file__))[0])
#from win32com.client import Dispatch
from rmdjr import rmdAndmkd as rmdir#import timeremove and makedir
from PIL.Image import open as imgopen,new as imgnew
# OFFICE=["PowerPoint.Application","Word.Application","Excel.Application"]
ppFixedFormatTypePDF = 2
class easyPPT():
def __init__(self):
self.ppt = win32com.client.DispatchEx('PowerPoint.Application')
self.ppt.DisplayAlerts=False
self.ppt.Visiable=False
self.filename,self.ppt_pref,self.outdir0="","",""
self.outdir0,self.label,self.outdir1,self.ppt_prefix ="","","",""
self.width,self.height,self.count_Slid=0,0,0
self.outfordir2,self.outfile_prefix,self.outslidir2,self.outresizedir2="","","",""
def open(self,filename=None,outDir0=None,label=None):
try:
if filename and os.path.isfile(filename):
self.filename = filename#给定文件名,chuangeilei
self.ppt_prefix=os.path.basename(self.filename).rsplit('.')[0]
self.outdir0=outDir0 if outDir0 else os.path.dirname(self.filename)#输出跟路径
self.outdir0=self.outdir0.replace('/','\\')
self.label = label if label else self.ppt_prefix
self.outdir1=os.path.join(self.outdir0,self.label)#输出跟文件夹路径+用户定义-同ppt文件名
self.pres = self.ppt.Presentations.Open(self.filename, WithWindow=False)
except:
self.pres = self.ppt.Presentations.Add()
self.filename = ''
else:
self.Slides=self.pres.Slides
self.count_Slid = self.Slides.Count
self.width,self.height = [self.pres.PageSetup.SlideWidth*3,self.pres.PageSetup.SlideHeight*3]
rmdir(self.outdir1)
self.outfordir2=os.path.join(self.outdir1,"OutFormats")#输出放多格式的二级目录,默认为"OurFormats"
rmdir(self.outfordir2)
self.outfile_prefix=os.path.join(self.outfordir2,self.label)#具体到文件格式的文件前缀(除了生成格式外的)
def closepres(self):
self.pres.Close()
def closeppt(self):
self.ppt.Quit()
def saveAs(self,Format=None,flag="f"):
try:
if flag=="f" and Format:
newname=u".".join([self.outfile_prefix,Format.lower()])#目标格式的完整路径
if Format in ["PDF","pdf","Pdf"]:
try:
self.pres.SaveAs(FileName=newname,FileFormat=32)
except:
newname=newname.replace('/','\\')
self.pres.SaveAs(FileName=newname, FileFormat=32)
if Format in ["txt", "TXT", "Txt"]:
self.exTXT()
except:
pass#return e
def pngExport(self,imgDir=None,newsize=None,imgtype="png",merge=0):#导出原图用这个
newsize=newsize if newsize else self.width
radio=newsize/self.width
if self.outdir1:
self.outslidir2=os.path.join(self.outdir1,"Slides")#存放原图的二级目录
if not imgDir:
rmdir(self.outslidir2)
Path,Wid,Het=self.outslidir2,self.width,self.height
self.outfile_prefix=self.outfile_prefix+'_raw'
#self.allslid=map(lambda x:os.path.join(Path,x),os.listdir(Path))#所有原图的绝对路径
else:
self.imDir=imgDir
self.outresizedir2=os.path.join(self.outdir1,self.imDir)#所以缩放图的绝对路径
rmdir(self.outresizedir2)
Path,Wid,Het=self.outresizedir2,newsize,round(self.height*radio,0)
#self.allres=map(lambda x:os.path.join(Path,x),os.listdir(Path))
self.pres.Export(Path,imgtype,Wid,Het)#可设参数导出幻灯片的宽度(以像素为单位)
self.renameFiles(Path,torep=u"幻灯片")
outfile=u"".join([self.outfile_prefix,u'.',imgtype])
redpi(Path,merge,pictype=imgtype,outimg=outfile)
"""
def redpi(path,append=0,pictype="png",outimg=None):##将大于、小于96dpi的都转换成96dpi
files=map(lambda x:os.path.join(path,x),os.listdir(path))
imgs,width, height=[], 0,0
for file in files:
img=Image.open(file)
img2=img.copy()
img.save(file)
if append:
img2 = img2.convert('RGB') if img2.mode != "RGB" else img2
imgs.append(img2)
width = img2.size[0] if img2.size[0] > width else width
height += img2.size[1]
del img2
if append:
pasteimg(imgs,width,height,outimg)"""
def renameFiles(self,imgdir_name,torep=None):#torep:带替换的字符
srcfiles = os.listdir(imgdir_name)
for srcfile in srcfiles:
inde = srcfile.split(torep)[-1].split('.')[0]#haha1.png
suffix=srcfile[srcfile.index(inde)+len(inde):].lower()
#sufix = os.path.splitext(srcfile)[1]
# 根据目录下具体的文件数修改%号后的值,"%04d"最多支持9999
newname="".join([self.label,"_",inde.zfill(2),suffix])
destfile = os.path.join(imgdir_name,newname)
srcfile = os.path.join(imgdir_name, srcfile)
os.rename(srcfile, destfile)
#index += 1
# for each in os.listdir(imgdir_name):
def slid2PPT(self,outDir=None,substr=""):#选择的编号的幻灯片单独发布为ppt文件,
try:
if not outDir:
outDir=os.path.join(self.outdir1 ,"Slide2PPT")
if not os.path.isdir(outDir):#只需要判断文件夹是否存在,默认是覆盖生成。
os.makedirs(outDir)
#if not sublst or not len(sublst):#如果不指定,列表为空或者是空列表
sublst=str2pptind(substr)
sublst=filter(lambda x:x>0 and x<self.count_Slid+1,sublst)#筛选出小于幻灯片总数的序号
map(lambda x:self.Slides(x).PublishSlides(outDir,True,True),sublst)
self.renameFiles(outDir,torep=self.ppt_prefix)
except Exception,e:
return e
def exTXT(self):
f=open("".join([self.outfile_prefix,r".txt"]),"wb+")
for x in range(1,self.count_Slid+1):#
s=[]
shape_count = self.Slides(x).Shapes.Count
page=u"".join([u"\r\n\r\nPage ",str(x),u":\r\n"])#
s.append(page)
for j in range(1, shape_count + 1):
txornot=self.Slides(x).Shapes(j).HasTextFrame
if txornot:#可正可负,只要不为0
txrg=self.Slides(x).Shapes(j).TextFrame.TextRange.Text
if txrg and len(txrg):#not in [u' ',u'',u"\r\n"]:
s.append(txrg)
f.write(u"\r\n".join(s).encode("utf-8"))
#print (u"\r\n".join(s))
f.close() #s=[]
# else :#如果没有字的情况
# return
def delslides(self):
rmdir(self.outslidir2,mksd=0)
def delresize(self):
rmdir(self.outresizedir2,mksd=0)
def str2pptind(strinput=""):##将输入处理范围的幻灯片编号转为顺序的、不重复的list列表
selppt=[]
if strinput and strinput not in [""," "]:
pptind=strinput.split(",")
tmp1=map(lambda x:x.split(r"-"),pptind)
for each in tmp1:
each1=map(int,each)
selppt+=range(each1[0],each1[-1]+1)
selppt=set(sorted(selppt))
selppt=list(selppt)
return selppt
def pasteimg(inlst,width,height,output_file):#拼接图片
merge_img,cur_height = imgnew('RGB', (width, height), 0xffffff),0
for img in inlst:
# 把图片粘贴上去
merge_img.paste(img, (0, cur_height))
cur_height += img.size[1]
merge_img.save(output_file)#自动识别扩展名
merge_img=None
def redpi(path,append=0,pictype="png",outimg=None):##将大于、小于96dpi的都转换成96dpi
files=map(lambda x:os.path.join(path,x),os.listdir(path))
imgs,width, height=[], 0,0
for file in files:
img=imgopen(file)
# img=Image().im
# img=imgt
img2 = img.copy()
if pictype not in ["gif","GIF"]:
scale=img.info['dpi']
scale2=max(scale[0],96)
img.save(file,dpi=(scale2,scale2))
else:
img.save(file)
img=None
if append:
img2 = img2.convert('RGB') if img2.mode != "RGB" else img2
imgs.append(img2)
width = img2.size[0] if img2.size[0] > width else width
height += img2.size[1]
img2=None
if append:
pasteimg(imgs,width,height,outimg)
if __name__ == "__main__":
label=u"深度学习"
imdir=u"反对果"
outDir = u"C:\\Users\\Administrator\\Desktop"
inpu=u"1,2,4,6-9,5,8-11,22-25"
pprange=str2pptind(inpu)
pptx=easyPPT()
pptx.open(u"C:\\Users\\Administrator\\Desktop\\EVERYDAY ACTIVITIES_1_.pptx")
#pptx.delslid()
# print pptx.width,pptx.height,pptx.count_Slid,pptx.pres.PageSetup.SlideHeight
# print pptx.pres.PageSetup.SlideWidth
#pptind=pptx.str2pptind(inpu)
#pptind2=pptx.str2pptind("")
format=["png","html","xml","ppt/pptx","txt","pdf"]#formatpptx.saveAs(Format="PNG")
# pptx.saveAs(Format=format[-2])#txt
# pptx.saveAs(Format=format[-1])#导出pdf
# pptx.pngExport()#留空为原尺寸导出
pptx.pngExport(u"啦啦 啦",900,imgtype="png")#imgedirnaem ,newidth.
# pptx.slid2PPT()
#pptx.slid2PPT(sublst=pptind)
#pptx.weboptions()
#print "dpi:",pptx.dpi_size[0],pptx.dpi_size[1]
#pptx.ppt.PresentationBeforeClose(pptx.pres, False)
#pptx.close()
| [
"[email protected]"
] | |
c39fb94a63fdbd19eb8a17838ffe3e6bce300a65 | 6e7aa175667d08d8d285fd66d13239205aff44ff | /apps/gcc_media/rest.py | 55a8f9eee75081aca883da6cf57845c16161ed9c | [] | no_license | jaredly/GameCC | c2a9d7b14fc45813a27bdde86e16a3e3594396e2 | babadbe9348c502d0f433fb82e72ceff475c3a3b | refs/heads/master | 2016-08-05T10:53:03.794386 | 2010-06-25T03:13:02 | 2010-06-25T03:13:02 | 269,735 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 717 | py | #!/usr/bin/env python
from django.conf.urls.defaults import *
from django.conf import settings
from models import Image, Font, Sound
from restive import Service
service = Service()
@service.add(name='list')
def list_all(request):
return {'_models': list(request.user.gcc_images.all().order_by('pk')) +
list(request.user.gcc_fonts.all().order_by('pk')) +
list(request.user.gcc_sounds.all()),
'media_url':settings.MEDIA_URL}
@service.add(name='remove')
def remove_(request, type, pk):
if type == 'image':
Image.objects.get(pk=pk).delete()
return {}
else:
raise Exception('Unsupported type')
urlpatterns = service.urls()
# vim: et sw=4 sts=4
| [
"[email protected]"
] | |
a2dc60b59d5b4e13c8f38e8012d5ca22b4fc4b68 | 77bde91c91d6ab173829a25fc3c3e0e80eb2c897 | /tests/et_md3/verletlist/verletlist_cpp/test_verletlist_cpp.py | 10fcb1daf1c7b54dff5d2305a0b2afbc0a7cbc69 | [] | no_license | etijskens/et-MD3 | ddddadbf4a8eb654277086f6f46bedb912bc1f01 | 9826ade15c546103d3fa1254c90f138b61e42fe7 | refs/heads/main | 2023-07-10T16:27:27.296806 | 2021-08-18T11:04:49 | 2021-08-18T11:04:49 | 395,253,565 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 748 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for C++ module et_md3.verletlist.cpp.
"""
import sys
sys.path.insert(0,'.')
import numpy as np
import et_md3.verletlist.verletlist_cpp
#===============================================================================
# The code below is for debugging a particular test in eclipse/pydev.
# (normally all tests are run with pytest)
#===============================================================================
if __name__ == "__main__":
the_test_you_want_to_debug = None
print(f"__main__ running {the_test_you_want_to_debug} ...")
the_test_you_want_to_debug()
print('-*# finished #*-')
#===============================================================================
| [
"[email protected]"
] | |
ecc0109c2c95ce9605015f86bfb5113ad2e28148 | 1dc4a70ad29989efbcb7c670c21838e6e42a60f0 | /dbaas/workflow/steps/build_database.py | 2be1cc55cc349091e0e4202ea1dce43b7239eea6 | [] | no_license | andrewsmedina/database-as-a-service | fb45ddb0f4bb0c5f35094f4b34cdb3aae63ad53d | bbe454631fad282c6e3acbed0d5bfddefd15d7ce | refs/heads/master | 2020-12-13T21:46:30.221961 | 2014-10-29T17:14:54 | 2014-10-29T17:14:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,110 | py | # -*- coding: utf-8 -*-
import logging
from base import BaseStep
from logical.models import Database
import datetime
from ..exceptions.error_codes import DBAAS_0003
from util import full_stack
LOG = logging.getLogger(__name__)
class BuildDatabase(BaseStep):
def __unicode__(self):
return "Creating logical database..."
def do(self, workflow_dict):
try:
if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']:
return False
LOG.info("Creating Database...")
database = Database.provision(name=workflow_dict['name'], databaseinfra=workflow_dict['databaseinfra'])
LOG.info("Database %s created!" % database)
workflow_dict['database'] = database
LOG.info("Updating database team")
database.team = workflow_dict['team']
if 'project' in workflow_dict:
LOG.info("Updating database project")
database.project = workflow_dict['project']
LOG.info("Updating database description")
database.description = workflow_dict['description']
database.save()
return True
except Exception, e:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0003)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
def undo(self, workflow_dict):
try:
if not 'database' in workflow_dict:
if 'databaseinfra' in workflow_dict:
LOG.info("Loading database into workflow_dict...")
workflow_dict['database'] = Database.objects.filter(databaseinfra=workflow_dict['databaseinfra'])[0]
else:
return False
if not workflow_dict['database'].is_in_quarantine:
LOG.info("Putting Database in quarentine...")
database = workflow_dict['database']
database.is_in_quarantine = True
database.quarantine_dt = datetime.datetime.now().date()
database.save()
LOG.info("Destroying the database....")
database.delete()
return True
except Exception, e:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0003)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
| [
"[email protected]"
] | |
2d201164d5d96ab0e272ba9cbbde60a03f5615a6 | 0f2b08b31fab269c77d4b14240b8746a3ba17d5e | /orttraining/orttraining/python/training/ortmodule/experimental/json_config/__init__.py | d4399b1ee9c09763510caa7de207a45a11dc26ff | [
"MIT"
] | permissive | microsoft/onnxruntime | f75aa499496f4d0a07ab68ffa589d06f83b7db1d | 5e747071be882efd6b54d7a7421042e68dcd6aff | refs/heads/main | 2023-09-04T03:14:50.888927 | 2023-09-02T07:16:28 | 2023-09-02T07:16:28 | 156,939,672 | 9,912 | 2,451 | MIT | 2023-09-14T21:22:46 | 2018-11-10T02:22:53 | C++ | UTF-8 | Python | false | false | 272 | py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# __init__.py
# JSON global constants goes here
JSON_PATH_ENVIRONMENT_KEY = "ORTMODULE_JSON_CONFIG_PATH"
from ._load_config_from_json import load_from_json # noqa: E402, F401
| [
"[email protected]"
] | |
5b3aa86b8d0fc8ff213bedf0c58f4d1b47b2f43f | cdd1901812799e5542ac6c2ecd5af06eb30aeacd | /Datasets/voc/find_cls_in_voc.py | 1183ca0e033352f784398f162221a1315bbea092 | [] | no_license | thinkinchaos/Tools | ff0030494996493aa75b355880961a5d6b511ba6 | f0571d101c7003ded516b036ce2d6552d38b443f | refs/heads/master | 2023-06-10T01:30:29.285972 | 2021-07-01T02:09:51 | 2021-07-01T02:09:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,107 | py | import glob
import xml.etree.ElementTree as ET
import numpy as np
ANNOTATIONS_PATH = 'E:/datasets/nuclear_obj_cold/Annotations'
# names=set()
from pathlib import Path
all=[]
train=[]
val=[]
for xml_file in Path(ANNOTATIONS_PATH).glob('*.xml'):
tree = ET.parse(str(xml_file))
xml_root = tree.getroot()
names_this_xml=[]
for obj in xml_root.findall('object'):
# names_this_xml.append(obj.find('name').text)
if obj.find('name').text == 'dog':
all.append(xml_file.name)
# obj.find('name').text = 'brick'
# tree.write(xml_file, encoding="utf-8", xml_declaration=True, method='xml')
# print(names_this_xml)
# if 'robat' in names_this_xml:
# element = ET.Element('object')
#
# sub_element1 = ET.Element('name')
# sub_element1.text = obj_info[1]
# element.append(sub_element1)
#
# sub_element2 = ET.Element('bndbox')
# xmin = ET.Element('xmin')
# xmin.text = str(obj_info[2])
# ymin = ET.Element('ymin')
# ymin.text = str(obj_info[3])
# xmax = ET.Element('xmax')
# xmax.text = str(obj_info[4])
# ymax = ET.Element('ymax')
# ymax.text = str(obj_info[5])
# sub_element2.append(xmin)
# sub_element2.append(ymin)
# sub_element2.append(xmax)
# sub_element2.append(ymax)
#
# element.append(sub_element2)
# root.append(element)
print(all)
# # from pathlib import Path
# import random
# # xmls=[i.name for i in Path('Annotations_CarPersonZebra').iterdir() if i.is_file()]
# random.shuffle(all)
# percent=0.9
# train_n = int(len(all)*percent)
# train=all[:train_n]
# val=all[train_n:]
#
# with open('//192.168.133.15/workspace/sunxin/DATA/2.7_Zebra_HardNeg/Annotations_CarPersonZebra/zebra_train.txt','w') as f:
# for i in train:
# f.write(i)
# f.write('\n')
#
# with open('//192.168.133.15/workspace/sunxin/DATA/2.7_Zebra_HardNeg/Annotations_CarPersonZebra/zebra_val.txt','w') as f:
# for i in val:
# f.write(i)
# f.write('\n')
| [
"[email protected]"
] | |
8871cdcc6760cba68626ebe15775032f93f8426c | fa6f91b50125150c8d77937e002b53788dbcb19d | /bin/pushmp | 013788499bc1a9c20a3a68eac484738d4faa3132 | [] | no_license | howiemac/mp | b5402be12cfe3b3a4be77adb673dc20371c3cf4b | 694568f45020f7fe2ed2b8914ddc875aada852d1 | refs/heads/master | 2020-05-22T09:33:53.160473 | 2018-04-07T22:09:14 | 2018-04-07T22:09:14 | 34,397,381 | 0 | 1 | null | 2017-08-17T13:04:31 | 2015-04-22T15:05:42 | Python | UTF-8 | Python | false | false | 4,840 | #! /usr/bin/python
#
# script to archive the master music system - REQUIRES mp to be running at the start
## - pulls from the archive, the slave log since the last update # CURRENTLY DISABLED
## - updates master system with the previous slave log # CURRENTLY DISABLED
# (note: up to here could alternatively be done in advance - eg immediately after storing the previous slave update in archive)
# - pushes => archive
# - current (master) max uid (retained for use in next update - see "last update max uid" below)
# - last update max uid (slave will checked this against its own record, to ensure that we are in sync on the prior update)
# - latest music SQL dump (in full)
# - latest mp code (in full, incuding evoke)
# - renames master log, so as not to be accidentally reused by slave
# - data additions since last update
#
# ASSUMES no more than one update per day
#
#from sys import argv
import os, sys, copy, subprocess
import datetime
today = datetime.date.today().strftime("%y%m%d")
print "starting archive %s..." % today
# required folders
#archive="/Volumes/TRANSFER/"
archive="/media/howie/archive/"
arccodefolder=archive+"code/mp.backup/"
arcdatafolder=archive+"data/music/"
homefolder="/home/howie/"
codefolder=homefolder+'code/'
mpfolder=codefolder+'mp/music/'
backupfolder=codefolder+"backup/mp/"
datafolder=homefolder+'data/music/'
#updatefolders - see below
# fetch the slave log
print "fetching log(s)..."
xarchivefolder= arccodefolder+sorted([i for i in os.listdir(arccodefolder) if i.startswith("mp.backup.")])[-1]+'/'
log=[i for i in os.listdir(xarchivefolder) if i.startswith("eee.")][0]
# copy it to the mp/logs/additions folder
os.system("cp %s%s %slogs/additions/%s " % (xarchivefolder,log,mpfolder,log))
# force mp to update
os.system('wget http://127.0.0.1:8088/1/add_logs')
f=open('add_logs')
print f.read()
f.close()
os.remove('add_logs') # os.system('rm add_logs')
# stop mp, before fetching any code or data
os.system('wget http://127.0.0.1:8088/halt')
os.remove('halt') # os.system('rm halt')
# create new update folder
#
# make sure that maxuid will be greater than xuid, by adding a page of kind=='archive'
os.system('''mysql music -e "insert into pages (kind, stage) values ('archive', 'hide');"''')
# get the maxuid
os.system('mysql music -e "select max(uid) from pages" >maxuid')
f=open("maxuid",'r')
maxuid=int(f.read().split('\n')[1])
f.close()
# define the folders
updatefolder=backupfolder+("mp.backup.%s/" % maxuid)
xupdatefolder= backupfolder+sorted([i for i in os.listdir(backupfolder) if i.startswith("mp.backup.")])[-1]+'/'
# create the new one
os.mkdir(updatefolder)
#move the maxuid file into the new folder
os.system('mv maxuid %smaxuid' % updatefolder)
# create the xuid file
os.system('cp %smaxuid %sxuid' % (xupdatefolder,updatefolder))
# get the xuid
f=open("%sxuid" % updatefolder,'r')
xuid=int(f.read().split('\n')[1])
f.close()
## copy maxuid to mp/music/logs/
#os.system('cp %smaxuid %smp/music/logs/maxuid' % (updatefolder,codefolder))
# rename the master log
os.chdir(codefolder)
if os.path.isfile("mp/music/logs/mp.log"):
os.rename("mp/music/logs/mp.log","mp/music/logs/mac.%s.mp.log" % maxuid)
# backup the music sql database
print "fetching music database..."
os.system('mysqldump music > %smusic.mysql.dump' % updatefolder)
# tar and bzip the code
print "bundling code..."
os.system("tar cf - mp/ | bzip2 -f > %smp.tar.bz2" % updatefolder)
# copy the data additions
print "archiving data..."
if True:
# - identify the data sub-folders
s="%09d" % xuid
subfolders=["%s/%s/" % (s[:-6],s[-6:-3],)]
uid=copy.copy(xuid)
while (maxuid//1000) > (uid//1000): # we have more than one subfolder
uid+=1000
s="%09d" % uid
subfolder="%s/%s/" % (s[:-6],s[-6:-3],)
subfolders.append(subfolder)
# create the new archive folder
os.makedirs(arcdatafolder+subfolder)
# - copy the files
files=[]
for subfolder in subfolders:
for i in os.listdir(datafolder+subfolder):
#
# print "XUID=",xuid
# print i
#
if i and (i.find(".")>0): # i.e. ignoring hidden folders and "no-dot" subfolders such as 'thumbs'
if int(i.split(".")[0])>xuid:
os.system("cp -v %s %s" % (datafolder+subfolder+i,arcdatafolder+subfolder+i))
files.append(subfolder+i+"\n")
# copy file list to datafiles.txt in update folder
f=open(updatefolder+'datafiles.txt','w')
f.writelines(files)
f.close()
# now, all of the data additions are archived
# copy the update folder to the archive
print "archiving code and database..."
os.system('cp -r %s %s' % (updatefolder[:-1],arccodefolder[:-1]))
### restart the system
#print "restarting"
#os.chdir(mpfolder+"code/")
#subprocess.call('./start', shell=True) # restart the system
# and we are done!
print "archive %s completed" % maxuid
| [
"[email protected]"
] | ||
0dfea63cd551aaa3e88d3dd5f3e72bf1481714c3 | ca4da546f815ef7e14fd79dfbc5a0c3f9f8c72c9 | /test/test_ICUNormalizer2Filter.py | 096bc618004010da29ad3ea48348ffd0537e8eda | [
"Apache-2.0"
] | permissive | qiugen/pylucene-trunk | be955aedca2d37411f0683e244c30b102d4839b4 | 990079ff0c76b972ce5ef2bac9b85334a0a1f27a | refs/heads/master | 2021-01-18T08:46:38.817236 | 2012-07-18T16:18:45 | 2012-07-18T16:18:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,110 | py | # -*- coding: utf-8 -*-
# ====================================================================
# 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.
# ====================================================================
#
# Port of java/org/apache/lucene/analysis/icu/ICUNormalizer2Filter.java
# using IBM's C++ ICU wrapped by PyICU (http://pyicu.osafoundation.org)
try:
from icu import Normalizer2, UNormalizationMode2
except ImportError, e:
pass
from unittest import main
from BaseTokenStreamTestCase import BaseTokenStreamTestCase
from lucene import *
class TestICUNormalizer2Filter(BaseTokenStreamTestCase):
def testDefaults(self):
from lucene.ICUNormalizer2Filter import ICUNormalizer2Filter
class analyzer(PythonAnalyzer):
def tokenStream(_self, fieldName, reader):
return ICUNormalizer2Filter(WhitespaceTokenizer(Version.LUCENE_CURRENT, reader))
a = analyzer()
# case folding
self._assertAnalyzesTo(a, "This is a test",
[ "this", "is", "a", "test" ])
# case folding
self._assertAnalyzesTo(a, "Ruß", [ "russ" ])
# case folding
self._assertAnalyzesTo(a, u"ΜΆΪΟΣ", [ u"μάϊοσ" ])
self._assertAnalyzesTo(a, u"Μάϊος", [ u"μάϊοσ" ])
# supplementary case folding
self._assertAnalyzesTo(a, u"𐐖", [ u"𐐾" ])
# normalization
self._assertAnalyzesTo(a, u"ﴳﴺﰧ", [ u"طمطمطم" ])
# removal of default ignorables
self._assertAnalyzesTo(a, u"क्ष", [ u"क्ष" ])
def testAlternate(self):
from lucene.ICUNormalizer2Filter import ICUNormalizer2Filter
class analyzer(PythonAnalyzer):
# specify nfc with decompose to get nfd
def tokenStream(_self, fieldName, reader):
return ICUNormalizer2Filter(WhitespaceTokenizer(Version.LUCENE_CURRENT, reader),
Normalizer2.getInstance(None, "nfc", UNormalizationMode2.DECOMPOSE))
a = analyzer()
# decompose EAcute into E + combining Acute
self._assertAnalyzesTo(a, u"\u00E9", [ u"\u0065\u0301" ])
if __name__ == "__main__":
import sys, lucene
try:
import icu
except ImportError:
pass
else:
lucene.initVM()
if '-loop' in sys.argv:
sys.argv.remove('-loop')
while True:
try:
main()
except:
pass
else:
main()
| [
"[email protected]"
] | |
c15fb530ecc23ae42a89c8cc953494b4dc1ca8ac | 6bd3c6875797750a9cf7b00817aaca6ed9c42e95 | /tensorflow/python/eager/tensor_test.py | f61d84781770b04db235e6ec700f3241c4faeabb | [
"Apache-2.0"
] | permissive | XunZhiyang/tensorflow | c2f71cc7167dfe886c4866a32af8a0dc4bd40739 | 345435812684b79fb47f494779ff6d037fbc4699 | refs/heads/master | 2020-04-05T17:16:00.139418 | 2018-11-11T06:03:03 | 2018-11-11T06:03:03 | 157,052,160 | 0 | 0 | Apache-2.0 | 2018-11-11T06:00:51 | 2018-11-11T06:00:51 | null | UTF-8 | Python | false | false | 15,499 | py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Unit tests for TensorFlow "Eager" Mode's Tensor class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import re
import sys
import numpy as np
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
from tensorflow.python.eager import core
from tensorflow.python.eager import test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import io_ops
def _create_tensor(value, device=None, dtype=None):
ctx = context.context()
if device is None:
device = ctx.device_name
if dtype is not None:
dtype = dtype.as_datatype_enum
try:
return ops.EagerTensor(
value, context=ctx._handle, device=device, dtype=dtype)
except core._NotOkStatusException as e: # pylint: disable=protected-access
raise core._status_to_exception(e.code, e.message)
class TFETensorTest(test_util.TensorFlowTestCase):
def testScalarTensor(self):
t = _create_tensor(3, dtype=dtypes.int32)
self.assertAllEqual(t, _create_tensor(np.array(3)))
self.assertEqual(dtypes.int32, t.dtype)
self.assertEqual(0, t.shape.ndims)
self.assertAllEqual([], t.shape.as_list())
self.assertIn("tf.Tensor", str(t))
self.assertIn("tf.Tensor", repr(t))
def testBadConstructorArgs(self):
ctx = context.context()
handle = ctx._handle
device = ctx.device_name
# Missing context.
with self.assertRaisesRegexp(
TypeError, r"Required argument 'context' \(pos 2\) not found"):
ops.EagerTensor(1, device=device)
# Missing device.
with self.assertRaisesRegexp(
TypeError, r"Required argument 'device' \(pos 3\) not found"):
ops.EagerTensor(1, context=handle)
# Bad dtype type.
with self.assertRaisesRegexp(TypeError,
"Expecting a DataType value for dtype. Got"):
ops.EagerTensor(1, context=handle, device=device, dtype="1")
# Following errors happen when trying to copy to GPU.
if not context.context().num_gpus():
self.skipTest("No GPUs found")
with ops.device("/device:GPU:0"):
device = ctx.device_name
# Bad context.
with self.assertRaisesRegexp(
TypeError, "Expecting a PyCapsule encoded context handle. Got"):
ops.EagerTensor(1.0, context=1, device=device)
# Bad device.
with self.assertRaisesRegexp(
TypeError, "Error parsing device argument to CopyToDevice"):
ops.EagerTensor(1.0, context=handle, device=1)
def testNumpyValue(self):
values = np.array([3.0])
t = _create_tensor(values)
self.assertAllEqual(values, t)
def testNumpyValueWithCast(self):
values = np.array([3.0], dtype=np.float32)
t = _create_tensor(values, dtype=dtypes.float64)
self.assertAllEqual(values, t)
ctx = context.context()
# Bad dtype value.
with self.assertRaisesRegexp(TypeError, "Invalid dtype argument value"):
ops.EagerTensor(
values, context=ctx._handle, device=ctx.device_name, dtype=12345)
def testNumpyOrderHandling(self):
n = np.array([[1, 2], [3, 4]], order="F")
t = _create_tensor(n)
self.assertAllEqual([[1, 2], [3, 4]], t)
def testNumpyArrayDtype(self):
tensor = constant_op.constant([1.0, 2.0, 3.0])
numpy_tensor = np.asarray(tensor, dtype=np.int32)
self.assertAllEqual(numpy_tensor, [1, 2, 3])
def testNdimsAgreesWithNumpy(self):
numpy_tensor = np.asarray(1.0)
tensor = constant_op.constant(numpy_tensor)
self.assertAllEqual(numpy_tensor.ndim, tensor.ndim)
numpy_tensor = np.asarray([1.0, 2.0, 3.0])
tensor = constant_op.constant(numpy_tensor)
self.assertAllEqual(numpy_tensor.ndim, tensor.ndim)
numpy_tensor = np.asarray([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]])
tensor = constant_op.constant(numpy_tensor)
self.assertAllEqual(numpy_tensor.ndim, tensor.ndim)
def testCopy(self):
t = constant_op.constant(1.0)
tt = copy.copy(t)
self.assertAllEqual(tt, 1.0)
del tt
tt = copy.deepcopy(t)
self.assertAllEqual(tt, 1.0)
del tt
self.assertAllEqual(t, 1.0)
def testConstantDtype(self):
self.assertEqual(
constant_op.constant(1, dtype=np.int64).dtype, dtypes.int64)
def testTensorAndNumpyMatrix(self):
expected = np.array([[1.0, 2.0], [3.0, 4.0]], np.float32)
actual = _create_tensor([[1.0, 2.0], [3.0, 4.0]])
self.assertAllEqual(expected, actual)
self.assertEqual(np.float32, actual.dtype)
self.assertEqual(dtypes.float32, actual.dtype)
self.assertAllEqual([2, 2], actual.shape.as_list())
def testFloatDowncast(self):
# Unless explicitly specified, float64->float32
t = _create_tensor(3.0)
self.assertEqual(dtypes.float32, t.dtype)
t = _create_tensor(3.0, dtype=dtypes.float64)
self.assertEqual(dtypes.float64, t.dtype)
def testBool(self):
t = _create_tensor(False)
if t:
self.assertFalse(True)
def testIntDowncast(self):
t = _create_tensor(3)
self.assertEqual(dtypes.int32, t.dtype)
t = _create_tensor(3, dtype=dtypes.int64)
self.assertEqual(dtypes.int64, t.dtype)
t = _create_tensor(2**33)
self.assertEqual(dtypes.int64, t.dtype)
def testTensorCreationFailure(self):
with self.assertRaises(ValueError):
# Should fail because the each row of the Python object has a different
# number of columns.
self.assertEqual(None, _create_tensor([[1], [1, 2]]))
def testMultiLineTensorStr(self):
t = _create_tensor(np.eye(3))
tensor_str = str(t)
self.assertIn("shape=%s, dtype=%s" % (t.shape, t.dtype.name), tensor_str)
self.assertIn(str(t), tensor_str)
def testMultiLineTensorRepr(self):
t = _create_tensor(np.eye(3))
tensor_repr = repr(t)
self.assertTrue(tensor_repr.startswith("<"))
self.assertTrue(tensor_repr.endswith(">"))
self.assertIn("id=%d, shape=%s, dtype=%s, numpy=\n%r" %
(t._id, t.shape, t.dtype.name, t.numpy()), tensor_repr)
def testTensorStrReprObeyNumpyPrintOptions(self):
orig_threshold = np.get_printoptions()["threshold"]
orig_edgeitems = np.get_printoptions()["edgeitems"]
np.set_printoptions(threshold=2, edgeitems=1)
t = _create_tensor(np.arange(10, dtype=np.int32))
self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", str(t)))
self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", repr(t)))
# Clean up: reset to previous printoptions.
np.set_printoptions(threshold=orig_threshold, edgeitems=orig_edgeitems)
def testZeroDimTensorStr(self):
t = _create_tensor(42)
self.assertIn("42, shape=(), dtype=int32", str(t))
def testZeroDimTensorRepr(self):
t = _create_tensor(42)
self.assertTrue(repr(t).startswith("<"))
self.assertTrue(repr(t).endswith(">"))
self.assertIn("id=%d, shape=(), dtype=int32, numpy=42" % t._id, repr(t))
def testZeroSizeTensorStr(self):
t = _create_tensor(np.zeros(0, dtype=np.float32))
self.assertIn("[], shape=(0,), dtype=float32", str(t))
def testZeroSizeTensorRepr(self):
t = _create_tensor(np.zeros(0, dtype=np.float32))
self.assertTrue(repr(t).startswith("<"))
self.assertTrue(repr(t).endswith(">"))
self.assertIn("id=%d, shape=(0,), dtype=float32, numpy=%r" % (t._id,
t.numpy()),
repr(t))
def testStringTensor(self):
t_np_orig = np.array([[b"a", b"ab"], [b"abc", b"abcd"]])
t = _create_tensor(t_np_orig)
t_np = t.numpy()
self.assertTrue(np.all(t_np == t_np_orig), "%s vs %s" % (t_np, t_np_orig))
def testIterateOverTensor(self):
l = [[1, 2], [3, 4]]
t = _create_tensor(l)
for list_element, tensor_element in zip(l, t):
self.assertAllEqual(list_element, tensor_element.numpy())
def testStringTensorOnGPU(self):
if not context.context().num_gpus():
self.skipTest("No GPUs found")
with ops.device("/device:GPU:0"):
with self.assertRaisesRegexp(
RuntimeError, "Can't copy Tensor with type string to device"):
_create_tensor("test string")
def testInvalidUTF8ProducesReasonableError(self):
if sys.version_info[0] < 3:
self.skipTest("Test is only valid in python3.")
with self.assertRaises(UnicodeDecodeError):
io_ops.read_file(b"\xff")
@test_util.run_in_graph_and_eager_modes
def testConvertToTensorPreferredDtypeIsRespected(self):
self.assertEqual(
ops.convert_to_tensor(0.5, preferred_dtype=dtypes.int32).dtype,
dtypes.float32)
self.assertEqual(
ops.convert_to_tensor(0.5, preferred_dtype=dtypes.float64).dtype,
dtypes.float64)
@test_util.run_in_graph_and_eager_modes
def testCompatibility(self):
integer_types = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64,
dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64]
# Floats are not compatible with ints
for t in integer_types:
with self.assertRaises(TypeError):
constant_op.constant(0.5, dtype=t)
# Ints compatible with floats
self.assertEqual(
self.evaluate(constant_op.constant(5, dtype=dtypes.float16)), 5.0)
self.assertEqual(
self.evaluate(constant_op.constant(5, dtype=dtypes.float32)), 5.0)
self.assertEqual(
self.evaluate(constant_op.constant(5, dtype=dtypes.float64)), 5.0)
self.assertEqual(
self.evaluate(constant_op.constant(5, dtype=dtypes.bfloat16)), 5.0)
# Ints and floats are compatible with complex types
self.assertEqual(
constant_op.constant([[1.0]], dtype=dtypes.complex128).dtype,
dtypes.complex128)
self.assertEqual(
constant_op.constant([[1]], dtype=dtypes.complex128).dtype,
dtypes.complex128)
# Quantized types are not compatible with floats
quantized_types = [dtypes.qint16, dtypes.qint32, dtypes.qint8,
dtypes.quint16, dtypes.quint8]
for t in quantized_types:
with self.assertRaises(TypeError):
constant_op.constant(0.5, dtype=t)
# TODO(b/118402529): quantized types are broken in eager.
@test_util.run_in_graph_and_eager_modes
def testCConvertToTensor(self):
with self.assertRaises(TypeError):
_ = constant_op.constant(0) < 0.5
@test_util.run_in_graph_and_eager_modes
def testConvertToTensorAllowsOverflow(self):
_ = ops.convert_to_tensor(123456789, dtype=dtypes.uint8)
class TFETensorUtilTest(test_util.TensorFlowTestCase):
def testListOfThree(self):
t1 = _create_tensor([[1, 2], [3, 4], [5, 6]], dtype=dtypes.int32)
t2 = _create_tensor([[1, 2, 5], [3, 4, 5]], dtype=dtypes.int32)
t3 = _create_tensor([[1], [3], [5], [6]], dtype=dtypes.int32)
r = pywrap_tensorflow.TFE_Py_TensorShapeSlice([t1, t2, t3], 0)
self.assertAllEqual(np.array([3, 2, 4]), r.numpy())
r = pywrap_tensorflow.TFE_Py_TensorShapeSlice([t1, t2, t3], 1)
self.assertAllEqual(np.array([2, 3, 1]), r.numpy())
def testEmptyTensorList(self):
a = pywrap_tensorflow.TFE_Py_TensorShapeSlice([], 0)
self.assertTrue(isinstance(a, ops.EagerTensor))
self.assertEqual(0, a.numpy().size)
def testTensorListContainsNonTensors(self):
t1 = _create_tensor([1, 2], dtype=dtypes.int32)
with self.assertRaisesRegexp(
TypeError,
r"Expected a list of EagerTensors but element 1 has type \"str\""):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([t1, "abc"], 0)
with self.assertRaisesRegexp(
TypeError,
r"Expected a list of EagerTensors but element 0 has type \"int\""):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([2, t1], 0)
def testTensorListNotList(self):
t1 = _create_tensor([1, 2], dtype=dtypes.int32)
with self.assertRaisesRegexp(
TypeError,
r"tensors argument must be a list or a tuple. Got.*EagerTensor"):
pywrap_tensorflow.TFE_Py_TensorShapeSlice(t1, -2)
def testNegativeSliceDim(self):
t1 = _create_tensor([1, 2], dtype=dtypes.int32)
with self.assertRaisesRegexp(
ValueError,
r"Slice dimension must be non-negative. Got -2"):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([t1], -2)
def testUnicode(self):
self.assertEqual(constant_op.constant(u"asdf").numpy(), b"asdf")
def testFloatTensor(self):
self.assertEqual(dtypes.float64, _create_tensor(np.float64()).dtype)
self.assertEqual(dtypes.float32, _create_tensor(np.float32()).dtype)
self.assertEqual(dtypes.float16, _create_tensor(np.float16()).dtype)
self.assertEqual(dtypes.float32, _create_tensor(0.0).dtype)
def testSliceDimOutOfRange(self):
t1 = _create_tensor([[1, 2], [3, 4], [5, 6]], dtype=dtypes.int32)
t2 = _create_tensor([1, 2], dtype=dtypes.int32)
t3 = _create_tensor(2, dtype=dtypes.int32)
with self.assertRaisesRegexp(
IndexError,
r"Slice dimension \(2\) must be smaller than rank of all tensors, "
"but tensor at index 0 has rank 2"):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([t1], 2)
with self.assertRaisesRegexp(
IndexError,
r"Slice dimension \(1\) must be smaller than rank of all tensors, "
"but tensor at index 0 has rank 1"):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([t2], 1)
with self.assertRaisesRegexp(
IndexError,
r"Slice dimension \(1\) must be smaller than rank of all tensors, "
"but tensor at index 1 has rank 1"):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([t1, t2], 1)
with self.assertRaisesRegexp(
IndexError,
r"Slice dimension \(0\) must be smaller than rank of all tensors, "
"but tensor at index 0 has rank 0"):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([t3], 0)
with self.assertRaisesRegexp(
IndexError,
r"Slice dimension \(0\) must be smaller than rank of all tensors, "
"but tensor at index 2 has rank 0"):
pywrap_tensorflow.TFE_Py_TensorShapeSlice([t2, t1, t3], 0)
@test_util.assert_no_new_pyobjects_executing_eagerly
def testTensorDir(self):
t = array_ops.zeros(1)
t.test_attr = "Test"
instance_dir = dir(t)
type_dir = dir(ops.EagerTensor)
# Monkey patched attributes should show up in dir(t)
self.assertIn("test_attr", instance_dir)
instance_dir.remove("test_attr")
self.assertEqual(instance_dir, type_dir)
def testNonRectangularPackAsConstant(self):
l = [array_ops.zeros((10, 1)).numpy(), array_ops.zeros(1).numpy()]
with self.assertRaisesRegexp(
ValueError, "non-rectangular Python sequence"):
constant_op.constant(l)
if __name__ == "__main__":
test.main()
| [
"[email protected]"
] | |
ee15b4c52486572ddb7c2958f1a220ec2a1e3528 | a19cd9aebb697fc1dd384e9ce8596d6cc728e6f2 | /fabfile.py | 88dfdbee00ddc4cb3a8ed9ede23f657a74cb2a73 | [] | no_license | aclark4life/Debian-Deploy-Plone | 315c52e5dfcf278f7e5b2f2dfc5f1045d0518d99 | 2a779c30f1f4b83f4f715ea5f5ae2a93f23afdda | refs/heads/master | 2021-06-04T03:57:38.743523 | 2016-07-27T09:44:30 | 2016-07-27T09:44:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | true | false | 2,580 | py | # A work in progress
from fabric.api import env, local, put, run
env.user = 'root'
env.warn_only = True
FORM_VARS = ('form.submitted:boolean=True',
'extension_ids:list=plonetheme.sunburst:default',
'setup_content:boolean=true')
MODULE_CONFS = ('filter.load', 'proxy.conf', 'proxy.load',
'proxy_http.load', 'rewrite.load')
PACKAGES = "apache2 apache2-dev build-essential less libbz2-dev libjpeg62 libjpeg62-dev libpng "
PACKAGES += "libpng-dev libreadline-dev libssl-dev "
PACKAGES += "rsync subversion unzip zlib1g-dev"
def deploy():
copy_pub_key()
update_packages()
install_packages()
install_python()
install_plone()
configure_apache()
def update_packages():
run('aptitude update')
run('aptitude -y safe-upgrade')
def copy_pub_key():
run('mkdir /root/.ssh')
run('chmod 700 /root/.ssh')
put('id_rsa.pub', '/root/.ssh/authorized_keys')
def install_packages():
run('aptitude -y install %s' % PACKAGES)
def install_python():
run('aptitude -y install python')
put('distribute_setup.py', 'distribute_setup.py')
run('python distribute_setup.py')
run('easy_install pip')
run('pip install virtualenv')
run('virtualenv --no-site-packages --distribute python')
run('svn co http://svn.plone.org/svn/collective/buildout/python/')
run('cd python; bin/python bootstrap.py -d')
run('cd python; bin/buildout')
def install_plone():
from time import sleep
run('mkdir /srv/plone')
put('plone.cfg', '/srv/plone/buildout.cfg')
put('bootstrap.py', '/srv/plone/bootstrap.py')
put('rc.local', '/etc/rc.local')
run('cd /srv/plone; /root/python/python-2.6/bin/python2.6 bootstrap.py -d')
install_theme()
run('cd /srv/plone; bin/buildout')
run('chown -R www-data:www-data /srv/plone')
run('cd /srv/plone; sudo -u www-data bin/supervisord')
sleep(5)
create_site()
def create_site():
url = 'http://127.0.0.1:8080/@@plone-addsite?site_id=Plone'
run('curl -u admin:admin -d %s %s' % (' -d '.join(FORM_VARS), url))
def install_theme():
args = '-av --partial --progress --delete'
local('zip -r theme.zip theme')
put('theme.zip', 'theme.zip')
run('cd /srv/plone; unzip -o /root/theme.zip')
run('rsync %s /srv/plone/theme/perfectblemish/ /var/www/static/' % args)
def configure_apache():
put('000-default', '/etc/apache2/sites-enabled')
run('mkdir /var/www/static')
for conf in MODULE_CONFS:
run('cd /etc/apache2/mods-enabled;ln -sf ../mods-available/%s' % conf)
run('/etc/init.d/apache2 restart')
| [
"[email protected]"
] | |
390bd290bfcf3c4bcda4e837f0b09c4b9049499e | f576f0ea3725d54bd2551883901b25b863fe6688 | /sdk/eventgrid/azure-mgmt-eventgrid/generated_samples/system_topics_get.py | 3c841e84e51e5d149b8c34c211d2202bcf26188d | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | permissive | Azure/azure-sdk-for-python | 02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c | c2ca191e736bb06bfbbbc9493e8325763ba990bb | refs/heads/main | 2023-09-06T09:30:13.135012 | 2023-09-06T01:08:06 | 2023-09-06T01:08:06 | 4,127,088 | 4,046 | 2,755 | MIT | 2023-09-14T21:48:49 | 2012-04-24T16:46:12 | Python | UTF-8 | Python | false | false | 1,580 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.eventgrid import EventGridManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-eventgrid
# USAGE
python system_topics_get.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = EventGridManagementClient(
credential=DefaultAzureCredential(),
subscription_id="8f6b6269-84f2-4d09-9e31-1127efcd1e40",
)
response = client.system_topics.get(
resource_group_name="examplerg",
system_topic_name="exampleSystemTopic2",
)
print(response)
# x-ms-original-file: specification/eventgrid/resource-manager/Microsoft.EventGrid/preview/2023-06-01-preview/examples/SystemTopics_Get.json
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
8e012c503d6ef8c4c7682c1d21641caa3adee5b1 | 2a8a6327fb9a7ce8696aa15b197d5170661fb94f | /zuora_client/models/put_credit_memo_tax_item_type_finance_information.py | 266d9a0b555a2462ed49fa8029542d9fcf9eb479 | [] | no_license | moderndatainc/zuora-client | 8b88e05132ddf7e8c411a6d7dad8c0baabaa6dad | d50da49ce1b8465c76723496c2561a3b8ebdf07d | refs/heads/master | 2021-09-21T19:17:34.752404 | 2018-08-29T23:24:07 | 2018-08-29T23:24:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 43,873 | py | # coding: utf-8
"""
Zuora API Reference
# Introduction Welcome to the reference for the Zuora REST API! <a href=\"http://en.wikipedia.org/wiki/REST_API\" target=\"_blank\">REST</a> is a web-service protocol that lends itself to rapid development by using everyday HTTP and JSON technology. The Zuora REST API provides a broad set of operations and resources that: * Enable Web Storefront integration from your website. * Support self-service subscriber sign-ups and account management. * Process revenue schedules through custom revenue rule models. * Enable manipulation of most objects in the Zuora Object Model. Want to share your opinion on how our API works for you? <a href=\"https://community.zuora.com/t5/Developers/API-Feedback-Form/gpm-p/21399\" target=\"_blank\">Tell us how you feel </a>about using our API and what we can do to make it better. ## Access to the API If you have a Zuora tenant, you can access the Zuora REST API via one of the following endpoints: | Tenant | Base URL for REST Endpoints | |-------------------------|-------------------------| |US Production | https://rest.zuora.com | |US API Sandbox | https://rest.apisandbox.zuora.com| |US Performance Test | https://rest.pt1.zuora.com | |EU Production | https://rest.eu.zuora.com | |EU Sandbox | https://rest.sandbox.eu.zuora.com | The Production endpoint provides access to your live user data. API Sandbox tenants are a good place to test code without affecting real-world data. If you would like Zuora to provision an API Sandbox tenant for you, contact your Zuora representative for assistance. **Note:** If you have a tenant in the Production Copy Environment, submit a request at <a href=\"http://support.zuora.com/\" target=\"_blank\">Zuora Global Support</a> to enable the Zuora REST API in your tenant and obtain the base URL for REST endpoints. If you do not have a Zuora tenant, go to <a href=\"https://www.zuora.com/resource/zuora-test-drive\" target=\"_blank\">https://www.zuora.com/resource/zuora-test-drive</a> and sign up for a Production Test Drive tenant. The tenant comes with seed data, including a sample product catalog. # API Changelog You can find the <a href=\"https://community.zuora.com/t5/Developers/API-Changelog/gpm-p/18092\" target=\"_blank\">Changelog</a> of the API Reference in the Zuora Community. # Authentication ## OAuth v2.0 Zuora recommends that you use OAuth v2.0 to authenticate to the Zuora REST API. Currently, OAuth is not available in every environment. See [Zuora Testing Environments](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/D_Zuora_Environments) for more information. Zuora recommends you to create a dedicated API user with API write access on a tenant when authenticating via OAuth, and then create an OAuth client for this user. See <a href=\"https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/Manage_Users/Create_an_API_User\" target=\"_blank\">Create an API User</a> for how to do this. By creating a dedicated API user, you can control permissions of the API user without affecting other non-API users. If a user is deactivated, all of the user's OAuth clients will be automatically deactivated. Authenticating via OAuth requires the following steps: 1. Create a Client 2. Generate a Token 3. Make Authenticated Requests ### Create a Client You must first [create an OAuth client](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/Manage_Users#Create_an_OAuth_Client_for_a_User) in the Zuora UI. To do this, you must be an administrator of your Zuora tenant. This is a one-time operation. You will be provided with a Client ID and a Client Secret. Please note this information down, as it will be required for the next step. **Note:** The OAuth client will be owned by a Zuora user account. If you want to perform PUT, POST, or DELETE operations using the OAuth client, the owner of the OAuth client must have a Platform role that includes the \"API Write Access\" permission. ### Generate a Token After creating a client, you must make a call to obtain a bearer token using the [Generate an OAuth token](https://www.zuora.com/developer/api-reference/#operation/createToken) operation. This operation requires the following parameters: - `client_id` - the Client ID displayed when you created the OAuth client in the previous step - `client_secret` - the Client Secret displayed when you created the OAuth client in the previous step - `grant_type` - must be set to `client_credentials` **Note**: The Client ID and Client Secret mentioned above were displayed when you created the OAuth Client in the prior step. The [Generate an OAuth token](https://www.zuora.com/developer/api-reference/#operation/createToken) response specifies how long the bearer token is valid for. Call [Generate an OAuth token](https://www.zuora.com/developer/api-reference/#operation/createToken) again to generate a new bearer token. ### Make Authenticated Requests To authenticate subsequent API requests, you must provide a valid bearer token in an HTTP header: `Authorization: Bearer {bearer_token}` If you have [Zuora Multi-entity](https://www.zuora.com/developer/api-reference/#tag/Entities) enabled, you need to set an additional header to specify the ID of the entity that you want to access. You can use the `scope` field in the [Generate an OAuth token](https://www.zuora.com/developer/api-reference/#operation/createToken) response to determine whether you need to specify an entity ID. If the `scope` field contains more than one entity ID, you must specify the ID of the entity that you want to access. For example, if the `scope` field contains `entity.1a2b7a37-3e7d-4cb3-b0e2-883de9e766cc` and `entity.c92ed977-510c-4c48-9b51-8d5e848671e9`, specify one of the following headers: - `Zuora-Entity-Ids: 1a2b7a37-3e7d-4cb3-b0e2-883de9e766cc` - `Zuora-Entity-Ids: c92ed977-510c-4c48-9b51-8d5e848671e9` **Note**: For a limited period of time, Zuora will accept the `entityId` header as an alternative to the `Zuora-Entity-Ids` header. If you choose to set the `entityId` header, you must remove all \"-\" characters from the entity ID in the `scope` field. If the `scope` field contains a single entity ID, you do not need to specify an entity ID. ## Other Supported Authentication Schemes Zuora continues to support the following additional legacy means of authentication: * Use username and password. Include authentication with each request in the header: * `apiAccessKeyId` * `apiSecretAccessKey` Zuora recommends that you create an API user specifically for making API calls. See <a href=\"https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/Manage_Users/Create_an_API_User\" target=\"_blank\">Create an API User</a> for more information. * Use an authorization cookie. The cookie authorizes the user to make calls to the REST API for the duration specified in **Administration > Security Policies > Session timeout**. The cookie expiration time is reset with this duration after every call to the REST API. To obtain a cookie, call the [Connections](https://www.zuora.com/developer/api-reference/#tag/Connections) resource with the following API user information: * ID * Password * For CORS-enabled APIs only: Include a 'single-use' token in the request header, which re-authenticates the user with each request. See below for more details. ### Entity Id and Entity Name The `entityId` and `entityName` parameters are only used for [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity \"Zuora Multi-entity\"). These are the legacy parameters that Zuora will only continue to support for a period of time. Zuora recommends you to use the `Zuora-Entity-Ids` parameter instead. The `entityId` and `entityName` parameters specify the Id and the [name of the entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity/B_Introduction_to_Entity_and_Entity_Hierarchy#Name_and_Display_Name \"Introduction to Entity and Entity Hierarchy\") that you want to access, respectively. Note that you must have permission to access the entity. You can specify either the `entityId` or `entityName` parameter in the authentication to access and view an entity. * If both `entityId` and `entityName` are specified in the authentication, an error occurs. * If neither `entityId` nor `entityName` is specified in the authentication, you will log in to the entity in which your user account is created. To get the entity Id and entity name, you can use the GET Entities REST call. For more information, see [API User Authentication](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity/A_Overview_of_Multi-entity#API_User_Authentication \"API User Authentication\"). ### Token Authentication for CORS-Enabled APIs The CORS mechanism enables REST API calls to Zuora to be made directly from your customer's browser, with all credit card and security information transmitted directly to Zuora. This minimizes your PCI compliance burden, allows you to implement advanced validation on your payment forms, and makes your payment forms look just like any other part of your website. For security reasons, instead of using cookies, an API request via CORS uses **tokens** for authentication. The token method of authentication is only designed for use with requests that must originate from your customer's browser; **it should not be considered a replacement to the existing cookie authentication** mechanism. See [Zuora CORS REST](https://knowledgecenter.zuora.com/DC_Developers/REST_API/A_REST_basics/G_CORS_REST \"Zuora CORS REST\") for details on how CORS works and how you can begin to implement customer calls to the Zuora REST APIs. See [HMAC Signatures](https://www.zuora.com/developer/api-reference/#operation/POSTHMACSignature \"HMAC Signatures\") for details on the HMAC method that returns the authentication token. # Requests and Responses ## Request IDs As a general rule, when asked to supply a \"key\" for an account or subscription (accountKey, account-key, subscriptionKey, subscription-key), you can provide either the actual ID or the number of the entity. ## HTTP Request Body Most of the parameters and data accompanying your requests will be contained in the body of the HTTP request. The Zuora REST API accepts JSON in the HTTP request body. No other data format (e.g., XML) is supported. ### Data Type ([Actions](https://www.zuora.com/developer/api-reference/#tag/Actions) and CRUD operations only) We recommend that you do not specify the decimal values with quotation marks, commas, and spaces. Use characters of `+-0-9.eE`, for example, `5`, `1.9`, `-8.469`, and `7.7e2`. Also, Zuora does not convert currencies for decimal values. ## Testing a Request Use a third party client, such as [curl](https://curl.haxx.se \"curl\"), [Postman](https://www.getpostman.com \"Postman\"), or [Advanced REST Client](https://advancedrestclient.com \"Advanced REST Client\"), to test the Zuora REST API. You can test the Zuora REST API from the Zuora API Sandbox or Production tenants. If connecting to Production, bear in mind that you are working with your live production data, not sample data or test data. ## Testing with Credit Cards Sooner or later it will probably be necessary to test some transactions that involve credit cards. For suggestions on how to handle this, see [Going Live With Your Payment Gateway](https://knowledgecenter.zuora.com/CB_Billing/M_Payment_Gateways/C_Managing_Payment_Gateways/B_Going_Live_Payment_Gateways#Testing_with_Credit_Cards \"C_Zuora_User_Guides/A_Billing_and_Payments/M_Payment_Gateways/C_Managing_Payment_Gateways/B_Going_Live_Payment_Gateways#Testing_with_Credit_Cards\" ). ## Concurrent Request Limits Zuora enforces tenant-level concurrent request limits. See <a href=\"https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Policies/Concurrent_Request_Limits\" target=\"_blank\">Concurrent Request Limits</a> for more information. ## Timeout Limit If a request does not complete within 120 seconds, the request times out and Zuora returns a Gateway Timeout error. ## Error Handling Responses and error codes are detailed in [Responses and errors](https://knowledgecenter.zuora.com/DC_Developers/REST_API/A_REST_basics/3_Responses_and_errors \"Responses and errors\"). # Pagination When retrieving information (using GET methods), the optional `pageSize` query parameter sets the maximum number of rows to return in a response. The maximum is `40`; larger values are treated as `40`. If this value is empty or invalid, `pageSize` typically defaults to `10`. The default value for the maximum number of rows retrieved can be overridden at the method level. If more rows are available, the response will include a `nextPage` element, which contains a URL for requesting the next page. If this value is not provided, no more rows are available. No \"previous page\" element is explicitly provided; to support backward paging, use the previous call. ## Array Size For data items that are not paginated, the REST API supports arrays of up to 300 rows. Thus, for instance, repeated pagination can retrieve thousands of customer accounts, but within any account an array of no more than 300 rate plans is returned. # API Versions The Zuora REST API are version controlled. Versioning ensures that Zuora REST API changes are backward compatible. Zuora uses a major and minor version nomenclature to manage changes. By specifying a version in a REST request, you can get expected responses regardless of future changes to the API. ## Major Version The major version number of the REST API appears in the REST URL. Currently, Zuora only supports the **v1** major version. For example, `POST https://rest.zuora.com/v1/subscriptions`. ## Minor Version Zuora uses minor versions for the REST API to control small changes. For example, a field in a REST method is deprecated and a new field is used to replace it. Some fields in the REST methods are supported as of minor versions. If a field is not noted with a minor version, this field is available for all minor versions. If a field is noted with a minor version, this field is in version control. You must specify the supported minor version in the request header to process without an error. If a field is in version control, it is either with a minimum minor version or a maximum minor version, or both of them. You can only use this field with the minor version between the minimum and the maximum minor versions. For example, the `invoiceCollect` field in the POST Subscription method is in version control and its maximum minor version is 189.0. You can only use this field with the minor version 189.0 or earlier. If you specify a version number in the request header that is not supported, Zuora will use the minimum minor version of the REST API. In our REST API documentation, if a field or feature requires a minor version number, we note that in the field description. You only need to specify the version number when you use the fields require a minor version. To specify the minor version, set the `zuora-version` parameter to the minor version number in the request header for the request call. For example, the `collect` field is in 196.0 minor version. If you want to use this field for the POST Subscription method, set the `zuora-version` parameter to `196.0` in the request header. The `zuora-version` parameter is case sensitive. For all the REST API fields, by default, if the minor version is not specified in the request header, Zuora will use the minimum minor version of the REST API to avoid breaking your integration. ### Minor Version History The supported minor versions are not serial. This section documents the changes made to each Zuora REST API minor version. The following table lists the supported versions and the fields that have a Zuora REST API minor version. | Fields | Minor Version | REST Methods | Description | |:--------|:--------|:--------|:--------| | invoiceCollect | 189.0 and earlier | [Create Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-reference/#operation/POST_Account \"Create Account\")|Generates an invoice and collects a payment for a subscription. | | collect | 196.0 and later | [Create Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-reference/#operation/POST_Account \"Create Account\")|Collects an automatic payment for a subscription. | | invoice | 196.0 and 207.0| [Create Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-reference/#operation/POST_Account \"Create Account\")|Generates an invoice for a subscription. | | invoiceTargetDate | 196.0 and earlier | [Preview Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_SubscriptionPreview \"Preview Subscription\") |Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | invoiceTargetDate | 207.0 and earlier | [Create Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-reference/#operation/POST_Account \"Create Account\")|Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | targetDate | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_SubscriptionPreview \"Preview Subscription\") |Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | targetDate | 211.0 and later | [Create Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-reference/#operation/POST_Account \"Create Account\")|Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | includeExisting DraftInvoiceItems | 196.0 and earlier| [Preview Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_SubscriptionPreview \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\") | Specifies whether to include draft invoice items in subscription previews. Specify it to be `true` (default) to include draft invoice items in the preview result. Specify it to be `false` to excludes draft invoice items in the preview result. | | includeExisting DraftDocItems | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_SubscriptionPreview \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\") | Specifies whether to include draft invoice items in subscription previews. Specify it to be `true` (default) to include draft invoice items in the preview result. Specify it to be `false` to excludes draft invoice items in the preview result. | | previewType | 196.0 and earlier| [Preview Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_SubscriptionPreview \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\") | The type of preview you will receive. The possible values are `InvoiceItem`(default), `ChargeMetrics`, and `InvoiceItemChargeMetrics`. | | previewType | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_SubscriptionPreview \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\") | The type of preview you will receive. The possible values are `LegalDoc`(default), `ChargeMetrics`, and `LegalDocChargeMetrics`. | | runBilling | 211.0 and later | [Create Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-reference/#operation/POST_Account \"Create Account\")|Generates an invoice or credit memo for a subscription. **Note:** Credit memos are only available if you have the Invoice Settlement feature enabled. | | invoiceDate | 214.0 and earlier | [Invoice and Collect](https://www.zuora.com/developer/api-reference/#operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date that should appear on the invoice being generated, as `yyyy-mm-dd`. | | invoiceTargetDate | 214.0 and earlier | [Invoice and Collect](https://www.zuora.com/developer/api-reference/#operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date through which to calculate charges on this account if an invoice is generated, as `yyyy-mm-dd`. | | documentDate | 215.0 and later | [Invoice and Collect](https://www.zuora.com/developer/api-reference/#operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date that should appear on the invoice and credit memo being generated, as `yyyy-mm-dd`. | | targetDate | 215.0 and later | [Invoice and Collect](https://www.zuora.com/developer/api-reference/#operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date through which to calculate charges on this account if an invoice or a credit memo is generated, as `yyyy-mm-dd`. | | memoItemAmount | 223.0 and earlier | [Create credit memo from charge](https://www.zuora.com/developer/api-reference/#operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-reference/#operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | Amount of the memo item. | | amount | 224.0 and later | [Create credit memo from charge](https://www.zuora.com/developer/api-reference/#operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-reference/#operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | Amount of the memo item. | | subscriptionNumbers | 222.4 and earlier | [Create order](https://www.zuora.com/developer/api-reference/#operation/POST_Order \"Create order\") | Container for the subscription numbers of the subscriptions in an order. | | subscriptions | 223.0 and later | [Create order](https://www.zuora.com/developer/api-reference/#operation/POST_Order \"Create order\") | Container for the subscription numbers and statuses in an order. | #### Version 207.0 and Later The response structure of the [Preview Subscription](https://www.zuora.com/developer/api-reference/#operation/POST_SubscriptionPreview \"Preview Subscription\") and [Update Subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription \"Update Subscription\") methods are changed. The following invoice related response fields are moved to the invoice container: * amount * amountWithoutTax * taxAmount * invoiceItems * targetDate * chargeMetrics # Zuora Object Model The following diagram presents a high-level view of the key Zuora objects. Click the image to open it in a new tab to resize it. <a href=\"https://www.zuora.com/wp-content/uploads/2017/01/ZuoraERD.jpeg\" target=\"_blank\"><img src=\"https://www.zuora.com/wp-content/uploads/2017/01/ZuoraERD.jpeg\" alt=\"Zuora Object Model Diagram\"></a> See the following articles for information about other parts of the Zuora business object model: * <a href=\"https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/D_Invoice_Settlement_Object_Model\" target=\"_blank\">Invoice Settlement Object Model</a> * <a href=\"https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/BA_Orders_Object_Model\" target=\"_blank\">Orders Object Model</a> You can use the [Describe object](https://www.zuora.com/developer/api-reference/#operation/GET_Describe) operation to list the fields of each Zuora object that is available in your tenant. When you call the operation, you must specify the API name of the Zuora object. The following table provides the API name of each Zuora object: | Object | API Name | |-----------------------------------------------|--------------------------------------------| | Account | `Account` | | Accounting Code | `AccountingCode` | | Accounting Period | `AccountingPeriod` | | Amendment | `Amendment` | | Application Group | `ApplicationGroup` | | Billing Run | <p>`BillingRun`</p><p>**Note:** The API name of this object is `BillingRun` in the [Describe object](https://www.zuora.com/developer/api-reference/#operation/GET_Describe) operation and Export ZOQL queries only. Otherwise, the API name of this object is `BillRun`.</p> | | Contact | `Contact` | | Contact Snapshot | `ContactSnapshot` | | Credit Balance Adjustment | `CreditBalanceAdjustment` | | Credit Memo | `CreditMemo` | | Credit Memo Application | `CreditMemoApplication` | | Credit Memo Application Item | `CreditMemoApplicationItem` | | Credit Memo Item | `CreditMemoItem` | | Credit Memo Part | `CreditMemoPart` | | Credit Memo Part Item | `CreditMemoPartItem` | | Credit Taxation Item | `CreditTaxationItem` | | Custom Exchange Rate | `FXCustomRate` | | Debit Memo | `DebitMemo` | | Debit Memo Item | `DebitMemoItem` | | Debit Taxation Item | `DebitTaxationItem` | | Discount Applied Metrics | `DiscountAppliedMetrics` | | Entity | `Tenant` | | Gateway Reconciliation Event | `PaymentGatewayReconciliationEventLog` | | Gateway Reconciliation Job | `PaymentReconciliationJob` | | Gateway Reconciliation Log | `PaymentReconciliationLog` | | Invoice | `Invoice` | | Invoice Adjustment | `InvoiceAdjustment` | | Invoice Item | `InvoiceItem` | | Invoice Item Adjustment | `InvoiceItemAdjustment` | | Invoice Payment | `InvoicePayment` | | Journal Entry | `JournalEntry` | | Journal Entry Item | `JournalEntryItem` | | Journal Run | `JournalRun` | | Order | `Order` | | Order Action | `OrderAction` | | Order ELP | `OrderElp` | | Order Item | `OrderItem` | | Order MRR | `OrderMrr` | | Order Quantity | `OrderQuantity` | | Order TCB | `OrderTcb` | | Order TCV | `OrderTcv` | | Payment | `Payment` | | Payment Application | `PaymentApplication` | | Payment Application Item | `PaymentApplicationItem` | | Payment Method | `PaymentMethod` | | Payment Method Snapshot | `PaymentMethodSnapshot` | | Payment Method Transaction Log | `PaymentMethodTransactionLog` | | Payment Method Update | `UpdaterDetail` | | Payment Part | `PaymentPart` | | Payment Part Item | `PaymentPartItem` | | Payment Run | `PaymentRun` | | Payment Transaction Log | `PaymentTransactionLog` | | Processed Usage | `ProcessedUsage` | | Product | `Product` | | Product Rate Plan | `ProductRatePlan` | | Product Rate Plan Charge | `ProductRatePlanCharge` | | Product Rate Plan Charge Tier | `ProductRatePlanChargeTier` | | Rate Plan | `RatePlan` | | Rate Plan Charge | `RatePlanCharge` | | Rate Plan Charge Tier | `RatePlanChargeTier` | | Refund | `Refund` | | Refund Application | `RefundApplication` | | Refund Application Item | `RefundApplicationItem` | | Refund Invoice Payment | `RefundInvoicePayment` | | Refund Part | `RefundPart` | | Refund Part Item | `RefundPartItem` | | Refund Transaction Log | `RefundTransactionLog` | | Revenue Charge Summary | `RevenueChargeSummary` | | Revenue Charge Summary Item | `RevenueChargeSummaryItem` | | Revenue Event | `RevenueEvent` | | Revenue Event Credit Memo Item | `RevenueEventCreditMemoItem` | | Revenue Event Debit Memo Item | `RevenueEventDebitMemoItem` | | Revenue Event Invoice Item | `RevenueEventInvoiceItem` | | Revenue Event Invoice Item Adjustment | `RevenueEventInvoiceItemAdjustment` | | Revenue Event Item | `RevenueEventItem` | | Revenue Event Item Credit Memo Item | `RevenueEventItemCreditMemoItem` | | Revenue Event Item Debit Memo Item | `RevenueEventItemDebitMemoItem` | | Revenue Event Item Invoice Item | `RevenueEventItemInvoiceItem` | | Revenue Event Item Invoice Item Adjustment | `RevenueEventItemInvoiceItemAdjustment` | | Revenue Event Type | `RevenueEventType` | | Revenue Schedule | `RevenueSchedule` | | Revenue Schedule Credit Memo Item | `RevenueScheduleCreditMemoItem` | | Revenue Schedule Debit Memo Item | `RevenueScheduleDebitMemoItem` | | Revenue Schedule Invoice Item | `RevenueScheduleInvoiceItem` | | Revenue Schedule Invoice Item Adjustment | `RevenueScheduleInvoiceItemAdjustment` | | Revenue Schedule Item | `RevenueScheduleItem` | | Revenue Schedule Item Credit Memo Item | `RevenueScheduleItemCreditMemoItem` | | Revenue Schedule Item Debit Memo Item | `RevenueScheduleItemDebitMemoItem` | | Revenue Schedule Item Invoice Item | `RevenueScheduleItemInvoiceItem` | | Revenue Schedule Item Invoice Item Adjustment | `RevenueScheduleItemInvoiceItemAdjustment` | | Subscription | `Subscription` | | Taxable Item Snapshot | `TaxableItemSnapshot` | | Taxation Item | `TaxationItem` | | Updater Batch | `UpdaterBatch` | | Usage | `Usage` | # noqa: E501
OpenAPI spec version: 2018-08-23
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PutCreditMemoTaxItemTypeFinanceInformation(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'on_account_accounting_code': 'str',
'sales_tax_payable_accounting_code': 'str'
}
attribute_map = {
'on_account_accounting_code': 'onAccountAccountingCode',
'sales_tax_payable_accounting_code': 'salesTaxPayableAccountingCode'
}
def __init__(self, on_account_accounting_code=None, sales_tax_payable_accounting_code=None): # noqa: E501
"""PutCreditMemoTaxItemTypeFinanceInformation - a model defined in Swagger""" # noqa: E501
self._on_account_accounting_code = None
self._sales_tax_payable_accounting_code = None
self.discriminator = None
if on_account_accounting_code is not None:
self.on_account_accounting_code = on_account_accounting_code
if sales_tax_payable_accounting_code is not None:
self.sales_tax_payable_accounting_code = sales_tax_payable_accounting_code
@property
def on_account_accounting_code(self):
"""Gets the on_account_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation. # noqa: E501
The accounting code that maps to an on account in your accounting system. # noqa: E501
:return: The on_account_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation. # noqa: E501
:rtype: str
"""
return self._on_account_accounting_code
@on_account_accounting_code.setter
def on_account_accounting_code(self, on_account_accounting_code):
"""Sets the on_account_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation.
The accounting code that maps to an on account in your accounting system. # noqa: E501
:param on_account_accounting_code: The on_account_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation. # noqa: E501
:type: str
"""
if on_account_accounting_code is not None and len(on_account_accounting_code) > 100:
raise ValueError("Invalid value for `on_account_accounting_code`, length must be less than or equal to `100`") # noqa: E501
if on_account_accounting_code is not None and len(on_account_accounting_code) < 0:
raise ValueError("Invalid value for `on_account_accounting_code`, length must be greater than or equal to `0`") # noqa: E501
self._on_account_accounting_code = on_account_accounting_code
@property
def sales_tax_payable_accounting_code(self):
"""Gets the sales_tax_payable_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation. # noqa: E501
The accounting code for the sales taxes payable. # noqa: E501
:return: The sales_tax_payable_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation. # noqa: E501
:rtype: str
"""
return self._sales_tax_payable_accounting_code
@sales_tax_payable_accounting_code.setter
def sales_tax_payable_accounting_code(self, sales_tax_payable_accounting_code):
"""Sets the sales_tax_payable_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation.
The accounting code for the sales taxes payable. # noqa: E501
:param sales_tax_payable_accounting_code: The sales_tax_payable_accounting_code of this PutCreditMemoTaxItemTypeFinanceInformation. # noqa: E501
:type: str
"""
if sales_tax_payable_accounting_code is not None and len(sales_tax_payable_accounting_code) > 100:
raise ValueError("Invalid value for `sales_tax_payable_accounting_code`, length must be less than or equal to `100`") # noqa: E501
if sales_tax_payable_accounting_code is not None and len(sales_tax_payable_accounting_code) < 0:
raise ValueError("Invalid value for `sales_tax_payable_accounting_code`, length must be greater than or equal to `0`") # noqa: E501
self._sales_tax_payable_accounting_code = sales_tax_payable_accounting_code
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PutCreditMemoTaxItemTypeFinanceInformation):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
ac86e7fd216d0562913ad2a8cb7dfa6b323d20d3 | 24595e74a83dcd263e92c121210c710c4438d979 | /lib/hammerlib.py | d5004d47f7133e87ce58e9a4ad8c21608fc953f8 | [] | no_license | amyth/hammer | 94dde5e6182da8368ed9859b4213226ac4543225 | 54e4fb07ee81055db47ccfd77ee6fc55bdb8fbe8 | refs/heads/master | 2021-01-17T15:30:30.717196 | 2016-05-20T07:00:43 | 2016-05-20T07:00:43 | 55,591,019 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,443 | py | from __future__ import division
def levenshtein_distance(x1, x2):
"""
Finds a match between mis-spelt string based on the lavenhtein
distance formula
"""
if len(x1) > len(x2):
x1, x2 = x2, x1
distances = range(len(x1) + 1)
for i2, c2 in enumerate(x2):
distances_ = [i2+1]
for i1, c1 in enumerate(x1):
if c1 == c2:
distances_.append(distances[i1])
else:
distances_.append(1 + min((distances[i1],
distances[i1 + 1], distances_[-1])))
distances = distances_
return distances[-1]
def spellmatch(x, y):
"""
Returns the match percentage between two given strings
using lavenhstein distance
"""
distance = levenshtein_distance(x, y)
return round(float(-(((distance/(len(x) + len(y)))*100)-100)),2)
def abbrmatch(x, y):
"""
Returns the match percentage between two strings assuming one of
the strings is the abbreviation for the other.
"""
sl = ['-', '&', ',', ', ', ' - ', ';', '; ', '/', '/ ', ' / ']
if len(x) > len(y):
x, y = y, x
for n in sl:
x = x.replace(n, ' ')
y = y.replace(n, ' ')
xl = [n.lower().strip() for n in x.split()]
yl = [n.lower().strip() for n in y.split()]
ps = []
for i, n in enumerate(xl[0]):
ps.append(levenshtein_distance(n, ''.join([z[0] for z in yl])))
return ps
| [
"[email protected]"
] | |
1a7c5e5a095621a27269f73ad97d5e16cd34c65c | 8e69eee9b474587925e22413717eb82e4b024360 | /v1.0.0.test/toontown/catalog/CatalogAccessoryItemGlobals.py | 75eda050eda7aa4d4e2bcc4c7daa23283e3857df | [
"MIT"
] | permissive | TTOFFLINE-LEAK/ttoffline | afaef613c36dc3b70514ccee7030ba73c3b5045b | bb0e91704a755d34983e94288d50288e46b68380 | refs/heads/master | 2020-06-12T15:41:59.411795 | 2020-04-17T08:22:55 | 2020-04-17T08:22:55 | 194,348,185 | 5 | 4 | null | null | null | null | UTF-8 | Python | false | false | 13,314 | py | ATArticle = 0
ATString = 1
ATBasePrice = 2
ATReleased = 3
ATEmblemPrices = 4
AHat = 0
AGlasses = 1
ABackpack = 2
AShoes = 3
ABoysHat = 4
ABoysGlasses = 5
ABoysBackpack = 6
ABoysShoes = 7
AGirlsHat = 8
AGirlsGlasses = 9
AGirlsBackpack = 10
AGirlsShoes = 11
APriceTest = 5
APriceBasic = 250
APriceBasicPlus = 400
APriceCool = 800
APriceAwesome = 1500
AccessoryTypes = {101: (AHat,
'hbb1',
APriceBasic,
1),
102: (
AHat,
'hsf1',
APriceCool,
5),
103: (
AGirlsHat,
'hrb1',
APriceBasic,
1),
104: (
AHat,
'hsf2',
APriceCool,
0),
105: (
AHat,
'hsf3',
APriceCool,
0),
106: (
AGirlsHat,
'hrb2',
APriceBasicPlus,
3),
107: (
AGirlsHat,
'hrb3',
APriceBasicPlus,
0),
108: (
AHat,
'hht1',
APriceCool,
4),
109: (
AHat,
'hht2',
APriceCool,
3),
110: (
AHat,
'htp1',
APriceCool,
3),
111: (
AHat,
'htp2',
APriceCool,
0),
112: (
AHat,
'hav1',
3500,
0),
113: (
AHat,
'hfp1',
3500,
0),
114: (
AHat,
'hsg1',
3500,
0),
115: (
AHat,
'hwt1',
3500,
0),
116: (
AHat,
'hfz1',
APriceCool,
5),
117: (
AHat,
'hgf1',
APriceCool,
1),
118: (
AHat,
'hpt1',
APriceBasicPlus,
1),
119: (
AHat,
'hpb1',
APriceBasicPlus,
6),
120: (
ABoysHat,
'hcr1',
10000,
5),
121: (
AHat,
'hbb2',
APriceBasic,
2),
122: (
AHat,
'hbb3',
APriceBasic,
2),
123: (
AHat,
'hcw1',
APriceCool,
1),
124: (
AHat,
'hpr1',
APriceAwesome,
1),
125: (
AHat,
'hpp1',
APriceBasicPlus,
1),
126: (
AHat,
'hfs1',
APriceCool,
1),
127: (
AHat,
'hsb1',
APriceAwesome,
1),
128: (
AHat,
'hst1',
APriceBasicPlus,
1),
129: (
AGirlsHat,
'hsu1',
APriceCool,
1),
130: (
AGirlsHat,
'hrb4',
APriceBasic,
1),
131: (
AGirlsHat,
'hrb5',
APriceBasicPlus,
4),
132: (
AGirlsHat,
'hrb6',
APriceBasic,
2),
133: (
AGirlsHat,
'hrb7',
APriceBasicPlus,
6),
134: (
AHat,
'hat1',
APriceCool,
2),
135: (
AGirlsHat,
'hhd1',
APriceCool,
2),
136: (
AHat,
'hbw1',
APriceCool,
6),
137: (
AHat,
'hch1',
APriceCool,
5),
138: (
AHat,
'hdt1',
APriceAwesome,
6),
139: (
AHat,
'hft1',
APriceCool,
4),
140: (
AHat,
'hfd1',
APriceCool,
6),
141: (
AHat,
'hmk1',
APriceAwesome,
2),
142: (
AHat,
'hft2',
APriceCool,
6),
143: (
ABoysHat,
'hhd2',
APriceCool,
3),
144: (
AGirlsHat,
'hpc1',
APriceCool,
5),
145: (
AHat,
'hrh1',
APriceCool,
2),
146: (
AHat,
'hhm1',
2500,
2),
147: (
AHat,
'hat2',
APriceCool,
2),
148: (
AGirlsHat,
'htr1',
10000,
3),
149: (
AHat,
'hhm2',
APriceAwesome,
2),
150: (
AHat,
'hwz1',
APriceCool,
2),
151: (
AHat,
'hwz2',
APriceCool,
2),
152: (
AHat,
'hhm3',
APriceAwesome,
6),
153: (
AHat,
'hhm4',
APriceAwesome,
5),
154: (
AHat,
'hfp2',
APriceCool,
5),
155: (
AHat,
'hhm5',
APriceAwesome,
4),
156: (
AHat,
'hnp1',
APriceAwesome,
6),
157: (
AHat,
'hpc2',
APriceAwesome,
3),
158: (
AHat,
'hph1',
APriceAwesome,
4),
159: (
AHat,
'hwg1',
APriceCool,
5),
160: (
AHat,
'hbb4',
APriceBasic,
5),
161: (
AHat,
'hbb5',
APriceBasic,
2),
162: (
AHat,
'hbb6',
APriceBasic,
5),
163: (
AHat,
'hsl1',
APriceCool,
5),
164: (
AHat,
'hfr1',
3000,
4),
165: (
AHat,
'hby1',
APriceAwesome,
5),
166: (
AGirlsHat,
'hrb8',
APriceBasicPlus,
6),
167: (
AHat,
'hjh1',
APriceAwesome,
3),
168: (
AHat,
'hbb7',
APriceBasic,
6),
169: (
AGirlsHat,
'hrb9',
APriceBasicPlus,
6),
170: (
AHat,
'hwt2',
APriceAwesome,
4),
171: (
AGirlsHat,
'hhw1',
APriceBasicPlus,
7),
172: (
AHat,
'hhw2',
900,
7),
173: (
AHat,
'hob1',
APriceAwesome,
6),
174: (
AHat,
'hbn1',
APriceAwesome,
8),
175: (
AHat,
'hpt2',
APriceCool,
9),
201: (
AGlasses,
'grd1',
APriceBasicPlus,
0),
202: (
AGlasses,
'gmb1',
APriceCool,
1),
203: (
AGlasses,
'gnr1',
APriceCool,
0),
204: (
AGlasses,
'gst1',
APriceBasicPlus,
1),
205: (
AGlasses,
'g3d1',
APriceCool,
1),
206: (
AGlasses,
'gav1',
APriceCool,
1),
207: (
AGlasses,
'gce1',
APriceCool,
2),
208: (
AGlasses,
'gdk1',
APriceBasic,
1),
209: (
AGlasses,
'gjo1',
APriceBasicPlus,
1),
210: (
AGlasses,
'gsb1',
APriceAwesome,
1),
211: (
AGlasses,
'ggl1',
APriceCool,
6),
212: (
AGlasses,
'ggm1',
APriceBasicPlus,
2),
213: (
AGlasses,
'ghg1',
APriceAwesome,
3),
214: (
AGlasses,
'gie1',
APriceCool,
2),
215: (
AGlasses,
'gmt1',
APriceCool,
2),
216: (
AGlasses,
'gmt2',
APriceCool,
2),
217: (
AGlasses,
'gmt3',
3500,
5),
218: (
AGlasses,
'gmt4',
3500,
5),
219: (
AGlasses,
'gmt5',
3500,
5),
220: (
AGlasses,
'gmn1',
APriceAwesome,
6),
221: (
AGlasses,
'gmo1',
APriceAwesome,
4),
222: (
AGlasses,
'gsr1',
APriceBasicPlus,
5),
223: (
ABoysGlasses,
'ghw1',
APriceTest,
0),
224: (
ABoysGlasses,
'ghw2',
APriceBasic,
7),
225: (
AGlasses,
'gag1',
APriceAwesome,
8),
301: (
ABackpack,
'bpb1',
APriceBasic,
4),
302: (
ABackpack,
'bpb2',
APriceBasic,
1),
303: (
ABackpack,
'bpb3',
APriceBasic,
5),
304: (
ABackpack,
'bpd1',
APriceBasicPlus,
4),
305: (
ABackpack,
'bpd2',
APriceBasicPlus,
5),
306: (
ABackpack,
'bwg1',
APriceCool,
2),
307: (
ABackpack,
'bwg2',
APriceCool,
2),
308: (
ABackpack,
'bwg3',
APriceCool,
1),
309: (
ABackpack,
'bst1',
APriceAwesome,
1),
310: (
ABackpack,
'bfn1',
APriceCool,
1),
311: (
ABackpack,
'baw1',
APriceCool,
3),
312: (
ABackpack,
'baw2',
APriceAwesome,
2),
313: (
ABackpack,
'bwt1',
3000,
3),
314: (
ABackpack,
'bwg4',
APriceAwesome,
6),
315: (
ABackpack,
'bwg5',
3000,
5),
316: (
ABackpack,
'bwg6',
3000,
4),
317: (
ABackpack,
'bjp1',
3000,
1),
318: (
ABackpack,
'blg1',
APriceCool,
2),
319: (
ABackpack,
'bsa1',
2500,
5),
320: (
ABackpack,
'bwg7',
APriceAwesome,
6),
321: (
ABackpack,
'bsa2',
2000,
2),
322: (
ABackpack,
'bsa3',
2000,
2),
323: (
ABackpack,
'bap1',
5000,
4),
324: (
ABackpack,
'bhw1',
900,
7),
325: (
ABackpack,
'bhw2',
APriceBasicPlus,
7),
326: (
ABackpack,
'bhw3',
APriceBasicPlus,
7),
327: (
ABackpack,
'bhw4',
900,
7),
328: (
ABackpack,
'bob1',
3000,
6),
329: (
ABackpack,
'bfg1',
3000,
6),
330: (
ABackpack,
'bfl1',
APriceAwesome,
8),
401: (
AShoes,
'sat1',
APriceBasic,
3),
402: (
AShoes,
'sat2',
APriceBasic,
1),
403: (
AShoes,
'smb1',
APriceAwesome,
1),
404: (
AShoes,
'scs1',
APriceBasicPlus,
6),
405: (
ABoysShoes,
'swt1',
APriceBasicPlus,
1),
406: (
AGirlsShoes,
'smj1',
APriceBasicPlus,
1),
407: (
AShoes,
'sdk1',
APriceBasic,
1),
408: (
AShoes,
'sat3',
APriceBasic,
1),
409: (
AShoes,
'scs2',
APriceBasicPlus,
1),
410: (
AShoes,
'scs3',
APriceBasicPlus,
1),
411: (
AShoes,
'scs4',
APriceBasicPlus,
1),
412: (
AShoes,
'scb1',
APriceAwesome,
1),
413: (
AShoes,
'sfb1',
APriceCool,
1),
414: (
AShoes,
'sht1',
APriceAwesome,
4),
415: (
AGirlsShoes,
'smj2',
APriceBasicPlus,
3),
416: (
AGirlsShoes,
'smj3',
APriceBasicPlus,
4),
417: (
AShoes,
'ssb1',
APriceAwesome,
2),
418: (
AShoes,
'sts1',
APriceBasic,
5),
419: (
AShoes,
'sts2',
APriceBasic,
4),
420: (
AShoes,
'scs5',
APriceBasicPlus,
4),
421: (
AShoes,
'smb2',
APriceAwesome,
3),
422: (
AShoes,
'smb3',
APriceAwesome,
2),
423: (
AShoes,
'smb4',
APriceAwesome,
5),
424: (
AShoes,
'sfb2',
2000,
6),
425: (
AShoes,
'sfb3',
2000,
4),
426: (
AShoes,
'sfb4',
2000,
3),
427: (
AShoes,
'sfb5',
2000,
5),
428: (
AShoes,
'sfb6',
2000,
4),
429: (
AShoes,
'slf1',
APriceBasicPlus,
3),
430: (
AGirlsShoes,
'smj4',
APriceBasicPlus,
2),
431: (
AShoes,
'smt1',
APriceAwesome,
4),
432: (
AShoes,
'sox1',
APriceAwesome,
5),
433: (
AShoes,
'srb1',
APriceAwesome,
6),
434: (
AShoes,
'sst1',
3000,
3),
435: (
AShoes,
'swb1',
APriceCool,
3),
436: (
AShoes,
'swb2',
APriceCool,
4),
437: (
AShoes,
'swk1',
APriceAwesome,
3),
438: (
AShoes,
'scs6',
APriceBasicPlus,
0),
439: (
AShoes,
'smb5',
APriceAwesome,
3),
440: (
AShoes,
'sht2',
APriceAwesome,
4),
441: (
AShoes,
'srb2',
APriceAwesome,
3),
442: (
AShoes,
'sts3',
APriceBasic,
6),
443: (
AShoes,
'sts4',
APriceBasic,
3),
444: (
AShoes,
'sts5',
APriceBasic,
2),
445: (
AShoes,
'srb3',
APriceCool,
5),
446: (
AShoes,
'srb4',
APriceCool,
3),
447: (
AShoes,
'sat4',
APriceBasic,
3),
448: (
AShoes,
'shw1',
APriceCool,
7),
449: (
AShoes,
'shw2',
APriceCool,
7)}
LoyaltyAccessoryItems = [] | [
"[email protected]"
] | |
bc0e8083bcf514fd9f3302b7fbdfdf561af9d5ae | 30a1a391444181473b1af54c994bb81781fe830d | /Recusrion-and-Dynamic-Programming/triple-step.py | 1f3a69e6be39a7e21e42a65c37f49bc49c7ad24e | [] | no_license | sharmayuvraj/cracking-the-coding-interview | 8b2a4760041fec98252f32c030a267c9951f0a18 | b8e63d4190e82cc6d4677ba3dbe27f991c34da8a | refs/heads/master | 2023-04-16T15:27:27.072935 | 2021-04-26T12:18:08 | 2021-04-26T12:18:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 830 | py | """
A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time.
Implement a method to count how many possible ways the child can run up the satirs.
"""
# Recursive Method
def countWays(n):
memo = [-1]*(n+1)
return countWaysRecursive(n,memo)
def countWaysRecursive(n, memo):
if n < 0:
return 0
elif n == 0:
return 1
elif memo[n] > -1:
return memo[n]
else:
memo[n] = countWaysRecursive(n-1, memo) + countWaysRecursive(n-2, memo) + countWaysRecursive(n-3, memo)
return memo[n]
# Iterative Method
def countWaysIterative(n) :
memo = [-1] * (n + 1)
memo[0] = 1
memo[1] = 1
memo[2] = 2
for i in range(3, n + 1) :
memo[i] = memo[i - 1] + memo[i - 2] + memo[i - 3]
return memo[n] | [
"[email protected]"
] | |
4801e1eaf02b1557859585316af8ce5e240b6fa3 | 281a10505f8044dbed73f11ed731bd0fbe23e0b5 | /expenseApp/migrations/0012_auto_20181023_1608.py | 18e381b3c7040d31723ae82e68cb0a57a0d68e76 | [
"Apache-2.0"
] | permissive | cs-fullstack-fall-2018/project3-django-jpark1914 | 7c6f57ab5f8055c11ac5b9d3c8bf0aa5057008d7 | 53bca13243d7e50263ec25b2fb8a299a8bbada1c | refs/heads/master | 2020-04-02T00:59:33.254360 | 2018-10-29T04:58:42 | 2018-10-29T04:58:42 | 153,831,819 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,053 | py | # Generated by Django 2.0.6 on 2018-10-23 16:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('expenseApp', '0011_auto_20181022_1942'),
]
operations = [
migrations.CreateModel(
name='TransactionModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.IntegerField()),
('time_of_transaction', models.DateField()),
],
),
migrations.RenameModel(
old_name='ExpensesModel',
new_name='AccountModel',
),
migrations.AddField(
model_name='transactionmodel',
name='account',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='expenseApp.AccountModel'),
),
]
| [
"[email protected]"
] | |
f1486683533caa71df3b0601c146e9d68192bb77 | 2d24c495ba7318c639043095b6bdf4707be29f7e | /test/test_vehicle_stats_nfc_card_scan_with_decoration.py | 5aaddd8883d10ce00e2189cac785c93e0a3cf360 | [] | no_license | samsarahq/samsara-python | e032d72b041f45a142566d7d9756c28e6acb24bd | 59704b2e2c8af94a069a512b0bc0db7494c8c10d | refs/heads/master | 2021-12-11T08:21:57.218305 | 2021-11-29T19:13:47 | 2021-11-29T19:13:47 | 66,108,617 | 13 | 7 | null | null | null | null | UTF-8 | Python | false | false | 10,521 | py | # coding: utf-8
"""
Samsara API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 2020-06-15
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import samsara
from samsara.models.vehicle_stats_nfc_card_scan_with_decoration import VehicleStatsNfcCardScanWithDecoration # noqa: E501
from samsara.rest import ApiException
class TestVehicleStatsNfcCardScanWithDecoration(unittest.TestCase):
"""VehicleStatsNfcCardScanWithDecoration unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test VehicleStatsNfcCardScanWithDecoration
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = samsara.models.vehicle_stats_nfc_card_scan_with_decoration.VehicleStatsNfcCardScanWithDecoration() # noqa: E501
if include_optional :
return VehicleStatsNfcCardScanWithDecoration(
card = samsara.models.vehicle_stats_nfc_card_scan_card.VehicleStatsNfcCardScan_card(
id = '835063', ),
decorations = samsara.models.vehicle_stats_decorations.VehicleStatsDecorations(
ambient_air_temperature_milli_c = samsara.models.vehicle_stats_decorations_ambient_air_temperature_milli_c.VehicleStatsDecorations_ambientAirTemperatureMilliC(
value = 31110, ),
aux_input1 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input10 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input2 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input3 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input4 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input5 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input6 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input7 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input8 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
aux_input9 = samsara.models.vehicle_stats_aux_input_decoration.VehicleStatsAuxInputDecoration(
name = 'boom',
value = True, ),
barometric_pressure_pa = samsara.models.vehicle_stats_decorations_barometric_pressure_pa.VehicleStatsDecorations_barometricPressurePa(
value = 99000, ),
battery_milli_volts = samsara.models.vehicle_stats_decorations_battery_milli_volts.VehicleStatsDecorations_batteryMilliVolts(
value = 7991, ),
def_level_milli_percent = samsara.models.vehicle_stats_decorations_def_level_milli_percent.VehicleStatsDecorations_defLevelMilliPercent(
value = 54200, ),
ecu_speed_mph = samsara.models.vehicle_stats_decorations_ecu_speed_mph.VehicleStatsDecorations_ecuSpeedMph(
value = 58.3, ),
engine_coolant_temperature_milli_c = samsara.models.vehicle_stats_decorations_engine_coolant_temperature_milli_c.VehicleStatsDecorations_engineCoolantTemperatureMilliC(
value = 31110, ),
engine_immobilizer = samsara.models.vehicle_stats_engine_immobilizer.VehicleStatsEngineImmobilizer(
connected = False,
state = 'ignition_disabled',
time = '2020-01-27T07:06:25Z', ),
engine_load_percent = samsara.models.vehicle_stats_decorations_engine_load_percent.VehicleStatsDecorations_engineLoadPercent(
value = 54, ),
engine_oil_pressure_k_pa = samsara.models.vehicle_stats_decorations_engine_oil_pressure_k_pa.VehicleStatsDecorations_engineOilPressureKPa(
value = 100, ),
engine_rpm = samsara.models.vehicle_stats_decorations_engine_rpm.VehicleStatsDecorations_engineRpm(
value = 1000, ),
engine_states = samsara.models.vehicle_stats_decorations_engine_states.VehicleStatsDecorations_engineStates(
value = 'On', ),
fault_codes = samsara.models.vehicle_stats_fault_codes_value.VehicleStatsFaultCodesValue(
can_bus_type = 'CANBUS_J1939_500',
j1939 = samsara.models.vehicle_stats_fault_codes_value_j1939.VehicleStatsFaultCodesValue_j1939(
check_engine_lights = samsara.models.vehicle_stats_fault_codes_value_j1939_check_engine_lights.VehicleStatsFaultCodesValue_j1939_checkEngineLights(
emissions_is_on = True,
protect_is_on = False,
stop_is_on = False,
warning_is_on = False, ),
diagnostic_trouble_codes = [
samsara.models.vehicle_stats_fault_codes_value_j1939_diagnostic_trouble_codes.VehicleStatsFaultCodesValue_j1939_diagnosticTroubleCodes(
fmi_description = 'Voltage Below Normal',
fmi_id = 9,
mil_status = 1,
occurrence_count = 1,
source_address_name = 'Engine #1',
spn_description = 'System Diagnostic Code #1',
spn_id = 3031,
tx_id = 0,
vendor_specific_fields = samsara.models.vehicle_stats_fault_codes_value_j1939_vendor_specific_fields.VehicleStatsFaultCodesValue_j1939_vendorSpecificFields(
dtc_description = 'false',
repair_instructions_url = 'false', ), )
], ),
obdii = samsara.models.vehicle_stats_fault_codes_value_obdii.VehicleStatsFaultCodesValue_obdii(
check_engine_light_is_on = True, ), ),
fuel_percents = samsara.models.vehicle_stats_decorations_fuel_percents.VehicleStatsDecorations_fuelPercents(
value = 54, ),
gps = samsara.models.vehicle_stats_decorations_gps.VehicleStatsDecorations_gps(
address = samsara.models.vehicle_location_address.VehicleLocationAddress(
id = '1234',
name = 'Address 1', ),
heading_degrees = 120,
is_ecu_speed = True,
latitude = 122.142,
longitude = -93.343,
reverse_geo = samsara.models.vehicle_location_reverse_geo.VehicleLocationReverseGeo(
formatted_location = '16 N Fair Oaks Ave, Pasadena, CA 91103', ),
speed_miles_per_hour = 48.3, ),
gps_distance_meters = samsara.models.vehicle_stats_decorations_gps_distance_meters.VehicleStatsDecorations_gpsDistanceMeters(
value = 81029.591434899, ),
gps_odometer_meters = samsara.models.vehicle_stats_decorations_gps_odometer_meters.VehicleStatsDecorations_gpsOdometerMeters(
value = 14010293, ),
intake_manifold_temperature_milli_c = samsara.models.vehicle_stats_decorations_intake_manifold_temperature_milli_c.VehicleStatsDecorations_intakeManifoldTemperatureMilliC(
value = 88000, ),
obd_engine_seconds = samsara.models.vehicle_stats_decorations_obd_engine_seconds.VehicleStatsDecorations_obdEngineSeconds(
value = 9723103, ),
obd_odometer_meters = samsara.models.vehicle_stats_decorations_obd_odometer_meters.VehicleStatsDecorations_obdOdometerMeters(
value = 14010293, ),
tire_pressure = samsara.models.vehicle_stats_tire_pressures.VehicleStatsTirePressures(
back_left_tire_pressure_k_pa = 200,
back_right_tire_pressure_k_pa = 200,
front_left_tire_pressure_k_pa = 200,
front_right_tire_pressure_k_pa = 200, ), ),
time = '2020-01-27T07:06:25Z'
)
else :
return VehicleStatsNfcCardScanWithDecoration(
card = samsara.models.vehicle_stats_nfc_card_scan_card.VehicleStatsNfcCardScan_card(
id = '835063', ),
time = '2020-01-27T07:06:25Z',
)
def testVehicleStatsNfcCardScanWithDecoration(self):
"""Test VehicleStatsNfcCardScanWithDecoration"""
inst_req_only = self.make_instance(include_optional=False)
inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
942b224bad7b2c2a6138e375dec16529a6d08fac | c91e32b5e7a28fd31698764086b88203fd3c8029 | /root_numpy/info.py | c669cbd8832aebac1169448f7ae98cad8eeb4a39 | [
"MIT"
] | permissive | balarsen/root_numpy | 5b409a1d90d499f2677990a95246e19d9f596144 | 6229f4eb7ab7884b1950210c92275299d631b9da | refs/heads/master | 2021-01-15T07:54:23.935985 | 2014-02-10T23:10:35 | 2014-02-10T23:10:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 394 | py | """
_
_ __ ___ ___ | |_ _ __ _ _ _ __ ___ _ __ _ _
| '__/ _ \ / _ \| __| | '_ \| | | | '_ ` _ \| '_ \| | | |
| | | (_) | (_) | |_ | | | | |_| | | | | | | |_) | |_| |
|_| \___/ \___/ \__|___|_| |_|\__,_|_| |_| |_| .__/ \__, | {0}
|_____| |_| |___/
"""
__version__ = '3.2.0.dev'
__doc__ = __doc__.format(__version__)
| [
"[email protected]"
] | |
48b0f55c8b8802c52876e069c124eb8a0fadbd56 | add74ecbd87c711f1e10898f87ffd31bb39cc5d6 | /xcp2k/classes/_move_mm_charge2.py | 9b960a7447c8177d8674a046b34f493d633239db | [] | no_license | superstar54/xcp2k | 82071e29613ccf58fc14e684154bb9392d00458b | e8afae2ccb4b777ddd3731fe99f451b56d416a83 | refs/heads/master | 2021-11-11T21:17:30.292500 | 2021-11-06T06:31:20 | 2021-11-06T06:31:20 | 62,589,715 | 8 | 2 | null | null | null | null | UTF-8 | Python | false | false | 985 | py | from xcp2k.inputsection import InputSection
class _move_mm_charge2(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Atom_index_1 = None
self.Atom_index_2 = None
self.Alpha = None
self.Radius = None
self.Corr_radius = None
self._name = "MOVE_MM_CHARGE"
self._keywords = {'Atom_index_1': 'ATOM_INDEX_1', 'Atom_index_2': 'ATOM_INDEX_2', 'Alpha': 'ALPHA', 'Radius': 'RADIUS', 'Corr_radius': 'CORR_RADIUS'}
self._aliases = {'Mm1': 'Atom_index_1', 'Mm2': 'Atom_index_2'}
@property
def Mm1(self):
"""
See documentation for Atom_index_1
"""
return self.Atom_index_1
@property
def Mm2(self):
"""
See documentation for Atom_index_2
"""
return self.Atom_index_2
@Mm1.setter
def Mm1(self, value):
self.Atom_index_1 = value
@Mm2.setter
def Mm2(self, value):
self.Atom_index_2 = value
| [
"[email protected]"
] | |
fc61d8ff3efe35ece110d4fef6228e3793921dc0 | f74dd098c3e665d8f605af5ebe7e2874ac31dd2f | /aiogithubapi/models/base.py | 086dcb1b6e17eb22f4c9629e7ea27c46c0145156 | [
"MIT"
] | permissive | ludeeus/aiogithubapi | ce87382698827939aaa127b378b9a11998f13c06 | 90f3fc98e5096300269763c9a5857481b2dec4d2 | refs/heads/main | 2023-08-20T19:30:05.309844 | 2023-08-14T20:24:21 | 2023-08-14T20:24:21 | 198,505,021 | 21 | 20 | MIT | 2023-09-11T06:12:10 | 2019-07-23T20:39:53 | Python | UTF-8 | Python | false | false | 2,080 | py | """Base class for all GitHub objects."""
from __future__ import annotations
from logging import Logger
from typing import Any, Dict
from ..const import LOGGER
IGNORE_KEYS = ("node_id", "performed_via_github_app", "_links")
class GitHubBase:
"""Base class for all GitHub objects."""
logger: Logger = LOGGER
@staticmethod
def slugify(value: str) -> str:
"""Slugify."""
return str(value).replace("-", "_").lower()
class GitHubDataModelBase(GitHubBase):
"""Base class for all GitHub data objects."""
_raw_data: Any | None = None
_log_missing: bool = True
_process_data: bool = True
_slugify_keys: bool = True
def __init__(self, data: Dict[str, Any]) -> None:
"""Init."""
self._raw_data = data
if self._process_data:
for key, value in self._raw_data.items():
if self._slugify_keys:
key = self.slugify(key)
if hasattr(self, key):
if handler := getattr(self, f"_generate_{key}", None):
value = handler(value)
self.__setattr__(key, value)
elif self._log_missing and key not in IGNORE_KEYS:
self.logger.debug(
"'%s' is missing key '%s' for %s",
self.__class__.__name__,
key,
type(value),
)
self.__post_init__()
def __post_init__(self):
"""Post init."""
@property
def as_dict(self) -> Dict[str, Any]:
"""Return attributes as a dict."""
def expand_value_if_needed(value: Any) -> Any:
if isinstance(value, GitHubDataModelBase):
return value.as_dict
if isinstance(value, list):
return [expand_value_if_needed(v) for v in value]
return value
return {
key: expand_value_if_needed(value)
for key, value in self.__dict__.items()
if not key.startswith("_")
}
| [
"[email protected]"
] | |
b0a5eda3acff547197ee9ca1ca43194ab7378f29 | 7142f2095fce389ee34c7c7141fb0d0bd99620cd | /backend/tst_daniel_connector_7521/urls.py | ea9923540bed669525d89baf4e28c94dff468c09 | [] | no_license | crowdbotics-apps/tst-daniel-connector-7521 | 4364df5be6e1f0662b4a5ff4c80b67e40a5f08f9 | c785608370fd02b2fa6b7971e2c63c3588b6784b | refs/heads/master | 2022-11-18T02:49:44.052058 | 2020-07-13T18:49:18 | 2020-07-13T18:49:18 | 279,385,556 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,995 | py | """tst_daniel_connector_7521 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from allauth.account.views import confirm_email
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
urlpatterns = [
path("", include("home.urls")),
path("accounts/", include("allauth.urls")),
path("api/v1/", include("home.api.v1.urls")),
path("admin/", admin.site.urls),
path("users/", include("users.urls", namespace="users")),
path("rest-auth/", include("rest_auth.urls")),
# Override email confirm to use allauth's HTML view instead of rest_auth's API view
path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email),
path("rest-auth/registration/", include("rest_auth.registration.urls")),
]
admin.site.site_header = "tst-daniel-connectors"
admin.site.site_title = "tst-daniel-connectors Admin Portal"
admin.site.index_title = "tst-daniel-connectors Admin"
# swagger
api_info = openapi.Info(
title="tst-daniel-connectors API",
default_version="v1",
description="API documentation for tst-daniel-connectors App",
)
schema_view = get_schema_view(
api_info,
public=True,
permission_classes=(permissions.IsAuthenticated,),
)
urlpatterns += [
path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs")
]
| [
"[email protected]"
] | |
9e86d85037eff55e36fd681cacb39e4363bb8e6d | 007c1bb62ee70fb387b24bac9387da90745a85db | /development/inelastic/vesuvio_calibration/VesuvioGeometryEnergyResolutionTest.py | a7ab85cc8ecbd72bb9eb655183d1bb744c990097 | [] | no_license | mantidproject/scripts | fc14040f0674fda31b28bbc668a923fecc00fe99 | f5a7b79825c7bdd8977e1409967bce979e4ca690 | refs/heads/master | 2021-01-17T11:36:00.426451 | 2017-08-25T13:01:26 | 2017-08-25T13:01:26 | 3,379,430 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 3,319 | py | #pylint: disable=too-many-public-methods
import unittest
from mantid.api import (ITableWorkspace, WorkspaceGroup)
from mantid.simpleapi import *
class VesuvioGeometryEnergyResolutionTest(unittest.TestCase):
def tearDown(self):
mtd.clear()
def _execute_resolution_algorithm(self, **argv):
default_args = {
'InstrumentParFile': 'IP0005.par',
'MonteCarloEvents': 1000
}
default_args.update(argv)
output, mean = VesuvioGeometryEnergyResolution(**default_args)
return (mean, output)
def _validate_result_shape(self, mean, resolution):
"""
Validates the shape of the result tables.
"""
self.assertTrue(isinstance(mean, ITableWorkspace))
self.assertEqual(mean.columnCount(), 6)
self.assertEqual(mean.rowCount(), 24)
self.assertTrue(isinstance(resolution, ITableWorkspace))
self.assertEqual(resolution.columnCount(), 17)
self.assertEqual(resolution.rowCount(), 196)
def test_resolution(self):
"""
Check values calculated by resolution algorithm match those expected.
"""
mean, resolution = self._execute_resolution_algorithm()
self._validate_result_shape(mean, resolution)
# Validate mean values
mean_values = mean.column('Mean')
TOLERANCE = 7
self.assertAlmostEqual(mean_values[0], 0.5023026, places=TOLERANCE)
self.assertAlmostEqual(mean_values[1], 0.9461753, places=TOLERANCE)
self.assertAlmostEqual(mean_values[2], 0.7906631, places=TOLERANCE)
self.assertAlmostEqual(mean_values[3], 0.0298165, places=TOLERANCE)
self.assertAlmostEqual(mean_values[4], 0.0206698, places=TOLERANCE)
self.assertAlmostEqual(mean_values[5], 0.2581127, places=TOLERANCE)
self.assertAlmostEqual(mean_values[6], 0.2972636, places=TOLERANCE)
self.assertAlmostEqual(mean_values[7], 0.0300434, places=TOLERANCE)
self.assertAlmostEqual(mean_values[8], 0.3971947, places=TOLERANCE)
self.assertAlmostEqual(mean_values[9], 7.1871166, places=TOLERANCE)
self.assertAlmostEqual(mean_values[10], 0.4046330, places=TOLERANCE)
self.assertAlmostEqual(mean_values[11], 7.6269999, places=TOLERANCE)
self.assertAlmostEqual(mean_values[12], 55.4417038, places=TOLERANCE)
self.assertAlmostEqual(mean_values[13], 55.4496880, places=TOLERANCE)
self.assertAlmostEqual(mean_values[14], 140.3843994, places=TOLERANCE)
self.assertAlmostEqual(mean_values[15], 53.2056618, places=TOLERANCE)
self.assertAlmostEqual(mean_values[16], 53.2166023, places=TOLERANCE)
self.assertAlmostEqual(mean_values[17], 31.4454365, places=TOLERANCE)
self.assertAlmostEqual(mean_values[18], 72.5857315, places=TOLERANCE)
self.assertAlmostEqual(mean_values[19], 72.5914993, places=TOLERANCE)
self.assertAlmostEqual(mean_values[20], 45.2145004, places=TOLERANCE)
self.assertAlmostEqual(mean_values[21], 143.4886322, places=TOLERANCE)
self.assertAlmostEqual(mean_values[22], 143.4915924, places=TOLERANCE)
self.assertAlmostEqual(mean_values[23], 97.8484039, places=TOLERANCE)
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
a237c65c46210c1e9d9669557d5d36a9d956ca26 | 9df2fb0bc59ab44f026b0a2f5ef50c72b2fb2ceb | /sdk/dynatrace/azure-mgmt-dynatrace/generated_samples/monitors_get_sso_details_minimum_set_gen.py | 660bfb94f9b61744d91446c0a3f37affbc7c7cf0 | [
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-generic-cla"
] | permissive | openapi-env-test/azure-sdk-for-python | b334a2b65eeabcf9b7673879a621abb9be43b0f6 | f61090e96094cfd4f43650be1a53425736bd8985 | refs/heads/main | 2023-08-30T14:22:14.300080 | 2023-06-08T02:53:04 | 2023-06-08T02:53:04 | 222,384,897 | 1 | 0 | MIT | 2023-09-08T08:38:48 | 2019-11-18T07:09:24 | Python | UTF-8 | Python | false | false | 1,631 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.dynatrace import DynatraceObservabilityMgmtClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-dynatrace
# USAGE
python monitors_get_sso_details_minimum_set_gen.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = DynatraceObservabilityMgmtClient(
credential=DefaultAzureCredential(),
subscription_id="00000000-0000-0000-0000-000000000000",
)
response = client.monitors.get_sso_details(
resource_group_name="myResourceGroup",
monitor_name="myMonitor",
)
print(response)
# x-ms-original-file: specification/dynatrace/resource-manager/Dynatrace.Observability/stable/2021-09-01/examples/Monitors_GetSSODetails_MinimumSet_Gen.json
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
5c51d540225abc65aba220b7b3bf103579c1f61a | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02913/s835324386.py | 047781bcb31ffe52b746c9b0454b01728cb1b3cc | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 655 | py | def main():
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
#from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
import math
#inf = 10**17
#mod = 10**9 + 7
n = int(input())
s = input().rstrip()
l, r = 0, 0
res = 0
while r < n:
r += 1
if not s[l:r] in s[r:]:
l += 1
res = max(res, r-l)
print(res)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
b8bf3ead37ab6905d1d3250e0dcc5ad2e961386e | 48a89c1ceb3a761f796ed054c59a44106adefba5 | /src/moveit_pose.py | baf76cbf90210ec3cb175469d503eb360f02bae6 | [] | no_license | ayushgargdroid/hsr_custom_launch | ec404519cc9e8096c078468f5336fc6852204fda | f84d4e3e6dc3fcbcb00e65b05d69c9a33e43b94f | refs/heads/master | 2020-09-20T14:26:41.354211 | 2019-12-05T21:36:16 | 2019-12-05T21:36:16 | 224,510,478 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,525 | py | #!/usr/bin/env python
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
import tf
import numpy as np
from math import pi
from std_msgs.msg import String
from moveit_commander.conversions import pose_to_list
if __name__ == '__main__':
moveit_commander.roscpp_initialize(sys.argv)
rospy.init_node('move_group_python_interface_tutorial',
anonymous=True)
robot = moveit_commander.RobotCommander()
scene = moveit_commander.PlanningSceneInterface()
group_name = "whole_body"
group = moveit_commander.MoveGroupCommander(group_name)
# display_trajectory_publisher = rospy.Publisher('/move_group/display_planned_path',
# moveit_msgs.msg.DisplayTrajectory,
# queue_size=20)
tf_listen = tf.TransformListener()
tf_broadcast = tf.TransformBroadcaster()
tf_ros = tf.TransformerROS()
trans = rot = None
rate = rospy.Rate(100)
while rospy.is_shutdown() or trans is None:
try:
(trans,rot) = tf_listen.lookupTransform('/odom', '/object', rospy.Time(0))
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
rate.sleep()
continue
rate.sleep()
rospy.loginfo('Position: '+str(trans)+' Orientation: '+str(rot))
change = tf_ros.fromTranslationRotation((-0.4,0,0),(0,0,0,1))
rospy.loginfo('\n'+str(change))
actual = tf_ros.fromTranslationRotation(trans,rot)
rospy.loginfo('\n'+str(actual))
pre = np.dot(actual,change)
rospy.loginfo('\n'+str(pre))
pre_rot = tf.transformations.quaternion_from_matrix(pre)
pre_trans = tf.transformations.translation_from_matrix(pre)
rospy.loginfo('Position: '+str(pre_trans)+' Orientation: '+str(pre_rot))
pose_goal = geometry_msgs.msg.Pose()
pose_goal.orientation.w = pre_rot[3]
pose_goal.orientation.x = pre_rot[0]
pose_goal.orientation.y = pre_rot[1]
pose_goal.orientation.z = pre_rot[2]
pose_goal.position.x = pre_trans[0]
pose_goal.position.y = pre_trans[1]
pose_goal.position.z = pre_trans[2]
group.set_pose_target(pose_goal)
plan = group.go(wait=True)
group.stop()
group.clear_pose_targets()
while not rospy.is_shutdown():
tf_broadcast.sendTransform(pre_trans,
pre_rot,
rospy.Time.now(),
"pre",
"odom")
rate.sleep()
| [
"[email protected]"
] | |
b8bcb78bbf8726eb8cc4098a99018c8f38990b6c | 3c000380cbb7e8deb6abf9c6f3e29e8e89784830 | /venv/Lib/site-packages/cobra/modelimpl/fv/apndg.py | 9bbc9206e5d94cae540d5d9b7a425e781af43b51 | [] | no_license | bkhoward/aciDOM | 91b0406f00da7aac413a81c8db2129b4bfc5497b | f2674456ecb19cf7299ef0c5a0887560b8b315d0 | refs/heads/master | 2023-03-27T23:37:02.836904 | 2021-03-26T22:07:54 | 2021-03-26T22:07:54 | 351,855,399 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,205 | py | # coding=UTF-8
# **********************************************************************
# Copyright (c) 2013-2020 Cisco Systems, Inc. All rights reserved
# written by zen warriors, do not modify!
# **********************************************************************
from cobra.mit.meta import ClassMeta
from cobra.mit.meta import StatsClassMeta
from cobra.mit.meta import CounterMeta
from cobra.mit.meta import PropMeta
from cobra.mit.meta import Category
from cobra.mit.meta import SourceRelationMeta
from cobra.mit.meta import NamedSourceRelationMeta
from cobra.mit.meta import TargetRelationMeta
from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory
from cobra.model.category import MoCategory, PropCategory, CounterCategory
from cobra.mit.mo import Mo
# ##################################################
class APndg(Mo):
meta = ClassMeta("cobra.model.fv.APndg")
meta.isAbstract = True
meta.moClassName = "fvAPndg"
meta.moClassName = "fvAPndg"
meta.rnFormat = ""
meta.category = MoCategory.REGULAR
meta.label = "Represent a Target Request whose Resolution has been Postponed"
meta.writeAccessMask = 0x1
meta.readAccessMask = 0x1
meta.isDomainable = False
meta.isReadOnly = True
meta.isConfigurable = False
meta.isDeletable = False
meta.isContextRoot = False
meta.superClasses.add("cobra.model.naming.NamedObject")
meta.concreteSubClasses.add("cobra.model.fv.PndgCtrct")
meta.concreteSubClasses.add("cobra.model.fv.PndgCtrctEpgCont")
meta.concreteSubClasses.add("cobra.model.fv.PndgAnyDef")
meta.concreteSubClasses.add("cobra.model.fv.PndgEpCP")
meta.concreteSubClasses.add("cobra.model.fv.PndgEpPCtrctInfo")
meta.concreteSubClasses.add("cobra.model.fv.PndgRtdOutDef")
meta.concreteSubClasses.add("cobra.model.fv.PndgRFltP")
meta.rnPrefixes = [
]
prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("deleteAll", "deleteall", 16384)
prop._addConstant("deleteNonPresent", "deletenonpresent", 8192)
prop._addConstant("ignore", "ignore", 4096)
meta.props.add("childAction", prop)
prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN)
prop.label = "None"
prop.isDn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("dn", prop)
prop = PropMeta("str", "name", "name", 5577, PropCategory.REGULAR)
prop.label = "Name"
prop.isConfig = True
prop.isAdmin = True
prop.range = [(0, 16)]
prop.regex = ['[a-zA-Z0-9_.:-]+']
meta.props.add("name", prop)
prop = PropMeta("str", "nameAlias", "nameAlias", 28417, PropCategory.REGULAR)
prop.label = "Name alias"
prop.isConfig = True
prop.isAdmin = True
prop.range = [(0, 63)]
prop.regex = ['[a-zA-Z0-9_.-]+']
meta.props.add("nameAlias", prop)
prop = PropMeta("str", "requestorDn", "requestorDn", 16605, PropCategory.REGULAR)
prop.label = "DN of the Policy Requestor"
prop.isImplicit = True
prop.isAdmin = True
meta.props.add("requestorDn", prop)
prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN)
prop.label = "None"
prop.isRn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("rn", prop)
prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("created", "created", 2)
prop._addConstant("deleted", "deleted", 8)
prop._addConstant("modified", "modified", 4)
meta.props.add("status", prop)
prop = PropMeta("str", "targetDn", "targetDn", 16604, PropCategory.REGULAR)
prop.label = "DN of the Policy to Resolve"
prop.isImplicit = True
prop.isAdmin = True
meta.props.add("targetDn", prop)
def __init__(self, parentMoOrDn, markDirty=True, **creationProps):
namingVals = []
Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps)
# End of package file
# ##################################################
| [
"[email protected]"
] | |
602852152151ceb503e5cf7d75816f4089723ef5 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /ZaEFRDBZ7ZMTiSEce_17.py | b22158d637597759d56d9b831520a39cf3c26141 | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 908 | py | """
You're given a string of words. You need to find the word "Nemo", and return a
string like this: `"I found Nemo at [the order of the word you find nemo]!"`.
If you can't find Nemo, return `"I can't find Nemo :("`.
### Examples
find_nemo("I am finding Nemo !") ➞ "I found Nemo at 4!"
find_nemo("Nemo is me") ➞ "I found Nemo at 1!"
find_nemo("I Nemo am") ➞ "I found Nemo at 2!"
### Notes
* `! , ? .` are always separated from the last word.
* Nemo will always look like _Nemo_ , and not _NeMo_ or other capital variations.
* _Nemo's_ , or anything that says _Nemo_ with something behind it, doesn't count as _Finding Nemo_.
* If there are multiple _Nemo's_ in the sentence, only return for the first one.
"""
def find_nemo(sentence):
try:
return "I found Nemo at %d!" %(sentence.split(' ').index("Nemo")+1)
except:
return "I can't find Nemo :("
| [
"[email protected]"
] | |
e72472b43e78f165604f008d221b85de375c397d | 78d3d78ebded691dd6a92f357c7cc75004ff2184 | /majorana/3/conductance_disorder.py | c73171b6058a0426c432f6e44c4eb66eb398e8bd | [] | no_license | rafaelha/paper_zbcp | 0b5bb9500d997ab99cea9959998e3651be75483b | db2096eb0cb2d7bb801b4e513320adc9cef7a0d9 | refs/heads/master | 2023-02-25T01:41:24.728767 | 2019-09-06T17:24:16 | 2019-09-06T17:24:16 | 199,933,622 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,911 | py | import matplotlib as mpl
#mpl.use('Agg')
import matplotlib.pyplot as plt
import kwant as kw
import numpy as np
import tinyarray
from numpy import kron, cos, sin, sqrt
import time
import scipy.sparse as sp
from scipy.sparse.linalg import eigsh
from numpy.random import rand
import pickle
import datetime as dt
import sys
import os
s0 = tinyarray.array([[1, 0], [0, 1]]); t0 = s0; sig0 = s0;
sx = tinyarray.array([[0, 1], [1, 0]]); tx = sx; sigx = sx;
sy = tinyarray.array([[0, -1j], [1j, 0]]); ty = sy; sigy = sy;
sz = tinyarray.array([[1, 0], [0, -1]]); tz = sz; sigz = sz;
def kr(a, b, c): # Kronecker product of three matrices
return kron(a, kron(b, c))
ax = 20 #lattice constant Angstrom
ax2 = ax**2 # material params Cano et al. (Bernevig) PRB 95 161306 (2017)
ay = 20; az = 20; ay2 = ay**2; az2 = az**2;
C0 = -0.0145
C1 = 10.59
C2 = 11.5
A = 0.889
M0 = 0.0205
M1 = -18.77
M2 = -13.5
Q = sqrt(-M0/M1)
# Magnetic field
Bx = 0.035 *0
ggap = 0.035
g = 1
mu_local =-28e-3 # local chemical potential to push magnetic ggap to fermi level
jx = np.zeros((4,4))
B1=0
#jx[0,0] = Bx**2 / ggap
jx[0,3] = - Bx**3 / ggap**2
jx[1,2] = -0.5 * g * Bx
jx[2,1] = -0.5 * g * Bx
jx[3,0] = -Bx**3 / ggap**2
#jx[3,3] = Bx **2 / ggap
#######################################
############### parameters ############
#######################################
kz=Q*0.0
delta = 100e-6#150*90e-6 # SC order parameter (real)
phi = np.pi
mu = (C0 - C1 * M0 / M1) #- 7e-3# tune chem pot to Dirac nodes
W = 0.050 # disorder strength
m=0#0.006
Lx =15
Ly = 300
xdir = 0 #set direction of transport to one
ydir = 1
def onsite(): # onsite energy without gap
return kr(sigz, t0, s0) * (C0 + 2*C1/az2*(1-cos(kz*az)) + 2*C2/ax2 + 2*C2/ay2 - mu)\
+ kr(sigz, tz, sz) * (M0 + 2*M1/az2*(1-cos(kz*az)) + 2*M2/ax2 + 2*M2/ay2)
def gap(): # onsite energy with gap
return kr(sigx, t0, s0) * delta
def gap_t(x, y): # onsite energy with gap
d = 0
if x == 0:
d = 1
return kr(sigx, t0, s0) * delta * d
def gap_b(x, y): # onsite energy with gap
d = 0
if x == Lx-1:
d = 1
return kr(sigx, t0, s0) * delta * d
def disorder(): # onsite energy with disorder in uniform interval [-W/2, W/2]
return (rand() - 1/2) * W * kr(sigz, t0, s0)
def disorder_t(x, y): # onsite energy with disorder in uniform interval [-W/2, W/2]
d = 0
if x == 0:
d = W
return (rand() - 1/2) * d * kr(sigz, t0, s0)
def disorder_b(x, y): # onsite energy with disorder in uniform interval [-W/2, W/2]
d = 0
if x == Lx-1:
d = W
return (rand() - 1/2) * d * kr(sigz, t0, s0)
def mag(): # Zeeman field
return kron(sig0, jx) + kr(sigz, t0, s0) * mu_local
def mag_t(x, y): # Zeeman field
d = 0
if x == 0:
d = 1
return ( kron(sig0, jx) + kr(sigz, t0, s0) * mu_local ) * d
def mag_b(x, y): # Zeeman field
d = 0
if x == Lx-1:
d = 1
return ( kron(sig0, jx) + kr(sigz, t0, s0) * mu_local ) * d
def DOS(sys, k=100, range=(-1.5*50e-6,1.5*50e-6), bins=1000, fignum=2): # plot the lowest eigenvalues in a hist-plot
H = sp.csc_matrix(sys.hamiltonian_submatrix(sparse=True))
ev, _ = eigsh(H, k=k, sigma=0)
plt.ion()
#plt.figure()
#plt.plot(ev,'.')
plt.figure()
plt.clf()
plt.hist(ev, range=range, bins=bins)
plt.xlim(range)
plt.xlabel('Energy')
plt.ylabel('Number of states')
return ev
def build_sys():
lat = kw.lattice.general([(ax,0), (0,ay)], norbs=8)
sys = kw.Builder()
# hopping
hx = kr(sigz, t0, s0) * (-C2)/ax2\
+ kr(sigz, tz, sz) * (-M2)/ax2\
+ kr(sigz, tz, sx) * A * (-1j)/(2 * ax)
hy = kr(sigz, t0, s0) * (-C2)/ay2\
+ kr(sigz, tz, sz) * (-M2)/ay2\
+ kr(sigz, tz, sy) * A * (-1j)/(2 * ay)
# on site potential
for i in np.arange(Lx):
for j in np.arange(Ly):
sys[lat(i, j)] = onsite() + disorder() #+ mag_b(i, j)
##############^^^^^^^^^^^^## middle ############################################
# Hoppings
sys[kw.builder.HoppingKind((1, 0), lat, lat)] = hx
sys[kw.builder.HoppingKind((0, 1), lat, lat)] = hy
# xdir, ydir, zdir = 0,1
sym_left = kw.TranslationalSymmetry((-1*ax*xdir, -1*ay*ydir))
sym_right = kw.TranslationalSymmetry((1*ax*xdir, 1*ay*ydir))
lead0 = kw.Builder(sym_left, conservation_law=-kr(sigz,t0,s0))
# set onsite energy along plane perpendicular to axis of transport (dir=1)
for i in np.arange(Lx * (1-xdir) + xdir):
for j in np.arange(Ly * (1-ydir) + ydir):
lead0[lat(i, j)] = onsite() #+ mag_b(i, j)
###############################^^^^^^^^^^^^^#### left #############
lead0[kw.builder.HoppingKind((1, 0), lat, lat)] = hx
lead0[kw.builder.HoppingKind((0, 1), lat, lat)] = hy
lead1 = kw.Builder(sym_right)
for i in np.arange(Lx * (1-xdir) + xdir):
for j in np.arange(Ly * (1-ydir) + ydir):
lead1[lat(i, j)] = onsite() +gap()#+ gap_t(i, j) #+ mag_b(i, j)
###############################^^^^^^^^^^^^^#### right ############
lead1[kw.builder.HoppingKind((1, 0), lat, lat)] = hx
lead1[kw.builder.HoppingKind((0, 1), lat, lat)] = hy
sys.attach_lead(lead0)
sys.attach_lead(lead1)
#kw.plot(sys)
sys = sys.finalized()
return sys, lead0, lead1
def sim(sys, range, plot=False):
n = len(range)
energies = range#np.linspace(range[0], range[1], n)
N = np.zeros(n)
Ree = np.zeros(n)
Reh = np.zeros(n)
#G2 = np.zeros(n)
for i in np.arange(n):
smatrix = kw.smatrix(sys, energies[i])
N[i] = smatrix.submatrix((0,0), (0,0)).shape[0]
Ree[i] = smatrix.transmission((0,0), (0,0))
Reh[i] = smatrix.transmission((0,1), (0,0))
#G2[i] = smatrix.transmission((1,0), (0,0))
print(str(i) + '/' + str(n-1))
if plot:
plotG(energies, N, Ree, Reh)
return energies, N, Ree, Reh, N-Ree+Reh
def plotG(en, N, Ree, Reh):
plt.ion()
plt.figure(figsize=(9,5))
plt.plot(np.block([-np.flip(en,0), en]), np.block([np.flip(G,0), G]), label='G')
plt.plot(np.block([-np.flip(en,0), en]), np.block([np.flip(N,0), N]), '-.', label='N')
plt.plot(np.block([-np.flip(en,0), en]), np.block([np.flip(Reh,0), Reh]), '-.', label='Reh')
plt.plot(np.block([-np.flip(en,0), en]), np.block([np.flip(Ree,0), Ree]), '-.', label='Ree')
"""
plt.plot(en, G, label='G')
plt.plot(en, N, '-.', label='N')
plt.plot(en, Reh, '-.', label='Reh')
plt.plot(en, Ree, '-.', label='Ree')
"""
plt.legend()
plt.xlabel('Bias in $\mu$eV')
plt.ylabel('Conductance G')
plt.title('$L_x=$'+str(Lx)+', $L_y=$'+str(Ly)+', $L_z=\infty, k_z/Q=$'+str(round(kz/Q,2))+', W='+str(round(W*1e3))+'meV, $\Delta=$'+str(np.round(delta*1e3,1))+'meV, B='+str(Bx*1e3)+', t='+str(np.round(duration))+'s' )
plt.tight_layout()
def plotLead(lead0, xlim=(0,np.pi/2), ylim=(-20,20), res=100):
plt.ion()
plt.figure(figsize=(4,4))
lead0 = lead0.finalized()
bands = kw.physics.Bands(lead0)
kz = np.linspace(xlim[0], xlim[1], res)
energies = [bands(k)*1000 for k in kz]
plt.plot(kz, energies, linewidth=0.5)
plt.ylim(ylim)
plt.xlim((np.min(kz), np.max(kz)))
if xdir != 0:
plt.xlabel("$k_x a$")
elif ydir != 0:
plt.xlabel("$k_y a$")
elif zdir != 0:
plt.xlabel("$k_z a$")
plt.ylabel("Energy in meV")
plt.title('$L_x=$'+str(Lx)+', $L_z=\infty$, B='+str(Bx*1e3))
plt.tight_layout()
#plt.savefig(next("C:/Users/Rafael/Desktop/MJ/transport/FT/figs/lead%s.pdf"))
return energies
def save(filename, duration, en, N, Ree, Reh, G):
f1 = open(filename, 'ab')
pickle.dump(Lx, f1)
pickle.dump(Ly, f1)
pickle.dump(0, f1)
pickle.dump(delta, f1)
pickle.dump(W, f1)
pickle.dump(duration, f1)
pickle.dump(mu - (C0 - C1 * M0 / M1), f1) # mu relative to cone crossing
pickle.dump(en, f1)
pickle.dump(N, f1)
pickle.dump(Ree, f1)
pickle.dump(Reh, f1)
pickle.dump(G, f1)
pickle.dump(Bx, f1)
pickle.dump(ggap, f1)
pickle.dump(g, f1)
pickle.dump(mu_local, f1)
pickle.dump(B1, f1)
pickle.dump(seed, f1)
f1.close()
def sweep_disorder(max=50e-3, steps=10, energy=0.03e-3):
ww = np.linspace(0e-3,max,steps)
G = np.zeros(steps)
N = np.zeros(steps)
Reh = np.zeros(steps)
Ree = np.zeros(steps)
G = np.zeros(steps)
global W #write changes of W to global variable
for i in np.arange(len(ww)):
W = ww[i]
sys, lead0, lead1 = build_sys()
en, N[i], Ree[i], Reh[i], G[i] = sim(sys, range=(energy,))
print(i)
filename = 'disorder/' + str(dt.datetime.now()).replace(':','_').replace('.','_').replace(' ','_')
save(filename, en[0], ww, N, Ree, Reh, G)
def loop(rg):
filename = str(dt.datetime.now()).replace(':','_').replace('.','_').replace(' ','_')+'.pickle'
for i in np.arange(10):
start(filename, rg)
def start(filename, rg):
start_time = time.time()
sys, lead0, lead1 = build_sys()
en, N, Ree, Reh, G = sim(sys, range=rg, plot=False)
duration = time.time()-start_time
save(filename, duration, en, N, Ree, Reh, G)
return lead0
def nextrun(name):
i = 10
while os.path.exists(name % i):
i += 5
return i, name % i
def next(name):
i = 0
while os.path.exists(name % i):
i += 1
return name % i
if __name__ == '__main__':
seed = int(sys.argv[1])
rg = np.linspace(-130e-6,130e-6,51)
#rg = np.sort(np.block([rg, -rg]))
loop(rg)
"""
plt.close('all')
start_time = time.time()
sys, lead0, lead1 = build_sys()
en, N, Ree, Reh, G = sim(sys, range=rg, plot=False)
duration = time.time()-start_time
plotG(en*1e6, N, Ree, Reh)
plt.savefig(next("cond%s.pdf"))
#plt.savefig('Lz_%s.pdf' % Lz)
#plt.close()
#save(filename, duration, en, N, Ree, Reh, G)
"""
| [
"[email protected]"
] | |
7a4c1f18a33fabea011455db37153243c394e77c | 5c5b75f09be052e3b2e8f40802100bb381cc041b | /src/kbqa/scripts/simpq_candgen.py | 60c870c2e9df647020ce6db7ef6649f47d219903 | [
"MIT"
] | permissive | xuehuiping/TransDG | a6f408a03adadf7cedb40039094628213c63b4a1 | ca55744594c5c8d6fe045bed499df72110880366 | refs/heads/master | 2022-04-22T10:49:53.245542 | 2020-04-24T02:05:38 | 2020-04-24T02:05:38 | 258,379,892 | 0 | 0 | MIT | 2020-04-24T02:04:40 | 2020-04-24T02:04:39 | null | UTF-8 | Python | false | false | 7,755 | py | """
Generate candidate query graph for SimpQ
"""
import os
import json
import codecs
import shutil
import pickle
import argparse
from src.kbqa.utils.link_data import LinkData
from src.kbqa.utils.log_util import LogInfo
from src.kbqa.dataset.schema import Schema
class SimpleQCandidateGenerator:
def __init__(self, freebase_fp, links_fp, verbose=0):
self.subj_pred_dict = {}
self.q_links_dict = {} # <q_idx, [LinkData]>
# verbose = 0: show basic flow of the process
# verbose = 1: show detail linking information
self.verbose = verbose
self._load_fb_subset(freebase_fp)
self._load_linkings(links_fp)
def _load_fb_subset(self, fb_fp):
LogInfo.begin_track('Loading freebase subset from [%s] ...', fb_fp)
prefix = 'www.freebase.com/'
pref_len = len(prefix)
with codecs.open(fb_fp, 'r', 'utf-8') as br:
lines = br.readlines()
LogInfo.logs('%d lines loaded.', len(lines))
for line_idx, line in enumerate(lines):
if line_idx % 500000 == 0:
LogInfo.logs('Current: %d / %d', line_idx, len(lines))
s, p, _ = line.strip().split('\t')
s = s[pref_len:].replace('/', '.')
p = p[pref_len:].replace('/', '.')
self.subj_pred_dict.setdefault(s, set([])).add(p)
LogInfo.logs('%d related entities and %d <S, P> pairs saved.',
len(self.subj_pred_dict), sum([len(v) for v in self.subj_pred_dict.values()]))
LogInfo.end_track()
def _load_linkings(self, links_fp):
with codecs.open(links_fp, 'r', 'utf-8') as br:
for line in br.readlines():
if line.startswith('#'):
continue
spt = line.strip().split('\t')
q_idx, st, ed, mention, mid, wiki_name, feats = spt
q_idx = int(q_idx)
st = int(st)
ed = int(ed)
feat_dict = json.loads(feats)
for k in feat_dict:
v = float('%.6f' % feat_dict[k])
feat_dict[k] = v
link_data = LinkData(category='Entity',
start=st, end=ed,
mention=mention, comp='==',
value=mid, name=wiki_name,
link_feat=feat_dict)
self.q_links_dict.setdefault(q_idx, []).append(link_data)
LogInfo.logs('%d questions of link data loaded.', len(self.q_links_dict))
def single_question_candgen(self, q_idx, qa, link_fp, schema_fp):
# =================== Linking first ==================== #
if os.path.isfile(link_fp):
gather_linkings = []
with codecs.open(link_fp, 'r', 'utf-8') as br:
for line in br.readlines():
tup_list = json.loads(line.strip())
ld_dict = {k: v for k, v in tup_list}
gather_linkings.append(LinkData(**ld_dict))
LogInfo.logs('Read %d links from file.', len(gather_linkings))
else:
gather_linkings = self.q_links_dict.get(q_idx, [])
for idx in range(len(gather_linkings)):
gather_linkings[idx].gl_pos = idx
LogInfo.begin_track('Show %d E links :', len(gather_linkings))
if self.verbose >= 1:
for gl in gather_linkings:
LogInfo.logs(gl.display())
LogInfo.end_track()
# ==================== Save linking results ================ #
if not os.path.isfile(link_fp):
with codecs.open(link_fp + '.tmp', 'w', 'utf-8') as bw:
for gl in gather_linkings:
bw.write(json.dumps(gl.serialize()) + '\n')
shutil.move(link_fp + '.tmp', link_fp)
LogInfo.logs('%d link data save to file.', len(gather_linkings))
# ===================== simple predicate finding ===================== #
gold_entity, gold_pred, _ = qa['targetValue']
sc_list = []
for gl_data in gather_linkings:
entity = gl_data.value
pred_set = self.subj_pred_dict.get(entity, set([]))
for pred in pred_set:
sc = Schema()
sc.hops = 1
sc.aggregate = False
sc.main_pred_seq = [pred]
sc.raw_paths = [('Main', gl_data, [pred])]
sc.ans_size = 1
if entity == gold_entity and pred == gold_pred:
sc.f1 = sc.p = sc.r = 1.
else:
sc.f1 = sc.p = sc.r = 0.
sc_list.append(sc)
# ==================== Save schema results ================ #
# p, r, f1, ans_size, hops, raw_paths, (agg)
# raw_paths: (category, gl_pos, gl_mid, pred_seq)
with codecs.open(schema_fp + '.tmp', 'w', 'utf-8') as bw:
for sc in sc_list:
sc_info_dict = {k: getattr(sc, k) for k in ('p', 'r', 'f1', 'ans_size', 'hops')}
if sc.aggregate is not None:
sc_info_dict['agg'] = sc.aggregate
opt_raw_paths = []
for cate, gl, pred_seq in sc.raw_paths:
opt_raw_paths.append((cate, gl.gl_pos, gl.value, pred_seq))
sc_info_dict['raw_paths'] = opt_raw_paths
bw.write(json.dumps(sc_info_dict) + '\n')
shutil.move(schema_fp + '.tmp', schema_fp)
LogInfo.logs('%d schemas successfully saved into [%s].', len(sc_list), schema_fp)
def main(args):
data_path = "%s/simpQ.data.pkl" % args.data_dir
freebase_path = "%s/freebase-FB2M.txt" % args.freebase_dir
links_path = "%s/SimpQ.all.links" % args.data_dir
with open(data_path, 'rb') as br:
qa_list = pickle.load(br)
LogInfo.logs('%d SimpleQuestions loaded.' % len(qa_list))
cand_gen = SimpleQCandidateGenerator(freebase_fp=freebase_path, links_fp=links_path,
verbose=args.verbose)
all_list_fp = args.output_dir + '/all_list'
all_lists = []
for q_idx, qa in enumerate(qa_list):
LogInfo.begin_track('Entering Q %d / %d [%s]:',
q_idx, len(qa_list), qa['utterance'])
sub_idx = int(q_idx / 1000) * 1000
index = 'data/%d-%d/%d_schema' % (sub_idx, sub_idx + 999, q_idx)
all_lists.append(index)
sub_dir = '%s/data/%d-%d' % (args.output_dir, sub_idx, sub_idx + 999)
if not os.path.exists(sub_dir):
os.makedirs(sub_dir)
schema_fp = '%s/%d_schema' % (sub_dir, q_idx)
link_fp = '%s/%d_links' % (sub_dir, q_idx)
if os.path.isfile(schema_fp):
LogInfo.end_track('Skip this question, already saved.')
continue
cand_gen.single_question_candgen(q_idx=q_idx, qa=qa,
link_fp=link_fp, schema_fp=schema_fp)
LogInfo.end_track()
with open(all_list_fp, 'w') as fw:
for i, idx_str in enumerate(all_lists):
if i == len(all_lists)-1:
fw.write(idx_str)
else:
fw.write(idx_str + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="SimpQ candidates generation")
parser.add_argument('--data_dir', type=str, help="SimpQ data directory")
parser.add_argument('--freebase_dir', type=str, help="Freebase subset directory")
parser.add_argument('--output_dir', type=str, help="Output candidates directory")
parser.add_argument('--verbose', type=int, default=0)
parsed_args = parser.parse_args()
main(parsed_args)
| [
"[email protected]"
] | |
e84fa4cea01f255f22566d3aa239eceff4c8ea21 | afc677459e46635ceffccf60d1daf50e62694557 | /ACME/math/perturb.py | 9dc7c4abb0a9e47c4955e89d1793b41b1c231f16 | [
"MIT"
] | permissive | mauriziokovacic/ACME | 056b06da4bf66d89087fcfcbe0fd0a2e255d09f3 | 2615b66dd4addfd5c03d9d91a24c7da414294308 | refs/heads/master | 2020-05-23T23:40:06.667416 | 2020-01-10T14:42:01 | 2020-01-10T14:42:01 | 186,997,977 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 314 | py | import torch
def perturb(tensor):
"""
Perturbs the input tensor with random noise
Parameters
----------
tensor : Tensor
the input tensor
Returns
-------
Tensor
the perturbed tensor
"""
return torch.randn_like(tensor) * tensor + torch.randn_like(tensor)
| [
"[email protected]"
] | |
9d897506defc849e1be82128a929f2bf07239fc0 | a1615563bb9b124e16f4163f660d677f3224553c | /LI/lib/python3.8/site-packages/astropy/table/tests/test_mixin.py | 1e694c2e508b7da524cd1c52fd7f4ee06682af60 | [
"MIT"
] | permissive | honeybhardwaj/Language_Identification | 2a247d98095bd56c1194a34a556ddfadf6f001e5 | 1b74f898be5402b0c1a13debf595736a3f57d7e7 | refs/heads/main | 2023-04-19T16:22:05.231818 | 2021-05-15T18:59:45 | 2021-05-15T18:59:45 | 351,470,447 | 5 | 4 | MIT | 2021-05-15T18:59:46 | 2021-03-25T14:42:26 | Python | UTF-8 | Python | false | false | 28,594 | py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
try:
import h5py # pylint: disable=W0611 # noqa
except ImportError:
HAS_H5PY = False
else:
HAS_H5PY = True
try:
import yaml # pylint: disable=W0611 # noqa
HAS_YAML = True
except ImportError:
HAS_YAML = False
import copy
import pickle
from io import StringIO
import pytest
import numpy as np
from astropy.coordinates import EarthLocation, SkyCoord
from astropy.table import Table, QTable, join, hstack, vstack, Column, NdarrayMixin
from astropy.table import serialize
from astropy import time
from astropy import coordinates
from astropy import units as u
from astropy.table.column import BaseColumn
from astropy.table import table_helpers
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.metadata import MergeConflictWarning
from astropy.coordinates.tests.test_representation import representation_equal
from astropy.io.misc.asdf.tags.helpers import skycoord_equal
from .conftest import MIXIN_COLS
def test_attributes(mixin_cols):
"""
Required attributes for a column can be set.
"""
m = mixin_cols['m']
m.info.name = 'a'
assert m.info.name == 'a'
m.info.description = 'a'
assert m.info.description == 'a'
# Cannot set unit for these classes
if isinstance(m, (u.Quantity, coordinates.SkyCoord, time.Time,
coordinates.BaseRepresentationOrDifferential)):
with pytest.raises(AttributeError):
m.info.unit = u.m
else:
m.info.unit = u.m
assert m.info.unit is u.m
m.info.format = 'a'
assert m.info.format == 'a'
m.info.meta = {'a': 1}
assert m.info.meta == {'a': 1}
with pytest.raises(AttributeError):
m.info.bad_attr = 1
with pytest.raises(AttributeError):
m.info.bad_attr
def check_mixin_type(table, table_col, in_col):
# We check for QuantityInfo rather than just isinstance(col, u.Quantity)
# since we want to treat EarthLocation as a mixin, even though it is
# a Quantity subclass.
if ((isinstance(in_col.info, u.QuantityInfo) and type(table) is not QTable)
or isinstance(in_col, Column)):
assert type(table_col) is table.ColumnClass
else:
assert type(table_col) is type(in_col)
# Make sure in_col got copied and creating table did not touch it
assert in_col.info.name is None
def test_make_table(table_types, mixin_cols):
"""
Make a table with the columns in mixin_cols, which is an ordered dict of
three cols: 'a' and 'b' are table_types.Column type, and 'm' is a mixin.
"""
t = table_types.Table(mixin_cols)
check_mixin_type(t, t['m'], mixin_cols['m'])
cols = list(mixin_cols.values())
t = table_types.Table(cols, names=('i', 'a', 'b', 'm'))
check_mixin_type(t, t['m'], mixin_cols['m'])
t = table_types.Table(cols)
check_mixin_type(t, t['col3'], mixin_cols['m'])
def test_io_ascii_write():
"""
Test that table with mixin column can be written by io.ascii for
every pure Python writer. No validation of the output is done,
this just confirms no exceptions.
"""
from astropy.io.ascii.connect import _get_connectors_table
t = QTable(MIXIN_COLS)
for fmt in _get_connectors_table():
if fmt['Format'] == 'ascii.ecsv' and not HAS_YAML:
continue
if fmt['Write'] and '.fast_' not in fmt['Format']:
out = StringIO()
t.write(out, format=fmt['Format'])
def test_votable_quantity_write(tmpdir):
"""
Test that table with Quantity mixin column can be round-tripped by
io.votable. Note that FITS and HDF5 mixin support are tested (much more
thoroughly) in their respective subpackage tests
(io/fits/tests/test_connect.py and io/misc/tests/test_hdf5.py).
"""
t = QTable()
t['a'] = u.Quantity([1, 2, 4], unit='Angstrom')
filename = str(tmpdir.join('table-tmp'))
t.write(filename, format='votable', overwrite=True)
qt = QTable.read(filename, format='votable')
assert isinstance(qt['a'], u.Quantity)
assert qt['a'].unit == 'Angstrom'
@pytest.mark.remote_data
@pytest.mark.parametrize('table_types', (Table, QTable))
def test_io_time_write_fits_standard(tmpdir, table_types):
"""
Test that table with Time mixin columns can be written by io.fits.
Validation of the output is done. Test that io.fits writes a table
containing Time mixin columns that can be partially round-tripped
(metadata scale, location).
Note that we postpone checking the "local" scale, since that cannot
be done with format 'cxcsec', as it requires an epoch.
"""
t = table_types([[1, 2], ['string', 'column']])
for scale in time.STANDARD_TIME_SCALES:
t['a' + scale] = time.Time([[1, 2], [3, 4]], format='cxcsec',
scale=scale, location=EarthLocation(
-2446354, 4237210, 4077985, unit='m'))
t['b' + scale] = time.Time(['1999-01-01T00:00:00.123456789',
'2010-01-01T00:00:00'], scale=scale)
t['c'] = [3., 4.]
filename = str(tmpdir.join('table-tmp'))
# Show that FITS format succeeds
with pytest.warns(
AstropyUserWarning,
match='Time Column "btai" has no specified location, '
'but global Time Position is present'):
t.write(filename, format='fits', overwrite=True)
with pytest.warns(
AstropyUserWarning,
match='Time column reference position "TRPOSn" is not specified'):
tm = table_types.read(filename, format='fits', astropy_native=True)
for scale in time.STANDARD_TIME_SCALES:
for ab in ('a', 'b'):
name = ab + scale
# Assert that the time columns are read as Time
assert isinstance(tm[name], time.Time)
# Assert that the scales round-trip
assert tm[name].scale == t[name].scale
# Assert that the format is jd
assert tm[name].format == 'jd'
# Assert that the location round-trips
assert tm[name].location == t[name].location
# Finally assert that the column data round-trips
assert (tm[name] == t[name]).all()
for name in ('col0', 'col1', 'c'):
# Assert that the non-time columns are read as Column
assert isinstance(tm[name], Column)
# Assert that the non-time columns' data round-trips
assert (tm[name] == t[name]).all()
# Test for conversion of time data to its value, as defined by its format
for scale in time.STANDARD_TIME_SCALES:
for ab in ('a', 'b'):
name = ab + scale
t[name].info.serialize_method['fits'] = 'formatted_value'
t.write(filename, format='fits', overwrite=True)
tm = table_types.read(filename, format='fits')
for scale in time.STANDARD_TIME_SCALES:
for ab in ('a', 'b'):
name = ab + scale
assert not isinstance(tm[name], time.Time)
assert (tm[name] == t[name].value).all()
@pytest.mark.parametrize('table_types', (Table, QTable))
def test_io_time_write_fits_local(tmpdir, table_types):
"""
Test that table with a Time mixin with scale local can also be written
by io.fits. Like ``test_io_time_write_fits_standard`` above, but avoiding
``cxcsec`` format, which requires an epoch and thus cannot be used for a
local time scale.
"""
t = table_types([[1, 2], ['string', 'column']])
t['a_local'] = time.Time([[50001, 50002], [50003, 50004]],
format='mjd', scale='local',
location=EarthLocation(-2446354, 4237210, 4077985,
unit='m'))
t['b_local'] = time.Time(['1999-01-01T00:00:00.123456789',
'2010-01-01T00:00:00'], scale='local')
t['c'] = [3., 4.]
filename = str(tmpdir.join('table-tmp'))
# Show that FITS format succeeds
with pytest.warns(AstropyUserWarning,
match='Time Column "b_local" has no specified location'):
t.write(filename, format='fits', overwrite=True)
with pytest.warns(AstropyUserWarning,
match='Time column reference position "TRPOSn" is not specified.'):
tm = table_types.read(filename, format='fits', astropy_native=True)
for ab in ('a', 'b'):
name = ab + '_local'
# Assert that the time columns are read as Time
assert isinstance(tm[name], time.Time)
# Assert that the scales round-trip
assert tm[name].scale == t[name].scale
# Assert that the format is jd
assert tm[name].format == 'jd'
# Assert that the location round-trips
assert tm[name].location == t[name].location
# Finally assert that the column data round-trips
assert (tm[name] == t[name]).all()
for name in ('col0', 'col1', 'c'):
# Assert that the non-time columns are read as Column
assert isinstance(tm[name], Column)
# Assert that the non-time columns' data round-trips
assert (tm[name] == t[name]).all()
# Test for conversion of time data to its value, as defined by its format.
for ab in ('a', 'b'):
name = ab + '_local'
t[name].info.serialize_method['fits'] = 'formatted_value'
t.write(filename, format='fits', overwrite=True)
tm = table_types.read(filename, format='fits')
for ab in ('a', 'b'):
name = ab + '_local'
assert not isinstance(tm[name], time.Time)
assert (tm[name] == t[name].value).all()
def test_votable_mixin_write_fail(mixin_cols):
"""
Test that table with mixin columns (excluding Quantity) cannot be written by
io.votable.
"""
t = QTable(mixin_cols)
# Only do this test if there are unsupported column types (i.e. anything besides
# BaseColumn and Quantity class instances).
unsupported_cols = t.columns.not_isinstance((BaseColumn, u.Quantity))
if not unsupported_cols:
pytest.skip("no unsupported column types")
out = StringIO()
with pytest.raises(ValueError) as err:
t.write(out, format='votable')
assert 'cannot write table with mixin column(s)' in str(err.value)
def test_join(table_types):
"""
Join tables with mixin cols. Use column "i" as proxy for what the
result should be for each mixin.
"""
t1 = table_types.Table()
t1['a'] = table_types.Column(['a', 'b', 'b', 'c'])
t1['i'] = table_types.Column([0, 1, 2, 3])
for name, col in MIXIN_COLS.items():
t1[name] = col
t2 = table_types.Table(t1)
t2['a'] = ['b', 'c', 'a', 'd']
for name, col in MIXIN_COLS.items():
t1[name].info.description = name
t2[name].info.description = name + '2'
for join_type in ('inner', 'left'):
t12 = join(t1, t2, keys='a', join_type=join_type)
idx1 = t12['i_1']
idx2 = t12['i_2']
for name, col in MIXIN_COLS.items():
name1 = name + '_1'
name2 = name + '_2'
assert_table_name_col_equal(t12, name1, col[idx1])
assert_table_name_col_equal(t12, name2, col[idx2])
assert t12[name1].info.description == name
assert t12[name2].info.description == name + '2'
for join_type in ('outer', 'right'):
with pytest.raises(NotImplementedError) as exc:
t12 = join(t1, t2, keys='a', join_type=join_type)
assert 'join requires masking column' in str(exc.value)
with pytest.raises(TypeError) as exc:
t12 = join(t1, t2, keys=['a', 'skycoord'])
assert 'one or more key columns are not sortable' in str(exc.value)
# Join does work for a mixin which is a subclass of np.ndarray
with pytest.warns(MergeConflictWarning,
match="In merged column 'quantity' the 'description' "
"attribute does not match"):
t12 = join(t1, t2, keys=['quantity'])
assert np.all(t12['a_1'] == t1['a'])
def test_hstack(table_types):
"""
Hstack tables with mixin cols. Use column "i" as proxy for what the
result should be for each mixin.
"""
t1 = table_types.Table()
t1['i'] = table_types.Column([0, 1, 2, 3])
for name, col in MIXIN_COLS.items():
t1[name] = col
t1[name].info.description = name
t1[name].info.meta = {'a': 1}
for join_type in ('inner', 'outer'):
for chop in (True, False):
t2 = table_types.Table(t1)
if chop:
t2 = t2[:-1]
if join_type == 'outer':
with pytest.raises(NotImplementedError) as exc:
t12 = hstack([t1, t2], join_type=join_type)
assert 'hstack requires masking column' in str(exc.value)
continue
t12 = hstack([t1, t2], join_type=join_type)
idx1 = t12['i_1']
idx2 = t12['i_2']
for name, col in MIXIN_COLS.items():
name1 = name + '_1'
name2 = name + '_2'
assert_table_name_col_equal(t12, name1, col[idx1])
assert_table_name_col_equal(t12, name2, col[idx2])
for attr in ('description', 'meta'):
assert getattr(t1[name].info, attr) == getattr(t12[name1].info, attr)
assert getattr(t2[name].info, attr) == getattr(t12[name2].info, attr)
def assert_table_name_col_equal(t, name, col):
"""
Assert all(t[name] == col), with special handling for known mixin cols.
"""
if isinstance(col, coordinates.SkyCoord):
assert np.all(t[name].ra == col.ra)
assert np.all(t[name].dec == col.dec)
elif isinstance(col, coordinates.BaseRepresentationOrDifferential):
assert np.all(representation_equal(t[name], col))
elif isinstance(col, u.Quantity):
if type(t) is QTable:
assert np.all(t[name] == col)
elif isinstance(col, table_helpers.ArrayWrapper):
assert np.all(t[name].data == col.data)
else:
assert np.all(t[name] == col)
def test_get_items(mixin_cols):
"""
Test that slicing / indexing table gives right values and col attrs inherit
"""
attrs = ('name', 'unit', 'dtype', 'format', 'description', 'meta')
m = mixin_cols['m']
m.info.name = 'm'
m.info.format = '{0}'
m.info.description = 'd'
m.info.meta = {'a': 1}
t = QTable([m])
for item in ([1, 3], np.array([0, 2]), slice(1, 3)):
t2 = t[item]
m2 = m[item]
assert_table_name_col_equal(t2, 'm', m[item])
for attr in attrs:
assert getattr(t2['m'].info, attr) == getattr(m.info, attr)
assert getattr(m2.info, attr) == getattr(m.info, attr)
def test_info_preserved_pickle_copy_init(mixin_cols):
"""
Test copy, pickle, and init from class roundtrip preserve info. This
tests not only the mixin classes but a regular column as well.
"""
def pickle_roundtrip(c):
return pickle.loads(pickle.dumps(c))
def init_from_class(c):
return c.__class__(c)
attrs = ('name', 'unit', 'dtype', 'format', 'description', 'meta')
for colname in ('i', 'm'):
m = mixin_cols[colname]
m.info.name = colname
m.info.format = '{0}'
m.info.description = 'd'
m.info.meta = {'a': 1}
for func in (copy.copy, copy.deepcopy, pickle_roundtrip, init_from_class):
m2 = func(m)
for attr in attrs:
assert getattr(m2.info, attr) == getattr(m.info, attr)
def test_add_column(mixin_cols):
"""
Test that adding a column preserves values and attributes
"""
attrs = ('name', 'unit', 'dtype', 'format', 'description', 'meta')
m = mixin_cols['m']
assert m.info.name is None
# Make sure adding column in various ways doesn't touch
t = QTable([m], names=['a'])
assert m.info.name is None
t['new'] = m
assert m.info.name is None
m.info.name = 'm'
m.info.format = '{0}'
m.info.description = 'd'
m.info.meta = {'a': 1}
t = QTable([m])
# Add columns m2, m3, m4 by two different methods and test expected equality
t['m2'] = m
m.info.name = 'm3'
t.add_columns([m], copy=True)
m.info.name = 'm4'
t.add_columns([m], copy=False)
for name in ('m2', 'm3', 'm4'):
assert_table_name_col_equal(t, name, m)
for attr in attrs:
if attr != 'name':
assert getattr(t['m'].info, attr) == getattr(t[name].info, attr)
# Also check that one can set using a scalar.
s = m[0]
if type(s) is type(m) and 'info' in s.__dict__:
# We're not going to worry about testing classes for which scalars
# are a different class than the real array, or where info is not copied.
t['s'] = m[0]
assert_table_name_col_equal(t, 's', m[0])
for attr in attrs:
if attr != 'name':
assert getattr(t['m'].info, attr) == getattr(t['s'].info, attr)
# While we're add it, also check a length-1 table.
t = QTable([m[1:2]], names=['m'])
if type(s) is type(m) and 'info' in s.__dict__:
t['s'] = m[0]
assert_table_name_col_equal(t, 's', m[0])
for attr in attrs:
if attr != 'name':
assert getattr(t['m'].info, attr) == getattr(t['s'].info, attr)
def test_vstack():
"""
Vstack tables with mixin cols.
"""
t1 = QTable(MIXIN_COLS)
t2 = QTable(MIXIN_COLS)
with pytest.raises(NotImplementedError):
vstack([t1, t2])
def test_insert_row(mixin_cols):
"""
Test inserting a row, which works for Column, Quantity, Time and SkyCoord.
"""
t = QTable(mixin_cols)
t0 = t.copy()
t['m'].info.description = 'd'
idxs = [0, -1, 1, 2, 3]
if isinstance(t['m'], (u.Quantity, Column, time.Time, coordinates.SkyCoord)):
t.insert_row(1, t[-1])
for name in t.colnames:
col = t[name]
if isinstance(col, coordinates.SkyCoord):
assert skycoord_equal(col, t0[name][idxs])
else:
assert np.all(col == t0[name][idxs])
assert t['m'].info.description == 'd'
else:
with pytest.raises(ValueError) as exc:
t.insert_row(1, t[-1])
assert "Unable to insert row" in str(exc.value)
def test_insert_row_bad_unit():
"""
Insert a row into a QTable with the wrong unit
"""
t = QTable([[1] * u.m])
with pytest.raises(ValueError) as exc:
t.insert_row(0, (2 * u.m / u.s,))
assert "'m / s' (speed) and 'm' (length) are not convertible" in str(exc.value)
def test_convert_np_array(mixin_cols):
"""
Test that converting to numpy array creates an object dtype and that
each instance in the array has the expected type.
"""
t = QTable(mixin_cols)
ta = t.as_array()
m = mixin_cols['m']
dtype_kind = m.dtype.kind if hasattr(m, 'dtype') else 'O'
assert ta['m'].dtype.kind == dtype_kind
def test_assignment_and_copy():
"""
Test that assignment of an int, slice, and fancy index works.
Along the way test that copying table works.
"""
for name in ('quantity', 'arraywrap'):
m = MIXIN_COLS[name]
t0 = QTable([m], names=['m'])
for i0, i1 in ((1, 2),
(slice(0, 2), slice(1, 3)),
(np.array([1, 2]), np.array([2, 3]))):
t = t0.copy()
t['m'][i0] = m[i1]
if name == 'arraywrap':
assert np.all(t['m'].data[i0] == m.data[i1])
assert np.all(t0['m'].data[i0] == m.data[i0])
assert np.all(t0['m'].data[i0] != t['m'].data[i0])
else:
assert np.all(t['m'][i0] == m[i1])
assert np.all(t0['m'][i0] == m[i0])
assert np.all(t0['m'][i0] != t['m'][i0])
def test_conversion_qtable_table():
"""
Test that a table round trips from QTable => Table => QTable
"""
qt = QTable(MIXIN_COLS)
names = qt.colnames
for name in names:
qt[name].info.description = name
t = Table(qt)
for name in names:
assert t[name].info.description == name
if name == 'quantity':
assert np.all(t['quantity'] == qt['quantity'].value)
assert np.all(t['quantity'].unit is qt['quantity'].unit)
assert isinstance(t['quantity'], t.ColumnClass)
else:
assert_table_name_col_equal(t, name, qt[name])
qt2 = QTable(qt)
for name in names:
assert qt2[name].info.description == name
assert_table_name_col_equal(qt2, name, qt[name])
def test_setitem_as_column_name():
"""
Test for mixin-related regression described in #3321.
"""
t = Table()
t['a'] = ['x', 'y']
t['b'] = 'b' # Previously was failing with KeyError
assert np.all(t['a'] == ['x', 'y'])
assert np.all(t['b'] == ['b', 'b'])
def test_quantity_representation():
"""
Test that table representation of quantities does not have unit
"""
t = QTable([[1, 2] * u.m])
assert t.pformat() == ['col0',
' m ',
'----',
' 1.0',
' 2.0']
def test_representation_representation():
"""
Test that Representations are represented correctly.
"""
# With no unit we get "None" in the unit row
c = coordinates.CartesianRepresentation([0], [1], [0], unit=u.one)
t = Table([c])
assert t.pformat() == [' col0 ',
'------------',
'(0., 1., 0.)']
c = coordinates.CartesianRepresentation([0], [1], [0], unit='m')
t = Table([c])
assert t.pformat() == [' col0 ',
' m ',
'------------',
'(0., 1., 0.)']
c = coordinates.SphericalRepresentation([10]*u.deg, [20]*u.deg, [1]*u.pc)
t = Table([c])
assert t.pformat() == [' col0 ',
' deg, deg, pc ',
'--------------',
'(10., 20., 1.)']
c = coordinates.UnitSphericalRepresentation([10]*u.deg, [20]*u.deg)
t = Table([c])
assert t.pformat() == [' col0 ',
' deg ',
'----------',
'(10., 20.)']
c = coordinates.SphericalCosLatDifferential(
[10]*u.mas/u.yr, [2]*u.mas/u.yr, [10]*u.km/u.s)
t = Table([c])
assert t.pformat() == [' col0 ',
'mas / yr, mas / yr, km / s',
'--------------------------',
' (10., 2., 10.)']
def test_skycoord_representation():
"""
Test that skycoord representation works, both in the way that the
values are output and in changing the frame representation.
"""
# With no unit we get "None" in the unit row
c = coordinates.SkyCoord([0], [1], [0], representation_type='cartesian')
t = Table([c])
assert t.pformat() == [' col0 ',
'None,None,None',
'--------------',
' 0.0,1.0,0.0']
# Test that info works with a dynamically changed representation
c = coordinates.SkyCoord([0], [1], [0], unit='m', representation_type='cartesian')
t = Table([c])
assert t.pformat() == [' col0 ',
' m,m,m ',
'-----------',
'0.0,1.0,0.0']
t['col0'].representation_type = 'unitspherical'
assert t.pformat() == [' col0 ',
'deg,deg ',
'--------',
'90.0,0.0']
t['col0'].representation_type = 'cylindrical'
assert t.pformat() == [' col0 ',
' m,deg,m ',
'------------',
'1.0,90.0,0.0']
def test_ndarray_mixin():
"""
Test directly adding a plain structured array into a table instead of the
view as an NdarrayMixin. Once added as an NdarrayMixin then all the previous
tests apply.
"""
a = np.array([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')],
dtype='<i4,' + ('|U1'))
b = np.array([(10, 'aa'), (20, 'bb'), (30, 'cc'), (40, 'dd')],
dtype=[('x', 'i4'), ('y', ('U2'))])
c = np.rec.fromrecords([(100, 'raa'), (200, 'rbb'), (300, 'rcc'), (400, 'rdd')],
names=['rx', 'ry'])
d = np.arange(8).reshape(4, 2).view(NdarrayMixin)
# Add one during initialization and the next as a new column.
t = Table([a], names=['a'])
t['b'] = b
t['c'] = c
t['d'] = d
assert isinstance(t['a'], NdarrayMixin)
assert t['a'][1][1] == a[1][1]
assert t['a'][2][0] == a[2][0]
assert t[1]['a'][1] == a[1][1]
assert t[2]['a'][0] == a[2][0]
assert isinstance(t['b'], NdarrayMixin)
assert t['b'][1]['x'] == b[1]['x']
assert t['b'][1]['y'] == b[1]['y']
assert t[1]['b']['x'] == b[1]['x']
assert t[1]['b']['y'] == b[1]['y']
assert isinstance(t['c'], NdarrayMixin)
assert t['c'][1]['rx'] == c[1]['rx']
assert t['c'][1]['ry'] == c[1]['ry']
assert t[1]['c']['rx'] == c[1]['rx']
assert t[1]['c']['ry'] == c[1]['ry']
assert isinstance(t['d'], NdarrayMixin)
assert t['d'][1][0] == d[1][0]
assert t['d'][1][1] == d[1][1]
assert t[1]['d'][0] == d[1][0]
assert t[1]['d'][1] == d[1][1]
assert t.pformat() == [' a b c d [2] ',
'-------- ---------- ------------ ------',
"(1, 'a') (10, 'aa') (100, 'raa') 0 .. 1",
"(2, 'b') (20, 'bb') (200, 'rbb') 2 .. 3",
"(3, 'c') (30, 'cc') (300, 'rcc') 4 .. 5",
"(4, 'd') (40, 'dd') (400, 'rdd') 6 .. 7"]
def test_possible_string_format_functions():
"""
The QuantityInfo info class for Quantity implements a
possible_string_format_functions() method that overrides the
standard pprint._possible_string_format_functions() function.
Test this.
"""
t = QTable([[1, 2] * u.m])
t['col0'].info.format = '%.3f'
assert t.pformat() == [' col0',
' m ',
'-----',
'1.000',
'2.000']
t['col0'].info.format = 'hi {:.3f}'
assert t.pformat() == [' col0 ',
' m ',
'--------',
'hi 1.000',
'hi 2.000']
t['col0'].info.format = '.4f'
assert t.pformat() == [' col0 ',
' m ',
'------',
'1.0000',
'2.0000']
def test_rename_mixin_columns(mixin_cols):
"""
Rename a mixin column.
"""
t = QTable(mixin_cols)
tc = t.copy()
t.rename_column('m', 'mm')
assert t.colnames == ['i', 'a', 'b', 'mm']
if isinstance(t['mm'], table_helpers.ArrayWrapper):
assert np.all(t['mm'].data == tc['m'].data)
elif isinstance(t['mm'], coordinates.SkyCoord):
assert np.all(t['mm'].ra == tc['m'].ra)
assert np.all(t['mm'].dec == tc['m'].dec)
elif isinstance(t['mm'], coordinates.BaseRepresentationOrDifferential):
assert np.all(representation_equal(t['mm'], tc['m']))
else:
assert np.all(t['mm'] == tc['m'])
def test_represent_mixins_as_columns_unit_fix():
"""
If the unit is invalid for a column that gets serialized this would
cause an exception. Fixed in #7481.
"""
t = Table({'a': [1, 2]}, masked=True)
t['a'].unit = 'not a valid unit'
t['a'].mask[1] = True
serialize.represent_mixins_as_columns(t)
@pytest.mark.skipif(not HAS_YAML, reason='mixin columns in .ecsv need yaml')
def test_skycoord_with_velocity():
# Regression test for gh-6447
sc = SkyCoord([1], [2], unit='deg', galcen_v_sun=None)
t = Table([sc])
s = StringIO()
t.write(s, format='ascii.ecsv', overwrite=True)
s.seek(0)
t2 = Table.read(s.read(), format='ascii.ecsv')
assert skycoord_equal(t2['col0'], sc)
| [
"[email protected]"
] | |
9fb0d5b275776d93f611e8155d9b45109e0e3a2e | 00c6ded41b84008489a126a36657a8dc773626a5 | /.history/Sizing_Method/ConstrainsAnalysis/DesignPointSelectStrategy_20210715190839.py | a2ac951ec777c61b515fff6cb84697d45b202fa7 | [] | no_license | 12libao/DEA | 85f5f4274edf72c7f030a356bae9c499e3afc2ed | 1c6f8109bbc18c4451a50eacad9b4dedd29682bd | refs/heads/master | 2023-06-17T02:10:40.184423 | 2021-07-16T19:05:18 | 2021-07-16T19:05:18 | 346,111,158 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,946 | py | # author: Bao Li #
# Georgia Institute of Technology #
import sys
import os
sys.path.insert(0, os.getcwd())
import numpy as np
import matplotlib.pylab as plt
import Sizing_Method.Other.US_Standard_Atmosphere_1976 as atm
import Sizing_Method.Aerodynamics.ThrustLapse as thrust_lapse
import Sizing_Method.Aerodynamics.Aerodynamics as ad
import Sizing_Method.ConstrainsAnalysis.ConstrainsAnalysis as ca
import Sizing_Method.ConstrainsAnalysis.ConstrainsAnalysisPD as ca_pd
import Sizing_Method.ConstrainsAnalysis.ConstrainsAnalysisPDP1P2 as ca_pd_12
from icecream import ic
import math
"""
The unit use is IS standard
"""
class Design_Point_Select_Strategy:
"""This is a design point select strategy from constrains analysis"""
def __init__(self, altitude, velocity, beta, method=2, strategy_apply=0, propulsion_constrains=0, n=12):
"""
:param altitude: m x 1 matrix
:param velocity: m x 1 matrix
:param beta: P_motor/P_total m x 1 matrix
:param p_turbofan_max: maximum propulsion power for turbofan (threshold value)
:param p_motorfun_max: maximum propulsion power for motorfun (threshold value)
:param n: number of motor
:param method: if method = 1, it is Mattingly Method, otherwise is Gudmundsson Method
:param strategy_apply: if strategy_apply = 0, no strategy apply
:param propulsion_constrains: if propulsion_constrains = 0, no propulsion_constrains apply
the first group of condition is for stall speed
the stall speed condition have to use motor, therefore with PD
:return:
power load: design point p/w and w/s
"""
self.h = altitude
self.v = velocity
self.beta = beta
self.n_motor = n
self.propulsion_constrains = propulsion_constrains
self.strategy_apply = strategy_apply
# initialize the p_w, w_s, hp, n, m
self.n = 100
self.m = altitude.size
self.hp = np.linspace(0, 1, self.n+1)
self.hp_threshold = 0.5
ic(self.hp)
# method = 1 = Mattingly_Method, method = 2 = Gudmundsson_Method
if method == 1:
self.method1 = ca_pd_12.ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun
self.method2 = ca_pd_12.ConstrainsAnalysis_Mattingly_Method_with_DP_electric
else:
self.method1 = ca_pd_12.ConstrainsAnalysis_Gudmundsson_Method_with_DP_turbofun
self.method2 = ca_pd_12.ConstrainsAnalysis_Gudmundsson_Method_with_DP_electric
problem = self.method1(
self.h[0], self.v[0], self.beta[0], 6000, self.hp_threshold)
self.w_s = problem.allFuncs[0](problem)
def p_w_compute(self, p_w_turbofan_max, p_w_motorfun_max, pc):
p_w = np.zeros([self.m, len(self.hp)]) # m x (n+1) matrix
p_w_1 = np.zeros([self.m, len(self.hp)]) # m x (n+1) matrix
p_w_2 = np.zeros([self.m, len(self.hp)]) # m x (n+1) matrix
for i in range(1, 8):
for j in range(len(self.hp)):
problem1 = self.method1(self.h[i], self.v[i],
self.beta[i], self.w_s, self.hp[j])
problem2 = self.method2(self.h[i], self.v[i],
self.beta[i], self.w_s, self.hp[j])
if i >= 5:
p_w_1[i, j] = problem1.allFuncs[-1](problem1, roc=15 - 5 * (i - 5))
p_w_2[i, j] = problem2.allFuncs[-1](problem2, roc=15 - 5 * (i - 5))
else:
p_w_1[i, j] = problem1.allFuncs[i](problem1)
p_w_2[i, j] = problem2.allFuncs[i](problem2)
if self.propulsion_constrains != 0 and pc != 0:
if p_w_1[i, j] > p_w_turbofan_max:
p_w_1[i, j] = 100000
elif p_w_2[i, j] > p_w_motorfun_max:
p_w_2[i, j] = 100000
p_w[i, j] = p_w_1[i, j] + p_w_2[i, j]
return p_w, p_w_1, p_w_2
def p_w_min(self, p_w):
#find the min p_w for difference hp for each flight condition:
p_w_min = np.amin(p_w, axis=1)
#find the index of p_w_min which is the hp
hp_p_w_min = np.zeros(8)
for i in range(1, 8):
for j in range(len(self.hp)):
if p_w[i, j] - p_w_min[i] < 0.001:
hp_p_w_min[i] = j * 0.01
p_w_1 = np.zeros(8)
p_w_2= np.zeros(8)
for i in range(1, 8):
problem1 = self.method1(
self.h[i], self.v[i], self.beta[i], self.w_s, hp_p_w_min[i])
problem2 = self.method2(
self.h[i], self.v[i], self.beta[i], self.w_s, hp_p_w_min[i])
if i >= 5:
p_w_1[i] = problem1.allFuncs[-1](
problem1, roc=15 - 5 * (i - 5))
p_w_2[i] = problem2.allFuncs[-1](
problem2, roc=15 - 5 * (i - 5))
else:
p_w_1[i] = problem1.allFuncs[i](problem1)
p_w_2[i] = problem2.allFuncs[i](problem2)
p_w_1_min = np.amax(p_w_1)
p_w_2_min = np.amax(p_w_2)
return p_w_1_min, p_w_2_min, p_w_min, hp_p_w_min
def strategy(self):
if self.strategy_apply == 0:
p_w_turbofan_max = 10000
p_w_motorfun_max = 10000
p_w, p_w_1, p_w_2 = Design_Point_Select_Strategy.p_w_compute(
self, p_w_turbofan_max, p_w_motorfun_max, pc=0)
p_w_min = p_w[:, 50]
p_w_1_min = np.array([self.w_s, np.amax(p_w_1[:, 50])])
p_w_2_min = np.array([self.w_s, np.amax(p_w_2[:, 50])])
hp_p_w_min = 0.5*np.ones(8)
else:
if self.propulsion_constrains == 0:
p_w_turbofan_max = 100000
p_w_motorfun_max = 100000
p_w, p_w_1, p_w_2 = Design_Point_Select_Strategy.p_w_compute(self, p_w_turbofan_max, p_w_motorfun_max, 0)
else:
p_w, _, _ = Design_Point_Select_Strategy.p_w_compute(self, 10000, 10000, pc=0)
p_w_1_min, p_w_2_min, _, _ = Design_Point_Select_Strategy.p_w_min(self, p_w)
p_w_turbofun_boundary = math.ceil(p_w_1_min)
p_w_motorfun_boundary = math.ceil(p_w_2_min)
ic(p_w_turbofun_boundary, p_w_motorfun_boundary)
# build p_w_design_point matrix, try p_w_max to find the best one
p_w_design_point = np.zeros([p_w_turbofun_boundary+1, p_w_motorfun_boundary+1])
for i in range(p_w_turbofun_boundary+1):
for j in range(p_w_motorfun_boundary+1):
p_w, _, _ = Design_Point_Select_Strategy.p_w_compute(self, i, j, 1)
#find the min p_w from hp: 0 --- 100 for each flight condition:
p_w_min = np.amin(p_w, axis=1)
p_w_design_point[i, j] = np.amax(p_w_min)
print(i)
p_w_turbofan_max = np.unravel_index(
p_w_design_point.argmin(), p_w_design_point.shape)[0]
p_w_motorfun_max = np.unravel_index(
p_w_design_point.argmin(), p_w_design_point.shape)[1]
p_w, p_w_1, p_w_2 = Design_Point_Select_Strategy.p_w_compute(
self, p_w_turbofan_max, p_w_motorfun_max, 1)
ic(p_w, p_w_1, p_w_2)
p_w_1_min, p_w_2_min, p_w_min, hp_p_w_min = Design_Point_Select_Strategy.p_w_min(self, p_w)
hp_p_w_min[0] = p_w_motorfun_max/(p_w_motorfun_max+p_w_turbofan_max)
return self.w_s, p_w_min, p_w_1_min, p_w_2_min, hp_p_w_min, p_w_turbofan_max, p_w_motorfun_max
if __name__ == "__main__":
n, m = 250, 8
w_s = np.linspace(100, 9000, n)
p_w = np.zeros([m, n, 6])
constrains = np.array([[0, 80, 1, 0.2], [0, 68, 0.988, 0.5], [11300, 230, 0.948, 0.8],
[11900, 230, 0.78, 0.8], [3000, 100,
0.984, 0.8], [0, 100, 0.984, 0.5],
[3000, 200, 0.975, 0.6], [7000, 230, 0.96, 0.7]])
constrains_name = ['stall speed', 'take off', 'cruise', 'service ceiling', 'level turn @3000m',
'climb @S-L', 'climb @3000m', 'climb @7000m', 'feasible region-hybrid', 'feasible region-conventional']
color = ['k', 'c', 'b', 'g', 'y', 'plum', 'violet', 'm']
l_style = ['-', '--', '-.-']
methods = [ca_pd_12.ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun,
ca_pd_12.ConstrainsAnalysis_Gudmundsson_Method_with_DP_turbofun,
ca_pd_12.ConstrainsAnalysis_Mattingly_Method_with_DP_electric,
ca_pd_12.ConstrainsAnalysis_Gudmundsson_Method_with_DP_electric]
strategy = [0, 1, 1]
propulsion = [0, 0, 1]
# plots
fig, ax = plt.subplots(3, 2, sharey=True, sharex=True, figsize=(10, 10))
ax = ax.flatten()
design_point_p_w, design_point_w_s, hp_p_w_min = np.zeros([3, 6]), np.zeros([3, 2]), np.zeros([6, 8])
for z in range(3):
h = constrains[:, 0]
v = constrains[:, 1]
beta = constrains[:, 2]
problem1 = Design_Point_Select_Strategy(
h, v, beta, method=1, strategy_apply=strategy[z], propulsion_constrains=propulsion[z])
problem2 = Design_Point_Select_Strategy(
h, v, beta, method=2, strategy_apply=strategy[z], propulsion_constrains=propulsion[z])
design_point_w_s[z, 0], design_point_p_w[z, 4],
design_point_p_w[z, 0], design_point_p_w[z, 2], hp_p_w_min[z, :], _, _ = problem1.strategy()
design_point_w_s[z, 0], design_point_p_w[z, 5],
design_point_p_w[z, 1], design_point_p_w[z, 3], hp_p_w_min[z+1, :], _, _ = problem1.strategy()
for k in range(6):
for i in range(m):
for j in range(n):
h = constrains[i, 0]
v = constrains[i, 1]
beta = constrains[i, 2]
hp = hp_p_w_min[i]
# calculate p_w
if k < 4:
problem = methods[k](h, v, beta, w_s[j], hp)
if i >= 5:
p_w[i, j, k] = problem.allFuncs[-1](problem, roc=15 - 5 * (i - 5))
else:
p_w[i, j, k] = problem.allFuncs[i](problem)
else:
if i == 0:
problem = methods[k-2](h, v, beta, w_s[j], hp)
p_w[i, j, k] = problem.allFuncs[i](problem)
else:
p_w[i, j, k] = p_w[i, j, k-4] + p_w[i, j, k-2]
# plot the lines
if i == 0:
ax[k].plot(p_w[i, :, k], np.linspace(0, 100, n),
linewidth=1, alpha=0.5, linestyle=l_style[z], label=constrains_name[i])
else:
ax[k].plot(w_s, p_w[i, :, k], color=color[i],
linewidth=1, alpha=0.5, linestyle=l_style[z], label=constrains_name[i])
# plot fill region
p_w[0, :, k] = 10 ** 10 * (w_s - p_w[0, 0, k])
ax[k].fill_between(w_s, np.amax(p_w[0:m, :, k], axis=0), 150, color='b', alpha=0.5, label=constrains_name[-2])
ax[k].grid()
ax[k-2].plot(6012, 72, 'r*', markersize=5, label='True Conventional')
handles, labels = plt.gca().get_legend_handles_labels()
fig.legend(handles, labels, bbox_to_anchor=(0.125, 0.02, 0.75, 0.25), loc="lower left",
mode="expand", borderaxespad=0, ncol=4, frameon=False)
hp = constrains[:, 3]
plt.xlim(200, 9000)
plt.ylim(0, 100)
plt.setp(ax[0].set_title(r'$\bf{Mattingly-Method}$'))
plt.setp(ax[1].set_title(r'$\bf{Gudmundsson-Method}$'))
plt.setp(ax[4:6], xlabel='Wing Load: $W_{TO}$/S (N/${m^2}$)')
plt.setp(ax[0], ylabel=r'$\bf{Turbofun}$''\n $P_{SL}$/$W_{TO}$ (W/N)')
plt.setp(ax[2], ylabel=r'$\bf{Motor}$ ''\n $P_{SL}$/$W_{TO}$ (W/N)')
plt.setp(
ax[4], ylabel=r'$\bf{Turbofun+Motor}$' '\n' r'$\bf{vs.Conventional}$ ''\n $P_{SL}$/$W_{TO}$ (W/N)')
plt.subplots_adjust(bottom=0.15)
plt.suptitle(r'$\bf{Component}$' ' ' r'$\bf{P_{SL}/W_{TO}}$' ' ' r'$\bf{Diagrams}$'
' ' r'$\bf{After}$' ' ' r'$\bf{Adjust}$' ' ' r'$\bf{Degree-of-Hybridization}$'
'\n hp: take-off=' +
str(hp[0]) + ' stall-speed=' +
str(hp[1]) + ' cruise=' +
str(hp[2]) + ' service-ceiling=' +
str(hp[3]) + '\n level-turn=@3000m' +
str(hp[4]) + ' climb@S-L=' +
str(hp[5]) + ' climb@3000m=' +
str(hp[6]) + ' climb@7000m=' + str(hp[7]))
plt.show()
| [
"[email protected]"
] | |
148cdb131a56fd63ff2ef0abeb3b986b26f89eea | ac4b9385b7ad2063ea51237fbd8d1b74baffd016 | /.history/google/docs_quickstart_20210213142716.py | 483f1642a07b3d11faa3808ec62f56fa18f7a9dd | [] | no_license | preethanpa/ssoemprep | 76297ef21b1d4893f1ac2f307f60ec72fc3e7c6f | ce37127845253c768d01aeae85e5d0d1ade64516 | refs/heads/main | 2023-03-09T00:15:55.130818 | 2021-02-20T06:54:58 | 2021-02-20T06:54:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,082 | py | from __future__ import print_function
import pickle
import os.path
import io
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
from oauth2client.service_account import ServiceAccountCredentials
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/documents.readonly', 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.activity', 'https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive']# 'https://www.googleapis.com/auth/documents.readonly']
# The ID of a sample document.
# DOCUMENT_ID = '1bQkFcQrWFHGlte8oTVtq_zyKGIgpFlWAS5_5fi8OzjY'
DOCUMENT_ID = '1sXQie19gQBRHODebxBZv4xUCJy-9rGpnlpM7_SUFor4'
def main():
"""Shows basic usage of the Docs API.
Prints the title of a sample document.
"""
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/documents.readonly', 'https://www.googleapis.com/auth/sqlservice.admin', 'https://www.googleapis.com/auth/drive.file']
SERVICE_ACCOUNT_FILE = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/google/domain-wide-credentials-gdrive.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# delegated_credentials = credentials.with_subject('[email protected]')
# service = build('docs', 'v1', credentials=credentials)
drive_service = build('drive', 'v3', credentials=credentials)
request = drive_service.files() .get_media(fileId=DOCUMENT_ID)
print(request)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
# print(f"Download % {int(status.progress() * 100)}")
if __name__ == '__main__':
main() | [
"{[email protected]}"
] | |
4c6abdca47eed860cbbbd80db8e8195616fdc873 | 7c3a066c2f4e3be8b3f8a418f0152f9d3de69599 | /google_kickstart/15683.py | 75639c55a00f4cf507ab52e131684ae11a8d1dab | [] | no_license | wkdtjsgur100/algorithm-python | 5c0fa5ac5f5c2b8618e53ab0f1f599427345734d | 134809388baac48195630e1398b8c2af7526966c | refs/heads/master | 2020-04-02T19:58:20.480391 | 2018-12-31T08:33:44 | 2018-12-31T08:33:44 | 154,753,276 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,143 | py | import copy, sys
cctv=[
[[0], [1], [2], [3]],
[[0, 1], [2, 3]],
[[0, 3], [0, 2], [2, 1], [1, 3]],
[[1, 2, 3], [0, 1, 2], [0, 2, 3], [0, 1, 3]],
[[0, 1, 2, 3]]
]
d = [[0, 1], [0, -1], [1, 0], [-1, 0]]
N, M = map(int, input().split())
m = [list(map(int, input().split())) for _ in range(N)]
cctv_poses = []
for i in range(len(m)):
for j in range(len(m[0])):
if 1 <= m[i][j] <= 5:
cctv_poses.append((i, j, m[i][j]))
def observe(m, i, j, d):
if 0 <= i < N and 0 <= j < M and m[i][j] != 6:
if m[i][j] == 0:
m[i][j] = -1
observe(m, i+d[0], j+d[1], d)
def simulate(m, cctv_i):
global N, M
if cctv_i == len(cctv_poses):
return sum(r.count(0) for r in m)
i = cctv_poses[cctv_i][0]
j = cctv_poses[cctv_i][1]
cam_num = cctv_poses[cctv_i][2]
temp_m = copy.deepcopy(m)
ret = sys.maxsize
for sight in range(len(cctv[cam_num-1])):
for d_num in cctv[cam_num-1][sight]:
observe(m, i, j, d[d_num])
ret = min(ret, simulate(m, cctv_i+1))
m = copy.deepcopy(temp_m)
return ret
print(simulate(m, 0))
| [
"[email protected]"
] | |
84de9302b013fd741256a039e1e919f9abfe13ce | 372edad1cd6399cadba82818e9fb9682c3bac1b4 | /packages/python/plotly/plotly/validators/_layout.py | 35ec745486825a04421fc837dfe6cb3b998c4fcc | [
"MIT"
] | permissive | OGVGdev/plotly.py | 78bfa9e25e92c367f0da30af7885cdd163ba612b | 96a9101c79aa588023f56153bf274d0d570ffcf6 | refs/heads/master | 2022-11-10T16:44:06.732450 | 2020-06-26T13:07:06 | 2020-06-26T13:07:06 | 275,173,321 | 1 | 0 | MIT | 2020-06-26T14:19:41 | 2020-06-26T14:19:40 | null | UTF-8 | Python | false | false | 25,576 | py | import _plotly_utils.basevalidators
class LayoutValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="layout", parent_name="", **kwargs):
super(LayoutValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Layout"),
data_docs=kwargs.pop(
"data_docs",
"""
activeshape
:class:`plotly.graph_objects.layout.Activeshape
` instance or dict with compatible properties
angularaxis
:class:`plotly.graph_objects.layout.AngularAxis
` instance or dict with compatible properties
annotations
A tuple of
:class:`plotly.graph_objects.layout.Annotation`
instances or dicts with compatible properties
annotationdefaults
When used in a template (as
layout.template.layout.annotationdefaults),
sets the default property values to use for
elements of layout.annotations
autosize
Determines whether or not a layout width or
height that has been left undefined by the user
is initialized on each relayout. Note that,
regardless of this attribute, an undefined
layout width or height is always initialized on
the first call to plot.
bargap
Sets the gap (in plot fraction) between bars of
adjacent location coordinates.
bargroupgap
Sets the gap (in plot fraction) between bars of
the same location coordinate.
barmode
Determines how bars at the same location
coordinate are displayed on the graph. With
"stack", the bars are stacked on top of one
another With "relative", the bars are stacked
on top of one another, with negative values
below the axis, positive values above With
"group", the bars are plotted next to one
another centered around the shared location.
With "overlay", the bars are plotted over one
another, you might need to an "opacity" to see
multiple bars.
barnorm
Sets the normalization for bar traces on the
graph. With "fraction", the value of each bar
is divided by the sum of all values at that
location coordinate. "percent" is the same but
multiplied by 100 to show percentages.
boxgap
Sets the gap (in plot fraction) between boxes
of adjacent location coordinates. Has no effect
on traces that have "width" set.
boxgroupgap
Sets the gap (in plot fraction) between boxes
of the same location coordinate. Has no effect
on traces that have "width" set.
boxmode
Determines how boxes at the same location
coordinate are displayed on the graph. If
"group", the boxes are plotted next to one
another centered around the shared location. If
"overlay", the boxes are plotted over one
another, you might need to set "opacity" to see
them multiple boxes. Has no effect on traces
that have "width" set.
calendar
Sets the default calendar system to use for
interpreting and displaying dates throughout
the plot.
clickmode
Determines the mode of single click
interactions. "event" is the default value and
emits the `plotly_click` event. In addition
this mode emits the `plotly_selected` event in
drag modes "lasso" and "select", but with no
event data attached (kept for compatibility
reasons). The "select" flag enables selecting
single data points via click. This mode also
supports persistent selections, meaning that
pressing Shift while clicking, adds to /
subtracts from an existing selection. "select"
with `hovermode`: "x" can be confusing,
consider explicitly setting `hovermode`:
"closest" when using this feature. Selection
events are sent accordingly as long as "event"
flag is set as well. When the "event" flag is
missing, `plotly_click` and `plotly_selected`
events are not fired.
coloraxis
:class:`plotly.graph_objects.layout.Coloraxis`
instance or dict with compatible properties
colorscale
:class:`plotly.graph_objects.layout.Colorscale`
instance or dict with compatible properties
colorway
Sets the default trace colors.
datarevision
If provided, a changed value tells
`Plotly.react` that one or more data arrays has
changed. This way you can modify arrays in-
place rather than making a complete new copy
for an incremental change. If NOT provided,
`Plotly.react` assumes that data arrays are
being treated as immutable, thus any data array
with a different identity from its predecessor
contains new data.
direction
Legacy polar charts are deprecated! Please
switch to "polar" subplots. Sets the direction
corresponding to positive angles in legacy
polar charts.
dragmode
Determines the mode of drag interactions.
"select" and "lasso" apply only to scatter
traces with markers or text. "orbit" and
"turntable" apply only to 3D scenes.
editrevision
Controls persistence of user-driven changes in
`editable: true` configuration, other than
trace names and axis titles. Defaults to
`layout.uirevision`.
extendfunnelareacolors
If `true`, the funnelarea slice colors (whether
given by `funnelareacolorway` or inherited from
`colorway`) will be extended to three times its
original length by first repeating every color
20% lighter then each color 20% darker. This is
intended to reduce the likelihood of reusing
the same color when you have many slices, but
you can set `false` to disable. Colors provided
in the trace, using `marker.colors`, are never
extended.
extendpiecolors
If `true`, the pie slice colors (whether given
by `piecolorway` or inherited from `colorway`)
will be extended to three times its original
length by first repeating every color 20%
lighter then each color 20% darker. This is
intended to reduce the likelihood of reusing
the same color when you have many slices, but
you can set `false` to disable. Colors provided
in the trace, using `marker.colors`, are never
extended.
extendsunburstcolors
If `true`, the sunburst slice colors (whether
given by `sunburstcolorway` or inherited from
`colorway`) will be extended to three times its
original length by first repeating every color
20% lighter then each color 20% darker. This is
intended to reduce the likelihood of reusing
the same color when you have many slices, but
you can set `false` to disable. Colors provided
in the trace, using `marker.colors`, are never
extended.
extendtreemapcolors
If `true`, the treemap slice colors (whether
given by `treemapcolorway` or inherited from
`colorway`) will be extended to three times its
original length by first repeating every color
20% lighter then each color 20% darker. This is
intended to reduce the likelihood of reusing
the same color when you have many slices, but
you can set `false` to disable. Colors provided
in the trace, using `marker.colors`, are never
extended.
font
Sets the global font. Note that fonts used in
traces and other layout components inherit from
the global font.
funnelareacolorway
Sets the default funnelarea slice colors.
Defaults to the main `colorway` used for trace
colors. If you specify a new list here it can
still be extended with lighter and darker
colors, see `extendfunnelareacolors`.
funnelgap
Sets the gap (in plot fraction) between bars of
adjacent location coordinates.
funnelgroupgap
Sets the gap (in plot fraction) between bars of
the same location coordinate.
funnelmode
Determines how bars at the same location
coordinate are displayed on the graph. With
"stack", the bars are stacked on top of one
another With "group", the bars are plotted next
to one another centered around the shared
location. With "overlay", the bars are plotted
over one another, you might need to an
"opacity" to see multiple bars.
geo
:class:`plotly.graph_objects.layout.Geo`
instance or dict with compatible properties
grid
:class:`plotly.graph_objects.layout.Grid`
instance or dict with compatible properties
height
Sets the plot's height (in px).
hiddenlabels
hiddenlabels is the funnelarea & pie chart
analog of visible:'legendonly' but it can
contain many labels, and can simultaneously
hide slices from several pies/funnelarea charts
hiddenlabelssrc
Sets the source reference on Chart Studio Cloud
for hiddenlabels .
hidesources
Determines whether or not a text link citing
the data source is placed at the bottom-right
cored of the figure. Has only an effect only on
graphs that have been generated via forked
graphs from the Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise).
hoverdistance
Sets the default distance (in pixels) to look
for data to add hover labels (-1 means no
cutoff, 0 means no looking for data). This is
only a real distance for hovering on point-like
objects, like scatter points. For area-like
objects (bars, scatter fills, etc) hovering is
on inside the area and off outside, but these
objects will not supersede hover on point-like
objects in case of conflict.
hoverlabel
:class:`plotly.graph_objects.layout.Hoverlabel`
instance or dict with compatible properties
hovermode
Determines the mode of hover interactions. If
"closest", a single hoverlabel will appear for
the "closest" point within the `hoverdistance`.
If "x" (or "y"), multiple hoverlabels will
appear for multiple points at the "closest" x-
(or y-) coordinate within the `hoverdistance`,
with the caveat that no more than one
hoverlabel will appear per trace. If *x
unified* (or *y unified*), a single hoverlabel
will appear multiple points at the closest x-
(or y-) coordinate within the `hoverdistance`
with the caveat that no more than one
hoverlabel will appear per trace. In this mode,
spikelines are enabled by default perpendicular
to the specified axis. If false, hover
interactions are disabled. If `clickmode`
includes the "select" flag, `hovermode`
defaults to "closest". If `clickmode` lacks the
"select" flag, it defaults to "x" or "y"
(depending on the trace's `orientation` value)
for plots based on cartesian coordinates. For
anything else the default value is "closest".
images
A tuple of
:class:`plotly.graph_objects.layout.Image`
instances or dicts with compatible properties
imagedefaults
When used in a template (as
layout.template.layout.imagedefaults), sets the
default property values to use for elements of
layout.images
legend
:class:`plotly.graph_objects.layout.Legend`
instance or dict with compatible properties
mapbox
:class:`plotly.graph_objects.layout.Mapbox`
instance or dict with compatible properties
margin
:class:`plotly.graph_objects.layout.Margin`
instance or dict with compatible properties
meta
Assigns extra meta information that can be used
in various `text` attributes. Attributes such
as the graph, axis and colorbar `title.text`,
annotation `text` `trace.name` in legend items,
`rangeselector`, `updatemenus` and `sliders`
`label` text all support `meta`. One can access
`meta` fields using template strings:
`%{meta[i]}` where `i` is the index of the
`meta` item in question. `meta` can also be an
object for example `{key: value}` which can be
accessed %{meta[key]}.
metasrc
Sets the source reference on Chart Studio Cloud
for meta .
modebar
:class:`plotly.graph_objects.layout.Modebar`
instance or dict with compatible properties
newshape
:class:`plotly.graph_objects.layout.Newshape`
instance or dict with compatible properties
orientation
Legacy polar charts are deprecated! Please
switch to "polar" subplots. Rotates the entire
polar by the given angle in legacy polar
charts.
paper_bgcolor
Sets the background color of the paper where
the graph is drawn.
piecolorway
Sets the default pie slice colors. Defaults to
the main `colorway` used for trace colors. If
you specify a new list here it can still be
extended with lighter and darker colors, see
`extendpiecolors`.
plot_bgcolor
Sets the background color of the plotting area
in-between x and y axes.
polar
:class:`plotly.graph_objects.layout.Polar`
instance or dict with compatible properties
radialaxis
:class:`plotly.graph_objects.layout.RadialAxis`
instance or dict with compatible properties
scene
:class:`plotly.graph_objects.layout.Scene`
instance or dict with compatible properties
selectdirection
When `dragmode` is set to "select", this limits
the selection of the drag to horizontal,
vertical or diagonal. "h" only allows
horizontal selection, "v" only vertical, "d"
only diagonal and "any" sets no limit.
selectionrevision
Controls persistence of user-driven changes in
selected points from all traces.
separators
Sets the decimal and thousand separators. For
example, *. * puts a '.' before decimals and a
space between thousands. In English locales,
dflt is ".," but other locales may alter this
default.
shapes
A tuple of
:class:`plotly.graph_objects.layout.Shape`
instances or dicts with compatible properties
shapedefaults
When used in a template (as
layout.template.layout.shapedefaults), sets the
default property values to use for elements of
layout.shapes
showlegend
Determines whether or not a legend is drawn.
Default is `true` if there is a trace to show
and any of these: a) Two or more traces would
by default be shown in the legend. b) One pie
trace is shown in the legend. c) One trace is
explicitly given with `showlegend: true`.
sliders
A tuple of
:class:`plotly.graph_objects.layout.Slider`
instances or dicts with compatible properties
sliderdefaults
When used in a template (as
layout.template.layout.sliderdefaults), sets
the default property values to use for elements
of layout.sliders
spikedistance
Sets the default distance (in pixels) to look
for data to draw spikelines to (-1 means no
cutoff, 0 means no looking for data). As with
hoverdistance, distance does not apply to area-
like objects. In addition, some objects can be
hovered on but will not generate spikelines,
such as scatter fills.
sunburstcolorway
Sets the default sunburst slice colors.
Defaults to the main `colorway` used for trace
colors. If you specify a new list here it can
still be extended with lighter and darker
colors, see `extendsunburstcolors`.
template
Default attributes to be applied to the plot.
This should be a dict with format: `{'layout':
layoutTemplate, 'data': {trace_type:
[traceTemplate, ...], ...}}` where
`layoutTemplate` is a dict matching the
structure of `figure.layout` and
`traceTemplate` is a dict matching the
structure of the trace with type `trace_type`
(e.g. 'scatter'). Alternatively, this may be
specified as an instance of
plotly.graph_objs.layout.Template. Trace
templates are applied cyclically to traces of
each type. Container arrays (eg `annotations`)
have special handling: An object ending in
`defaults` (eg `annotationdefaults`) is applied
to each array item. But if an item has a
`templateitemname` key we look in the template
array for an item with matching `name` and
apply that instead. If no matching `name` is
found we mark the item invisible. Any named
template item not referenced is appended to the
end of the array, so this can be used to add a
watermark annotation or a logo image, for
example. To omit one of these items on the
plot, make an item with matching
`templateitemname` and `visible: false`.
ternary
:class:`plotly.graph_objects.layout.Ternary`
instance or dict with compatible properties
title
:class:`plotly.graph_objects.layout.Title`
instance or dict with compatible properties
titlefont
Deprecated: Please use layout.title.font
instead. Sets the title font. Note that the
title's font used to be customized by the now
deprecated `titlefont` attribute.
transition
Sets transition options used during
Plotly.react updates.
treemapcolorway
Sets the default treemap slice colors. Defaults
to the main `colorway` used for trace colors.
If you specify a new list here it can still be
extended with lighter and darker colors, see
`extendtreemapcolors`.
uirevision
Used to allow user interactions with the plot
to persist after `Plotly.react` calls that are
unaware of these interactions. If `uirevision`
is omitted, or if it is given and it changed
from the previous `Plotly.react` call, the
exact new figure is used. If `uirevision` is
truthy and did NOT change, any attribute that
has been affected by user interactions and did
not receive a different value in the new figure
will keep the interaction value.
`layout.uirevision` attribute serves as the
default for `uirevision` attributes in various
sub-containers. For finer control you can set
these sub-attributes directly. For example, if
your app separately controls the data on the x
and y axes you might set
`xaxis.uirevision=*time*` and
`yaxis.uirevision=*cost*`. Then if only the y
data is changed, you can update
`yaxis.uirevision=*quantity*` and the y axis
range will reset but the x axis range will
retain any user-driven zoom.
uniformtext
:class:`plotly.graph_objects.layout.Uniformtext
` instance or dict with compatible properties
updatemenus
A tuple of
:class:`plotly.graph_objects.layout.Updatemenu`
instances or dicts with compatible properties
updatemenudefaults
When used in a template (as
layout.template.layout.updatemenudefaults),
sets the default property values to use for
elements of layout.updatemenus
violingap
Sets the gap (in plot fraction) between violins
of adjacent location coordinates. Has no effect
on traces that have "width" set.
violingroupgap
Sets the gap (in plot fraction) between violins
of the same location coordinate. Has no effect
on traces that have "width" set.
violinmode
Determines how violins at the same location
coordinate are displayed on the graph. If
"group", the violins are plotted next to one
another centered around the shared location. If
"overlay", the violins are plotted over one
another, you might need to set "opacity" to see
them multiple violins. Has no effect on traces
that have "width" set.
waterfallgap
Sets the gap (in plot fraction) between bars of
adjacent location coordinates.
waterfallgroupgap
Sets the gap (in plot fraction) between bars of
the same location coordinate.
waterfallmode
Determines how bars at the same location
coordinate are displayed on the graph. With
"group", the bars are plotted next to one
another centered around the shared location.
With "overlay", the bars are plotted over one
another, you might need to an "opacity" to see
multiple bars.
width
Sets the plot's width (in px).
xaxis
:class:`plotly.graph_objects.layout.XAxis`
instance or dict with compatible properties
yaxis
:class:`plotly.graph_objects.layout.YAxis`
instance or dict with compatible properties
""",
),
**kwargs
)
| [
"[email protected]"
] | |
131d239b5a8e340e9dbe95bf2ef6172b9a91bb12 | 97ee5c0f2320aab2ca1b6ad0f18a4020dbd83d1c | /venv/Lib/site-packages/ibm_watson_machine_learning/libs/repo/swagger_client/models/error_schema_repository.py | ff5393cbefcc0d009faa312008628d9bfc6d0141 | [] | no_license | yusufcet/healty-hearts | 4d80471e82a98ea1902b00c8998faed43f99616c | a4cd429484e857b849df08d93688d35e632b3e29 | refs/heads/main | 2023-05-28T13:57:09.323953 | 2021-05-06T04:15:27 | 2021-05-06T04:15:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,486 | py | # coding: utf-8
"""
Copyright 2016 SmartBear Software
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.
Ref: https://github.com/swagger-api/swagger-codegen
"""
# (C) Copyright IBM Corp. 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.
from pprint import pformat
from six import iteritems
class ErrorSchemaRepository(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
ErrorSchemaRepository - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'trace': 'str',
'errors': 'list[ErrorRepository]'
}
self.attribute_map = {
'trace': 'trace',
'errors': 'errors'
}
self._trace = None
self._errors = None
@property
def trace(self):
"""
Gets the trace of this ErrorSchemaRepository.
:return: The trace of this ErrorSchemaRepository.
:rtype: str
"""
return self._trace
@trace.setter
def trace(self, trace):
"""
Sets the trace of this ErrorSchemaRepository.
:param trace: The trace of this ErrorSchemaRepository.
:type: str
"""
self._trace = trace
@property
def errors(self):
"""
Gets the errors of this ErrorSchemaRepository.
:return: The errors of this ErrorSchemaRepository.
:rtype: list[ErrorRepository]
"""
return self._errors
@errors.setter
def errors(self, errors):
"""
Sets the errors of this ErrorSchemaRepository.
:param errors: The errors of this ErrorSchemaRepository.
:type: list[ErrorRepository]
"""
self._errors = errors
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"[email protected]"
] | |
3e4b223cc21e71e5175421f134ba6136f711a6dd | af1a5e8245a34cb205216bc3e196045bb53f27d1 | /cottonformation/res/amazonmq.py | 4a7e5bc34197f0cfd5cbb067327746fc7a517eef | [
"BSD-2-Clause"
] | permissive | gitter-badger/cottonformation-project | b77dfca5679566fb23a63d94c0f56aebdd6f2508 | 354f1dce7ea106e209af2d5d818b6033a27c193c | refs/heads/main | 2023-06-02T05:51:51.804770 | 2021-06-27T02:52:39 | 2021-06-27T02:52:39 | 380,639,731 | 0 | 0 | BSD-2-Clause | 2021-06-27T03:08:21 | 2021-06-27T03:08:21 | null | UTF-8 | Python | false | false | 41,076 | py | # -*- coding: utf-8 -*-
"""
This module
"""
import attr
import typing
from ..core.model import (
Property, Resource, Tag, GetAtt, TypeHint, TypeCheck,
)
from ..core.constant import AttrMeta
#--- Property declaration ---
@attr.s
class BrokerLogList(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Broker.LogList"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-loglist.html
Property Document:
- ``p_Audit``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-loglist.html#cfn-amazonmq-broker-loglist-audit
- ``p_General``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-loglist.html#cfn-amazonmq-broker-loglist-general
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker.LogList"
p_Audit: bool = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(bool)),
metadata={AttrMeta.PROPERTY_NAME: "Audit"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-loglist.html#cfn-amazonmq-broker-loglist-audit"""
p_General: bool = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(bool)),
metadata={AttrMeta.PROPERTY_NAME: "General"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-loglist.html#cfn-amazonmq-broker-loglist-general"""
@attr.s
class BrokerUser(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Broker.User"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html
Property Document:
- ``rp_Password``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-password
- ``rp_Username``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-username
- ``p_ConsoleAccess``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-consoleaccess
- ``p_Groups``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-groups
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker.User"
rp_Password: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Password"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-password"""
rp_Username: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Username"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-username"""
p_ConsoleAccess: bool = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(bool)),
metadata={AttrMeta.PROPERTY_NAME: "ConsoleAccess"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-consoleaccess"""
p_Groups: typing.List[TypeHint.intrinsic_str] = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.deep_iterable(member_validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type), iterable_validator=attr.validators.instance_of(list))),
metadata={AttrMeta.PROPERTY_NAME: "Groups"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-groups"""
@attr.s
class BrokerLdapServerMetadata(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Broker.LdapServerMetadata"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html
Property Document:
- ``rp_Hosts``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-hosts
- ``rp_RoleBase``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolebase
- ``rp_RoleSearchMatching``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolesearchmatching
- ``rp_ServiceAccountPassword``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-serviceaccountpassword
- ``rp_ServiceAccountUsername``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-serviceaccountusername
- ``rp_UserBase``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-userbase
- ``rp_UserSearchMatching``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-usersearchmatching
- ``p_RoleName``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolename
- ``p_RoleSearchSubtree``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolesearchsubtree
- ``p_UserRoleName``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-userrolename
- ``p_UserSearchSubtree``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-usersearchsubtree
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker.LdapServerMetadata"
rp_Hosts: typing.List[TypeHint.intrinsic_str] = attr.ib(
default=None,
validator=attr.validators.deep_iterable(member_validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type), iterable_validator=attr.validators.instance_of(list)),
metadata={AttrMeta.PROPERTY_NAME: "Hosts"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-hosts"""
rp_RoleBase: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "RoleBase"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolebase"""
rp_RoleSearchMatching: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "RoleSearchMatching"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolesearchmatching"""
rp_ServiceAccountPassword: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "ServiceAccountPassword"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-serviceaccountpassword"""
rp_ServiceAccountUsername: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "ServiceAccountUsername"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-serviceaccountusername"""
rp_UserBase: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "UserBase"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-userbase"""
rp_UserSearchMatching: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "UserSearchMatching"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-usersearchmatching"""
p_RoleName: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(TypeCheck.intrinsic_str_type)),
metadata={AttrMeta.PROPERTY_NAME: "RoleName"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolename"""
p_RoleSearchSubtree: bool = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(bool)),
metadata={AttrMeta.PROPERTY_NAME: "RoleSearchSubtree"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-rolesearchsubtree"""
p_UserRoleName: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(TypeCheck.intrinsic_str_type)),
metadata={AttrMeta.PROPERTY_NAME: "UserRoleName"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-userrolename"""
p_UserSearchSubtree: bool = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(bool)),
metadata={AttrMeta.PROPERTY_NAME: "UserSearchSubtree"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-ldapservermetadata.html#cfn-amazonmq-broker-ldapservermetadata-usersearchsubtree"""
@attr.s
class BrokerEncryptionOptions(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Broker.EncryptionOptions"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-encryptionoptions.html
Property Document:
- ``rp_UseAwsOwnedKey``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-encryptionoptions.html#cfn-amazonmq-broker-encryptionoptions-useawsownedkey
- ``p_KmsKeyId``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-encryptionoptions.html#cfn-amazonmq-broker-encryptionoptions-kmskeyid
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker.EncryptionOptions"
rp_UseAwsOwnedKey: bool = attr.ib(
default=None,
validator=attr.validators.instance_of(bool),
metadata={AttrMeta.PROPERTY_NAME: "UseAwsOwnedKey"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-encryptionoptions.html#cfn-amazonmq-broker-encryptionoptions-useawsownedkey"""
p_KmsKeyId: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(TypeCheck.intrinsic_str_type)),
metadata={AttrMeta.PROPERTY_NAME: "KmsKeyId"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-encryptionoptions.html#cfn-amazonmq-broker-encryptionoptions-kmskeyid"""
@attr.s
class BrokerMaintenanceWindow(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Broker.MaintenanceWindow"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html
Property Document:
- ``rp_DayOfWeek``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-dayofweek
- ``rp_TimeOfDay``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-timeofday
- ``rp_TimeZone``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-timezone
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker.MaintenanceWindow"
rp_DayOfWeek: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "DayOfWeek"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-dayofweek"""
rp_TimeOfDay: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "TimeOfDay"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-timeofday"""
rp_TimeZone: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "TimeZone"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-timezone"""
@attr.s
class BrokerTagsEntry(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Broker.TagsEntry"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-tagsentry.html
Property Document:
- ``rp_Key``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-tagsentry.html#cfn-amazonmq-broker-tagsentry-key
- ``rp_Value``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-tagsentry.html#cfn-amazonmq-broker-tagsentry-value
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker.TagsEntry"
rp_Key: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Key"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-tagsentry.html#cfn-amazonmq-broker-tagsentry-key"""
rp_Value: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Value"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-tagsentry.html#cfn-amazonmq-broker-tagsentry-value"""
@attr.s
class ConfigurationTagsEntry(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Configuration.TagsEntry"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configuration-tagsentry.html
Property Document:
- ``rp_Key``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configuration-tagsentry.html#cfn-amazonmq-configuration-tagsentry-key
- ``rp_Value``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configuration-tagsentry.html#cfn-amazonmq-configuration-tagsentry-value
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Configuration.TagsEntry"
rp_Key: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Key"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configuration-tagsentry.html#cfn-amazonmq-configuration-tagsentry-key"""
rp_Value: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Value"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configuration-tagsentry.html#cfn-amazonmq-configuration-tagsentry-value"""
@attr.s
class BrokerConfigurationId(Property):
"""
AWS Object Type = "AWS::AmazonMQ::Broker.ConfigurationId"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-configurationid.html
Property Document:
- ``rp_Id``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-configurationid.html#cfn-amazonmq-broker-configurationid-id
- ``rp_Revision``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-configurationid.html#cfn-amazonmq-broker-configurationid-revision
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker.ConfigurationId"
rp_Id: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Id"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-configurationid.html#cfn-amazonmq-broker-configurationid-id"""
rp_Revision: int = attr.ib(
default=None,
validator=attr.validators.instance_of(int),
metadata={AttrMeta.PROPERTY_NAME: "Revision"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-configurationid.html#cfn-amazonmq-broker-configurationid-revision"""
@attr.s
class ConfigurationAssociationConfigurationId(Property):
"""
AWS Object Type = "AWS::AmazonMQ::ConfigurationAssociation.ConfigurationId"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configurationassociation-configurationid.html
Property Document:
- ``rp_Id``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configurationassociation-configurationid.html#cfn-amazonmq-configurationassociation-configurationid-id
- ``rp_Revision``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configurationassociation-configurationid.html#cfn-amazonmq-configurationassociation-configurationid-revision
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::ConfigurationAssociation.ConfigurationId"
rp_Id: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Id"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configurationassociation-configurationid.html#cfn-amazonmq-configurationassociation-configurationid-id"""
rp_Revision: int = attr.ib(
default=None,
validator=attr.validators.instance_of(int),
metadata={AttrMeta.PROPERTY_NAME: "Revision"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-configurationassociation-configurationid.html#cfn-amazonmq-configurationassociation-configurationid-revision"""
#--- Resource declaration ---
@attr.s
class ConfigurationAssociation(Resource):
"""
AWS Object Type = "AWS::AmazonMQ::ConfigurationAssociation"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html
Property Document:
- ``rp_Broker``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html#cfn-amazonmq-configurationassociation-broker
- ``rp_Configuration``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html#cfn-amazonmq-configurationassociation-configuration
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::ConfigurationAssociation"
rp_Broker: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Broker"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html#cfn-amazonmq-configurationassociation-broker"""
rp_Configuration: typing.Union['ConfigurationAssociationConfigurationId', dict] = attr.ib(
default=None,
converter=ConfigurationAssociationConfigurationId.from_dict,
validator=attr.validators.instance_of(ConfigurationAssociationConfigurationId),
metadata={AttrMeta.PROPERTY_NAME: "Configuration"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html#cfn-amazonmq-configurationassociation-configuration"""
@attr.s
class Configuration(Resource):
"""
AWS Object Type = "AWS::AmazonMQ::Configuration"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html
Property Document:
- ``rp_Data``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-data
- ``rp_EngineType``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-enginetype
- ``rp_EngineVersion``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-engineversion
- ``rp_Name``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-name
- ``p_AuthenticationStrategy``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-authenticationstrategy
- ``p_Description``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-description
- ``p_Tags``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-tags
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Configuration"
rp_Data: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Data"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-data"""
rp_EngineType: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "EngineType"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-enginetype"""
rp_EngineVersion: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "EngineVersion"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-engineversion"""
rp_Name: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "Name"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-name"""
p_AuthenticationStrategy: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(TypeCheck.intrinsic_str_type)),
metadata={AttrMeta.PROPERTY_NAME: "AuthenticationStrategy"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-authenticationstrategy"""
p_Description: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(TypeCheck.intrinsic_str_type)),
metadata={AttrMeta.PROPERTY_NAME: "Description"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-description"""
p_Tags: typing.List[typing.Union['ConfigurationTagsEntry', dict]] = attr.ib(
default=None,
converter=ConfigurationTagsEntry.from_list,
validator=attr.validators.optional(attr.validators.deep_iterable(member_validator=attr.validators.instance_of(ConfigurationTagsEntry), iterable_validator=attr.validators.instance_of(list))),
metadata={AttrMeta.PROPERTY_NAME: "Tags"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#cfn-amazonmq-configuration-tags"""
@property
def rv_Revision(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#aws-resource-amazonmq-configuration-return-values"""
return GetAtt(resource=self, attr_name="Revision")
@property
def rv_Id(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#aws-resource-amazonmq-configuration-return-values"""
return GetAtt(resource=self, attr_name="Id")
@property
def rv_Arn(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configuration.html#aws-resource-amazonmq-configuration-return-values"""
return GetAtt(resource=self, attr_name="Arn")
@attr.s
class Broker(Resource):
"""
AWS Object Type = "AWS::AmazonMQ::Broker"
Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html
Property Document:
- ``rp_AutoMinorVersionUpgrade``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-autominorversionupgrade
- ``rp_BrokerName``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-brokername
- ``rp_DeploymentMode``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-deploymentmode
- ``rp_EngineType``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-enginetype
- ``rp_EngineVersion``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-engineversion
- ``rp_HostInstanceType``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-hostinstancetype
- ``rp_PubliclyAccessible``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-publiclyaccessible
- ``rp_Users``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-users
- ``p_AuthenticationStrategy``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-authenticationstrategy
- ``p_Configuration``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-configuration
- ``p_EncryptionOptions``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-encryptionoptions
- ``p_LdapServerMetadata``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-ldapservermetadata
- ``p_Logs``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-logs
- ``p_MaintenanceWindowStartTime``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-maintenancewindowstarttime
- ``p_SecurityGroups``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-securitygroups
- ``p_StorageType``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-storagetype
- ``p_SubnetIds``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-subnetids
- ``p_Tags``: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-tags
"""
AWS_OBJECT_TYPE = "AWS::AmazonMQ::Broker"
rp_AutoMinorVersionUpgrade: bool = attr.ib(
default=None,
validator=attr.validators.instance_of(bool),
metadata={AttrMeta.PROPERTY_NAME: "AutoMinorVersionUpgrade"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-autominorversionupgrade"""
rp_BrokerName: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "BrokerName"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-brokername"""
rp_DeploymentMode: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "DeploymentMode"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-deploymentmode"""
rp_EngineType: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "EngineType"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-enginetype"""
rp_EngineVersion: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "EngineVersion"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-engineversion"""
rp_HostInstanceType: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type),
metadata={AttrMeta.PROPERTY_NAME: "HostInstanceType"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-hostinstancetype"""
rp_PubliclyAccessible: bool = attr.ib(
default=None,
validator=attr.validators.instance_of(bool),
metadata={AttrMeta.PROPERTY_NAME: "PubliclyAccessible"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-publiclyaccessible"""
rp_Users: typing.List[typing.Union['BrokerUser', dict]] = attr.ib(
default=None,
converter=BrokerUser.from_list,
validator=attr.validators.deep_iterable(member_validator=attr.validators.instance_of(BrokerUser), iterable_validator=attr.validators.instance_of(list)),
metadata={AttrMeta.PROPERTY_NAME: "Users"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-users"""
p_AuthenticationStrategy: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(TypeCheck.intrinsic_str_type)),
metadata={AttrMeta.PROPERTY_NAME: "AuthenticationStrategy"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-authenticationstrategy"""
p_Configuration: typing.Union['BrokerConfigurationId', dict] = attr.ib(
default=None,
converter=BrokerConfigurationId.from_dict,
validator=attr.validators.optional(attr.validators.instance_of(BrokerConfigurationId)),
metadata={AttrMeta.PROPERTY_NAME: "Configuration"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-configuration"""
p_EncryptionOptions: typing.Union['BrokerEncryptionOptions', dict] = attr.ib(
default=None,
converter=BrokerEncryptionOptions.from_dict,
validator=attr.validators.optional(attr.validators.instance_of(BrokerEncryptionOptions)),
metadata={AttrMeta.PROPERTY_NAME: "EncryptionOptions"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-encryptionoptions"""
p_LdapServerMetadata: typing.Union['BrokerLdapServerMetadata', dict] = attr.ib(
default=None,
converter=BrokerLdapServerMetadata.from_dict,
validator=attr.validators.optional(attr.validators.instance_of(BrokerLdapServerMetadata)),
metadata={AttrMeta.PROPERTY_NAME: "LdapServerMetadata"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-ldapservermetadata"""
p_Logs: typing.Union['BrokerLogList', dict] = attr.ib(
default=None,
converter=BrokerLogList.from_dict,
validator=attr.validators.optional(attr.validators.instance_of(BrokerLogList)),
metadata={AttrMeta.PROPERTY_NAME: "Logs"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-logs"""
p_MaintenanceWindowStartTime: typing.Union['BrokerMaintenanceWindow', dict] = attr.ib(
default=None,
converter=BrokerMaintenanceWindow.from_dict,
validator=attr.validators.optional(attr.validators.instance_of(BrokerMaintenanceWindow)),
metadata={AttrMeta.PROPERTY_NAME: "MaintenanceWindowStartTime"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-maintenancewindowstarttime"""
p_SecurityGroups: typing.List[TypeHint.intrinsic_str] = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.deep_iterable(member_validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type), iterable_validator=attr.validators.instance_of(list))),
metadata={AttrMeta.PROPERTY_NAME: "SecurityGroups"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-securitygroups"""
p_StorageType: TypeHint.intrinsic_str = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(TypeCheck.intrinsic_str_type)),
metadata={AttrMeta.PROPERTY_NAME: "StorageType"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-storagetype"""
p_SubnetIds: typing.List[TypeHint.intrinsic_str] = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.deep_iterable(member_validator=attr.validators.instance_of(TypeCheck.intrinsic_str_type), iterable_validator=attr.validators.instance_of(list))),
metadata={AttrMeta.PROPERTY_NAME: "SubnetIds"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-subnetids"""
p_Tags: typing.List[typing.Union['BrokerTagsEntry', dict]] = attr.ib(
default=None,
converter=BrokerTagsEntry.from_list,
validator=attr.validators.optional(attr.validators.deep_iterable(member_validator=attr.validators.instance_of(BrokerTagsEntry), iterable_validator=attr.validators.instance_of(list))),
metadata={AttrMeta.PROPERTY_NAME: "Tags"},
)
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-tags"""
@property
def rv_IpAddresses(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="IpAddresses")
@property
def rv_OpenWireEndpoints(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="OpenWireEndpoints")
@property
def rv_ConfigurationRevision(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="ConfigurationRevision")
@property
def rv_StompEndpoints(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="StompEndpoints")
@property
def rv_MqttEndpoints(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="MqttEndpoints")
@property
def rv_AmqpEndpoints(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="AmqpEndpoints")
@property
def rv_Arn(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="Arn")
@property
def rv_ConfigurationId(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="ConfigurationId")
@property
def rv_WssEndpoints(self) -> GetAtt:
"""Doc: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#aws-resource-amazonmq-broker-return-values"""
return GetAtt(resource=self, attr_name="WssEndpoints")
| [
"[email protected]"
] | |
1eaf0839de9bc5dadf576355771ad319fe60ef55 | 2f330fc050de11676ab46b963b7878882e9b6614 | /test/test_conversations_api.py | 57e18e0156fc8c9ab6b181d2209168880857eefa | [
"Apache-2.0"
] | permissive | zerodayz/memsource-cli-client | 609f48c18a2b6daaa639d4cb8a61da43763b5143 | c2574f1467539a49e6637c874e88d75c7ef789b3 | refs/heads/master | 2020-08-01T12:43:06.497982 | 2019-09-30T11:14:13 | 2019-09-30T11:14:13 | 210,999,654 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,966 | py | # coding: utf-8
"""
Memsource REST API
Welcome to Memsource's API documentation. To view our legacy APIs please [visit our documentation](https://wiki.memsource.com/wiki/Memsource_API) and for more information about our new APIs, [visit our blog](https://www.memsource.com/blog/2017/10/24/introducing-rest-apis-qa-with-the-memsource-api-team/). If you have any questions, please contact [Memsource Support](<mailto:[email protected]>). # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import memsource_cli
from memsource_cli.api.conversations_api import ConversationsApi # noqa: E501
from memsource_cli.rest import ApiException
class TestConversationsApi(unittest.TestCase):
"""ConversationsApi unit test stubs"""
def setUp(self):
self.api = memsource_cli.api.conversations_api.ConversationsApi() # noqa: E501
def tearDown(self):
pass
def test_add_lqa_comment(self):
"""Test case for add_lqa_comment
Add LQA comment # noqa: E501
"""
pass
def test_add_plain_comment(self):
"""Test case for add_plain_comment
Add plain comment # noqa: E501
"""
pass
def test_create_lqa_conversation(self):
"""Test case for create_lqa_conversation
Create LQA conversation # noqa: E501
"""
pass
def test_create_segment_target_conversation(self):
"""Test case for create_segment_target_conversation
Create plain conversation # noqa: E501
"""
pass
def test_delete_lqa_comment(self):
"""Test case for delete_lqa_comment
Delete LQA comment # noqa: E501
"""
pass
def test_delete_lqa_conversation(self):
"""Test case for delete_lqa_conversation
Delete conversation # noqa: E501
"""
pass
def test_delete_plain_comment(self):
"""Test case for delete_plain_comment
Delete plain comment # noqa: E501
"""
pass
def test_delete_plain_conversation(self):
"""Test case for delete_plain_conversation
Delete plain conversation # noqa: E501
"""
pass
def test_find_conversations(self):
"""Test case for find_conversations
Find all conversation # noqa: E501
"""
pass
def test_get_lqa_conversation(self):
"""Test case for get_lqa_conversation
Get LQA conversation # noqa: E501
"""
pass
def test_get_plain_conversation(self):
"""Test case for get_plain_conversation
Get plain conversation # noqa: E501
"""
pass
def test_list_all_conversations(self):
"""Test case for list_all_conversations
List all conversations # noqa: E501
"""
pass
def test_list_lqa_conversations(self):
"""Test case for list_lqa_conversations
List LQA conversations # noqa: E501
"""
pass
def test_list_plain_conversations(self):
"""Test case for list_plain_conversations
List plain conversations # noqa: E501
"""
pass
def test_update_lqa_comment(self):
"""Test case for update_lqa_comment
Edit LQA comment # noqa: E501
"""
pass
def test_update_lqa_conversation(self):
"""Test case for update_lqa_conversation
Edit LQA conversation # noqa: E501
"""
pass
def test_update_plain_comment(self):
"""Test case for update_plain_comment
Edit plain comment # noqa: E501
"""
pass
def test_update_plain_conversation(self):
"""Test case for update_plain_conversation
Edit plain conversation # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
6d72846e5637395a9e8186735df19ecf8593262c | 6d24a0820a2e1227e8caff083a8fef4f6f207c6f | /django_test8remotedb/django_test8remotedb/wsgi.py | e1c3c34a28f8e9da506e1712d7ee44b07b95f92e | [] | no_license | pyh3887/Django | 45d4b3be955634edba924cc18bbc8d3454c7355b | a44e1067494391ff4a7473aeaeb63bbeba43b3d8 | refs/heads/master | 2022-11-08T08:36:04.750050 | 2020-06-28T14:00:53 | 2020-06-28T14:00:53 | 275,596,275 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 417 | py | """
WSGI config for django_test8remotedb project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_test8remotedb.settings')
application = get_wsgi_application()
| [
"[email protected]"
] | |
c22e5285f55b9a024db9c6a181f7be86ac4aa38d | d0fcc2198f1caf5633c4fc0d004ba68714396f1b | /bc4py/__init__.py | e4f948768169653f959d63eacfa2036467347985 | [
"MIT"
] | permissive | webclinic017/bc4py | 4bfce04b666c2aaadda4b7ecc2a8270839231850 | 620b7d855ec957b3e2b4021cf8069d9dd128587a | refs/heads/master | 2022-12-09T22:23:49.842255 | 2019-06-21T14:24:17 | 2019-06-21T14:24:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 648 | py | __version__ = '0.0.27-alpha'
__chain_version__ = 0
__block_version__ = 1
__message__ = 'This is alpha version - use at your own risk, do not use for merchant applications'
__logo__ = r"""
_____ _____ _ _
| __ \ / ____| | | | |
| |__) | _ | | ___ _ __ | |_ _ __ __ _ ___| |_
| ___/ | | | | | / _ \| '_ \| __| '__/ _` |/ __| __|
| | | |_| | | |___| (_) | | | | |_| | | (_| | (__| |_
|_| \__, | \_____\___/|_| |_|\__|_| \__,_|\___|\__|
__/ |
|___/
"""
| [
"[email protected]"
] | |
4d7c7bef47a7b0a60f1eb495d804d2eb2c8ade27 | 93022749a35320a0c5d6dad4db476b1e1795e318 | /issm/bamgmesh.py | a74e7b1994e1ba700f8cf936b7d747286f4f44d7 | [
"BSD-3-Clause"
] | permissive | pf4d/issm_python | 78cd88e9ef525bc74e040c1484aaf02e46c97a5b | 6bf36016cb0c55aee9bf3f7cf59694cc5ce77091 | refs/heads/master | 2022-01-17T16:20:20.257966 | 2019-07-10T17:46:31 | 2019-07-10T17:46:31 | 105,887,661 | 2 | 3 | null | null | null | null | UTF-8 | Python | false | false | 2,051 | py | import numpy as np
class bamgmesh(object):
"""
BAMGMESH class definition
Usage:
bamgmesh(varargin)
"""
def __init__(self,*args): # {{{
self.Vertices=np.empty((0,3))
self.Edges=np.empty((0,3))
self.Triangles=np.empty((0,0))
self.IssmEdges=np.empty((0,0))
self.IssmSegments=np.empty((0,0))
self.VerticesOnGeomVertex=np.empty((0,0))
self.VerticesOnGeomEdge=np.empty((0,0))
self.EdgesOnGeomEdge=np.empty((0,0))
self.SubDomains=np.empty((0,4))
self.SubDomainsFromGeom=np.empty((0,0))
self.ElementConnectivity=np.empty((0,0))
self.NodalConnectivity=np.empty((0,0))
self.NodalElementConnectivity=np.empty((0,0))
self.CrackedVertices=np.empty((0,0))
self.CrackedEdges=np.empty((0,0))
if not len(args):
# if no input arguments, create a default object
pass
elif len(args) == 1:
object=args[0]
for field in object.iterkeys():
if field in vars(self):
setattr(self,field,object[field])
else:
raise TypeError("bamgmesh constructor error message: unknown type of constructor call")
# }}}
def __repr__(self): # {{{
s ="class '%s' object '%s' = \n" % (type(self),'self')
s+=" Vertices: %s\n" % str(self.Vertices)
s+=" Edges: %s\n" % str(self.Edges)
s+=" Triangles: %s\n" % str(self.Triangles)
s+=" IssmEdges: %s\n" % str(self.IssmEdges)
s+=" IssmSegments: %s\n" % str(self.IssmSegments)
s+=" VerticesOnGeomVertex: %s\n" % str(self.VerticesOnGeomVertex)
s+=" VerticesOnGeomEdge: %s\n" % str(self.VerticesOnGeomEdge)
s+=" EdgesOnGeomEdge: %s\n" % str(self.EdgesOnGeomEdge)
s+=" SubDomains: %s\n" % str(self.SubDomains)
s+=" SubDomainsFromGeom: %s\n" % str(self.SubDomainsFromGeom)
s+=" ElementConnectivity: %s\n" % str(self.ElementConnectivity)
s+=" NodalConnectivity: %s\n" % str(self.NodalConnectivity)
s+=" NodalElementConnectivity: %s\n" % str(self.NodalElementConnectivity)
s+=" CrackedVertices: %s\n" % str(self.CrackedVertices)
s+=" CrackedEdges: %s\n" % str(self.CrackedEdges)
return s
# }}}
| [
"[email protected]"
] | |
28d0aafa50a59f4ae999a524de929130e15508da | 7b82b6189e0e5ebeb5cc84e22d87edecc3cb38ba | /charlies_revenge/lib/python2.7/UserDict.py | 335a99e253d13a9929832dbb451f80ab47b57b78 | [
"BSD-2-Clause"
] | permissive | rv816/omop_harvest | 6ef52f44e8196e52815774737274de8871826784 | 629b69559bb04d495b4499e0d277d7deeb849b79 | refs/heads/master | 2021-01-15T13:19:53.542160 | 2014-12-04T16:08:44 | 2014-12-04T16:08:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 47 | py | /Users/vassr/anaconda/lib/python2.7/UserDict.py | [
"[email protected]"
] | |
2aeb9fcb51b0105557890554d8ed3a4f83d5f27c | d489eb7998aa09e17ce8d8aef085a65f799e6a02 | /lib/modules/powershell/management/get_domain_sid.py | 61786bf029320aa283e34ee9af48782232a1b12b | [
"MIT"
] | permissive | fengjixuchui/invader | d36078bbef3d740f95930d9896b2d7dd7227474c | 68153dafbe25e7bb821c8545952d0cc15ae35a3e | refs/heads/master | 2020-07-21T19:45:10.479388 | 2019-09-26T11:32:38 | 2019-09-26T11:32:38 | 206,958,809 | 2 | 1 | MIT | 2019-09-26T11:32:39 | 2019-09-07T11:32:17 | PowerShell | UTF-8 | Python | false | false | 2,979 | py | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Get-DomainSID',
'Author': ['@harmj0y'],
'Description': ('Returns the SID for the current of specified domain.'),
'Background' : True,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : True,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [ ]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
},
'Domain' : {
'Description' : 'Domain to resolve SID for, defaults to the current domain.',
'Required' : False,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self, obfuscate=False, obfuscationCommand=""):
moduleName = self.info["Name"]
# read in the common powerview.ps1 module source code
moduleSource = self.mainMenu.installPath + "/data/module_source/situational_awareness/network/powerview.ps1"
try:
f = open(moduleSource, 'r')
except:
print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
return ""
moduleCode = f.read()
f.close()
# get just the code needed for the specified function
script = helpers.generate_dynamic_powershell_script(moduleCode, moduleName)
script += moduleName + " "
scriptEnd = ""
for option,values in self.options.iteritems():
if option.lower() != "agent":
if values['Value'] and values['Value'] != '':
if values['Value'].lower() == "true":
# if we're just adding a switch
scriptEnd += " -" + str(option)
else:
scriptEnd += " -" + str(option) + " " + str(values['Value'])
scriptEnd += ' | Out-String | %{$_ + \"`n\"};"`n'+str(moduleName)+' completed!"'
if obfuscate:
script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand)
return script
| [
"[email protected]"
] | |
d6cd273dd70bb1adf7a00656ce07e3a7d18afb1e | ebae416013607b045b505dbb0b5598c9e732dcf4 | /2b Rozmienianie monet.py | fc4f0377b9bf95a51b48d6343a5b1bcf82548afb | [] | no_license | Ernest93/Ernest93 | 08bbadc067e9ef277bad5f0922ca89a8ae298fb8 | 7570ccf18631c5e88bd38c0498d7c9348e81dd7b | refs/heads/master | 2020-04-06T15:24:56.128434 | 2018-12-10T16:21:06 | 2018-12-10T16:21:06 | 157,577,667 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 285 | py | """
2) Program przyjmuje kwotę w parametrze i wylicza jak rozmienić to na monety: 5, 2, 1, 0.5, 0.2, 0.1 wydając ich jak najmniej.
"""
moneta5 = 5
moneta2 = 2
moneta1 = 1
moneta50 = 0.50
moneta20 = 0.20
moneta10 = 0.10
kwota = input("Podaj kwotę do wymiany na drobne: ")
if kwota | [
"[email protected]"
] | |
3bd394ba3bd4bde21e3af8745d23d7012a1674fa | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/88/usersdata/216/59764/submittedfiles/listas.py | 59dcb46254afeaa8ea7c2cfa8c36ed1c7c2a8dfa | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 646 | py | # -*- coding: utf-8 -*-
def degrau(a):
for i in range(0,len(a)-1,1):
menos=0
l=[]
if a[i]<0:
a[i]=a[i]*(-1)
menos=menos+(a[i]-a[i+1])
l.append(menos)
if a[i]>=0:
menos=menos+(a[i]-a[i+1])
l.append(menos)
return(l)
l=degrau(a)
def maior(l):
for i in range(0,len(l)-1,1):
maior=0
if l[i]>l[i+1]:
maior=a[i]
return(a[i])
a=[]
n=int(input('Digite o tamanho da lista:'))
for i in range(0,n,1):
x=int(input('Digite o numero:'))
a.append(x)
print (maior(l))
| [
"[email protected]"
] | |
0ea486071cf97380f79f7282e57c31033c2db52a | e573161a9d4fc74ef4debdd9cfd8956bdd1d0416 | /src/products/migrations/0001_initial.py | c5e75cc6b8ce4aa5d27f37b4086623b92994f43b | [] | no_license | tanjibpa/rx-verify | a11c471afc628524bf95103711102258e6e04c19 | 3947fd2f9a640b422014d1857b9377e42d8961a5 | refs/heads/main | 2023-02-23T08:16:43.910998 | 2021-01-23T07:07:43 | 2021-01-23T07:07:43 | 331,103,311 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,357 | py | # Generated by Django 3.1.5 on 2021-01-21 05:22
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', django.contrib.postgres.fields.jsonb.JSONField(default=dict)),
('updated_by', django.contrib.postgres.fields.jsonb.JSONField(default=dict)),
('name', models.CharField(max_length=100)),
('mfg_date', models.DateField()),
('expiration_date', models.DateField()),
],
options={
'verbose_name': 'Product',
'verbose_name_plural': 'Products',
'db_table': 'products',
'ordering': ['-updated_at'],
},
),
migrations.CreateModel(
name='RawMaterial',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', django.contrib.postgres.fields.jsonb.JSONField(default=dict)),
('updated_by', django.contrib.postgres.fields.jsonb.JSONField(default=dict)),
('name', models.CharField(max_length=100)),
],
options={
'verbose_name': 'Raw Material',
'verbose_name_plural': 'Raw Materials',
'db_table': 'raw_materials',
'ordering': ['-updated_at'],
},
),
migrations.CreateModel(
name='ProductBatch',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', django.contrib.postgres.fields.jsonb.JSONField(default=dict)),
('updated_by', django.contrib.postgres.fields.jsonb.JSONField(default=dict)),
('batch_number', models.UUIDField(default=uuid.uuid4, editable=False)),
('mfg_date', models.DateField()),
('expiration_date', models.DateField()),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.product')),
],
options={
'verbose_name': 'Product Batch',
'verbose_name_plural': 'Product Batches',
'db_table': 'product_batches',
'ordering': ['-updated_at'],
},
),
migrations.AddField(
model_name='product',
name='raw_materials',
field=models.ManyToManyField(to='products.RawMaterial'),
),
]
| [
"[email protected]"
] | |
9e1a9f7e8ff63503ca25b48244d1b4f4cc6212e7 | cc9a0d5608b2209b02591ceace0a7416823a9de5 | /hyk/users/urls.py | 752239befcc25821e106299311f9a488a257c93b | [
"MIT"
] | permissive | morwen1/hack_your_body | 240838e75dd4447c944d47d37635d2064d4210fd | d4156d4fbe2dd4123d5b5bceef451803a50a39f8 | refs/heads/master | 2020-11-24T01:55:46.323849 | 2019-12-15T18:15:51 | 2019-12-15T18:15:51 | 226,505,010 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 403 | py | #django
from django.urls import path , include
#rest_framework
from rest_framework.routers import SimpleRouter
#views
from hyk.users.views import UserViewset ,ProfileViewset
router = SimpleRouter()
router.register(r'' , UserViewset , basename='users_urls')
router.register(r'profile', ProfileViewset , basename='profile_update')
app_name = "users"
urlpatterns = [
path('' , include(router.urls))
]
| [
"[email protected]"
] | |
25a5631cbd7c7365beaf481e7e89807d81afbfe9 | ca4fff998b3a345595adfc8a33fb273f2ac10a58 | /tensorflow/python/keras/layers/preprocessing/text_vectorization_distribution_test.py | ebf68e3bce2897f82a7bef4c73b6900c69018e69 | [
"Apache-2.0"
] | permissive | yair-ehrenwald/tensorflow | d485cef7847ab027639550fe2b19fd7521ea640e | eaceb03d7f5ec31c0d27c464f17ae003027980ca | refs/heads/master | 2023-05-04T19:43:16.142132 | 2021-03-21T06:10:13 | 2021-03-21T06:16:59 | 287,766,702 | 2 | 0 | Apache-2.0 | 2020-08-15T14:51:47 | 2020-08-15T14:51:46 | null | UTF-8 | Python | false | false | 3,914 | py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Distribution tests for keras.layers.preprocessing.text_vectorization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import combinations as ds_combinations
from tensorflow.python.framework import config
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_combinations as combinations
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras.distribute.strategy_combinations import all_strategies
from tensorflow.python.keras.layers.preprocessing import preprocessing_test_utils
from tensorflow.python.keras.layers.preprocessing import text_vectorization
from tensorflow.python.platform import test
@ds_combinations.generate(
combinations.combine(distribution=all_strategies, mode=["eager"]))
class TextVectorizationDistributionTest(
keras_parameterized.TestCase,
preprocessing_test_utils.PreprocessingLayerTest):
def test_distribution_strategy_output(self, distribution):
vocab_data = ["earth", "wind", "and", "fire"]
input_array = np.array([["earth", "wind", "and", "fire"],
["fire", "and", "earth", "michigan"]])
input_dataset = dataset_ops.Dataset.from_tensor_slices(input_array).batch(
2, drop_remainder=True)
expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]
config.set_soft_device_placement(True)
with distribution.scope():
input_data = keras.Input(shape=(None,), dtype=dtypes.string)
layer = text_vectorization.TextVectorization(
max_tokens=None,
standardize=None,
split=None,
output_mode=text_vectorization.INT)
layer.set_vocabulary(vocab_data)
int_data = layer(input_data)
model = keras.Model(inputs=input_data, outputs=int_data)
output_dataset = model.predict(input_dataset)
self.assertAllEqual(expected_output, output_dataset)
def test_distribution_strategy_output_with_adapt(self, distribution):
vocab_data = [[
"earth", "earth", "earth", "earth", "wind", "wind", "wind", "and",
"and", "fire"
]]
vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)
input_array = np.array([["earth", "wind", "and", "fire"],
["fire", "and", "earth", "michigan"]])
input_dataset = dataset_ops.Dataset.from_tensor_slices(input_array).batch(
2, drop_remainder=True)
expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]
config.set_soft_device_placement(True)
with distribution.scope():
input_data = keras.Input(shape=(None,), dtype=dtypes.string)
layer = text_vectorization.TextVectorization(
max_tokens=None,
standardize=None,
split=None,
output_mode=text_vectorization.INT)
layer.adapt(vocab_dataset)
int_data = layer(input_data)
model = keras.Model(inputs=input_data, outputs=int_data)
output_dataset = model.predict(input_dataset)
self.assertAllEqual(expected_output, output_dataset)
if __name__ == "__main__":
test.main()
| [
"[email protected]"
] | |
895e18e52390f46b88c59c8e8bb946d861c58834 | 6237a1d1aa61be65f1a71bb645ec6d8689f24715 | /PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/jedi/api/helpers.py | 77fc7827a66f2f8eac56ccec40c4e65833df446f | [] | no_license | Tkizzy/PythonistaAppTemplate | cf8485dc8e9e45c65af624916d71b38e2e11ce56 | f196581cfee4a1c10168892a20ddcf16270c91b0 | refs/heads/master | 2021-01-16T00:17:04.628848 | 2016-03-13T08:15:35 | 2016-03-13T08:15:35 | 52,062,119 | 1 | 0 | null | 2016-02-19T04:48:36 | 2016-02-19T04:48:35 | null | UTF-8 | Python | false | false | 2,568 | py |
"""
Helpers for the API
"""
import re
from jedi.parser import tree as pt
from jedi.evaluate import imports
def completion_parts(path_until_cursor):
"""
Returns the parts for the completion
:return: tuple - (path, dot, like)
"""
match = re.match(r'^(.*?)(\.|)(\w?[\w\d]*)$', path_until_cursor, flags=re.S)
return match.groups()
def sorted_definitions(defs):
# Note: `or ''` below is required because `module_path` could be
return sorted(defs, key=lambda x: (x.module_path or '', x.line or 0, x.column or 0))
def get_on_import_stmt(evaluator, user_context, user_stmt, is_like_search=False):
"""
Resolve the user statement, if it is an import. Only resolve the
parts until the user position.
"""
name = user_stmt.name_for_position(user_context.position)
if name is None:
return None, None
i = imports.ImportWrapper(evaluator, name)
return i, name
def check_error_statements(module, pos):
for error_statement in module.error_statement_stacks:
if error_statement.first_type in ('import_from', 'import_name') \
and error_statement.first_pos < pos <= error_statement.next_start_pos:
return importer_from_error_statement(error_statement, pos)
return None, 0, False, False
def importer_from_error_statement(error_statement, pos):
def check_dotted(children):
for name in children[::2]:
if name.start_pos <= pos:
yield name
names = []
level = 0
only_modules = True
unfinished_dotted = False
for typ, nodes in error_statement.stack:
if typ == 'dotted_name':
names += check_dotted(nodes)
if nodes[-1] == '.':
# An unfinished dotted_name
unfinished_dotted = True
elif typ == 'import_name':
if nodes[0].start_pos <= pos <= nodes[0].end_pos:
# We are on the import.
return None, 0, False, False
elif typ == 'import_from':
for node in nodes:
if node.start_pos >= pos:
break
elif isinstance(node, pt.Node) and node.type == 'dotted_name':
names += check_dotted(node.children)
elif node in ('.', '...'):
level += len(node.value)
elif isinstance(node, pt.Name):
names.append(node)
elif node == 'import':
only_modules = False
return names, level, only_modules, unfinished_dotted
| [
"[email protected]"
] | |
926040ad10f55d950cc51d7ce892409565567b4a | 7585016de4256206dbc3219248f1a266e2b853a4 | /tests/processes/test_convert.py | f79352d7a5104c20ed6cd3619216cb74b242ff93 | [
"Apache-2.0"
] | permissive | pedringcoding/weaver | fe7db0d75dafaff9c677f458b57f0230af25c441 | 691c8b820c24b53d6a4a86a421477b611206bef1 | refs/heads/master | 2023-07-13T21:42:48.574816 | 2021-05-25T21:59:10 | 2021-05-25T21:59:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,461 | py | """
Unit tests of functions within :mod:`weaver.processes.convert`.
"""
from copy import deepcopy
import pytest
from pywps.inout.formats import Format
from pywps.inout.inputs import LiteralInput
from pywps.inout.literaltypes import AllowedValue, AnyValue
from pywps.validator.mode import MODE
from weaver.exceptions import PackageTypeError
from weaver.formats import CONTENT_TYPE_APP_JSON, CONTENT_TYPE_APP_NETCDF, CONTENT_TYPE_APP_XML, CONTENT_TYPE_TEXT_PLAIN
from weaver.processes.constants import WPS_INPUT, WPS_LITERAL
from weaver.processes.convert import _are_different_and_set # noqa: W0212
from weaver.processes.convert import (
DEFAULT_FORMAT,
PACKAGE_ARRAY_MAX_SIZE,
cwl2wps_io,
is_cwl_array_type,
is_cwl_enum_type,
is_cwl_file_type,
json2wps_datatype,
merge_io_formats
)
from weaver.utils import null
class ObjectWithEqProperty(object):
"""Dummy object for some test evaluations."""
_prop = "prop"
def __init__(self, prop="prop"):
self._prop = prop
@property
def some_property(self):
return self._prop
def __eq__(self, other):
return self.some_property == other.some_property
def test_are_different_and_set_both_set():
assert _are_different_and_set(1, 2) is True
assert _are_different_and_set(1, 1) is False
assert _are_different_and_set({"a": 1}, {"a": 2}) is True
assert _are_different_and_set({"a": 1}, {"a": 1}) is False
assert _are_different_and_set({"a": 1, "b": 2}, {"a": 1}) is True
assert _are_different_and_set(ObjectWithEqProperty(), ObjectWithEqProperty()) is False
assert _are_different_and_set(ObjectWithEqProperty("a"), ObjectWithEqProperty("b")) is True
def test_are_different_and_set_similar_str_formats():
assert _are_different_and_set(b"something", u"something") is False
assert _are_different_and_set(u"something", u"something") is False
assert _are_different_and_set(b"something", b"something") is False
assert _are_different_and_set(b"something", u"else") is True
assert _are_different_and_set(u"something", u"else") is True
assert _are_different_and_set(b"something", b"else") is True
def test_are_different_and_set_both_null():
assert _are_different_and_set(null, null) is False
def test_are_different_and_set_single_null():
"""
Tests that equality check is correctly handled when a single item amongst the two is ``null``.
This was identified as problematic is case when the checked and set item implements ``__eq__`` and expects a
property to exist, which is not the case for the second item being ``null``.
"""
item = ObjectWithEqProperty()
assert _are_different_and_set(item, null) is False
assert _are_different_and_set(null, item) is False
def test_json2wps_datatype():
test_cases = [
("float", {"type": WPS_LITERAL, "data_type": "float"}), # noqa: E241
("integer", {"type": WPS_LITERAL, "data_type": "integer"}), # noqa: E241
("integer", {"type": WPS_LITERAL, "data_type": "int"}), # noqa: E241
("boolean", {"type": WPS_LITERAL, "data_type": "boolean"}), # noqa: E241
("boolean", {"type": WPS_LITERAL, "data_type": "bool"}), # noqa: E241
("string", {"type": WPS_LITERAL, "data_type": "string"}), # noqa: E241
("float", {"type": WPS_LITERAL, "default": 1.0}), # noqa: E241
("integer", {"type": WPS_LITERAL, "default": 1}), # noqa: E241
("boolean", {"type": WPS_LITERAL, "default": True}), # noqa: E241
("string", {"type": WPS_LITERAL, "default": "1"}), # noqa: E241
("float", {"type": WPS_LITERAL, "supported_values": [1.0, 2.0]}), # noqa: E241
("integer", {"type": WPS_LITERAL, "supported_values": [1, 2]}), # noqa: E241
("boolean", {"type": WPS_LITERAL, "supported_values": [True, False]}), # noqa: E241
("string", {"type": WPS_LITERAL, "supported_values": ["yes", "no"]}), # noqa: E241
("float", {"data_type": "float"}), # noqa: E241
("integer", {"data_type": "integer"}), # noqa: E241
("integer", {"data_type": "int"}), # noqa: E241
("boolean", {"data_type": "boolean"}), # noqa: E241
("boolean", {"data_type": "bool"}), # noqa: E241
("string", {"data_type": "string"}), # noqa: E241
]
for expect, test_io in test_cases:
copy_io = deepcopy(test_io) # can get modified by function
assert json2wps_datatype(test_io) == expect, "Failed for [{}]".format(copy_io)
def test_cwl2wps_io_null_or_array_of_enums():
"""
I/O `CWL` with ``["null", "<enum-type>", "<array-enum-type>]`` must be parsed as `WPS` with
parameters ``minOccurs=0``, ``maxOccurs>1`` and ``allowedValues`` as restricted set of values.
"""
allowed_values = ["A", "B", "C"]
io_info = {
"name": "test",
"type": [
"null", # minOccurs=0
{"type": "enum", "symbols": allowed_values}, # if maxOccurs=1, only this variant would be provided
{"type": "array", "items": {"type": "enum", "symbols": allowed_values}}, # but also this for maxOccurs>1
],
}
wps_io = cwl2wps_io(io_info, WPS_INPUT)
assert isinstance(wps_io, LiteralInput)
assert wps_io.min_occurs == 0
assert wps_io.max_occurs == PACKAGE_ARRAY_MAX_SIZE
assert wps_io.data_type == "string"
assert wps_io.allowed_values == [AllowedValue(value=val) for val in allowed_values]
def test_cwl2wps_io_raise_mixed_types():
io_type1 = ["string", "int"]
io_type2 = [
"int",
{"type": "array", "items": "string"}
]
io_type3 = [
{"type": "enum", "symbols": ["1", "2"]}, # symbols as literal strings != int literal
"null",
"int"
]
io_type4 = [
"null",
{"type": "enum", "symbols": ["1", "2"]}, # symbols as literal strings != int items
{"type": "array", "items": "int"}
]
for i, test_type in enumerate([io_type1, io_type2, io_type3, io_type4]):
io_info = {"name": "test-{}".format(i), "type": test_type}
with pytest.raises(PackageTypeError):
cwl2wps_io(io_info, WPS_INPUT)
def testis_cwl_array_type_explicit_invalid_item():
io_info = {
"name": "test",
"type": {
"type": "array",
"items": "unknown-type-item"
}
}
with pytest.raises(PackageTypeError):
is_cwl_array_type(io_info)
def testis_cwl_array_type_shorthand_invalid_item():
"""
In case of shorthand syntax, because type is only a string, it shouldn't raise.
Type is returned as is and value validation is left to later calls.
"""
io_info = {
"name": "test",
"type": "unknown[]"
}
try:
res = is_cwl_array_type(io_info)
assert res[0] is False
assert res[1] == "unknown[]"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
except PackageTypeError:
pytest.fail("should not raise an error in this case")
def testis_cwl_array_type_not_array():
io_info = {
"name": "test",
"type": "float",
}
res = is_cwl_array_type(io_info)
assert res[0] is False
assert res[1] == "float"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_simple_enum():
io_info = {
"name": "test",
"type": "enum",
"symbols": ["a", "b", "c"]
}
res = is_cwl_array_type(io_info)
assert res[0] is False
assert res[1] == "enum"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_explicit_base():
io_info = {
"name": "test",
"type": {
"type": "array",
"items": "string"
}
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_explicit_enum():
io_info = {
"name": "test",
"type": {
"type": "array",
"items": {
"type": "enum",
"symbols": ["a", "b", "c"]
}
}
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.SIMPLE
assert res[3] == ["a", "b", "c"]
def testis_cwl_array_type_shorthand_base():
io_info = {
"name": "test",
"type": "string[]",
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_shorthand_enum():
io_info = {
"name": "test",
"type": "enum[]",
"symbols": ["a", "b", "c"]
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.SIMPLE
assert res[3] == ["a", "b", "c"]
def testis_cwl_array_type_explicit_optional_not_array():
io_info = {
"name": "test",
"type": ["null", "float"],
}
res = is_cwl_array_type(io_info)
assert res[0] is False
assert res[1] == "float"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_explicit_optional_simple_enum():
io_info = {
"name": "test",
"type": ["null", "enum"],
"symbols": ["a", "b", "c"]
}
res = is_cwl_array_type(io_info)
assert res[0] is False
assert res[1] == "enum"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_explicit_optional_explicit_base():
io_info = {
"name": "test",
"type": [
"null",
{"type": "array", "items": "string"}
]
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_explicit_optional_explicit_enum():
io_info = {
"name": "test",
"type": [
"null",
{
"type": "array",
"items": {
"type": "enum",
"symbols": ["a", "b", "c"]
}
}
]
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.SIMPLE
assert res[3] == ["a", "b", "c"]
def testis_cwl_array_type_explicit_optional_shorthand_base():
io_info = {
"name": "test",
"type": ["null", "string[]"]
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.NONE
assert res[3] == AnyValue
def testis_cwl_array_type_explicit_optional_shorthand_enum():
io_info = {
"name": "test",
"type": ["null", "enum[]"],
"symbols": ["a", "b", "c"]
}
res = is_cwl_array_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.SIMPLE
assert res[3] == ["a", "b", "c"]
def testis_cwl_enum_type_string():
io_info = {
"name": "test",
"type": {
"type": "enum",
"symbols": ["a", "b", "c"]
}
}
res = is_cwl_enum_type(io_info)
assert res[0] is True
assert res[1] == "string"
assert res[2] == MODE.SIMPLE
assert res[3] == ["a", "b", "c"]
def testis_cwl_enum_type_float():
io_info = {
"name": "test",
"type": {
"type": "enum",
"symbols": [1.9, 2.8, 3.7]
}
}
res = is_cwl_enum_type(io_info)
assert res[0] is True
assert res[1] == "float"
assert res[2] == MODE.SIMPLE
assert res[3] == [1.9, 2.8, 3.7]
def testis_cwl_enum_type_int():
io_info = {
"name": "test",
"type": {
"type": "enum",
"symbols": [1, 2, 3]
}
}
res = is_cwl_enum_type(io_info)
assert res[0] is True
assert res[1] == "int"
assert res[2] == MODE.SIMPLE
assert res[3] == [1, 2, 3]
def test_is_cwl_file_type_guaranteed_file():
io_info = {
"name": "test",
"type": "File"
}
assert is_cwl_file_type(io_info)
def test_is_cwl_file_type_potential_file():
io_info = {
"name": "test",
"type": ["null", "File"]
}
assert is_cwl_file_type(io_info)
def test_is_cwl_file_type_file_array():
io_info = {
"name": "test",
"type": {"type": "array", "items": "File"}
}
assert is_cwl_file_type(io_info)
def test_is_cwl_file_type_none_one_or_many_files():
io_info = {
"name": "test",
"type": [
"null",
"File",
{"type": "array", "items": "File"}
]
}
assert is_cwl_file_type(io_info)
def test_is_cwl_file_type_not_files():
test_types = [
"int",
"string",
"float",
["null", "string"],
{"type": "enum", "symbols": [1, 2]},
{"type": "enum", "symbols": ["A", "B"]},
{"type": "array", "items": "string"},
{"type": "array", "items": "int"},
["null", {"type": "array", "items": "string"}],
]
for i, io_type in enumerate(test_types):
io_info = {"name": "test-{}".format(i), "type": io_type}
assert not is_cwl_file_type(io_info), "Test [{}]: {}".format(i, io_info)
def assert_formats_equal_any_order(format_result, format_expect):
assert len(format_result) == len(format_expect), "Expected formats sizes mismatch"
for r_fmt in format_result:
for e_fmt in format_expect:
if r_fmt.json == e_fmt.json:
format_expect.remove(e_fmt)
break
assert not format_expect, "Not all expected formats matched {}".format([fmt.json for fmt in format_expect])
def test_merge_io_formats_no_wps():
wps_fmt = []
cwl_fmt = [DEFAULT_FORMAT]
res_fmt = merge_io_formats(wps_fmt, cwl_fmt)
assert isinstance(res_fmt, list)
assert len(res_fmt) == 1
assert res_fmt[0] is DEFAULT_FORMAT
def test_merge_io_formats_with_wps_and_default_cwl():
wps_fmt = [Format(CONTENT_TYPE_APP_NETCDF)]
cwl_fmt = [DEFAULT_FORMAT]
res_fmt = merge_io_formats(wps_fmt, cwl_fmt)
assert isinstance(res_fmt, list)
assert_formats_equal_any_order(res_fmt, [Format(CONTENT_TYPE_APP_NETCDF)])
def test_merge_io_formats_both_wps_and_cwl():
wps_fmt = [Format(CONTENT_TYPE_APP_NETCDF)]
cwl_fmt = [Format(CONTENT_TYPE_APP_JSON)]
res_fmt = merge_io_formats(wps_fmt, cwl_fmt)
assert isinstance(res_fmt, list)
assert_formats_equal_any_order(res_fmt, [Format(CONTENT_TYPE_APP_NETCDF), Format(CONTENT_TYPE_APP_JSON)])
def test_merge_io_formats_wps_complements_cwl():
wps_fmt = [Format(CONTENT_TYPE_APP_JSON, encoding="utf-8")]
cwl_fmt = [Format(CONTENT_TYPE_APP_JSON)]
res_fmt = merge_io_formats(wps_fmt, cwl_fmt)
assert isinstance(res_fmt, list)
assert_formats_equal_any_order(res_fmt, [Format(CONTENT_TYPE_APP_JSON, encoding="utf-8")])
def test_merge_io_formats_wps_overlaps_cwl():
wps_fmt = [
Format(CONTENT_TYPE_APP_JSON, encoding="utf-8"), # complements CWL details
Format(CONTENT_TYPE_APP_NETCDF), # duplicated in CWL (but different index)
Format(CONTENT_TYPE_TEXT_PLAIN) # extra (but not default)
]
cwl_fmt = [
Format(CONTENT_TYPE_APP_JSON), # overridden by WPS version
Format(CONTENT_TYPE_APP_XML), # extra preserved
Format(CONTENT_TYPE_APP_NETCDF), # duplicated with WPS, merged
]
res_fmt = merge_io_formats(wps_fmt, cwl_fmt)
assert isinstance(res_fmt, list)
assert_formats_equal_any_order(res_fmt, [
Format(CONTENT_TYPE_APP_JSON, encoding="utf-8"),
Format(CONTENT_TYPE_APP_NETCDF),
Format(CONTENT_TYPE_APP_XML),
Format(CONTENT_TYPE_TEXT_PLAIN),
])
| [
"[email protected]"
] | |
6176ca8999bab8c589d13d80a4c7c5c7ac8ff137 | a543a24f1b5aebf500c2200cd1d139435948500d | /satory074/_abc004/c.py | 9227c0ec27dc1aa64b43222d4668fa5c0f98ccc1 | [] | no_license | HomeSox/AtCoder | 18c89660762c3e0979596f0bcc9918c8962e4abb | 93e5ffab02ae1f763682aecb032c4f6f4e4b5588 | refs/heads/main | 2023-09-05T03:39:34.591433 | 2023-09-04T13:53:36 | 2023-09-04T13:53:36 | 219,873,371 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 178 | py | n = int(input())
ordlist = ['123456']
for i in range(29):
l = list(ordlist[-1])
l[i%5], l[i%5+1] = l[i%5+1], l[i%5]
ordlist.append(''.join(l))
print(ordlist[n%30])
| [
"[email protected]"
] | |
c0994aa64dbf0307204e0f6d0a5b88fe03b6d811 | 12c1b764e0f339aed6ac3538111ec0d5bef70698 | /pythonutils/cgiutils.py | ab3053610f73ae47ed4d4bf63c1c94804d3a812c | [] | no_license | bashu/pythonutils | d63b879b901ba06a35d12ad47e2d3633e86d6060 | 8214207fc611690ca93fc139a802cd491eed8c30 | refs/heads/master | 2016-08-11T22:11:56.343437 | 2015-10-01T09:35:32 | 2015-10-01T09:35:32 | 43,283,424 | 0 | 0 | null | 2015-10-01T09:35:32 | 2015-09-28T06:16:41 | Python | UTF-8 | Python | false | false | 18,733 | py | # Version 0.3.6
# 2009/06/08
# Copyright Michael Foord 2004-2009
# cgiutils.py
# Functions and constants useful for working with CGIs
# http://www.voidspace.org.uk/python/modules.shtml
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml
# For information about bugfixes, updates and support, please join the Pythonutils mailing list.
# http://groups.google.com/group/pythonutils/
# Comments, suggestions and bug reports welcome.
# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
# E-mail [email protected]
import os
import sys
__version__ = '0.3.6'
__all__ = (
'serverline',
'SENDMAIL',
'validchars',
'alphanums',
'getrequest',
'getform',
'getall',
'isblank',
'formencode',
'formdecode',
'mailme',
'sendmailme',
'createhtmlmail',
'environdata',
'validemail',
'cgiprint',
'ucgiprint',
'replace',
'error',
'makeindexline',
'istrue',
'randomstring',
'blacklisted',
'__version__',
)
serverline = "Content-Type: text/html"
# A common location of sendmail on servers
SENDMAIL = "/usr/sbin/sendmail"
validchars = 'abcdefghijklmnopqrstuvwxyz0123456789!-_*'
alphanums = 'abcdefghijklmnopqrstuvwxyz0123456789'
#######################################################
# Some functions for dealing with CGI forms (instances of FieldStorage)
def getrequest(valuelist=None, nolist=False):
"""
Initialise the ``FieldStorage`` and return the specified list of values as
a dictionary.
If you don't specify a list of values, then *all* values will be returned.
If you set ``nolist`` to ``True`` then any parameters supplied as lists
will only have their first entry returned.
"""
import cgi
form = cgi.FieldStorage()
if valuelist is not None:
return getform(valuelist, form, nolist=nolist)
else:
return getall(form, nolist=nolist)
def getform(valuelist, theform, notpresent='', nolist=False):
"""
This function, given a CGI form, extracts the data from it, based on
valuelist passed in. Any non-present values are set to '' - although this
can be changed.
It also takes a keyword argument 'nolist'. If this is True list values only
return their first value.
Returns a dictionary.
"""
data = {}
for field in valuelist:
if field not in theform:
data[field] = notpresent
else:
if not isinstance(theform[field], list):
data[field] = theform[field].value
else:
if not nolist:
# allows for list type values
data[field] = [x.value for x in theform[field]]
else:
# just fetch the first item
data[field] = theform[field][0].value
return data
def getall(theform, nolist=False):
"""
Passed a form (FieldStorage instance) return all the values.
This doesn't take into account file uploads.
Also accepts the 'nolist' keyword argument as ``getform``.
Returns a dictionary.
"""
data = {}
for field in list(theform.keys()):
if not isinstance(theform[field], list):
data[field] = theform[field].value
else:
if not nolist:
# allows for list type values
data[field] = [x.value for x in theform[field]]
else:
# just fetch the first item
data[field] = theform[field][0].value
return data
def isblank(indict):
"""
Passed an indict of values it checks if any of the values are set.
Returns ``True`` if every member of the indict is empty (evaluates as False).
I use it on a form processed with getform to tell if my CGI has been
activated without any values.
"""
return not [val for val in list(indict.values()) if val]
def formencode(theform):
"""
A version that turns a cgi form into a single string.
It only handles single and list values, not multipart.
This allows the contents of a form requested to be encoded into a single value as part of another request.
"""
try:
from urllib.parse import urlencode, quote_plus
except ImportError:
from urllib import urlencode, quote_plus
return quote_plus(urlencode(getall(theform)))
def formdecode(thestring):
"""Decode a single string back into a form like dictionary."""
from cgi import parse_qs
try:
from urllib.parse import unquote_plus
except ImportError:
from urllib import unquote_plus
return parse_qs(unquote_plus(thestring), True)
#############################################################
# Functions for handling emails
#
# Use mailme for sending email - specify a path to sendmail *or* a host, port etc (optionally username)
def mailme(to_email, msg, email_subject=None, from_email=None,
host='localhost', port=25, username=None, password=None,
html=True, sendmail=None):
"""
This function will send an email using ``sendmail`` or ``smtplib``, depending
on what parameters you pass it.
If you want to use ``sendmail`` to send the email then set
``sendmail='/path/to/sendmail'``. (The ``SENDMAIL`` value from Constants_ often
works).
If you aren't using sendmail then you will need to set ``host`` and ``port`` to
the correct values. If your server requires authentication then you'll need to
supply the correct ``username`` and ``password``.
``to_email`` can be a single email address, *or* a list of addresses.
``mailme`` *assumes* you are sending an html email created by
``createhtmlmail``. If this isn't the case then set ``html=False``.
Some servers won't let you send a message without supplying a ``from_email``.
"""
if sendmail:
# use sendmailme if specified
return sendmailme(to_email, msg, email_subject, from_email,
html, sendmail)
if not isinstance(to_email, list):
# if we have a single email then change it into a list
to_email = [to_email]
#
import smtplib
#
head = "To: %s\r\n" % ','.join(to_email)
if from_email is not None:
head += ('From: %s\r\n' % from_email)
# subject is in the body of an html email
if not html and email_subject is not None:
head += ("Subject: %s\r\n\r\n" % email_subject)
msg = head + msg
#
server = smtplib.SMTP(host, port)
if username:
server.login(username, password)
server.sendmail(from_email, to_email, msg)
server.quit()
def sendmailme(to_email, msg, email_subject=None, from_email=None,
html=True, sendmail=SENDMAIL):
"""
Quick and dirty, pipe a message to sendmail. Can only work on UNIX type systems
with sendmail.
Will need the path to sendmail - defaults to the 'SENDMAIL' constant.
``to_email`` can be a single email address, *or* a list of addresses.
*Assumes* you are sending an html email created by ``createhtmlmail``. If this
isn't the case then set ``html=False``.
"""
if not isinstance(to_email, list):
to_email = [to_email]
o = os.popen("%s -t" % sendmail,"w")
o.write("To: %s\r\n" % ','.join(to_email))
if from_email:
o.write("From: %s\r\n" % from_email)
if not html and email_subject:
o.write("Subject: %s\r\n" % email_subject)
o.write("\r\n")
o.write("%s\r\n" % msg)
o.close()
def createhtmlmail(subject, html, text=None):
"""
Create a mime-message that will render as HTML or text as appropriate.
If no text is supplied we use htmllib to guess a text rendering.
(so html needs to be well formed)
Adapted from recipe 13.5 from Python Cookbook 2
"""
import MimeWriter, mimetools, io
if text is None:
# produce an approximate text from the HTML input
import htmllib
import formatter
textout = io.StringIO()
formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
parser = htmllib.HTMLParser(formtext)
parser.feed(html)
parser.close()
text = textout.getvalue()
del textout, formtext, parser
out = io.StringIO() # output buffer for our message
htmlin = io.StringIO(html) # input buffer for the HTML
txtin = io.StringIO(text) # input buffer for the plain text
writer = MimeWriter.MimeWriter(out)
# Set up some basic headers. Place subject here because smtplib.sendmail
# expects it to be in the message, as relevant RFCs prescribe.
writer.addheader("Subject", subject)
writer.addheader("MIME-Version", "1.0")
# Start the multipart section of the message. Multipart/alternative seems
# to work better on some MUAs than multipart/mixed.
writer.startmultipartbody("alternative")
writer.flushheaders()
# the plain-text section: just copied through, assuming iso-8859-1 # XXXX always true ?
subpart = writer.nextpart()
pout = subpart.startbody("text/plain", [("charset", 'iso-8859-l')])
pout.write(txtin.read())
txtin.close()
# the HTML subpart of the message: quoted-printable, just in case
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()
# You're done; close your writer and return the message as a string
writer.lastpart()
msg = out.getvalue()
out.close()
return msg
def environdata():
"""Returns some data about the CGI environment, in a way that can be mailed."""
ENVIRONLIST = [ 'REQUEST_URI','HTTP_USER_AGENT','REMOTE_ADDR','HTTP_FROM','REMOTE_HOST','REMOTE_PORT','SERVER_SOFTWARE','HTTP_REFERER','REMOTE_IDENT','REMOTE_USER','QUERY_STRING','DATE_LOCAL' ] # XXX put this in template ??
environs = []
environs.append("\n\n---------------------------------------\n")
for x in ENVIRONLIST:
if x in os.environ:
environs.append("%s: %s\n" % (x, os.environ[x]))
environs.append("---------------------------------------\n")
return ''.join(environs)
def validemail(email):
"""
A quick function to do a basic email validation.
Returns False or the email address.
"""
if ' ' in email:
return False
dot = email.rfind('.')
at = email.find('@')
if dot == -1 or at < 1 or at > dot:
return False
return email
##########################################################
def error(errorval=''):
"""The generic error function."""
print(serverline)
print()
print('''<html><head><title>An Error Has Occurred</title>
<body><center>
<h1>Very Sorry</h1>
<h2>An Error Has Occurred</h2>''')
if errorval:
print('<h3>%s</h3>' % errorval)
print('</center></body></html>')
sys.exit()
#########################################################
def makeindexline(url, startpage, total, numonpage=10, pagesonscreen=5):
"""
Make a menu line for a given number of inputs, with a certain number per page.
Will look something like : ::
First Previous 22 23 24 25 26 27 28 29 30 31 32 Next Last
Each number or word will be a link to the relevant page.
url should be in the format : ``'<a href="script.py?start=%s">%s</a>'`` -
it will have the two ``%s`` values filled in by the function.
The url will automatically be put between ``<strong></strong>`` tags. Your
script needs to accepts a parameter ``start`` telling it which page to
display.
``startpage`` is the page actually being viewed - which won't be a link.
``total`` is the number of total inputs.
``numonpage`` is the number of inputs per page - this tells makeindexline how
many pages to divide the total into.
The links shown will be some before startpage and some after. The amount of
pages links are shown for is ``pagesonscreen``. (The actual total number shown
will be *2 \* pagesonscreen + 1*).
The indexes generated are *a bit* like the ones created by google. Unlike
google however, next and previous jump you into the *middle* of the next set of
links. i.e. If you are on page 27 next will take you to 33 and previous to 21.
(assuming pagesonscreen is 5). This makes it possible to jump more quickly
through a lot of links. Also - the current page will always be in the center of
the index. (So you never *need* Next just to get to the next page).
"""
b = '<strong>%s</strong>'
url = b % url
outlist = []
last = ''
next = ''
numpages = total//numonpage
if total%numonpage:
numpages += 1
if startpage - pagesonscreen > 1:
outlist.append(url % (1, 'First'))
outlist.append(' ')
outlist.append(url % (startpage-pagesonscreen-1, 'Previous'))
outlist.append(' ')
index = max(startpage - pagesonscreen, 1)
end = min(startpage+pagesonscreen, numpages)
while index <= end:
if index == startpage:
outlist.append(b % startpage)
else:
outlist.append(url % (index, index))
index += 1
outlist.append(' ')
if (startpage+pagesonscreen) < numpages:
outlist.append(url % (startpage+pagesonscreen+1, 'Next'))
outlist.append(' ')
outlist.append(url % (numpages, 'Last'))
#
return ' '.join(outlist)
######################################
def istrue(value):
"""
Accepts a string as input.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
``False``.
``istrue`` is not case sensitive.
Any other input will raise a ``KeyError``.
"""
return {
'yes': True, 'no': False,
'on': True, 'off': False,
'1': True, '0': False,
'true': True, 'false': False,
}[value.lower()]
def randomstring(length):
"""
Return a random string of length 'length'.
The string is comprised only of numbers and lowercase letters.
"""
import random
outstring = []
while length > 0:
length -= 1
outstring.append(alphanums[int(random.random()*36)])
return ''.join(outstring)
##################################
def cgiprint(inline='', unbuff=False, line_end='\r\n'):
"""
Print to the ``stdout``.
Set ``unbuff=True`` to flush the buffer after every write.
It prints the inline you send it, followed by the ``line_end``. By default this
is ``\r\n`` - which is the standard specified by the RFC for http headers.
"""
sys.stdout.write(inline)
sys.stdout.write(line_end)
if unbuff:
sys.stdout.flush()
def ucgiprint(inline='', unbuff=False, encoding='UTF-8', line_end='\r\n'):
"""
A unicode version of ``cgiprint``. It allows you to store everything in your
script as unicode and just do your encoding in one place.
Print to the ``stdout``.
Set ``unbuff=True`` to flush the buffer after every write.
It prints the inline you send it, followed by the ``line_end``. By default this
is ``\r\n`` - which is the standard specified by the RFC for http headers.
``inline`` should be a unicode string.
``encoding`` is the encoding used to encode ``inline`` to a byte-string. It
defaults to ``UTF-8``, set it to ``None`` if you pass in ``inline`` as a byte
string rather than a unicode string.
"""
if encoding:
inline = inline.encode(encoding)
# don't need to encode the line endings
sys.stdout.write(inline)
sys.stdout.write(line_end)
if unbuff:
sys.stdout.flush()
def replace(instring, indict):
"""
This function provides a simple but effective template system for your html
pages. Effectively it is a convenient way of doing multiple replaces in a
single string.
Takes a string and a dictionary of replacements.
This function goes through the string and replaces every occurrence of every
dicitionary key with it's value.
``indict`` can also be a list of tuples instead of a dictionary (or anything
accepted by the dict function).
"""
indict = dict(indict)
if len(indict) > 40:
regex = re.compile("(%s)" % "|".join(map(re.escape, list(indict.keys()))))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: indict[mo.string[mo.start():mo.end()]],
instring)
for key in indict:
instring = instring.replace(key, indict[key])
return instring
############################
def blacklisted(ip, DNSBL_HOST='sbl-xbl.spamhaus.org'):
"""
Returns ``True`` if ip address is a blacklisted IP (i.e. from a spammer).
ip can also be a domain name - this raises ``socket.gaierror`` if the ip is
a domain name that cannot be resolved.
The DNS blacklist host (``DNSBL_HOST``) defaults to *sbl-xbl.spamhaus.org*.
Other ones you could use include :
- 'dns.rfc-ignorant.org'
- 'postmaster.rfc-ignorant.org'
- 'http.dnsbl.sorbs.net'
- 'misc.dnsbl.sorbs.net'
- 'spam.dnsbl.sorbs.net'
- 'bl.spamcop.net'
.. note::
Another, possibly more effective, way of coping with spam input to web
applications is to use the `Akismet Web Service <http://akismet.com>`_.
For this you can use the
`Python Akismet API Interface <http://www.voidspace.org.uk/python/modules.shtml#akismet>`_.
"""
# turn '1.2.3.4' into '4.3.2.1.sbl-xbl.spamhaus.org'
import socket
# convert domain name to IP
# raises an error if domain name can't be resolved
ip = socket.gethostbyname(ip)
iplist = ip.split('.')
iplist.reverse()
ip = '%s.%s' % ('.'.join(iplist), DNSBL_HOST)
try:
socket.gethostbyname(ip)
return True
except socket.gaierror:
return False
"""
TODO/ISSUES
===========
The indexes generated by makeindexline use next to jump 10 pages. This is
different to what people will expect if they are used to the 'Google' type
index lines.
createhtmlmail assumes iso-8859-1 input encoding for the html
email functions to support 'cc' and 'bcc'
Need doctests
"""
| [
"[email protected]"
] | |
3af98569cf8e2029999739ed562ac539f5bce4fb | e1b94d6fc781af26c08d7d108d9f9a463b154cac | /test20.py | a544b507f3842c31604ac995a8c10d3f87e05daf | [] | no_license | 404akhan/math6450 | b27d6928bbbddd9903122099b66e8adf49b7525b | 818baf5ad9c47e7237b3d21f4a698f684649b9f4 | refs/heads/master | 2021-01-20T07:42:58.415286 | 2017-05-02T13:02:44 | 2017-05-02T13:02:44 | 90,034,123 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,657 | py | import numpy as np
import pandas as pd
import random
import statsmodels.api as sm
from sklearn.feature_selection import RFE
from sklearn.svm import SVC
import sys
from pylab import pcolor, show, colorbar, xticks, yticks
df = pd.read_csv("./speed_code.csv", encoding="ISO-8859-1")
input_vars = np.array(['attr', 'sinc', 'intel', 'fun', 'amb', 'shar', 'like', 'prob',
'attr_o', 'sinc_o', 'intel_o', 'fun_o', 'amb_o', 'shar_o', 'like_o', 'prob_o',
'samerace', 'met', 'met_o'])
attribute_num = len(input_vars)
print 'attribute_num', attribute_num
xs = np.zeros((8378, attribute_num))
ys = np.zeros((8378, 1))
for i in range(attribute_num):
xs[:, i] = df[input_vars[i]]
ys[:, 0] = df['dec_o']
xs[np.isnan(xs)] = 0.
random.seed(1339)
shuf_arr = range(0, 8378)
random.shuffle(shuf_arr)
train_size = int(8378 * 0.7)
lr = 0.03
# for i in range(attribute_num):
# d1 = xs[: ,i]
# d2 = ys[: ,0]
# print input_vars[i], np.corrcoef(d1, d2)[0][1]
#
xs_train = xs[shuf_arr[0:train_size], :]
xs_cross_val = xs[shuf_arr[train_size:], :]
ys_train = ys[shuf_arr[0:train_size], :]
ys_cross_val = ys[shuf_arr[train_size:], :]
xs_mean = np.mean(xs_train, axis=0)
xs_std = np.std(xs_train, axis=0)
xs_train = (xs_train - xs_mean) / xs_std
xs_cross_val = (xs_cross_val - xs_mean) / xs_std
def sigmoid(x):
return 1. / (1 + np.exp(-x))
def get_loss():
scores = np.matmul(xs_cross_val, W) + b
predict = sigmoid(scores)
error = predict - ys_cross_val
return np.mean(np.square(error))
def get_accuracy():
scores = np.matmul(xs_cross_val, W) + b
predict = sigmoid(scores)
predict = (predict > 0.5).astype(np.int)
error = predict - ys_cross_val
return np.mean(np.abs(error))
def get_train_loss():
scores = np.matmul(xs_train, W) + b
predict = sigmoid(scores)
error = predict - ys_train
return np.mean(np.square(error))
def get_train_accuracy():
scores = np.matmul(xs_train, W) + b
predict = sigmoid(scores)
predict = (predict > 0.5).astype(np.int)
error = predict - ys_train
return np.mean(np.abs(error))
W = 0.01 * np.random.randn(attribute_num, 1)
b = 0.
for i in range(100*1000):
scores = np.matmul(xs_train, W) + b
predict = sigmoid(scores)
dpredict = 1. / train_size * (predict - ys_train)
dscores = dpredict * predict * (1 - predict)
dW = np.matmul(xs_train.transpose(), dscores)
db = np.sum(dscores)
W -= lr * dW
b -= lr * db
if i % 10 == 0:
print 'iter: %d, loss: %f, acc: %f, tr loss: %f, tr acc: %f' % (i, get_loss(), get_accuracy(), get_train_loss(), get_train_accuracy())
| [
"[email protected]"
] | |
a6b1f0bbee7fe4666bf8d05fb29773efb460b249 | 47a08ca494ee35cf553d223ff7fd69fdf92c1aa5 | /sourcebook_app/migrations/0006_auto_20180509_1922.py | f298c34ae95a14332538631cab4e9c4526eb1522 | [] | no_license | apjanco/90s-sourcebook | 010541d2718613a08008285d00ec59d96f742bb0 | 183fb012f87285d641678fe5c9c8da8ab6998084 | refs/heads/master | 2021-07-17T01:36:40.098417 | 2019-02-09T02:15:17 | 2019-02-09T02:15:17 | 132,296,098 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 927 | py | # Generated by Django 2.0.5 on 2018-05-09 19:22
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sourcebook_app', '0005_auto_20180509_1917'),
]
operations = [
migrations.CreateModel(
name='category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(blank=True, max_length=200, null=True)),
('essay', ckeditor.fields.RichTextField(blank=True)),
],
),
migrations.RemoveField(
model_name='item',
name='category',
),
migrations.AddField(
model_name='item',
name='category',
field=models.ManyToManyField(blank=True, to='sourcebook_app.category'),
),
]
| [
"[email protected]"
] | |
e2eff4ea305101f35ffcf05f15cc188ccb32ced6 | d044e88e622d9f4ca350aa4fd9d95d7ba2fae50b | /application/dataentry/migrations/0207_auto_20211119_1807.py | a61f3dfa9a81a9f94de6886491918e4ab7c650cc | [] | no_license | Tiny-Hands/tinyhands | 337d5845ab99861ae189de2b97b8b36203c33eef | 77aa0bdcbd6f2cbedc7eaa1fa4779bb559d88584 | refs/heads/develop | 2023-09-06T04:23:06.330489 | 2023-08-31T11:31:17 | 2023-08-31T11:31:17 | 24,202,150 | 7 | 3 | null | 2023-08-31T11:31:18 | 2014-09-18T19:35:02 | PLpgSQL | UTF-8 | Python | false | false | 615 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-11-19 18:07
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dataentry', '0206_personmatch_match_results'),
]
operations = [
migrations.RunSQL("delete from dataentry_userlocationpermission where permission_id in "\
"(select id from dataentry_permission where permission_group in ('FORMS','VIF'))"),
migrations.RunSQL("delete from dataentry_permission where permission_group in ('FORMS','VIF')"),
]
| [
"[email protected]"
] | |
3109b75d342ecc7144506e06f756165024efbfde | 751cf52d62dba7d88387fc5734d6ee3954054fc2 | /opencv/commercial/Instructions/Examples/Backprojection/backProjection.py | 6700e987ebba4ac4cd7f725e033de35ffb5792a4 | [
"MIT"
] | permissive | nooralight/lab-computer-vision | 70a4d84a47a14dc8f5e9796ff6ccb59d4451ff27 | 0c3d89b35d0468d4d3cc5ce2653b3f0ac82652a9 | refs/heads/master | 2023-03-17T12:45:22.700237 | 2017-07-11T22:17:09 | 2017-07-11T22:17:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,081 | py | import numpy as np
import cv2
xi, yi, xf, yf = 0, 0, 0, 0
selecting = False
newHist = False
begin = False
def regionSelect( event, x, y, flags, param ):
global xi, yi, xf, yf, selecting, newHist, begin
if event == cv2.EVENT_LBUTTONDOWN:
selecting = True
xi, yi = x, y
elif event == cv2.EVENT_LBUTTONUP:
xf, yf = x, y
selecting = False
newHist = True
begin = True
cap = cv2.VideoCapture( 0 )
cv2.namedWindow( 'frame' )
cv2.setMouseCallback( 'frame', regionSelect )
while( True ):
if not selecting:
_, frame = cap.read()
if begin:
hsv = cv2.cvtColor( frame, cv2.COLOR_BGR2HSV )
mask = np.zeros( frame.shape[:2], np.uint8 )
mask[min( yi, yf ) : max( yi, yf ), min( xi, xf ):max( xi, xf )] = 255
if newHist:
roiHist = cv2.calcHist( [hsv], [0, 1], mask, [180, 256], [0, 180, 0, 256] )
roiHist = cv2.normalize( roiHist, roiHist, 0, 255, cv2.NORM_MINMAX )
newHist = False
targetHist = cv2.calcHist( [hsv], [0, 1], None, [180, 256], [0, 180, 0, 256] )
dst = cv2.calcBackProject( [hsv], [0, 1], roiHist, [0, 180, 0, 256], 1 )
disk = cv2.getStructuringElement( cv2.MORPH_ELLIPSE, ( 15,15 ) )
dst = cv2.filter2D( dst, -1, disk )
prox = np.copy( dst )
# # threshold and binary AND
_, thresh = cv2.threshold( dst, 250, 255, 0 )
kernel = cv2.getStructuringElement( cv2.MORPH_ELLIPSE, ( 5,5 ) )
thresh = cv2.erode( thresh, kernel, iterations = 3 )
thresh = cv2.dilate( thresh, kernel, iterations= 3 )
masked_dots = cv2.bitwise_and( prox, prox, mask = thresh )
# prox = cv2.applyColorMap( prox, cv2.COLORMAP_JET )
masked_dots = cv2.applyColorMap( masked_dots, cv2.COLORMAP_JET )
cv2.imshow( 'distance', masked_dots )
cv2.imshow( 'frame', frame )
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
| [
"[email protected]"
] | |
11c815726dd58daf7008db0bd038e4928eabfdf4 | 4323ef02073a8e3c9e6aceba738aef5fc72c3aa6 | /PythonExercicio/ex101.py | baf7c053bab3f6e080ca4354ddfda5d608c417b9 | [
"MIT"
] | permissive | fotavio16/PycharmProjects | e1e57816b5a0dbda7d7921ac024a71c712adac78 | f5be49db941de69159ec543e8a6dde61f9f94d86 | refs/heads/master | 2022-10-19T15:45:52.773005 | 2020-06-14T02:23:02 | 2020-06-14T02:23:02 | 258,865,834 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 514 | py | from time import gmtime
def voto(ano):
anoAtual = gmtime().tm_year
idade = anoAtual - ano
#print(f'Com {idade} anos: ', end='')
if idade < 16:
return "NEGADO", idade
elif idade < 18:
return "OPCIONAL", idade
elif idade < 70:
return "OBRIGATÓRIO", idade
else:
return "OPCIONAL", idade
# Progama Principal
print("-" *30)
anoNasc = int(input("Em que ano você nasceu? "))
situação, idade = voto(anoNasc)
print(f'Com {idade} anos: VOTO {situação}.')
| [
"[email protected]"
] | |
dddfb5db6026c566353c7f826f4552c02c9021c0 | bc441bb06b8948288f110af63feda4e798f30225 | /state_workflow_sdk/model/cmdb/instance_tree_root_node_pb2.py | 6ee3af86e87fa1990cdee356016a84a48a148421 | [
"Apache-2.0"
] | permissive | easyopsapis/easyops-api-python | 23204f8846a332c30f5f3ff627bf220940137b6b | adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0 | refs/heads/master | 2020-06-26T23:38:27.308803 | 2020-06-16T07:25:41 | 2020-06-16T07:25:41 | 199,773,131 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | true | 4,421 | py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: instance_tree_root_node.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from state_workflow_sdk.model.cmdb import instance_tree_child_node_pb2 as state__workflow__sdk_dot_model_dot_cmdb_dot_instance__tree__child__node__pb2
from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='instance_tree_root_node.proto',
package='cmdb',
syntax='proto3',
serialized_options=_b('Z>go.easyops.local/contracts/protorepo-models/easyops/model/cmdb'),
serialized_pb=_b('\n\x1dinstance_tree_root_node.proto\x12\x04\x63mdb\x1a<state_workflow_sdk/model/cmdb/instance_tree_child_node.proto\x1a\x1cgoogle/protobuf/struct.proto\"\xa6\x01\n\x14InstanceTreeRootNode\x12\x11\n\tobject_id\x18\x01 \x01(\t\x12&\n\x05query\x18\x02 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\'\n\x06\x66ields\x18\x03 \x01(\x0b\x32\x17.google.protobuf.Struct\x12*\n\x05\x63hild\x18\x04 \x03(\x0b\x32\x1b.cmdb.InstanceTreeChildNodeB@Z>go.easyops.local/contracts/protorepo-models/easyops/model/cmdbb\x06proto3')
,
dependencies=[state__workflow__sdk_dot_model_dot_cmdb_dot_instance__tree__child__node__pb2.DESCRIPTOR,google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,])
_INSTANCETREEROOTNODE = _descriptor.Descriptor(
name='InstanceTreeRootNode',
full_name='cmdb.InstanceTreeRootNode',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='object_id', full_name='cmdb.InstanceTreeRootNode.object_id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='query', full_name='cmdb.InstanceTreeRootNode.query', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='fields', full_name='cmdb.InstanceTreeRootNode.fields', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='child', full_name='cmdb.InstanceTreeRootNode.child', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=132,
serialized_end=298,
)
_INSTANCETREEROOTNODE.fields_by_name['query'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT
_INSTANCETREEROOTNODE.fields_by_name['fields'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT
_INSTANCETREEROOTNODE.fields_by_name['child'].message_type = state__workflow__sdk_dot_model_dot_cmdb_dot_instance__tree__child__node__pb2._INSTANCETREECHILDNODE
DESCRIPTOR.message_types_by_name['InstanceTreeRootNode'] = _INSTANCETREEROOTNODE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
InstanceTreeRootNode = _reflection.GeneratedProtocolMessageType('InstanceTreeRootNode', (_message.Message,), {
'DESCRIPTOR' : _INSTANCETREEROOTNODE,
'__module__' : 'instance_tree_root_node_pb2'
# @@protoc_insertion_point(class_scope:cmdb.InstanceTreeRootNode)
})
_sym_db.RegisterMessage(InstanceTreeRootNode)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
| [
"[email protected]"
] | |
b79bee798fa0c9f83afa01e877fb1c6112869372 | 51885da54b320351bfea42c7dd629f41985454cd | /abc061/b.py | 2bb0198431586f9681539f68d514ce6e49ba67fc | [] | no_license | mskt4440/AtCoder | dd266247205faeda468f911bff279a792eef5113 | f22702e3932e129a13f0683e91e5cc1a0a99c8d5 | refs/heads/master | 2021-12-15T10:21:31.036601 | 2021-12-14T08:19:11 | 2021-12-14T08:19:11 | 185,161,276 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,154 | py | #
# abc061 b
#
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_入力例_1(self):
input = """4 3
1 2
2 3
1 4"""
output = """2
2
1
1"""
self.assertIO(input, output)
def test_入力例_2(self):
input = """2 5
1 2
2 1
1 2
2 1
1 2"""
output = """5
5"""
self.assertIO(input, output)
def test_入力例_3(self):
input = """8 8
1 2
3 4
1 5
2 8
3 7
5 2
4 1
6 8"""
output = """3
3
2
2
2
1
1
2"""
self.assertIO(input, output)
def resolve():
N, M = map(int, input().split())
ans = [0] * N
for i in range(M):
a, b = map(int, input().split())
ans[a-1] += 1
ans[b-1] += 1
for i in range(N):
print(ans[i])
if __name__ == "__main__":
# unittest.main()
resolve()
| [
"[email protected]"
] | |
78bae165bd0366eb263356cb6ad9e5697febb35e | 7e8fcf142e5192be045263fe886cb0d29d9b69c3 | /huaweicloud-sdk-meeting/huaweicloudsdkmeeting/v1/meeting_async_client.py | eaf9697e8f16111a0c48a8939b1553da984ab8f4 | [
"Apache-2.0"
] | permissive | bobo123-dev/huaweicloud-sdk-python-v3 | 97b5bf20e87d2326d561402e634f5d7f9f5e8341 | 61e2ba5bc5a9dea5cec7001c0f952afb607e2fe5 | refs/heads/master | 2023-03-10T15:07:16.306615 | 2021-02-27T10:37:46 | 2021-02-27T10:37:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 289,385 | py | # coding: utf-8
from __future__ import absolute_import
import datetime
import re
import importlib
import six
from huaweicloudsdkcore.client import Client, ClientBuilder
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.utils import http_utils
from huaweicloudsdkcore.sdk_stream_request import SdkStreamRequest
class MeetingAsyncClient(Client):
"""
:param configuration: .Configuration object for this client
:param pool_threads: The number of threads to use for async requests
to the API. More threads means more concurrent API requests.
"""
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
NATIVE_TYPES_MAPPING = {
'int': int,
'long': int if six.PY3 else long,
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'object': object,
}
def __init__(self):
super(MeetingAsyncClient, self).__init__()
self.model_package = importlib.import_module("huaweicloudsdkmeeting.v1.model")
self.preset_headers = {'User-Agent': 'HuaweiCloud-SDK-Python'}
@classmethod
def new_builder(cls, clazz=None):
if clazz is None:
return ClientBuilder(cls, "MeetingCredentials")
if clazz.__name__ != "MeetingClient":
raise TypeError("client type error, support client type is MeetingClient")
return ClientBuilder(clazz, "MeetingCredentials")
def add_corp_async(self, request):
"""SP管理员创建企业
创建企业,默认管理员及分配资源。
:param AddCorpRequest request
:return: AddCorpResponse
"""
return self.add_corp_with_http_info(request)
def add_corp_with_http_info(self, request):
"""SP管理员创建企业
创建企业,默认管理员及分配资源。
:param AddCorpRequest request
:return: AddCorpResponse
"""
all_params = ['corp_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddCorpResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_corp_admin_async(self, request):
"""添加企业管理员
企业默认管理员添加企业普通管理员
:param AddCorpAdminRequest request
:return: AddCorpAdminResponse
"""
return self.add_corp_admin_with_http_info(request)
def add_corp_admin_with_http_info(self, request):
"""添加企业管理员
企业默认管理员添加企业普通管理员
:param AddCorpAdminRequest request
:return: AddCorpAdminResponse
"""
all_params = ['admin_dto', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/admin',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddCorpAdminResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_department_async(self, request):
"""添加部门
企业管理员通过该接口添加部门,最多支持10级部门,每级子部门最多支持100个,默认企业最大部门数量为3000个。
:param AddDepartmentRequest request
:return: AddDepartmentResponse
"""
return self.add_department_with_http_info(request)
def add_department_with_http_info(self, request):
"""添加部门
企业管理员通过该接口添加部门,最多支持10级部门,每级子部门最多支持100个,默认企业最大部门数量为3000个。
:param AddDepartmentRequest request
:return: AddDepartmentResponse
"""
all_params = ['dept_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/dept',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddDepartmentResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_device_async(self, request):
"""增加终端
企业管理员通过该接口添加硬终端。
:param AddDeviceRequest request
:return: AddDeviceResponse
"""
return self.add_device_with_http_info(request)
def add_device_with_http_info(self, request):
"""增加终端
企业管理员通过该接口添加硬终端。
:param AddDeviceRequest request
:return: AddDeviceResponse
"""
all_params = ['device_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/device',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddDeviceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_program_async(self, request):
"""新增全球窗节目
新增全球窗节目
:param AddProgramRequest request
:return: AddProgramResponse
"""
return self.add_program_with_http_info(request)
def add_program_with_http_info(self, request):
"""新增全球窗节目
新增全球窗节目
:param AddProgramRequest request
:return: AddProgramResponse
"""
all_params = ['program_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/programs',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddProgramResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_publication_async(self, request):
"""新增全球窗发布
新增全球窗发布
:param AddPublicationRequest request
:return: AddPublicationResponse
"""
return self.add_publication_with_http_info(request)
def add_publication_with_http_info(self, request):
"""新增全球窗发布
新增全球窗发布
:param AddPublicationRequest request
:return: AddPublicationResponse
"""
all_params = ['publication_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/publications',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddPublicationResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_resource_async(self, request):
"""分配企业资源
企业新增资源发放。优化适配,该接口同时支持修改,带resourceId后会判断该资源是否存在,存在即修改(支持修改的参数见修改接口),否则按新增处理
:param AddResourceRequest request
:return: AddResourceResponse
"""
return self.add_resource_with_http_info(request)
def add_resource_with_http_info(self, request):
"""分配企业资源
企业新增资源发放。优化适配,该接口同时支持修改,带resourceId后会判断该资源是否存在,存在即修改(支持修改的参数见修改接口),否则按新增处理
:param AddResourceRequest request
:return: AddResourceResponse
"""
all_params = ['corp_id', 'resource_list', 'x_request_id', 'accept_language', 'force_edit_flag']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'corp_id' in local_var_params:
path_params['corp_id'] = local_var_params['corp_id']
query_params = []
if 'force_edit_flag' in local_var_params:
query_params.append(('forceEditFlag', local_var_params['force_edit_flag']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{corp_id}/resource',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddResourceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_to_personal_space_async(self, request):
"""保存会议纪要到个人云空间
用户使用手机扫码后,手机端请求服务端将当前会议纪要文件保存到个人云空间。二维码内容 cloudlink://cloudlink.huawei.com/h5page?action=SAVE_MEETING_FILE&key1=value1&key2=value2 key/value的个数可能变化,终端解析后,在发起后续请求时,将所有key/value存为map,作为入参即可。
:param AddToPersonalSpaceRequest request
:return: AddToPersonalSpaceResponse
"""
return self.add_to_personal_space_with_http_info(request)
def add_to_personal_space_with_http_info(self, request):
"""保存会议纪要到个人云空间
用户使用手机扫码后,手机端请求服务端将当前会议纪要文件保存到个人云空间。二维码内容 cloudlink://cloudlink.huawei.com/h5page?action=SAVE_MEETING_FILE&key1=value1&key2=value2 key/value的个数可能变化,终端解析后,在发起后续请求时,将所有key/value存为map,作为入参即可。
:param AddToPersonalSpaceRequest request
:return: AddToPersonalSpaceResponse
"""
all_params = ['info', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/meeting-files/save-to-personal-space',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddToPersonalSpaceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def add_user_async(self, request):
"""添加用户
企业管理员通过该接口添加企业用户。
:param AddUserRequest request
:return: AddUserResponse
"""
return self.add_user_with_http_info(request)
def add_user_with_http_info(self, request):
"""添加用户
企业管理员通过该接口添加企业用户。
:param AddUserRequest request
:return: AddUserResponse
"""
all_params = ['user_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/member',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AddUserResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def allow_guest_unmute_async(self, request):
"""与会者自己解除静音
决定与会者是否可以自己解除静音。
:param AllowGuestUnmuteRequest request
:return: AllowGuestUnmuteResponse
"""
return self.allow_guest_unmute_with_http_info(request)
def allow_guest_unmute_with_http_info(self, request):
"""与会者自己解除静音
决定与会者是否可以自己解除静音。
:param AllowGuestUnmuteRequest request
:return: AllowGuestUnmuteResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/mute/guestUnMute',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AllowGuestUnmuteResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def associate_vmr_async(self, request):
"""分配专用云会议室
企业管理员通过该接口将云会议室分配给用户、硬终端(当前仅支持分配TE10、TE20、HUAWEI Board、HUAWEI Bar 500及HUAWEI Box系列硬件终端)。云会议室分配给硬件终端后,需要重启或重新激活硬件终端。若需要管理云会议室、预约会议、录制会议或进行完整的会控操作,请同时将该云会议室分配给会议用户。
:param AssociateVmrRequest request
:return: AssociateVmrResponse
"""
return self.associate_vmr_with_http_info(request)
def associate_vmr_with_http_info(self, request):
"""分配专用云会议室
企业管理员通过该接口将云会议室分配给用户、硬终端(当前仅支持分配TE10、TE20、HUAWEI Board、HUAWEI Bar 500及HUAWEI Box系列硬件终端)。云会议室分配给硬件终端后,需要重启或重新激活硬件终端。若需要管理云会议室、预约会议、录制会议或进行完整的会控操作,请同时将该云会议室分配给会议用户。
:param AssociateVmrRequest request
:return: AssociateVmrResponse
"""
all_params = ['account', 'assign_list', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'account' in local_var_params:
path_params['account'] = local_var_params['account']
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/vmr/assign-to-member/{account}',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='AssociateVmrResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_delete_corp_admins_async(self, request):
"""批量删除企业管理员
批量删除企业管理员
:param BatchDeleteCorpAdminsRequest request
:return: BatchDeleteCorpAdminsResponse
"""
return self.batch_delete_corp_admins_with_http_info(request)
def batch_delete_corp_admins_with_http_info(self, request):
"""批量删除企业管理员
批量删除企业管理员
:param BatchDeleteCorpAdminsRequest request
:return: BatchDeleteCorpAdminsResponse
"""
all_params = ['del_list', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/admin/delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchDeleteCorpAdminsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_delete_devices_async(self, request):
"""批量删除终端
企业管理员通过该接口批量删除终端,返回删除失败的列表。
:param BatchDeleteDevicesRequest request
:return: BatchDeleteDevicesResponse
"""
return self.batch_delete_devices_with_http_info(request)
def batch_delete_devices_with_http_info(self, request):
"""批量删除终端
企业管理员通过该接口批量删除终端,返回删除失败的列表。
:param BatchDeleteDevicesRequest request
:return: BatchDeleteDevicesResponse
"""
all_params = ['del_list', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/device/delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchDeleteDevicesResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_delete_materials_async(self, request):
"""删除全球窗素材
删除全球窗素材
:param BatchDeleteMaterialsRequest request
:return: BatchDeleteMaterialsResponse
"""
return self.batch_delete_materials_with_http_info(request)
def batch_delete_materials_with_http_info(self, request):
"""删除全球窗素材
删除全球窗素材
:param BatchDeleteMaterialsRequest request
:return: BatchDeleteMaterialsResponse
"""
all_params = ['ids_request_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/materials/batch-delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchDeleteMaterialsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_delete_programs_async(self, request):
"""删除全球窗节目
删除全球窗节目
:param BatchDeleteProgramsRequest request
:return: BatchDeleteProgramsResponse
"""
return self.batch_delete_programs_with_http_info(request)
def batch_delete_programs_with_http_info(self, request):
"""删除全球窗节目
删除全球窗节目
:param BatchDeleteProgramsRequest request
:return: BatchDeleteProgramsResponse
"""
all_params = ['ids_request_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/programs/batch-delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchDeleteProgramsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_delete_publications_async(self, request):
"""删除全球窗发布
删除全球窗发布
:param BatchDeletePublicationsRequest request
:return: BatchDeletePublicationsResponse
"""
return self.batch_delete_publications_with_http_info(request)
def batch_delete_publications_with_http_info(self, request):
"""删除全球窗发布
删除全球窗发布
:param BatchDeletePublicationsRequest request
:return: BatchDeletePublicationsResponse
"""
all_params = ['ids_request_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/publications/batch-delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchDeletePublicationsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_delete_users_async(self, request):
"""批量删除用户
企业管理员通过该接口批量删除企业用户,全量成功或全量失败。
:param BatchDeleteUsersRequest request
:return: BatchDeleteUsersResponse
"""
return self.batch_delete_users_with_http_info(request)
def batch_delete_users_with_http_info(self, request):
"""批量删除用户
企业管理员通过该接口批量删除企业用户,全量成功或全量失败。
:param BatchDeleteUsersRequest request
:return: BatchDeleteUsersResponse
"""
all_params = ['del_list', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/member/delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchDeleteUsersResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_update_devices_status_async(self, request):
"""批量修改终端状态
批量修改终端状态
:param BatchUpdateDevicesStatusRequest request
:return: BatchUpdateDevicesStatusResponse
"""
return self.batch_update_devices_status_with_http_info(request)
def batch_update_devices_status_with_http_info(self, request):
"""批量修改终端状态
批量修改终端状态
:param BatchUpdateDevicesStatusRequest request
:return: BatchUpdateDevicesStatusResponse
"""
all_params = ['value', 'sn_list', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'value' in local_var_params:
path_params['value'] = local_var_params['value']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/device/status/{value}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchUpdateDevicesStatusResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def batch_update_user_status_async(self, request):
"""批量修改用户状态
企业管理员通过该接口批量修改用户状态,当用户账号数资源或者第三方电子白板资源到期后,若企业内对应资源的用户账号超过数量后会被系统随机自动停用,此时可通过该接口修改用户的状态。
:param BatchUpdateUserStatusRequest request
:return: BatchUpdateUserStatusResponse
"""
return self.batch_update_user_status_with_http_info(request)
def batch_update_user_status_with_http_info(self, request):
"""批量修改用户状态
企业管理员通过该接口批量修改用户状态,当用户账号数资源或者第三方电子白板资源到期后,若企业内对应资源的用户账号超过数量后会被系统随机自动停用,此时可通过该接口修改用户的状态。
:param BatchUpdateUserStatusRequest request
:return: BatchUpdateUserStatusResponse
"""
all_params = ['value', 'account_list', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'value' in local_var_params:
path_params['value'] = local_var_params['value']
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/member/status/{value}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BatchUpdateUserStatusResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def broadcast_participant_async(self, request):
"""广播会场
同一时间,只允许一个与会者被广播。
:param BroadcastParticipantRequest request
:return: BroadcastParticipantResponse
"""
return self.broadcast_participant_with_http_info(request)
def broadcast_participant_with_http_info(self, request):
"""广播会场
同一时间,只允许一个与会者被广播。
:param BroadcastParticipantRequest request
:return: BroadcastParticipantResponse
"""
all_params = ['conference_id', 'participant_id', 'x_conference_authorization']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'participant_id' in local_var_params:
query_params.append(('participantID', local_var_params['participant_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants/broadcast',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='BroadcastParticipantResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def cancel_meeting_async(self, request):
"""取消预约会议
取消预约会议。
:param CancelMeetingRequest request
:return: CancelMeetingResponse
"""
return self.cancel_meeting_with_http_info(request)
def cancel_meeting_with_http_info(self, request):
"""取消预约会议
取消预约会议。
:param CancelMeetingRequest request
:return: CancelMeetingResponse
"""
all_params = ['conference_id', 'user_uuid', 'type', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
if 'type' in local_var_params:
query_params.append(('type', local_var_params['type']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences',
method='DELETE',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CancelMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def check_slide_verify_code_async(self, request):
"""校验滑块验证码
该接口提供校验滑块验证码。服务器收到请求,返回校验结果。用户在前台界面通过滑块操作匹配图形,使得抠图和原图吻合。然后服务器进行校验滑块验证码。
:param CheckSlideVerifyCodeRequest request
:return: CheckSlideVerifyCodeResponse
"""
return self.check_slide_verify_code_with_http_info(request)
def check_slide_verify_code_with_http_info(self, request):
"""校验滑块验证码
该接口提供校验滑块验证码。服务器收到请求,返回校验结果。用户在前台界面通过滑块操作匹配图形,使得抠图和原图吻合。然后服务器进行校验滑块验证码。
:param CheckSlideVerifyCodeRequest request
:return: CheckSlideVerifyCodeResponse
"""
all_params = ['slide_verify_code_check_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/auth/slideverifycode/check',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CheckSlideVerifyCodeResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def check_token_async(self, request):
"""校验Token
该接口提供校验token合法性功能。服务器收到请求后,验证token合法性并返回结果。如果参数needGenNewToken为true时,生成新的token并返回。
:param CheckTokenRequest request
:return: CheckTokenResponse
"""
return self.check_token_with_http_info(request)
def check_token_with_http_info(self, request):
"""校验Token
该接口提供校验token合法性功能。服务器收到请求后,验证token合法性并返回结果。如果参数needGenNewToken为true时,生成新的token并返回。
:param CheckTokenRequest request
:return: CheckTokenResponse
"""
all_params = ['validate_token_req_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/token/validate',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CheckTokenResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def check_veri_code_for_update_user_info_async(self, request):
"""校验手机和邮箱对应的验证码
企业用户通过该接口校验手机和邮箱对应的验证码,一分钟内记录尝试次数不得超过5次。
:param CheckVeriCodeForUpdateUserInfoRequest request
:return: CheckVeriCodeForUpdateUserInfoResponse
"""
return self.check_veri_code_for_update_user_info_with_http_info(request)
def check_veri_code_for_update_user_info_with_http_info(self, request):
"""校验手机和邮箱对应的验证码
企业用户通过该接口校验手机和邮箱对应的验证码,一分钟内记录尝试次数不得超过5次。
:param CheckVeriCodeForUpdateUserInfoRequest request
:return: CheckVeriCodeForUpdateUserInfoResponse
"""
all_params = ['verification_code_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member/verification-code/verify',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CheckVeriCodeForUpdateUserInfoResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def check_verify_code_async(self, request):
"""校验验证码
该接口提供校验验证码,服务器收到请求,返回结果。
:param CheckVerifyCodeRequest request
:return: CheckVerifyCodeResponse
"""
return self.check_verify_code_with_http_info(request)
def check_verify_code_with_http_info(self, request):
"""校验验证码
该接口提供校验验证码,服务器收到请求,返回结果。
:param CheckVerifyCodeRequest request
:return: CheckVerifyCodeResponse
"""
all_params = ['verify_code_check_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/verifycode/check',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CheckVerifyCodeResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def create_anonymous_auth_random_async(self, request):
"""匿名用户会议鉴权
未登陆终端,通过输入会议ID进行会议鉴权,返回鉴权随机数。如果需要密码则返回需要会议密码错误码,然后终端弹出输入会议ID输入框,用户输入密码后,终端再次调用该接口进行鉴权。
:param CreateAnonymousAuthRandomRequest request
:return: CreateAnonymousAuthRandomResponse
"""
return self.create_anonymous_auth_random_with_http_info(request)
def create_anonymous_auth_random_with_http_info(self, request):
"""匿名用户会议鉴权
未登陆终端,通过输入会议ID进行会议鉴权,返回鉴权随机数。如果需要密码则返回需要会议密码错误码,然后终端弹出输入会议ID输入框,用户输入密码后,终端再次调用该接口进行鉴权。
:param CreateAnonymousAuthRandomRequest request
:return: CreateAnonymousAuthRandomResponse
"""
all_params = ['conference_id', 'x_password']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_password' in local_var_params:
header_params['X-Password'] = local_var_params['x_password']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/anonymous/auth',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CreateAnonymousAuthRandomResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def create_conf_token_async(self, request):
"""获取会控Token
获取会控授权令牌,然后会议会被拉起。
:param CreateConfTokenRequest request
:return: CreateConfTokenResponse
"""
return self.create_conf_token_with_http_info(request)
def create_conf_token_with_http_info(self, request):
"""获取会控Token
获取会控授权令牌,然后会议会被拉起。
:param CreateConfTokenRequest request
:return: CreateConfTokenResponse
"""
all_params = ['conference_id', 'x_password', 'x_login_type', 'x_conference_authorization', 'x_nonce']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
if 'x_password' in local_var_params:
header_params['X-Password'] = local_var_params['x_password']
if 'x_login_type' in local_var_params:
header_params['X-Login-Type'] = local_var_params['x_login_type']
if 'x_nonce' in local_var_params:
header_params['X-Nonce'] = local_var_params['x_nonce']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/token',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CreateConfTokenResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def create_meeting_async(self, request):
"""创建会议
您可根据需要创建立即会议和预约会议。
:param CreateMeetingRequest request
:return: CreateMeetingResponse
"""
return self.create_meeting_with_http_info(request)
def create_meeting_with_http_info(self, request):
"""创建会议
您可根据需要创建立即会议和预约会议。
:param CreateMeetingRequest request
:return: CreateMeetingResponse
"""
all_params = ['req_body', 'user_uuid', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CreateMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def create_portal_ref_nonce_async(self, request):
"""获取页面免登陆跳转的nonce信息
通过token生成页面免登陆跳转到华为云会议的Portal的nonce信息。获取到nonce信息后,通过链接https://bmeeting.huaweicloud.com/?lang=zh-CN&nonce=xxxxxxxxxxxxx#/login进行免登陆跳转。
:param CreatePortalRefNonceRequest request
:return: CreatePortalRefNonceResponse
"""
return self.create_portal_ref_nonce_with_http_info(request)
def create_portal_ref_nonce_with_http_info(self, request):
"""获取页面免登陆跳转的nonce信息
通过token生成页面免登陆跳转到华为云会议的Portal的nonce信息。获取到nonce信息后,通过链接https://bmeeting.huaweicloud.com/?lang=zh-CN&nonce=xxxxxxxxxxxxx#/login进行免登陆跳转。
:param CreatePortalRefNonceRequest request
:return: CreatePortalRefNonceResponse
"""
all_params = ['x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/auth/portal-ref-nonce',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='CreatePortalRefNonceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def delete_attendees_async(self, request):
"""删除与会者
删除与会者。
:param DeleteAttendeesRequest request
:return: DeleteAttendeesResponse
"""
return self.delete_attendees_with_http_info(request)
def delete_attendees_with_http_info(self, request):
"""删除与会者
删除与会者。
:param DeleteAttendeesRequest request
:return: DeleteAttendeesResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/attendees/delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='DeleteAttendeesResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def delete_corp_async(self, request):
"""SP管理员删除企业
删除企业
:param DeleteCorpRequest request
:return: DeleteCorpResponse
"""
return self.delete_corp_with_http_info(request)
def delete_corp_with_http_info(self, request):
"""SP管理员删除企业
删除企业
:param DeleteCorpRequest request
:return: DeleteCorpResponse
"""
all_params = ['id', 'x_request_id', 'accept_language', 'force_delete']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
if 'force_delete' in local_var_params:
query_params.append(('forceDelete', local_var_params['force_delete']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{id}',
method='DELETE',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='DeleteCorpResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def delete_corp_vmr_async(self, request):
"""删除专用云会议室
企业管理员通过该接口删除企业的专用云会议室
:param DeleteCorpVmrRequest request
:return: DeleteCorpVmrResponse
"""
return self.delete_corp_vmr_with_http_info(request)
def delete_corp_vmr_with_http_info(self, request):
"""删除专用云会议室
企业管理员通过该接口删除企业的专用云会议室
:param DeleteCorpVmrRequest request
:return: DeleteCorpVmrResponse
"""
all_params = ['del_list', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/vmr/delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='DeleteCorpVmrResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def delete_department_async(self, request):
"""删除部门
企业管理员通过该接口删除部门。
:param DeleteDepartmentRequest request
:return: DeleteDepartmentResponse
"""
return self.delete_department_with_http_info(request)
def delete_department_with_http_info(self, request):
"""删除部门
企业管理员通过该接口删除部门。
:param DeleteDepartmentRequest request
:return: DeleteDepartmentResponse
"""
all_params = ['dept_code', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'dept_code' in local_var_params:
path_params['dept_code'] = local_var_params['dept_code']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/dept/{dept_code}',
method='DELETE',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='DeleteDepartmentResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def delete_recordings_async(self, request):
"""批量删除录制
批量删除录制。
:param DeleteRecordingsRequest request
:return: DeleteRecordingsResponse
"""
return self.delete_recordings_with_http_info(request)
def delete_recordings_with_http_info(self, request):
"""批量删除录制
批量删除录制。
:param DeleteRecordingsRequest request
:return: DeleteRecordingsResponse
"""
all_params = ['conf_uui_ds', 'user_uuid', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conf_uui_ds' in local_var_params:
query_params.append(('confUUIDs', local_var_params['conf_uui_ds']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/record/files',
method='DELETE',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='DeleteRecordingsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def delete_resource_async(self, request):
"""删除企业资源
企业删除资源项,删除资源项后,企业资源总数会自动减少
:param DeleteResourceRequest request
:return: DeleteResourceResponse
"""
return self.delete_resource_with_http_info(request)
def delete_resource_with_http_info(self, request):
"""删除企业资源
企业删除资源项,删除资源项后,企业资源总数会自动减少
:param DeleteResourceRequest request
:return: DeleteResourceResponse
"""
all_params = ['corp_id', 'resource_id_list', 'x_request_id', 'accept_language', 'force_edit_flag']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'corp_id' in local_var_params:
path_params['corp_id'] = local_var_params['corp_id']
query_params = []
if 'force_edit_flag' in local_var_params:
query_params.append(('forceEditFlag', local_var_params['force_edit_flag']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{corp_id}/resource/delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='DeleteResourceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def disassociate_vmr_async(self, request):
"""从用户或终端回收企业专用VMR
给企业用户回收vmr,需要做好纵向越权校验,避免企业管理员给其他企业的账号分配
:param DisassociateVmrRequest request
:return: DisassociateVmrResponse
"""
return self.disassociate_vmr_with_http_info(request)
def disassociate_vmr_with_http_info(self, request):
"""从用户或终端回收企业专用VMR
给企业用户回收vmr,需要做好纵向越权校验,避免企业管理员给其他企业的账号分配
:param DisassociateVmrRequest request
:return: DisassociateVmrResponse
"""
all_params = ['account', 'recycle_list', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'account' in local_var_params:
path_params['account'] = local_var_params['account']
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/vmr/recycle-from-member/{account}',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='DisassociateVmrResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def hand_async(self, request):
"""举手
所有来宾可以举手。来宾举手后,可以取消自己的举手。主持人可以取消所有来宾的举手。
:param HandRequest request
:return: HandResponse
"""
return self.hand_with_http_info(request)
def hand_with_http_info(self, request):
"""举手
所有来宾可以举手。来宾举手后,可以取消自己的举手。主持人可以取消所有来宾的举手。
:param HandRequest request
:return: HandResponse
"""
all_params = ['conference_id', 'participant_id', 'x_conference_authorization', 'rest_hands_up_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'participant_id' in local_var_params:
query_params.append(('participantID', local_var_params['participant_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants/hands',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='HandResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def hang_up_async(self, request):
"""挂断与会者
挂断正在通话中的与会者。
:param HangUpRequest request
:return: HangUpResponse
"""
return self.hang_up_with_http_info(request)
def hang_up_with_http_info(self, request):
"""挂断与会者
挂断正在通话中的与会者。
:param HangUpRequest request
:return: HangUpResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants/delete',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='HangUpResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def invite_participant_async(self, request):
"""邀请与会者
邀请与会者加入会议。
:param InviteParticipantRequest request
:return: InviteParticipantResponse
"""
return self.invite_participant_with_http_info(request)
def invite_participant_with_http_info(self, request):
"""邀请与会者
邀请与会者加入会议。
:param InviteParticipantRequest request
:return: InviteParticipantResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='InviteParticipantResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def invite_with_pwd_async(self, request):
"""通过会议ID和密码邀请与会者
通过会议ID和密码邀请与会者
:param InviteWithPwdRequest request
:return: InviteWithPwdResponse
"""
return self.invite_with_pwd_with_http_info(request)
def invite_with_pwd_with_http_info(self, request):
"""通过会议ID和密码邀请与会者
通过会议ID和密码邀请与会者
:param InviteWithPwdRequest request
:return: InviteWithPwdResponse
"""
all_params = ['conference_id', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/inviteWithPwd',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='InviteWithPwdResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def live_async(self, request):
"""启停会议直播
启动或停止会议直播。
:param LiveRequest request
:return: LiveResponse
"""
return self.live_with_http_info(request)
def live_with_http_info(self, request):
"""启停会议直播
启动或停止会议直播。
:param LiveRequest request
:return: LiveResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'rest_set_live_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/live',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='LiveResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def lock_meeting_async(self, request):
"""锁定会议
锁定或解锁会议。锁定会议后,不允许与会者加入会议。
:param LockMeetingRequest request
:return: LockMeetingResponse
"""
return self.lock_meeting_with_http_info(request)
def lock_meeting_with_http_info(self, request):
"""锁定会议
锁定或解锁会议。锁定会议后,不允许与会者加入会议。
:param LockMeetingRequest request
:return: LockMeetingResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'rest_lock_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/lock',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='LockMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def lock_view_async(self, request):
"""锁定会场视频源
锁定或者解锁某在线会场的视频源。
:param LockViewRequest request
:return: LockViewResponse
"""
return self.lock_view_with_http_info(request)
def lock_view_with_http_info(self, request):
"""锁定会场视频源
锁定或者解锁某在线会场的视频源。
:param LockViewRequest request
:return: LockViewResponse
"""
all_params = ['conference_id', 'participant_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'participant_id' in local_var_params:
query_params.append(('participantID', local_var_params['participant_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/lockView',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='LockViewResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def mute_meeting_async(self, request):
"""全场静音
主持人可以通过该接口静音/取消静音整个会议所有与会者(主持人除外)。
:param MuteMeetingRequest request
:return: MuteMeetingResponse
"""
return self.mute_meeting_with_http_info(request)
def mute_meeting_with_http_info(self, request):
"""全场静音
主持人可以通过该接口静音/取消静音整个会议所有与会者(主持人除外)。
:param MuteMeetingRequest request
:return: MuteMeetingResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'rest_mute_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/mute',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='MuteMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def mute_participant_async(self, request):
"""静音与会者
主持人可以静音/取消静音任意与会者,来宾也可静音/取消静音自己。
:param MuteParticipantRequest request
:return: MuteParticipantResponse
"""
return self.mute_participant_with_http_info(request)
def mute_participant_with_http_info(self, request):
"""静音与会者
主持人可以静音/取消静音任意与会者,来宾也可静音/取消静音自己。
:param MuteParticipantRequest request
:return: MuteParticipantResponse
"""
all_params = ['conference_id', 'participant_id', 'x_conference_authorization', 'rest_mute_participant_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'participant_id' in local_var_params:
query_params.append(('participantID', local_var_params['participant_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants/mute',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='MuteParticipantResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def prolong_meeting_async(self, request):
"""延长会议
延长会议。
:param ProlongMeetingRequest request
:return: ProlongMeetingResponse
"""
return self.prolong_meeting_with_http_info(request)
def prolong_meeting_with_http_info(self, request):
"""延长会议
延长会议。
:param ProlongMeetingRequest request
:return: ProlongMeetingResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'rest_prolong_dur_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/duration',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ProlongMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def record_async(self, request):
"""启停会议录制
启动或停止会议录制。
:param RecordRequest request
:return: RecordResponse
"""
return self.record_with_http_info(request)
def record_with_http_info(self, request):
"""启停会议录制
启动或停止会议录制。
:param RecordRequest request
:return: RecordResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'rest_set_record_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/record',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='RecordResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def rename_participant_async(self, request):
"""重命名与会者
重命名某个与会者。
:param RenameParticipantRequest request
:return: RenameParticipantResponse
"""
return self.rename_participant_with_http_info(request)
def rename_participant_with_http_info(self, request):
"""重命名与会者
重命名某个与会者。
:param RenameParticipantRequest request
:return: RenameParticipantResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'rest_rename_part_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants/name',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='RenameParticipantResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def reset_activecode_async(self, request):
"""重置激活码
当硬终端激活码失效时,企业管理员可以通过该接口重置激活码,使用重新获取的激活码激活终端,每24小时可重新激活5次。
:param ResetActivecodeRequest request
:return: ResetActivecodeResponse
"""
return self.reset_activecode_with_http_info(request)
def reset_activecode_with_http_info(self, request):
"""重置激活码
当硬终端激活码失效时,企业管理员可以通过该接口重置激活码,使用重新获取的激活码激活终端,每24小时可重新激活5次。
:param ResetActivecodeRequest request
:return: ResetActivecodeResponse
"""
all_params = ['sn', 'active_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'sn' in local_var_params:
path_params['sn'] = local_var_params['sn']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/device/{sn}/activecode',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ResetActivecodeResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def reset_pwd_async(self, request):
"""用户重置密码
该接口提供给用户重置密码功能,服务器收到请求,重新设置用户密码并返回结果。
:param ResetPwdRequest request
:return: ResetPwdResponse
"""
return self.reset_pwd_with_http_info(request)
def reset_pwd_with_http_info(self, request):
"""用户重置密码
该接口提供给用户重置密码功能,服务器收到请求,重新设置用户密码并返回结果。
:param ResetPwdRequest request
:return: ResetPwdResponse
"""
all_params = ['reset_pwd_req_dtov1', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/password/reset',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ResetPwdResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def reset_pwd_by_admin_async(self, request):
"""企业管理员重置企业成员密码
企业管理员通过该接口提供企业管理员重置企业成员密码的功能。当服务器收到重置密码的请求时,发送新的密码到企业成员的邮箱或者短信,并返回结果。
:param ResetPwdByAdminRequest request
:return: ResetPwdByAdminResponse
"""
return self.reset_pwd_by_admin_with_http_info(request)
def reset_pwd_by_admin_with_http_info(self, request):
"""企业管理员重置企业成员密码
企业管理员通过该接口提供企业管理员重置企业成员密码的功能。当服务器收到重置密码的请求时,发送新的密码到企业成员的邮箱或者短信,并返回结果。
:param ResetPwdByAdminRequest request
:return: ResetPwdByAdminResponse
"""
all_params = ['admin_reset_pwd_req_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/password/admin/reset',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ResetPwdByAdminResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def rollcall_participant_async(self, request):
"""点名会场
同一时间,只允许一个与会者被点名。点名会场的效果是除了主持人外,点名与会者为非静音状态,未点名的与会者统一为静音状态。
:param RollcallParticipantRequest request
:return: RollcallParticipantResponse
"""
return self.rollcall_participant_with_http_info(request)
def rollcall_participant_with_http_info(self, request):
"""点名会场
同一时间,只允许一个与会者被点名。点名会场的效果是除了主持人外,点名与会者为非静音状态,未点名的与会者统一为静音状态。
:param RollcallParticipantRequest request
:return: RollcallParticipantResponse
"""
all_params = ['conference_id', 'participant_id', 'x_conference_authorization']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'participant_id' in local_var_params:
query_params.append(('participantID', local_var_params['participant_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants/rollCall',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='RollcallParticipantResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_attendance_records_of_his_meeting_async(self, request):
"""查询历史会议的与会者记录
查询指定历史会议的与会者记录。
:param SearchAttendanceRecordsOfHisMeetingRequest request
:return: SearchAttendanceRecordsOfHisMeetingResponse
"""
return self.search_attendance_records_of_his_meeting_with_http_info(request)
def search_attendance_records_of_his_meeting_with_http_info(self, request):
"""查询历史会议的与会者记录
查询指定历史会议的与会者记录。
:param SearchAttendanceRecordsOfHisMeetingRequest request
:return: SearchAttendanceRecordsOfHisMeetingResponse
"""
all_params = ['conf_uuid', 'offset', 'limit', 'search_key', 'user_uuid', 'x_authorization_type', 'x_site_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conf_uuid' in local_var_params:
query_params.append(('confUUID', local_var_params['conf_uuid']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/history/confAttendeeRecord',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchAttendanceRecordsOfHisMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_corp_async(self, request):
"""SP管理员分页搜索企业
分页搜索企业,支持名称、企业ID搜索
:param SearchCorpRequest request
:return: SearchCorpResponse
"""
return self.search_corp_with_http_info(request)
def search_corp_with_http_info(self, request):
"""SP管理员分页搜索企业
分页搜索企业,支持名称、企业ID搜索
:param SearchCorpRequest request
:return: SearchCorpResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchCorpResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_corp_admins_async(self, request):
"""分页查询企业管理员
通过该接口分页查询企业管理员。
:param SearchCorpAdminsRequest request
:return: SearchCorpAdminsResponse
"""
return self.search_corp_admins_with_http_info(request)
def search_corp_admins_with_http_info(self, request):
"""分页查询企业管理员
通过该接口分页查询企业管理员。
:param SearchCorpAdminsRequest request
:return: SearchCorpAdminsResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/admin',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchCorpAdminsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_corp_dir_async(self, request):
"""查询企业通讯录
企业用户(含管理员)通过该接口查询该企业的通讯录。
:param SearchCorpDirRequest request
:return: SearchCorpDirResponse
"""
return self.search_corp_dir_with_http_info(request)
def search_corp_dir_with_http_info(self, request):
"""查询企业通讯录
企业用户(含管理员)通过该接口查询该企业的通讯录。
:param SearchCorpDirRequest request
:return: SearchCorpDirResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key', 'dept_code', 'query_sub_dept', 'search_scope']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'dept_code' in local_var_params:
query_params.append(('deptCode', local_var_params['dept_code']))
if 'query_sub_dept' in local_var_params:
query_params.append(('querySubDept', local_var_params['query_sub_dept']))
if 'search_scope' in local_var_params:
query_params.append(('searchScope', local_var_params['search_scope']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/abs/users',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchCorpDirResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_corp_vmr_async(self, request):
"""分页查询专用云会议室
企业管理员通过该接口分页查询企业的专用云会议室。
:param SearchCorpVmrRequest request
:return: SearchCorpVmrResponse
"""
return self.search_corp_vmr_with_http_info(request)
def search_corp_vmr_with_http_info(self, request):
"""分页查询专用云会议室
企业管理员通过该接口分页查询企业的专用云会议室。
:param SearchCorpVmrRequest request
:return: SearchCorpVmrResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key', 'status']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'status' in local_var_params:
query_params.append(('status', local_var_params['status']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/vmr',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchCorpVmrResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_ctl_records_of_his_meeting_async(self, request):
"""查询历史会议的会控记录
查询指定历史会议的会控记录。
:param SearchCtlRecordsOfHisMeetingRequest request
:return: SearchCtlRecordsOfHisMeetingResponse
"""
return self.search_ctl_records_of_his_meeting_with_http_info(request)
def search_ctl_records_of_his_meeting_with_http_info(self, request):
"""查询历史会议的会控记录
查询指定历史会议的会控记录。
:param SearchCtlRecordsOfHisMeetingRequest request
:return: SearchCtlRecordsOfHisMeetingResponse
"""
all_params = ['conf_uuid', 'offset', 'limit', 'user_uuid', 'x_authorization_type', 'x_site_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conf_uuid' in local_var_params:
query_params.append(('confUUID', local_var_params['conf_uuid']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/history/confCtlRecord',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchCtlRecordsOfHisMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_department_by_name_async(self, request):
"""按名称查询所有的部门
企业管理员通过该接口按名称查询所有的部门。
:param SearchDepartmentByNameRequest request
:return: SearchDepartmentByNameResponse
"""
return self.search_department_by_name_with_http_info(request)
def search_department_by_name_with_http_info(self, request):
"""按名称查询所有的部门
企业管理员通过该接口按名称查询所有的部门。
:param SearchDepartmentByNameRequest request
:return: SearchDepartmentByNameResponse
"""
all_params = ['dept_name', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'dept_name' in local_var_params:
query_params.append(('deptName', local_var_params['dept_name']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member/dept',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchDepartmentByNameResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_devices_async(self, request):
"""分页查询终端
企业管理员通过该接口分页查询终端信息。
:param SearchDevicesRequest request
:return: SearchDevicesResponse
"""
return self.search_devices_with_http_info(request)
def search_devices_with_http_info(self, request):
"""分页查询终端
企业管理员通过该接口分页查询终端信息。
:param SearchDevicesRequest request
:return: SearchDevicesResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key', 'model', 'dept_code', 'enable_sub_dept']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'model' in local_var_params:
query_params.append(('model', local_var_params['model']))
if 'dept_code' in local_var_params:
query_params.append(('deptCode', local_var_params['dept_code']))
if 'enable_sub_dept' in local_var_params:
query_params.append(('enableSubDept', local_var_params['enable_sub_dept']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/device',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchDevicesResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_his_meetings_async(self, request):
"""查询历史会议列表
管理员可以查询管理权限域内所有的历史会议,普通用户仅能查询当前帐号管理的历史会议。不带查询参数时,默认查询权限范围内的历史会议。
:param SearchHisMeetingsRequest request
:return: SearchHisMeetingsResponse
"""
return self.search_his_meetings_with_http_info(request)
def search_his_meetings_with_http_info(self, request):
"""查询历史会议列表
管理员可以查询管理权限域内所有的历史会议,普通用户仅能查询当前帐号管理的历史会议。不带查询参数时,默认查询权限范围内的历史会议。
:param SearchHisMeetingsRequest request
:return: SearchHisMeetingsResponse
"""
all_params = ['start_date', 'end_date', 'user_uuid', 'offset', 'limit', 'search_key', 'query_all', 'sort_type', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'query_all' in local_var_params:
query_params.append(('queryAll', local_var_params['query_all']))
if 'start_date' in local_var_params:
query_params.append(('startDate', local_var_params['start_date']))
if 'end_date' in local_var_params:
query_params.append(('endDate', local_var_params['end_date']))
if 'sort_type' in local_var_params:
query_params.append(('sortType', local_var_params['sort_type']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/history',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchHisMeetingsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_materials_async(self, request):
"""分页查询全球窗素材
分页查询全球窗素材
:param SearchMaterialsRequest request
:return: SearchMaterialsResponse
"""
return self.search_materials_with_http_info(request)
def search_materials_with_http_info(self, request):
"""分页查询全球窗素材
分页查询全球窗素材
:param SearchMaterialsRequest request
:return: SearchMaterialsResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/materials',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchMaterialsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_meeting_file_list_async(self, request):
"""查询会议纪要列表
用户查询自己的会议纪要列表
:param SearchMeetingFileListRequest request
:return: SearchMeetingFileListResponse
"""
return self.search_meeting_file_list_with_http_info(request)
def search_meeting_file_list_with_http_info(self, request):
"""查询会议纪要列表
用户查询自己的会议纪要列表
:param SearchMeetingFileListRequest request
:return: SearchMeetingFileListResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/meeting-files',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchMeetingFileListResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_meetings_async(self, request):
"""查询会议列表
管理员可以查询管理权限域内所有的会议,普通用户仅能查询当前帐号管理的会议。不带查询参数时,默认查询权限范围内正在召开或还未召开的会议。
:param SearchMeetingsRequest request
:return: SearchMeetingsResponse
"""
return self.search_meetings_with_http_info(request)
def search_meetings_with_http_info(self, request):
"""查询会议列表
管理员可以查询管理权限域内所有的会议,普通用户仅能查询当前帐号管理的会议。不带查询参数时,默认查询权限范围内正在召开或还未召开的会议。
:param SearchMeetingsRequest request
:return: SearchMeetingsResponse
"""
all_params = ['user_uuid', 'offset', 'limit', 'query_all', 'search_key', 'query_conf_mode', 'sort_type', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'query_all' in local_var_params:
query_params.append(('queryAll', local_var_params['query_all']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'query_conf_mode' in local_var_params:
query_params.append(('queryConfMode', local_var_params['query_conf_mode']))
if 'sort_type' in local_var_params:
query_params.append(('sortType', local_var_params['sort_type']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchMeetingsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_member_vmr_async(self, request):
"""分页查询用户云会议室
企业用户通过该接口查询个人已分配的云会议室,包括个人及专用两种。
:param SearchMemberVmrRequest request
:return: SearchMemberVmrResponse
"""
return self.search_member_vmr_with_http_info(request)
def search_member_vmr_with_http_info(self, request):
"""分页查询用户云会议室
企业用户通过该接口查询个人已分配的云会议室,包括个人及专用两种。
:param SearchMemberVmrRequest request
:return: SearchMemberVmrResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key', 'special_vmr']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'special_vmr' in local_var_params:
query_params.append(('specialVmr', local_var_params['special_vmr']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member/vmr',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchMemberVmrResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_online_meetings_async(self, request):
"""查询在线会议列表
管理员可以查询管理权限域内所有在线会议,普通用户仅能查询当前自己帐号管理的在线会议。不带查询参数时,默认查询权限范围内的在线会议,按开始时间升序排列。
:param SearchOnlineMeetingsRequest request
:return: SearchOnlineMeetingsResponse
"""
return self.search_online_meetings_with_http_info(request)
def search_online_meetings_with_http_info(self, request):
"""查询在线会议列表
管理员可以查询管理权限域内所有在线会议,普通用户仅能查询当前自己帐号管理的在线会议。不带查询参数时,默认查询权限范围内的在线会议,按开始时间升序排列。
:param SearchOnlineMeetingsRequest request
:return: SearchOnlineMeetingsResponse
"""
all_params = ['user_uuid', 'offset', 'limit', 'query_all', 'search_key', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'query_all' in local_var_params:
query_params.append(('queryAll', local_var_params['query_all']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/online',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchOnlineMeetingsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_programs_async(self, request):
"""查询全球窗节目
获取全球窗节目
:param SearchProgramsRequest request
:return: SearchProgramsResponse
"""
return self.search_programs_with_http_info(request)
def search_programs_with_http_info(self, request):
"""查询全球窗节目
获取全球窗节目
:param SearchProgramsRequest request
:return: SearchProgramsResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/programs',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchProgramsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_publications_async(self, request):
"""查询全球窗发布
获取全球窗发布
:param SearchPublicationsRequest request
:return: SearchPublicationsResponse
"""
return self.search_publications_with_http_info(request)
def search_publications_with_http_info(self, request):
"""查询全球窗发布
获取全球窗发布
:param SearchPublicationsRequest request
:return: SearchPublicationsResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/publications',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchPublicationsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_recordings_async(self, request):
"""查询录制列表
管理员可以查询管理权限域内所有的录制,普通用户仅能查询当前帐号管理的录制。不带查询参数时,默认查询权限范围内的录制。
:param SearchRecordingsRequest request
:return: SearchRecordingsResponse
"""
return self.search_recordings_with_http_info(request)
def search_recordings_with_http_info(self, request):
"""查询录制列表
管理员可以查询管理权限域内所有的录制,普通用户仅能查询当前帐号管理的录制。不带查询参数时,默认查询权限范围内的录制。
:param SearchRecordingsRequest request
:return: SearchRecordingsResponse
"""
all_params = ['start_date', 'end_date', 'user_uuid', 'offset', 'limit', 'query_all', 'search_key', 'sort_type', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'query_all' in local_var_params:
query_params.append(('queryAll', local_var_params['query_all']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'start_date' in local_var_params:
query_params.append(('startDate', local_var_params['start_date']))
if 'end_date' in local_var_params:
query_params.append(('endDate', local_var_params['end_date']))
if 'sort_type' in local_var_params:
query_params.append(('sortType', local_var_params['sort_type']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/record/files',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchRecordingsResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_resource_async(self, request):
"""分页查询企业资源
sp根据条件查询企业的资源项
:param SearchResourceRequest request
:return: SearchResourceResponse
"""
return self.search_resource_with_http_info(request)
def search_resource_with_http_info(self, request):
"""分页查询企业资源
sp根据条件查询企业的资源项
:param SearchResourceRequest request
:return: SearchResourceResponse
"""
all_params = ['corp_id', 'x_request_id', 'accept_language', 'offset', 'limit', 'search_key', 'start_expire_date', 'end_expire_date', 'type', 'type_id', 'status']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'corp_id' in local_var_params:
path_params['corp_id'] = local_var_params['corp_id']
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'start_expire_date' in local_var_params:
query_params.append(('startExpireDate', local_var_params['start_expire_date']))
if 'end_expire_date' in local_var_params:
query_params.append(('endExpireDate', local_var_params['end_expire_date']))
if 'type' in local_var_params:
query_params.append(('type', local_var_params['type']))
if 'type_id' in local_var_params:
query_params.append(('typeId', local_var_params['type_id']))
if 'status' in local_var_params:
query_params.append(('status', local_var_params['status']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{corp_id}/resource',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchResourceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_resource_op_record_async(self, request):
"""分页查询企业资源操作记录
sp根据条件查询企业的资源操作记录,支持根据resourceId模糊搜索
:param SearchResourceOpRecordRequest request
:return: SearchResourceOpRecordResponse
"""
return self.search_resource_op_record_with_http_info(request)
def search_resource_op_record_with_http_info(self, request):
"""分页查询企业资源操作记录
sp根据条件查询企业的资源操作记录,支持根据resourceId模糊搜索
:param SearchResourceOpRecordRequest request
:return: SearchResourceOpRecordResponse
"""
all_params = ['corp_id', 'x_request_id', 'accept_language', 'offset', 'limit', 'search_key', 'start_expire_date', 'end_expire_date', 'start_operate_date', 'end_operate_date', 'type', 'type_id', 'operate_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'corp_id' in local_var_params:
path_params['corp_id'] = local_var_params['corp_id']
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'start_expire_date' in local_var_params:
query_params.append(('startExpireDate', local_var_params['start_expire_date']))
if 'end_expire_date' in local_var_params:
query_params.append(('endExpireDate', local_var_params['end_expire_date']))
if 'start_operate_date' in local_var_params:
query_params.append(('startOperateDate', local_var_params['start_operate_date']))
if 'end_operate_date' in local_var_params:
query_params.append(('endOperateDate', local_var_params['end_operate_date']))
if 'type' in local_var_params:
query_params.append(('type', local_var_params['type']))
if 'type_id' in local_var_params:
query_params.append(('typeId', local_var_params['type_id']))
if 'operate_type' in local_var_params:
query_params.append(('operateType', local_var_params['operate_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{corp_id}/resource-record',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchResourceOpRecordResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def search_users_async(self, request):
"""分页查询用户
企业管理员通过该接口分页查询企业用户。
:param SearchUsersRequest request
:return: SearchUsersResponse
"""
return self.search_users_with_http_info(request)
def search_users_with_http_info(self, request):
"""分页查询用户
企业管理员通过该接口分页查询企业用户。
:param SearchUsersRequest request
:return: SearchUsersResponse
"""
all_params = ['x_request_id', 'accept_language', 'offset', 'limit', 'search_key', 'sort_field', 'is_asc', 'dept_code', 'enable_sub_dept', 'admin_type', 'enable_room', 'user_type', 'status']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'sort_field' in local_var_params:
query_params.append(('sortField', local_var_params['sort_field']))
if 'is_asc' in local_var_params:
query_params.append(('isAsc', local_var_params['is_asc']))
if 'dept_code' in local_var_params:
query_params.append(('deptCode', local_var_params['dept_code']))
if 'enable_sub_dept' in local_var_params:
query_params.append(('enableSubDept', local_var_params['enable_sub_dept']))
if 'admin_type' in local_var_params:
query_params.append(('adminType', local_var_params['admin_type']))
if 'enable_room' in local_var_params:
query_params.append(('enableRoom', local_var_params['enable_room']))
if 'user_type' in local_var_params:
query_params.append(('userType', local_var_params['user_type']))
collection_formats['userType'] = 'csv'
if 'status' in local_var_params:
query_params.append(('status', local_var_params['status']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/member',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SearchUsersResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def send_slide_verify_code_async(self, request):
"""发送滑块验证码
该接口提供发送滑块验证码。服务器收到请求,返回抠图以及抠图后的原图等结果。需要在前台界面显示出抠图以及抠图后的原图,用户通过滑块操作来匹配图形。
:param SendSlideVerifyCodeRequest request
:return: SendSlideVerifyCodeResponse
"""
return self.send_slide_verify_code_with_http_info(request)
def send_slide_verify_code_with_http_info(self, request):
"""发送滑块验证码
该接口提供发送滑块验证码。服务器收到请求,返回抠图以及抠图后的原图等结果。需要在前台界面显示出抠图以及抠图后的原图,用户通过滑块操作来匹配图形。
:param SendSlideVerifyCodeRequest request
:return: SendSlideVerifyCodeResponse
"""
all_params = ['slide_verify_code_send_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/auth/slideverifycode/send',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SendSlideVerifyCodeResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def send_veri_code_for_change_pwd_async(self, request):
"""发送验证码
该接口提供发送验证码,服务器收到请求,发送验证码到邮箱或者短信并返回结果。用户在前台界面通过滑块验证后,再进行发送验证码操作。
:param SendVeriCodeForChangePwdRequest request
:return: SendVeriCodeForChangePwdResponse
"""
return self.send_veri_code_for_change_pwd_with_http_info(request)
def send_veri_code_for_change_pwd_with_http_info(self, request):
"""发送验证码
该接口提供发送验证码,服务器收到请求,发送验证码到邮箱或者短信并返回结果。用户在前台界面通过滑块验证后,再进行发送验证码操作。
:param SendVeriCodeForChangePwdRequest request
:return: SendVeriCodeForChangePwdResponse
"""
all_params = ['verify_code_send_dtov1', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/verifycode/send',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SendVeriCodeForChangePwdResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def send_veri_code_for_update_user_info_async(self, request):
"""获取验证码
获取验证码,向手机或邮箱发送,一分钟内只会发送一次。
:param SendVeriCodeForUpdateUserInfoRequest request
:return: SendVeriCodeForUpdateUserInfoResponse
"""
return self.send_veri_code_for_update_user_info_with_http_info(request)
def send_veri_code_for_update_user_info_with_http_info(self, request):
"""获取验证码
获取验证码,向手机或邮箱发送,一分钟内只会发送一次。
:param SendVeriCodeForUpdateUserInfoRequest request
:return: SendVeriCodeForUpdateUserInfoResponse
"""
all_params = ['verification_code_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member/verification-code',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SendVeriCodeForUpdateUserInfoResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def set_custom_multi_picture_async(self, request):
"""设置自定义多画面
场景描述:会议管理员在confportal手动设置多画面 功能描述:提供给会议管理员手动设置多画面的功能
:param SetCustomMultiPictureRequest request
:return: SetCustomMultiPictureResponse
"""
return self.set_custom_multi_picture_with_http_info(request)
def set_custom_multi_picture_with_http_info(self, request):
"""设置自定义多画面
场景描述:会议管理员在confportal手动设置多画面 功能描述:提供给会议管理员手动设置多画面的功能
:param SetCustomMultiPictureRequest request
:return: SetCustomMultiPictureResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/display/customMultiPicture',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SetCustomMultiPictureResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def set_host_view_async(self, request):
"""主持人选看
用于主持人轮询、主持人选看多画面、主持人选看会场操作。目前只适用于硬终端为主持人的场景。
:param SetHostViewRequest request
:return: SetHostViewResponse
"""
return self.set_host_view_with_http_info(request)
def set_host_view_with_http_info(self, request):
"""主持人选看
用于主持人轮询、主持人选看多画面、主持人选看会场操作。目前只适用于硬终端为主持人的场景。
:param SetHostViewRequest request
:return: SetHostViewResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/chairView',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SetHostViewResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def set_multi_picture_async(self, request):
"""设置多画面
设置会议多画面。
:param SetMultiPictureRequest request
:return: SetMultiPictureResponse
"""
return self.set_multi_picture_with_http_info(request)
def set_multi_picture_with_http_info(self, request):
"""设置多画面
设置会议多画面。
:param SetMultiPictureRequest request
:return: SetMultiPictureResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/display/multiPicture',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SetMultiPictureResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def set_participant_view_async(self, request):
"""会场选看
目前只适用于硬终端选看其他会场人的场景。
:param SetParticipantViewRequest request
:return: SetParticipantViewResponse
"""
return self.set_participant_view_with_http_info(request)
def set_participant_view_with_http_info(self, request):
"""会场选看
目前只适用于硬终端选看其他会场人的场景。
:param SetParticipantViewRequest request
:return: SetParticipantViewResponse
"""
all_params = ['conference_id', 'participant_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'participant_id' in local_var_params:
query_params.append(('participantID', local_var_params['participant_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/partView',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SetParticipantViewResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def set_role_async(self, request):
"""申请主持人
申请或释放主持人。普通用户可申请主持人,主持人可释放主持人权限。
:param SetRoleRequest request
:return: SetRoleResponse
"""
return self.set_role_with_http_info(request)
def set_role_with_http_info(self, request):
"""申请主持人
申请或释放主持人。普通用户可申请主持人,主持人可释放主持人权限。
:param SetRoleRequest request
:return: SetRoleResponse
"""
all_params = ['conference_id', 'participant_id', 'x_conference_authorization', 'rest_chair_token_req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'participant_id' in local_var_params:
query_params.append(('participantID', local_var_params['participant_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/participants/role',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SetRoleResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_conf_org_async(self, request):
"""通过会议ID查询企业ID
与某个会议在同一个SP下的用户,可以通过会议ID查询到该会议对应的企业ID。
:param ShowConfOrgRequest request
:return: ShowConfOrgResponse
"""
return self.show_conf_org_with_http_info(request)
def show_conf_org_with_http_info(self, request):
"""通过会议ID查询企业ID
与某个会议在同一个SP下的用户,可以通过会议ID查询到该会议对应的企业ID。
:param ShowConfOrgRequest request
:return: ShowConfOrgResponse
"""
all_params = ['conference_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/confOrg',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowConfOrgResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_corp_async(self, request):
"""SP管理员查询企业
获取企业
:param ShowCorpRequest request
:return: ShowCorpResponse
"""
return self.show_corp_with_http_info(request)
def show_corp_with_http_info(self, request):
"""SP管理员查询企业
获取企业
:param ShowCorpRequest request
:return: ShowCorpResponse
"""
all_params = ['id', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{id}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowCorpResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_corp_admin_async(self, request):
"""查询企业管理员
通过该接口查询企业管理员。
:param ShowCorpAdminRequest request
:return: ShowCorpAdminResponse
"""
return self.show_corp_admin_with_http_info(request)
def show_corp_admin_with_http_info(self, request):
"""查询企业管理员
通过该接口查询企业管理员。
:param ShowCorpAdminRequest request
:return: ShowCorpAdminResponse
"""
all_params = ['account', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'account' in local_var_params:
path_params['account'] = local_var_params['account']
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/admin/{account}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowCorpAdminResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_corp_basic_info_async(self, request):
"""企业管理员查询企业注册信息
企业管理员通过该接口查询企业注册信息。
:param ShowCorpBasicInfoRequest request
:return: ShowCorpBasicInfoResponse
"""
return self.show_corp_basic_info_with_http_info(request)
def show_corp_basic_info_with_http_info(self, request):
"""企业管理员查询企业注册信息
企业管理员通过该接口查询企业注册信息。
:param ShowCorpBasicInfoRequest request
:return: ShowCorpBasicInfoResponse
"""
all_params = ['x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowCorpBasicInfoResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_corp_resource_async(self, request):
"""企业管理员查询企业内资源及业务权限
企业管理员通过该接口查询企业内资源及业务权限,包括查询已使用的资源情况。
:param ShowCorpResourceRequest request
:return: ShowCorpResourceResponse
"""
return self.show_corp_resource_with_http_info(request)
def show_corp_resource_with_http_info(self, request):
"""企业管理员查询企业内资源及业务权限
企业管理员通过该接口查询企业内资源及业务权限,包括查询已使用的资源情况。
:param ShowCorpResourceRequest request
:return: ShowCorpResourceResponse
"""
all_params = ['x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/resource',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowCorpResourceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_dept_and_child_dept_async(self, request):
"""查询部门及其一级子部门列表
企业管理员通过该接口查询部门及其一级子部门列表。
:param ShowDeptAndChildDeptRequest request
:return: ShowDeptAndChildDeptResponse
"""
return self.show_dept_and_child_dept_with_http_info(request)
def show_dept_and_child_dept_with_http_info(self, request):
"""查询部门及其一级子部门列表
企业管理员通过该接口查询部门及其一级子部门列表。
:param ShowDeptAndChildDeptRequest request
:return: ShowDeptAndChildDeptResponse
"""
all_params = ['dept_code', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'dept_code' in local_var_params:
path_params['dept_code'] = local_var_params['dept_code']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member/dept/{dept_code}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowDeptAndChildDeptResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_device_detail_async(self, request):
"""查询终端详情
企业管理员通过该接口查询终端详情。
:param ShowDeviceDetailRequest request
:return: ShowDeviceDetailResponse
"""
return self.show_device_detail_with_http_info(request)
def show_device_detail_with_http_info(self, request):
"""查询终端详情
企业管理员通过该接口查询终端详情。
:param ShowDeviceDetailRequest request
:return: ShowDeviceDetailResponse
"""
all_params = ['sn', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'sn' in local_var_params:
path_params['sn'] = local_var_params['sn']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/device/{sn}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowDeviceDetailResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_device_status_async(self, request):
"""查询设备状态
调用本接口可以查询硬终端的状态。 硬终端与发起查询请求的帐号需在同一企业下,否则会鉴权失败。
:param ShowDeviceStatusRequest request
:return: ShowDeviceStatusResponse
"""
return self.show_device_status_with_http_info(request)
def show_device_status_with_http_info(self, request):
"""查询设备状态
调用本接口可以查询硬终端的状态。 硬终端与发起查询请求的帐号需在同一企业下,否则会鉴权失败。
:param ShowDeviceStatusRequest request
:return: ShowDeviceStatusResponse
"""
all_params = ['number', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/ap/userstatus',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowDeviceStatusResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_device_types_async(self, request):
"""获取所有终端类型
企业管理员通过该接口获取所有的终端类型。
:param ShowDeviceTypesRequest request
:return: ShowDeviceTypesResponse
"""
return self.show_device_types_with_http_info(request)
def show_device_types_with_http_info(self, request):
"""获取所有终端类型
企业管理员通过该接口获取所有的终端类型。
:param ShowDeviceTypesRequest request
:return: ShowDeviceTypesResponse
"""
all_params = ['x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/termdevtype',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowDeviceTypesResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_his_meeting_detail_async(self, request):
"""查询历史会议详情
管理员可以查询管理权限域内所有的历史会议详情,普通用户仅能查询当前帐号管理的历史会议详情。
:param ShowHisMeetingDetailRequest request
:return: ShowHisMeetingDetailResponse
"""
return self.show_his_meeting_detail_with_http_info(request)
def show_his_meeting_detail_with_http_info(self, request):
"""查询历史会议详情
管理员可以查询管理权限域内所有的历史会议详情,普通用户仅能查询当前帐号管理的历史会议详情。
:param ShowHisMeetingDetailRequest request
:return: ShowHisMeetingDetailResponse
"""
all_params = ['conf_uuid', 'offset', 'limit', 'search_key', 'user_uuid', 'x_type', 'x_query_type', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conf_uuid' in local_var_params:
query_params.append(('confUUID', local_var_params['conf_uuid']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_type' in local_var_params:
header_params['X-Type'] = local_var_params['x_type']
if 'x_query_type' in local_var_params:
header_params['X-Query-Type'] = local_var_params['x_query_type']
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/history/confDetail',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowHisMeetingDetailResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_meeting_detail_async(self, request):
"""查询会议详情
管理员可以查询管理权限域内所有会议的详情,普通用户仅能查询当前帐号管理的会议详情。
:param ShowMeetingDetailRequest request
:return: ShowMeetingDetailResponse
"""
return self.show_meeting_detail_with_http_info(request)
def show_meeting_detail_with_http_info(self, request):
"""查询会议详情
管理员可以查询管理权限域内所有会议的详情,普通用户仅能查询当前帐号管理的会议详情。
:param ShowMeetingDetailRequest request
:return: ShowMeetingDetailResponse
"""
all_params = ['conference_id', 'offset', 'limit', 'search_key', 'user_uuid', 'x_type', 'x_query_type', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_type' in local_var_params:
header_params['X-Type'] = local_var_params['x_type']
if 'x_query_type' in local_var_params:
header_params['X-Query-Type'] = local_var_params['x_query_type']
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/confDetail',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowMeetingDetailResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_meeting_file_async(self, request):
"""查询会议纪要详情
用户查询单个会议纪要详情(主要目的是为了得到外链)。 IdeaHub是使用fileCode来查,所以终端保持一致。
:param ShowMeetingFileRequest request
:return: ShowMeetingFileResponse
"""
return self.show_meeting_file_with_http_info(request)
def show_meeting_file_with_http_info(self, request):
"""查询会议纪要详情
用户查询单个会议纪要详情(主要目的是为了得到外链)。 IdeaHub是使用fileCode来查,所以终端保持一致。
:param ShowMeetingFileRequest request
:return: ShowMeetingFileResponse
"""
all_params = ['file_code', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'file_code' in local_var_params:
path_params['file_code'] = local_var_params['file_code']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/meeting-files/{file_code}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowMeetingFileResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_meeting_file_list_async(self, request):
"""打开会议纪要文件列表
用户使用手机扫码后,手机端请求服务端,让服务端通知指定IdeaHub打开指定用户的会议纪要文件列表。二维码内容 cloudlink://cloudlink.huawei.com/h5page?action=OPEN_MEETING_FILE_LIST&key1=value1&key2=value2 key/value的个数可能变化,终端解析后,在发起后续请求时,将所有key/value存为map,作为入参即可。
:param ShowMeetingFileListRequest request
:return: ShowMeetingFileListResponse
"""
return self.show_meeting_file_list_with_http_info(request)
def show_meeting_file_list_with_http_info(self, request):
"""打开会议纪要文件列表
用户使用手机扫码后,手机端请求服务端,让服务端通知指定IdeaHub打开指定用户的会议纪要文件列表。二维码内容 cloudlink://cloudlink.huawei.com/h5page?action=OPEN_MEETING_FILE_LIST&key1=value1&key2=value2 key/value的个数可能变化,终端解析后,在发起后续请求时,将所有key/value存为map,作为入参即可。
:param ShowMeetingFileListRequest request
:return: ShowMeetingFileListResponse
"""
all_params = ['info', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/meeting-files/open-meeting-file-list',
method='POST',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowMeetingFileListResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_my_info_async(self, request):
"""用户查询自己的信息
企业用户通过该接口查询自己的信息。
:param ShowMyInfoRequest request
:return: ShowMyInfoResponse
"""
return self.show_my_info_with_http_info(request)
def show_my_info_with_http_info(self, request):
"""用户查询自己的信息
企业用户通过该接口查询自己的信息。
:param ShowMyInfoRequest request
:return: ShowMyInfoResponse
"""
all_params = ['x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowMyInfoResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_online_meeting_detail_async(self, request):
"""查询在线会议详情
管理员可以查询管理权限域内所有的在线会议详情,普通用户仅能查询当前自己的帐号管理的在线会议详情。
:param ShowOnlineMeetingDetailRequest request
:return: ShowOnlineMeetingDetailResponse
"""
return self.show_online_meeting_detail_with_http_info(request)
def show_online_meeting_detail_with_http_info(self, request):
"""查询在线会议详情
管理员可以查询管理权限域内所有的在线会议详情,普通用户仅能查询当前自己的帐号管理的在线会议详情。
:param ShowOnlineMeetingDetailRequest request
:return: ShowOnlineMeetingDetailResponse
"""
all_params = ['conference_id', 'offset', 'limit', 'search_key', 'user_uuid', 'x_type', 'x_query_type', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'offset' in local_var_params:
query_params.append(('offset', local_var_params['offset']))
if 'limit' in local_var_params:
query_params.append(('limit', local_var_params['limit']))
if 'search_key' in local_var_params:
query_params.append(('searchKey', local_var_params['search_key']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_type' in local_var_params:
header_params['X-Type'] = local_var_params['x_type']
if 'x_query_type' in local_var_params:
header_params['X-Query-Type'] = local_var_params['x_query_type']
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/online/confDetail',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowOnlineMeetingDetailResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_org_res_async(self, request):
"""查询企业的资源使用信息
企业管理员查询资源使用信息
:param ShowOrgResRequest request
:return: ShowOrgResResponse
"""
return self.show_org_res_with_http_info(request)
def show_org_res_with_http_info(self, request):
"""查询企业的资源使用信息
企业管理员查询资源使用信息
:param ShowOrgResRequest request
:return: ShowOrgResResponse
"""
all_params = []
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/orgRes',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowOrgResResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_program_async(self, request):
"""根据ID查询节目详情
根据ID获取节目详情
:param ShowProgramRequest request
:return: ShowProgramResponse
"""
return self.show_program_with_http_info(request)
def show_program_with_http_info(self, request):
"""根据ID查询节目详情
根据ID获取节目详情
:param ShowProgramRequest request
:return: ShowProgramResponse
"""
all_params = ['id', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/programs/{id}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowProgramResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_publication_async(self, request):
"""根据ID查询全球窗发布详情
根据ID获取发布详情
:param ShowPublicationRequest request
:return: ShowPublicationResponse
"""
return self.show_publication_with_http_info(request)
def show_publication_with_http_info(self, request):
"""根据ID查询全球窗发布详情
根据ID获取发布详情
:param ShowPublicationRequest request
:return: ShowPublicationResponse
"""
all_params = ['id', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/publications/{id}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowPublicationResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_real_time_info_of_meeting_async(self, request):
"""查询会议实时信息
查询会议实时信息
:param ShowRealTimeInfoOfMeetingRequest request
:return: ShowRealTimeInfoOfMeetingResponse
"""
return self.show_real_time_info_of_meeting_with_http_info(request)
def show_real_time_info_of_meeting_with_http_info(self, request):
"""查询会议实时信息
查询会议实时信息
:param ShowRealTimeInfoOfMeetingRequest request
:return: ShowRealTimeInfoOfMeetingResponse
"""
all_params = ['conference_id', 'x_conference_authorization']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/realTimeInfo',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowRealTimeInfoOfMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_recording_detail_async(self, request):
"""查询录制详情
查询某个录制详情。
:param ShowRecordingDetailRequest request
:return: ShowRecordingDetailResponse
"""
return self.show_recording_detail_with_http_info(request)
def show_recording_detail_with_http_info(self, request):
"""查询录制详情
查询某个录制详情。
:param ShowRecordingDetailRequest request
:return: ShowRecordingDetailResponse
"""
all_params = ['conf_uuid', 'user_uuid', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conf_uuid' in local_var_params:
query_params.append(('confUUID', local_var_params['conf_uuid']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/record/files',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowRecordingDetailResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_region_info_of_meeting_async(self, request):
"""查询会议所在区域信息
查询会议所在区域信息,如果会议不存在或者会议未召开,返回对应的错误码。
:param ShowRegionInfoOfMeetingRequest request
:return: ShowRegionInfoOfMeetingResponse
"""
return self.show_region_info_of_meeting_with_http_info(request)
def show_region_info_of_meeting_with_http_info(self, request):
"""查询会议所在区域信息
查询会议所在区域信息,如果会议不存在或者会议未召开,返回对应的错误码。
:param ShowRegionInfoOfMeetingRequest request
:return: ShowRegionInfoOfMeetingResponse
"""
all_params = ['conference_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences/region/info',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowRegionInfoOfMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_sp_res_async(self, request):
"""查询SP的共享资源使用信息
SP管理查询所属SP的共享资源使用信息
:param ShowSpResRequest request
:return: ShowSpResResponse
"""
return self.show_sp_res_with_http_info(request)
def show_sp_res_with_http_info(self, request):
"""查询SP的共享资源使用信息
SP管理查询所属SP的共享资源使用信息
:param ShowSpResRequest request
:return: ShowSpResResponse
"""
all_params = []
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/spRes',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowSpResResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def show_user_detail_async(self, request):
"""查询用户详情
企业管理员通过该接口查询企业用户详情
:param ShowUserDetailRequest request
:return: ShowUserDetailResponse
"""
return self.show_user_detail_with_http_info(request)
def show_user_detail_with_http_info(self, request):
"""查询用户详情
企业管理员通过该接口查询企业用户详情
:param ShowUserDetailRequest request
:return: ShowUserDetailResponse
"""
all_params = ['account', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'account' in local_var_params:
path_params['account'] = local_var_params['account']
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/member/{account}',
method='GET',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='ShowUserDetailResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def stop_meeting_async(self, request):
"""结束会议
结束会议。
:param StopMeetingRequest request
:return: StopMeetingResponse
"""
return self.stop_meeting_with_http_info(request)
def stop_meeting_with_http_info(self, request):
"""结束会议
结束会议。
:param StopMeetingRequest request
:return: StopMeetingResponse
"""
all_params = ['conference_id', 'x_conference_authorization']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/stop',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='StopMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def switch_mode_async(self, request):
"""切换视频显示策略
切换视频显示策略
:param SwitchModeRequest request
:return: SwitchModeResponse
"""
return self.switch_mode_with_http_info(request)
def switch_mode_with_http_info(self, request):
"""切换视频显示策略
切换视频显示策略
:param SwitchModeRequest request
:return: SwitchModeResponse
"""
all_params = ['conference_id', 'x_conference_authorization', 'req_body']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
header_params = {}
if 'x_conference_authorization' in local_var_params:
header_params['X-Conference-Authorization'] = local_var_params['x_conference_authorization']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/control/conferences/display/mode',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='SwitchModeResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_contact_async(self, request):
"""修改手机或邮箱
企业用户通过该接口修改手机或邮箱,需要先获取验证码,验证多次失败会禁止修改。
:param UpdateContactRequest request
:return: UpdateContactResponse
"""
return self.update_contact_with_http_info(request)
def update_contact_with_http_info(self, request):
"""修改手机或邮箱
企业用户通过该接口修改手机或邮箱,需要先获取验证码,验证多次失败会禁止修改。
:param UpdateContactRequest request
:return: UpdateContactResponse
"""
all_params = ['verification_code_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member/contact',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateContactResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_corp_async(self, request):
"""SP管理员修改企业
修改企业,若任一参数为null或者不携带则不修改
:param UpdateCorpRequest request
:return: UpdateCorpResponse
"""
return self.update_corp_with_http_info(request)
def update_corp_with_http_info(self, request):
"""SP管理员修改企业
修改企业,若任一参数为null或者不携带则不修改
:param UpdateCorpRequest request
:return: UpdateCorpResponse
"""
all_params = ['id', 'corp_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{id}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateCorpResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_corp_basic_info_async(self, request):
"""企业管理员修改企业注册信息
企业管理员通过该接口修改企业注册信息。当前只支持修改地址。
:param UpdateCorpBasicInfoRequest request
:return: UpdateCorpBasicInfoResponse
"""
return self.update_corp_basic_info_with_http_info(request)
def update_corp_basic_info_with_http_info(self, request):
"""企业管理员修改企业注册信息
企业管理员通过该接口修改企业注册信息。当前只支持修改地址。
:param UpdateCorpBasicInfoRequest request
:return: UpdateCorpBasicInfoResponse
"""
all_params = ['mod_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateCorpBasicInfoResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_department_async(self, request):
"""修改部门
企业管理员通过该接口修改部门。
:param UpdateDepartmentRequest request
:return: UpdateDepartmentResponse
"""
return self.update_department_with_http_info(request)
def update_department_with_http_info(self, request):
"""修改部门
企业管理员通过该接口修改部门。
:param UpdateDepartmentRequest request
:return: UpdateDepartmentResponse
"""
all_params = ['dept_code', 'dept_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'dept_code' in local_var_params:
path_params['dept_code'] = local_var_params['dept_code']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/dept/{dept_code}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateDepartmentResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_device_async(self, request):
"""修改终端
企业管理员通过该接口修改终端。
:param UpdateDeviceRequest request
:return: UpdateDeviceResponse
"""
return self.update_device_with_http_info(request)
def update_device_with_http_info(self, request):
"""修改终端
企业管理员通过该接口修改终端。
:param UpdateDeviceRequest request
:return: UpdateDeviceResponse
"""
all_params = ['sn', 'device_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'sn' in local_var_params:
path_params['sn'] = local_var_params['sn']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/device/{sn}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateDeviceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_material_async(self, request):
"""更新全球窗素材
更新全球窗素材
:param UpdateMaterialRequest request
:return: UpdateMaterialResponse
"""
return self.update_material_with_http_info(request)
def update_material_with_http_info(self, request):
"""更新全球窗素材
更新全球窗素材
:param UpdateMaterialRequest request
:return: UpdateMaterialResponse
"""
all_params = ['id', 'update_material_request_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/materials/{id}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateMaterialResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_meeting_async(self, request):
"""编辑预约会议
编辑预约会议。会议开始后,不能被编辑。
:param UpdateMeetingRequest request
:return: UpdateMeetingResponse
"""
return self.update_meeting_with_http_info(request)
def update_meeting_with_http_info(self, request):
"""编辑预约会议
编辑预约会议。会议开始后,不能被编辑。
:param UpdateMeetingRequest request
:return: UpdateMeetingResponse
"""
all_params = ['conference_id', 'req_body', 'user_uuid', 'x_authorization_type', 'x_site_id']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
if 'conference_id' in local_var_params:
query_params.append(('conferenceID', local_var_params['conference_id']))
if 'user_uuid' in local_var_params:
query_params.append(('userUUID', local_var_params['user_uuid']))
header_params = {}
if 'x_authorization_type' in local_var_params:
header_params['X-Authorization-Type'] = local_var_params['x_authorization_type']
if 'x_site_id' in local_var_params:
header_params['X-Site-Id'] = local_var_params['x_site_id']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/mmc/management/conferences',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateMeetingResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_member_vmr_async(self, request):
"""修改用户云会议室
企业用户登录后可以修改分配给用户的专用云会议室及个人云会议室。
:param UpdateMemberVmrRequest request
:return: UpdateMemberVmrResponse
"""
return self.update_member_vmr_with_http_info(request)
def update_member_vmr_with_http_info(self, request):
"""修改用户云会议室
企业用户登录后可以修改分配给用户的专用云会议室及个人云会议室。
:param UpdateMemberVmrRequest request
:return: UpdateMemberVmrResponse
"""
all_params = ['id', 'mod_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member/vmr/{id}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateMemberVmrResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_my_info_async(self, request):
"""用户修改自己的信息
企业用户通过该接口修改自己的信息。
:param UpdateMyInfoRequest request
:return: UpdateMyInfoResponse
"""
return self.update_my_info_with_http_info(request)
def update_my_info_with_http_info(self, request):
"""用户修改自己的信息
企业用户通过该接口修改自己的信息。
:param UpdateMyInfoRequest request
:return: UpdateMyInfoResponse
"""
all_params = ['member_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/member',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateMyInfoResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_program_async(self, request):
"""更新全球窗节目
更新全球窗节目
:param UpdateProgramRequest request
:return: UpdateProgramResponse
"""
return self.update_program_with_http_info(request)
def update_program_with_http_info(self, request):
"""更新全球窗节目
更新全球窗节目
:param UpdateProgramRequest request
:return: UpdateProgramResponse
"""
all_params = ['id', 'program_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/programs/{id}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateProgramResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_publication_async(self, request):
"""修改全球窗发布
修改全球窗发布
:param UpdatePublicationRequest request
:return: UpdatePublicationResponse
"""
return self.update_publication_with_http_info(request)
def update_publication_with_http_info(self, request):
"""修改全球窗发布
修改全球窗发布
:param UpdatePublicationRequest request
:return: UpdatePublicationResponse
"""
all_params = ['id', 'publication_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id']
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/sss/publications/{id}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdatePublicationResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_pwd_async(self, request):
"""修改密码
企业成员通过该接口提供用户修改密码功能,服务器收到请求,修改用户密码并返回结果。
:param UpdatePwdRequest request
:return: UpdatePwdResponse
"""
return self.update_pwd_with_http_info(request)
def update_pwd_with_http_info(self, request):
"""修改密码
企业成员通过该接口提供用户修改密码功能,服务器收到请求,修改用户密码并返回结果。
:param UpdatePwdRequest request
:return: UpdatePwdResponse
"""
all_params = ['mod_pwd_req_dto', 'x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/password',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdatePwdResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_resource_async(self, request):
"""修改企业资源
企业修改资源的过期时间、停用状态
:param UpdateResourceRequest request
:return: UpdateResourceResponse
"""
return self.update_resource_with_http_info(request)
def update_resource_with_http_info(self, request):
"""修改企业资源
企业修改资源的过期时间、停用状态
:param UpdateResourceRequest request
:return: UpdateResourceResponse
"""
all_params = ['corp_id', 'resource_list', 'x_request_id', 'accept_language', 'force_edit_flag']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'corp_id' in local_var_params:
path_params['corp_id'] = local_var_params['corp_id']
query_params = []
if 'force_edit_flag' in local_var_params:
query_params.append(('forceEditFlag', local_var_params['force_edit_flag']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/sp/corp/{corp_id}/resource',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateResourceResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_token_async(self, request):
"""刷新Token
该接口提供刷新Token功能,根据传入的Token,刷新Token失效时间并返回结果。
:param UpdateTokenRequest request
:return: UpdateTokenResponse
"""
return self.update_token_with_http_info(request)
def update_token_with_http_info(self, request):
"""刷新Token
该接口提供刷新Token功能,根据传入的Token,刷新Token失效时间并返回结果。
:param UpdateTokenRequest request
:return: UpdateTokenResponse
"""
all_params = ['x_request_id', 'accept_language']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-ID'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/acs/token',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateTokenResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def update_user_async(self, request):
"""修改用户
企业管理员通过该接口修改企业用户。
:param UpdateUserRequest request
:return: UpdateUserResponse
"""
return self.update_user_with_http_info(request)
def update_user_with_http_info(self, request):
"""修改用户
企业管理员通过该接口修改企业用户。
:param UpdateUserRequest request
:return: UpdateUserResponse
"""
all_params = ['account', 'user_dto', 'x_request_id', 'accept_language', 'account_type']
local_var_params = {}
for attr in request.attribute_map:
if hasattr(request, attr):
local_var_params[attr] = getattr(request, attr)
collection_formats = {}
path_params = {}
if 'account' in local_var_params:
path_params['account'] = local_var_params['account']
query_params = []
if 'account_type' in local_var_params:
query_params.append(('accountType', local_var_params['account_type']))
header_params = {}
if 'x_request_id' in local_var_params:
header_params['X-Request-Id'] = local_var_params['x_request_id']
if 'accept_language' in local_var_params:
header_params['Accept-Language'] = local_var_params['accept_language']
form_params = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
if isinstance(request, SdkStreamRequest):
body_params = request.get_file_stream()
response_headers = []
header_params['Content-Type'] = http_utils.select_header_content_type(
['application/json'])
auth_settings = []
return self.call_api(
resource_path='/v1/usg/dcs/corp/member/{account}',
method='PUT',
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
post_params=form_params,
response_type='UpdateUserResponse',
response_headers=response_headers,
auth_settings=auth_settings,
collection_formats=collection_formats,
request_type=request.__class__.__name__)
def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None,
post_params=None, response_type=None, response_headers=None, auth_settings=None,
collection_formats=None, request_type=None):
"""Makes the HTTP request and returns deserialized data.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response_type: Response data type.
:param response_headers: Header should be added to response data.
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param request_type: Request data type.
:return:
Return the response directly.
"""
return self.do_http_request(
method=method,
resource_path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body,
post_params=post_params,
response_type=response_type,
response_headers=response_headers,
collection_formats=collection_formats,
request_type=request_type,
async_request=True)
| [
"[email protected]"
] | |
13cadb461e8dcc7eb8ec1196d1b737fac51cb3b8 | 55a8940b41527a79c3c45f34f2035a53ee7f3621 | /repositorioDeReferencias/pycom-libraries/examples/lorawan-nano-gateway/config.py | 78f770651d3c373e06cd4ac367be4d4df16f8036 | [] | no_license | RegisMelgaco/LoPyLearn | ec37a58d334e2bf2dfd9aaf93b4e1bed016c957b | 3e8115545675947b24d646945a8859cae94b82b1 | refs/heads/master | 2021-09-03T10:55:49.614250 | 2018-01-08T13:45:46 | 2018-01-08T13:45:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 630 | py | """ LoPy LoRaWAN Nano Gateway configuration options """
import machine
import ubinascii
WIFI_MAC = ubinascii.hexlify(machine.unique_id()).upper()
# Set the Gateway ID to be the first 3 bytes of MAC address + 'FFFE' + last 3 bytes of MAC address
GATEWAY_ID = WIFI_MAC[:6] + "FFFE" + WIFI_MAC[6:12]
SERVER = 'router.eu.thethings.network'
PORT = 1700
NTP = "pool.ntp.org"
NTP_PERIOD_S = 3600
WIFI_SSID = 'TESTES-NASH'
WIFI_PASS = 'nashifce8556'
# for EU868
LORA_FREQUENCY = 868100000
LORA_GW_DR = "SF7BW125" # DR_5
LORA_NODE_DR = 5
# for US915
# LORA_FREQUENCY = 903900000
# LORA_GW_DR = "SF7BW125" # DR_3
# LORA_NODE_DR = 3
| [
"[email protected]"
] | |
e9b4e4732fa50f1e05c1f15dce5454ddf633aa9a | ca1f95723d29f3c72f36e98a69aa86f827f90812 | /request_helpers.py | ea665a3d2e9335db2cff53907e780f2486cb7478 | [] | no_license | zzaakiirr/parser_stackoverflow | 70b0376f487303fafe7cbb739b65da8299dea4bb | 3f39240107fcc8b1cfef95e6f63c0dc8dd3c81ad | refs/heads/master | 2020-03-08T14:44:36.083748 | 2018-04-05T21:09:41 | 2018-04-05T21:09:41 | 128,193,857 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 665 | py | import requests
def is_url(request):
try:
requests.get(request)
except requests.exceptions.MissingSchema:
return False
return True
def create_request_url(request):
key_words = request.split()
key_words_sting = ''
for key_word in key_words:
key_words_sting += '+%s' % key_word
request_url = 'https://stackoverflow.com/search?q=%s' % key_words_sting[1:]
return request_url
def get_response(request):
if is_url(request):
response = requests.get(request).content
else:
request_url = create_request_url(request)
response = requests.get(request_url).content
return response | [
"[email protected]"
] | |
18416831775dcf5a874ae485a50a8664e7427803 | 8acffb8c4ddca5bfef910e58d3faa0e4de83fce8 | /ml-flask/Lib/site-packages/sklearn/feature_selection/tests/test_mutual_info.py | 90912a4817535201553ce92bef653d054964f5a5 | [
"MIT"
] | permissive | YaminiHP/SimilitudeApp | 8cbde52caec3c19d5fa73508fc005f38f79b8418 | 005c59894d8788c97be16ec420c0a43aaec99b80 | refs/heads/master | 2023-06-27T00:03:00.404080 | 2021-07-25T17:51:27 | 2021-07-25T17:51:27 | 389,390,951 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:20a5dcd51f98742f23b8c7f37c2a42a52dc8089b83f2d8acc528fd88f1288e3c
size 7293
| [
"[email protected]"
] | |
b65417573b6585e83dc4f560df7a9195ef2c53f2 | 83cfd4dec02d1bfe36663b1ef1c5344a9ac922ef | /orco/report.py | f1d920f1ff9343abb58ef7e82f8100ac1f58a86d | [
"MIT"
] | permissive | spirali/orco | f170a968725408caca08ec0915b835cebd19423d | 32c839b4d691a3eb83cfa379a1ec429adcf7f1b0 | refs/heads/master | 2021-07-22T11:41:19.430670 | 2020-06-10T08:56:17 | 2020-06-10T08:56:17 | 195,656,806 | 4 | 2 | MIT | 2020-07-13T08:40:46 | 2019-07-07T13:50:34 | Python | UTF-8 | Python | false | false | 1,389 | py | class Report:
"""
Report of an event in ORCO. It can be viewed via ORCO browser.
Attributes:
* report_type - "info" / "error" / "timeout"
* executor_id - Id of executor where even comes from
* message - string representation of message
* builder_name - name of builder where event occurs (or None if not related)
* config - config related to the event (or None if not related)
* timestamp - datetime when event was created
"""
__slots__ = (
"report_type",
"executor_id",
"message",
"builder_name",
"config",
"timestamp",
)
def __init__(
self,
report_type,
executor_id,
message,
builder_name=None,
config=None,
timestamp=None,
):
self.executor_id = executor_id
self.timestamp = timestamp
self.report_type = report_type
self.message = message
self.builder_name = builder_name
self.config = config
def to_dict(self):
return {
"executor": self.executor_id,
"timestamp": self.timestamp,
"type": self.report_type,
"message": self.message,
"builder": self.builder_name,
"config": self.config,
}
def __repr__(self):
return "<Report {}: {}>".format(self.report_type, self.message)
| [
"[email protected]"
] | |
1456ea0a97ad69d4665eccefa722464babba6e6a | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2539/60617/267823.py | 0ac81f42b23d79d08df13bc7a0bd2236501f741b | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 339 | py | def cutinous_subArr():
arr=eval(input())
start=0
end=0
for i in range(1, len(arr)):
if start==0:
if arr[i]<arr[i-1]:
start=i-1
end=i
else:
if arr[i]<arr[i-1]:
end=i
print(end-start+1)
if __name__=='__main__':
cutinous_subArr() | [
"[email protected]"
] | |
3ef8cce8910cc02ab0f2bd51f71613ab2e31635b | 1e6eb70f63fe91e40fab63675eee2bb05e6f1f28 | /src/orion/core/worker/strategy.py | 7a9df26908bb86f08e4632434176667a03fa6dfb | [
"BSD-3-Clause"
] | permissive | jerrychatz/orion | ed587abc81bceaef5bd8e90e432112df0aad5f43 | 0ef3eea2decafce1985dc6a1cbea80cc2a92e9e8 | refs/heads/master | 2023-08-07T01:31:19.195565 | 2021-09-14T18:52:18 | 2021-09-14T18:52:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,335 | py | # -*- coding: utf-8 -*-
"""
Parallel Strategies
===================
Register objectives for incomplete trials
"""
import logging
from abc import ABCMeta, abstractmethod
from orion.core.utils import Factory
from orion.core.worker.trial import Trial
log = logging.getLogger(__name__)
CORRUPTED_DB_WARNING = """\
Trial `%s` has an objective but status is not completed.
This is likely due to a corrupted database, possibly because of
database timeouts. Try setting manually status to `completed`.
You can find documention to do this at
https://orion.readthedocs.io/en/stable/user/storage.html#storage-backend.
If you encounter this issue often, please consider reporting it to
https://github.com/Epistimio/orion/issues."""
def get_objective(trial):
"""Get the value for the objective, if it exists, for this trial
:return: Float or None
The value of the objective, or None if it doesn't exist
"""
objectives = [
result.value for result in trial.results if result.type == "objective"
]
if not objectives:
objective = None
elif len(objectives) == 1:
objective = objectives[0]
elif len(objectives) > 1:
raise RuntimeError(
"Trial {} has {} objectives".format(trial.id, len(objectives))
)
return objective
class BaseParallelStrategy(object, metaclass=ABCMeta):
"""Strategy to give intermediate results for incomplete trials"""
def __init__(self, *args, **kwargs):
pass
@abstractmethod
def observe(self, points, results):
"""Observe completed trials
.. seealso:: `orion.algo.base.BaseAlgorithm.observe` method
Parameters
----------
points: list of tuples of array-likes
Points from a `orion.algo.space.Space`.
Evaluated problem parameters by a consumer.
results: list of dict
Contains the result of an evaluation; partial information about the
black-box function at each point in `params`.
"""
# NOTE: In future points and results will be converted to trials for coherence with
# `Strategy.lie()` as well as for coherence with `Algorithm.observe` which will also be
# converted to expect trials instead of lists and dictionaries.
pass
# pylint: disable=no-self-use
def lie(self, trial):
"""Construct a fake result for an incomplete trial
Parameters
----------
trial: `orion.core.worker.trial.Trial`
A trial object which is not supposed to be completed.
Returns
-------
``orion.core.worker.trial.Trial.Result``
The fake objective result corresponding to the trial given.
Notes
-----
If the trial has an objective even if not completed, a warning is printed to user
with a pointer to documentation to resolve the database corruption. The result returned is
the corresponding objective instead of the lie.
"""
objective = get_objective(trial)
if objective:
log.warning(CORRUPTED_DB_WARNING, trial.id)
return Trial.Result(name="lie", type="lie", value=objective)
return None
@property
def configuration(self):
"""Provide the configuration of the strategy as a dictionary."""
return self.__class__.__name__
class NoParallelStrategy(BaseParallelStrategy):
"""No parallel strategy"""
def observe(self, points, results):
"""See BaseParallelStrategy.observe"""
pass
def lie(self, trial):
"""See BaseParallelStrategy.lie"""
result = super(NoParallelStrategy, self).lie(trial)
if result:
return result
return None
class MaxParallelStrategy(BaseParallelStrategy):
"""Parallel strategy that uses the max of completed objectives"""
def __init__(self, default_result=float("inf")):
"""Initialize the maximum result used to lie"""
super(MaxParallelStrategy, self).__init__()
self.default_result = default_result
self.max_result = default_result
@property
def configuration(self):
"""Provide the configuration of the strategy as a dictionary."""
return {self.__class__.__name__: {"default_result": self.default_result}}
def observe(self, points, results):
"""See BaseParallelStrategy.observe"""
super(MaxParallelStrategy, self).observe(points, results)
results = [
result["objective"] for result in results if result["objective"] is not None
]
if results:
self.max_result = max(results)
def lie(self, trial):
"""See BaseParallelStrategy.lie"""
result = super(MaxParallelStrategy, self).lie(trial)
if result:
return result
return Trial.Result(name="lie", type="lie", value=self.max_result)
class MeanParallelStrategy(BaseParallelStrategy):
"""Parallel strategy that uses the mean of completed objectives"""
def __init__(self, default_result=float("inf")):
"""Initialize the mean result used to lie"""
super(MeanParallelStrategy, self).__init__()
self.default_result = default_result
self.mean_result = default_result
@property
def configuration(self):
"""Provide the configuration of the strategy as a dictionary."""
return {self.__class__.__name__: {"default_result": self.default_result}}
def observe(self, points, results):
"""See BaseParallelStrategy.observe"""
super(MeanParallelStrategy, self).observe(points, results)
objective_values = [
result["objective"] for result in results if result["objective"] is not None
]
if objective_values:
self.mean_result = sum(value for value in objective_values) / float(
len(objective_values)
)
def lie(self, trial):
"""See BaseParallelStrategy.lie"""
result = super(MeanParallelStrategy, self).lie(trial)
if result:
return result
return Trial.Result(name="lie", type="lie", value=self.mean_result)
class StubParallelStrategy(BaseParallelStrategy):
"""Parallel strategy that returns static objective value for incompleted trials."""
def __init__(self, stub_value=None):
"""Initialize the stub value"""
super(StubParallelStrategy, self).__init__()
self.stub_value = stub_value
@property
def configuration(self):
"""Provide the configuration of the strategy as a dictionary."""
return {self.__class__.__name__: {"stub_value": self.stub_value}}
def observe(self, points, results):
"""See BaseParallelStrategy.observe"""
pass
def lie(self, trial):
"""See BaseParallelStrategy.lie"""
result = super(StubParallelStrategy, self).lie(trial)
if result:
return result
return Trial.Result(name="lie", type="lie", value=self.stub_value)
# pylint: disable=too-few-public-methods,abstract-method
class Strategy(BaseParallelStrategy, metaclass=Factory):
"""Class used to build a parallel strategy given name and params
.. seealso:: `orion.core.utils.Factory` metaclass and `BaseParallelStrategy` interface.
"""
pass
| [
"[email protected]"
] | |
f9fc77089bab51a5b86d400aa82d54397353ecd0 | c0bf1f7ca6d9d7562f72b4a668e97a2d5ffe7c88 | /veriloggen/core/vtypes.py | ed03be3a6259773264d44a823248877bfb205062 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | 00mjk/veriloggen | cee0da16182c3c9bd95340a966d6a3febc0e7ad1 | 9d0af9638470b3b85cbf9cb53f16b853932571c8 | refs/heads/master | 2023-06-23T07:10:20.645734 | 2021-07-18T14:53:13 | 2021-07-18T14:53:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 56,115 | py | from __future__ import absolute_import
from __future__ import print_function
import re
# Object ID counter for object sorting key
global_object_counter = 0
operator_dict = {
'Uminus': '-', 'Ulnot': '!', 'Unot': '~', 'Uand': '&', 'Unand': '~&',
'Uor': '|', 'Unor': '~|', 'Uxor': '^', 'Uxnor': '~^',
'Power': '**', 'Times': '*', 'Divide': '/', 'Mod': '%',
'Plus': '+', 'Minus': '-',
'Sll': '<<', 'Srl': '>>', 'Sra': '>>>',
'LessThan': '<', 'GreaterThan': '>', 'LessEq': '<=', 'GreaterEq': '>=',
'Eq': '==', 'NotEq': '!=', 'Eql': '===', 'NotEql': '!==',
'And': '&', 'Xor': '^', 'Xnor': '~^',
'Or': '|', 'Land': '&&', 'Lor': '||'
}
def op2mark(op):
if op in operator_dict:
return operator_dict[op]
return op
def str_to_signed(s):
targ = s.replace('_', '')
match = re.search(r's(.+)', targ)
if match is not None:
return True
return False
def check_int_hex(v):
if not re.search(r'^[0-9a-fA-FxzXZ]+$', v):
raise ValueError("Illegal value format '%s' for hex" % v)
def check_int_dec(v):
if not re.search(r'^[0-9xzXZ]+$', v):
raise ValueError("Illegal value format '%s' for dec" % v)
def check_int_dec_pure(v):
if not re.search(r'^[0-9]+$', v):
raise ValueError("Illegal value format '%s' for dec" % v)
def check_int_oct(v):
if not re.search(r'^[0-7xzXZ]+$', v):
raise ValueError("Illegal value format '%s' for oct" % v)
def check_int_bin(v):
if not re.search(r'^[01xzXZ]+$', v):
raise ValueError("Illegal value format '%s' for bin" % v)
def str_to_value(s):
targ = s.replace('_', '')
match = re.search(r'h(.+)', targ)
if match is not None:
try:
v = int(match.group(1), 16)
except:
v = match.group(1)
check_int_hex(v)
return v, 16
match = re.search(r'd(.+)', targ)
if match is not None:
try:
v = int(match.group(1), 10)
except:
v = match.group(1)
check_int_dec(v)
return v, 10
match = re.search(r'o(.+)', targ)
if match is not None:
try:
v = int(match.group(1), 8)
except:
v = match.group(1)
check_int_oct(v)
return v, 8
match = re.search(r'b(.+)', targ)
if match is not None:
try:
v = int(match.group(1), 2)
except:
v = match.group(1)
check_int_bin(v)
return v, 2
try:
v = int(targ, 10)
except:
v = targ
check_int_dec_pure(v)
return v, None
def str_to_width(s):
targ = s.replace('_', '')
match = re.search(r'(.+)\'h.+', targ)
if match is not None:
return int(match.group(1), 10)
match = re.search(r'(.+)\'d.+', targ)
if match is not None:
return int(match.group(1), 10)
match = re.search(r'(.+)\'o.+', targ)
if match is not None:
return int(match.group(1), 10)
match = re.search(r'(.+)\'b.+', targ)
if match is not None:
return int(match.group(1), 10)
return None
def get_width(v):
if hasattr(v, 'get_width'):
return v.get_width()
w = v.bit_length()
if isinstance(v, int):
w += 1
return w
def get_signed(obj):
if hasattr(obj, 'get_signed'):
return obj.get_signed()
if isinstance(obj, (int, float)):
return True
return False
def get_dims(obj):
if hasattr(obj, 'dims'):
return obj.dims
return None
def get_value(obj):
if hasattr(obj, 'value'):
return obj.value
return None
def get_initval(obj):
if hasattr(obj, 'initval'):
return obj.initval
return None
def max_width(left, right):
if left is None and right is None:
return None
if left is None:
return right
if right is None:
return left
return Mux(left >= right, left, right)
def raw_value(v):
if isinstance(v, Int):
return v.value
if isinstance(v, Float):
return v.value
if isinstance(v, Str):
return v.value
return v
def to_int(v):
if isinstance(v, int):
return v
if isinstance(v, (bool, float)):
return int(v)
if isinstance(v, Int):
v = v.value
if isinstance(v, int):
return v
raise TypeError('can not convert to int')
def equals(a, b):
if type(a) != type(b):
return False
if isinstance(a, (tuple, list)) and isinstance(b, (tuple, list)):
for aa, bb in zip(a, b):
v = equals(aa, bb)
if not v:
return False
return True
if not isinstance(a, _Numeric) and not isinstance(b, _Numeric):
return a == b
if hasattr(a, 'equals'):
return a.equals(b)
if hasattr(b, 'equals'):
return b.equals(a)
raise False
def _write_subst(obj, value, blk=False, ldelay=None, rdelay=None):
if ((not hasattr(obj, 'no_write_check') or not obj.no_write_check) and
hasattr(value, 'to_int')):
value = value.to_int()
return Subst(obj, value, blk=blk, ldelay=ldelay, rdelay=rdelay)
class VeriloggenNode(object):
""" Base class of Veriloggen AST object """
attr_names = ('object_id',)
def __init__(self):
global global_object_counter
self.object_id = global_object_counter
global_object_counter += 1
def equals(self, other):
if type(self) != type(other):
return False
for attr in self.attr_names:
v = equals(getattr(self, attr), getattr(other, attr))
if not v:
return False
return True
def __hash__(self):
return hash((id(self), self.object_id))
def __eq__(self, other):
return (id(self), self.object_id) == (id(other), other.object_id)
def __lt__(self, r):
raise TypeError('Not allowed operation.')
def __le__(self, r):
raise TypeError('Not allowed operation.')
# def __eq__(self, r):
# raise TypeError('Not allowed operation.')
# def __ne__(self, r):
# raise TypeError('Not allowed operation.')
def __ge__(self, r):
raise TypeError('Not allowed operation.')
def __gt__(self, r):
raise TypeError('Not allowed operation.')
def __add__(self, r):
raise TypeError('Not allowed operation.')
def __sub__(self, r):
raise TypeError('Not allowed operation.')
def __pow__(self, r):
raise TypeError('Not allowed operation.')
def __mul__(self, r):
raise TypeError('Not allowed operation.')
def __div__(self, r):
raise TypeError('Not allowed operation.')
def __truediv__(self, r):
raise TypeError('Not allowed operation.')
def __floordiv__(self, r):
raise TypeError('Not allowed operation.')
def __mod__(self, r):
raise TypeError('Not allowed operation.')
def __and__(self, r):
raise TypeError('Not allowed operation.')
def __or__(self, r):
raise TypeError('Not allowed operation.')
def __xor__(self, r):
raise TypeError('Not allowed operation.')
def __lshift__(self, r):
raise TypeError('Not allowed operation.')
def __rshift__(self, r):
raise TypeError('Not allowed operation.')
def __neg__(self):
raise TypeError('Not allowed operation.')
def __pos__(self):
raise TypeError('Not allowed operation.')
def __invert__(self):
raise TypeError('Not allowed operation.')
def __abs__(self):
raise TypeError('Not allowed operation.')
def __getitem__(self, r):
raise TypeError('Not allowed operation.')
class _Numeric(VeriloggenNode):
def __init__(self):
VeriloggenNode.__init__(self)
def __hash__(self):
return hash((id(self), self.object_id))
def __lt__(self, r):
return LessThan(self, r)
def __le__(self, r):
return LessEq(self, r)
def __eq__(self, r):
return Eq(self, r)
def __ne__(self, r):
return NotEq(self, r)
def __ge__(self, r):
return GreaterEq(self, r)
def __gt__(self, r):
return GreaterThan(self, r)
def __add__(self, r):
return Plus(self, r)
def __sub__(self, r):
return Minus(self, r)
def __pow__(self, r):
return Power(self, r)
def __mul__(self, r):
return Times(self, r)
def __div__(self, r):
return Divide(self, r)
def __truediv__(self, r):
return Divide(self, r)
def __floordiv__(self, r):
return Divide(self, r)
def __mod__(self, r):
return Mod(self, r)
def __and__(self, r):
return And(self, r)
def __or__(self, r):
return Or(self, r)
def __xor__(self, r):
return Xor(self, r)
def __lshift__(self, r):
return Sll(self, r)
def __rshift__(self, r):
return Srl(self, r)
def __neg__(self):
return Uminus(self)
def __pos__(self):
return Uplus(self)
def __invert__(self):
return Unot(self)
def __abs__(self):
return Abs(self)
def __getitem__(self, r):
if isinstance(r, slice):
size = self._len()
right = r.start
left = r.stop
step = r.step
if isinstance(left, Int):
left = left.value
if isinstance(right, Int):
right = right.value
if isinstance(step, Int):
step = step.value
if right is None:
right = 0
elif isinstance(right, int) and right < 0:
right = size - abs(right)
if left is None:
left = size
elif isinstance(left, int) and left < 0:
left = size - abs(left)
left -= 1
if isinstance(left, int) and left < 0:
raise ValueError("Illegal slice index: left = %d" % left)
if step is None:
return Slice(self, left, right)
else:
if not (isinstance(left, int) and
isinstance(right, int) and
isinstance(step, int)):
raise ValueError(
"Slice with step is not supported in Verilog Slice.")
if step == 0:
raise ValueError("Illegal slice step: step = %d" % step)
values = [Pointer(self, i)
for i in range(right, left + 1, step)]
values.reverse()
return Cat(*values)
if isinstance(r, int) and r < 0:
r = self.get_width() - abs(r)
return Pointer(self, r)
def sra(self, r): # shift right arithmetically
return Sra(self, r)
def repeat(self, times):
return Repeat(self, times)
def slice(self, msb, lsb):
return Slice(self, msb, lsb)
def bit_length(self):
return self.get_width()
def get_width(self):
raise TypeError("get_width() is not supported.")
def get_signed(self):
if hasattr(self, 'signed') and getattr(self, 'signed'):
return True
return False
def __iter__(self):
self.iter_size = len(self)
self.iter_count = 0
return self
def __next__(self):
if self.iter_count >= self.iter_size:
raise StopIteration()
ret = Pointer(self, self.iter_count)
self.iter_count += 1
return ret
# for Python2
def next(self):
return self.__next__()
def _len(self):
return self.get_width()
def __len__(self):
ret = self._len()
if not isinstance(ret, int):
raise TypeError("Non int length.")
return ret
class _Variable(_Numeric):
def __init__(self, width=1, dims=None, signed=False, value=None, initval=None, name=None,
raw_width=None, raw_dims=None, module=None):
_Numeric.__init__(self)
self.name = name
self.width = width
if dims is not None and not isinstance(dims, (tuple, list)):
dims = tuple([dims])
self.dims = dims
self.signed = signed
self.value = value
self.initval = initval
self.raw_width = raw_width # (MSB, LSB)
if raw_dims is not None:
for raw_dim in raw_dims:
if not isinstance(raw_dim, tuple):
raise TypeError('dim must be tuple.')
if len(raw_dim) != 2:
raise TypeError('len of dim must be 2.')
self.raw_dims = tuple(raw_dims) # [(L, R), ...]
else:
self.raw_dims = None
self.module = module
self.subst = []
self.assign_value = None
@property
def shape(self):
return self.dims
def write(self, value, blk=False, ldelay=None, rdelay=None):
return _write_subst(self, value, blk, ldelay, rdelay)
def read(self):
return self
def assign(self, value):
if self.module is None:
raise ValueError(
"Variable '%s' has no parent module information" % self.name)
return self.module.Assign(self.write(value))
def connect(self, value):
if self.module is None:
raise ValueError(
"Variable '%s' has no parent module information" % self.name)
if isinstance(self, Reg):
wire_self = self.module.TmpWireLike(self)
wire_self.assign(value)
self.module.Always()(self(wire_self, blk=True))
elif isinstance(self, (Wire, Output)):
self.assign(value)
else:
raise TypeError('connect() is not supported')
def comb(self, value):
return self.assign(value)
def reset(self):
return None
def get_width(self):
return self.width
def get_signed(self):
return self.signed
def _add_assign(self, s):
if self.assign_value is not None:
raise ValueError('already assigned')
self.assign_value = s
def _get_assign(self):
return self.assign_value
def _add_subst(self, s):
self.subst.append(s)
def _get_subst(self):
return self.subst
def _get_module(self):
return self.module
def __setattr__(self, attr, value):
if attr == 'width':
object.__setattr__(self, 'raw_width', None)
if attr == 'dims':
object.__setattr__(self, 'raw_dims', None)
object.__setattr__(self, attr, value)
def __str__(self):
return self.name
def __call__(self, value, blk=False, ldelay=None, rdelay=None):
return self.write(value, blk=blk, ldelay=ldelay, rdelay=rdelay)
def _len(self):
if self.dims is not None:
return self.dims[0]
return self.get_width()
class Input(_Variable):
pass
class Output(_Variable):
pass
class Inout(_Variable):
pass
class Tri(_Variable):
pass
class Reg(_Variable):
def assign(self, value):
raise TypeError("Reg object accept no combinational assignment.")
def reset(self):
if self.initval is None:
return None
return self.write(self.initval)
def add(self, r):
return self.write(self + r)
def sub(self, r):
return self.write(self - r)
def inc(self):
return self.add(1)
def dec(self):
return self.sub(1)
class Wire(_Variable):
def _add_subst(self, s):
if len(self.subst) > 0:
raise ValueError('Wire %s is already assigned.' % self.name)
self.subst.append(s)
class Integer(_Variable):
def reset(self):
if self.initval is None:
return None
return self.write(self.initval)
def add(self, r):
return self.write(self + r)
def sub(self, r):
return self.write(self - r)
def inc(self):
return self.add(1)
def dec(self):
return self.sub(1)
class Real(_Variable):
def reset(self):
if self.initval is None:
return None
return self.write(self.initval)
def add(self, r):
return self.write(self + r)
def sub(self, r):
return self.write(self - r)
def inc(self):
return self.add(1)
def dec(self):
return self.sub(1)
class Genvar(_Variable):
def add(self, r):
return self.write(self + r)
def sub(self, r):
return self.write(self - r)
def inc(self):
return self.add(1)
def dec(self):
return self.sub(1)
# for undetermined identifier
class AnyType(_Variable):
pass
class _ParameterVariable(_Variable):
def __init__(self, value, width=None, signed=False, name=None,
raw_width=None, module=None):
if isinstance(value, _ParameterVariable):
value = value.value
if value is None:
raise ValueError('value must not be None.')
_Variable.__init__(self, width=width, signed=signed, value=value, name=name,
raw_width=raw_width, module=module)
def get_width(self):
if self.width is None:
return 32
return self.width
class Parameter(_ParameterVariable):
pass
class Localparam(_ParameterVariable):
pass
class Supply(_ParameterVariable):
pass
class _Constant(_Numeric):
attr_names = ('value',)
def __init__(self, value, width=None, base=None):
_Numeric.__init__(self)
self.value = value
self.width = width
self.base = base
self._type_check_value(value)
self._type_check_width(width)
self._type_check_base(base)
def _type_check_value(self, value): pass
def _type_check_width(self, width): pass
def _type_check_base(self, base): pass
def __str__(self):
return str(self.value)
def get_width(self):
if self.width is None:
return 32
return self.width
class Int(_Constant):
def __init__(self, value, width=None, base=None, signed=False, is_raw_value=False):
_Constant.__init__(self, value, width, base)
if is_raw_value:
if width is None:
raise ValueError(
'width is required when is_raw_value is enabled.')
if base is None:
raise ValueError(
'base is required when is_raw_value is enabled.')
self.value = value
self.width = width
self.base = base
self.signed = signed
elif isinstance(value, int):
self.value = value
self.width = width
self.base = base
self.signed = signed if value >= 0 else value < 0
else:
self.value, self.base = str_to_value(value)
if base is not None:
self.base = base
if not isinstance(self.value, int):
if self.base is None:
check_int_dec_pure(self.value)
elif self.base == 16:
check_int_hex(self.value)
elif self.base == 10:
check_int_dec(self.value)
elif self.base == 8:
check_int_oct(self.value)
elif self.base == 2:
check_int_bin(self.value)
else:
raise ValueError(
"Illegal base number %d for Int." % self.base)
self.width = str_to_width(value) if width is None else width
self.signed = str_to_signed(value) if signed == False else signed
def _type_check_value(self, value):
if not isinstance(value, (int, str)):
raise TypeError(
'value of Int must be int or str, not %s.' % str(type(value)))
def _type_check_width(self, width):
if width is None:
return
if not isinstance(width, int):
raise TypeError('width of Int must be int, not %s.' %
str(type(width)))
def _type_check_base(self, base):
if base is None:
return
if not isinstance(base, int):
raise TypeError('base of Int must be int, not %s.' %
str(type(base)))
def __str__(self):
value_list = []
if self.width:
value_list.append(str(self.width))
if self.base is None:
if self.signed:
value_list.append("'sd")
elif self.width:
value_list.append("'d")
if isinstance(self.value, str):
value_list.append(self.value)
else:
value_list.append(str(self.value))
elif self.base == 2:
if self.signed:
value_list.append("'sb")
else:
value_list.append("'b")
if isinstance(self.value, str):
value_list.append(self.value)
else:
value_list.append(bin(self .value).replace('0b', ''))
elif self.base == 8:
if self.signed:
value_list.append("'so")
else:
value_list.append("'o")
if isinstance(self.value, str):
value_list.append(self.value)
else:
value_list.append(oct(self.value).replace('0o', ''))
elif self.base == 10:
if self.signed:
value_list.append("'sd")
else:
value_list.append("'d")
if isinstance(self.value, str):
value_list.append(self.value)
else:
value_list.append(str(self.value))
elif self.base == 16:
if self.signed:
value_list.append("'sh")
else:
value_list.append("'h")
if isinstance(self.value, str):
value_list.append(self.value)
else:
value_list.append(hex(self.value).replace('0x', ''))
else:
raise ValueError("Int.base must be 2, 8, 10, or 16")
return ''.join(value_list)
def get_signed(self):
return self.signed
def IntX(width=None, base=None, signed=False):
return Int("'hx", width, base, signed)
def IntZ(width=None, base=None, signed=False):
return Int("'hz", width, base, signed)
class Float(_Constant):
def __init__(self, value):
_Constant.__init__(self, value, None, None)
self.value = value
self.width = 32
def _type_check_value(self, value):
if not isinstance(value, (float, int)):
raise TypeError(
'value of Float must be float, not %s.' % str(type(value)))
def __str__(self):
return str(self.value)
def get_signed(self):
return True
class Str(_Constant):
def __init__(self, value):
_Constant.__init__(self, value, None, None)
self.value = value
def _type_check_value(self, value):
if not isinstance(value, str):
raise TypeError('value of Str must be str, not %s.' %
str(type(value)))
def __str__(self):
return str(self.value)
class _Operator(_Numeric):
def __init__(self):
_Numeric.__init__(self)
self.signed = False
def get_signed(self):
return self.signed
class _BinaryOperator(_Operator):
attr_names = ('left', 'right')
def __init__(self, left, right):
_Operator.__init__(self)
self._type_check(left, right)
self.left = left
self.right = right
self.signed = get_signed(self.left) and get_signed(self.right)
def _type_check(self, left, right):
if not isinstance(left, (_Numeric, bool, int, float, str)):
raise TypeError(
'BinaryOperator does not support Type %s' % str(type(left)))
if not isinstance(right, (_Numeric, bool, int, float, str)):
raise TypeError(
'BinaryOperator does not support Type %s' % str(type(right)))
def _get_module(self):
if hasattr(self.left, '_get_module'):
return self.left._get_module()
if hasattr(self.right, '_get_module'):
return self.right._get_module()
return None
def __str__(self):
return ''.join(['(', str(self.left), ' ', op2mark(self.__class__.__name__), ' ',
str(self.right), ')'])
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return max_width(left, right) + 1
def get_signed(self):
return self.signed
class _UnaryOperator(_Operator):
attr_names = ('right',)
def __init__(self, right):
_Operator.__init__(self)
self._type_check(right)
self.right = right
self.signed = get_signed(self.right)
def _type_check(self, right):
if not isinstance(right, (_Numeric, bool, int, float, str)):
raise TypeError(
'BinaryOperator does not support Type %s' % str(type(right)))
def _get_module(self):
if hasattr(self.right, '_get_module'):
return self.right._get_module()
return None
def __str__(self):
return ''.join(['(', op2mark(self.__class__.__name__), str(self.right), ')'])
def get_width(self):
return get_width(self.right)
# for FixedPoint
class _SkipUnaryOperator(_UnaryOperator):
pass
# class names must be same the ones in pyverilog.vparser.ast
class Power(_BinaryOperator):
@staticmethod
def op(left, right, lwidth, rwidth):
return left ** right
class Times(_BinaryOperator):
@staticmethod
def op(left, right, lwidth, rwidth):
return left * right
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return left + right
class Divide(_BinaryOperator):
@staticmethod
def op(left, right, lwidth, rwidth):
return left // right
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return max_width(left, right)
class Mod(_BinaryOperator):
@staticmethod
def op(left, right, lwidth, rwidth):
return left % right
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return max_width(left, right)
class Plus(_BinaryOperator):
@staticmethod
def op(left, right, lwidth, rwidth):
return left + right
class Minus(_BinaryOperator):
@staticmethod
def op(left, right, lwidth, rwidth):
return left - right
# general name alias
def Add(left, right):
return Plus(left, right)
def Sub(left, right):
return Minus(left, right)
def Mul(left, right):
return Times(left, right)
def Div(left, right):
return Divide(left, right)
class Sll(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = get_signed(self.left)
@staticmethod
def op(left, right, lwidth, rwidth):
return left << right
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return Int(2) ** right + left
class Srl(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left >> right
def get_width(self):
left = get_width(self.left)
return left
class Sra(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = get_signed(self.left)
@staticmethod
def op(left, right, lwidth, rwidth):
sign = left >= 0
left = abs(left)
ret = left >> right
if not sign:
return -1 * ret
return ret
def get_width(self):
left = get_width(self.left)
return left
class LessThan(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left < right
def get_width(self):
return 1
class GreaterThan(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left > right
def get_width(self):
return 1
class LessEq(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left <= right
def get_width(self):
return 1
class GreaterEq(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left >= right
def get_width(self):
return 1
class Eq(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left == right
def get_width(self):
return 1
class NotEq(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left != right
def get_width(self):
return 1
class Eql(_BinaryOperator): # ===
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left == right
def get_width(self):
return 1
class NotEql(_BinaryOperator): # !==
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left != right
def get_width(self):
return 1
class And(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left & right
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return max_width(left, right)
class Xor(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left ^ right
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return max_width(left, right)
class Xnor(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
width = max(lwidth, rwidth)
value = ~(left ^ right)
mask = 0
for i in range(width):
mask = (0x1 << i) | mask
return mask & value
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return max_width(left, right)
class Or(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
return left | right
def get_width(self):
left = get_width(self.left)
right = get_width(self.right)
return max_width(left, right)
class Land(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
if left and right:
return True
return False
def get_width(self):
return 1
class Lor(_BinaryOperator):
def __init__(self, left, right):
_BinaryOperator.__init__(self, left, right)
self.signed = False
@staticmethod
def op(left, right, lwidth, rwidth):
if left or right:
return True
return False
def get_width(self):
return 1
class Uplus(_UnaryOperator):
@staticmethod
def op(right, rwidth):
return right
class Uminus(_UnaryOperator):
@staticmethod
def op(right, rwidth):
return -right
class Ulnot(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
return not right
def get_width(self):
return 1
class Unot(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
return ~right
class Uand(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
for i in range(rwidth):
v = (right >> i) & 0x1
if not v:
return False
return True
def get_width(self):
return 1
class Unand(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
for i in range(rwidth):
v = (right >> i) & 0x1
if not v:
return True
return False
def get_width(self):
return 1
class Uor(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
for i in range(rwidth):
v = (right >> i) & 0x1
if v:
return True
return False
def get_width(self):
return 1
class Unor(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
for i in range(rwidth):
v = (right >> i) & 0x1
if v:
return False
return True
def get_width(self):
return 1
class Uxor(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
ret = False
for i in range(rwidth):
v = (right >> i) & 0x1
ret = ret ^ v
return ret
def get_width(self):
return 1
class Uxnor(_UnaryOperator):
def __init__(self, right):
_UnaryOperator.__init__(self, right)
self.signed = False
@staticmethod
def op(right, rwidth):
ret = True
for i in range(rwidth):
v = (right >> i) & 0x1
ret = ret ^ v
return ret
def get_width(self):
return 1
# alias
def Not(*args):
return Ulnot(*args)
def AndList(*args):
if len(args) == 0:
raise ValueError("LandList requires at least one argument.")
if len(args) == 1:
return args[0]
left = args[0]
for right in args[1:]:
left = Land(left, right)
return left
def OrList(*args):
if len(args) == 0:
raise ValueError("LorList requires at least one argument.")
if len(args) == 1:
return args[0]
left = args[0]
for right in args[1:]:
left = Lor(left, right)
return left
Ands = AndList
Ors = OrList
class _SpecialOperator(_Operator):
attr_names = ('args', 'kwargs')
def __init__(self, *args, **kwargs):
_Operator.__init__(self)
self.args = args
self.kwargs = kwargs
self.signed = False
def _get_module(self):
return None
class Pointer(_SpecialOperator):
attr_names = ('var', 'pos')
def __init__(self, var, pos):
_SpecialOperator.__init__(self)
self.var = var
self.pos = pos
self.subst = []
self.assign_value = None
self._type_check_var(var)
def write(self, value, blk=False, ldelay=None, rdelay=None):
return _write_subst(self, value, blk, ldelay, rdelay)
def read(self):
return self
def get_width(self):
if isinstance(self.var, _Variable) and self.var.dims is not None:
return get_width(self.var)
if isinstance(self.var, Pointer):
root = self.var
depth = 1
while True:
if not isinstance(root, Pointer):
break
root = root.var
depth += 1
if not hasattr(root, 'dims'):
return 1
if len(root.dims) >= depth:
return get_width(root)
return 1
return 1
def assign(self, value):
module = self._get_module()
if module is None:
raise ValueError("This Pointer has no parent module information")
return module.Assign(self.write(value))
def _type_check_var(self, var):
if not isinstance(var, (_Variable, Scope, Pointer)):
raise TypeError(
'var of Pointer must be Variable, not %s' % str(type(var)))
def _add_assign(self, s):
if self.assign_value is not None:
raise ValueError('already assigned')
self.assign_value = s
def _get_assign(self):
return self.assign_value
def _add_subst(self, s):
self.subst.append(s)
def _get_subst(self):
return self.subst
def _get_module(self):
if not hasattr(self.var, '_get_module'):
return None
return self.var._get_module()
def __str__(self):
return ''.join([str(self.var), '[', str(self.pos), ']'])
def __call__(self, value, blk=False, ldelay=None, rdelay=None):
return self.write(value, blk=blk, ldelay=ldelay, rdelay=rdelay)
def _len(self):
root = self.var
depth = 1
while True:
if not isinstance(root, Pointer):
break
root = root.var
depth += 1
if not hasattr(root, 'dims'):
return 1
if len(root.dims) > depth:
return root.dims[depth - 1]
return self.get_width()
@staticmethod
def op(var, pos):
return (var >> pos) & 0x1
class Slice(_SpecialOperator):
attr_names = ('var', 'msb', 'lsb')
def __init__(self, var, msb, lsb):
_SpecialOperator.__init__(self)
self.var = var
self.msb = msb
self.lsb = lsb
self.subst = []
self.assign_value = None
self._type_check_var(var)
def write(self, value, blk=False, ldelay=None, rdelay=None):
return _write_subst(self, value, blk, ldelay, rdelay)
def read(self):
return self
def get_width(self):
return self.msb - self.lsb + 1
def assign(self, value):
module = self._get_module()
if module is None:
raise ValueError("This Slice has no parent module information")
return module.Assign(self.write(value))
def _type_check_var(self, var):
if not isinstance(var, (_Variable, Scope)):
raise TypeError(
'var of Slice must be Variable, not %s' % str(type(var)))
def _add_assign(self, s):
if self.assign_value is not None:
raise ValueError('already assigned')
self.assign_value = s
def _get_assign(self):
return self.assign_value
def _add_subst(self, s):
self.subst.append(s)
def _get_subst(self):
return self.subst
def _get_module(self):
if not hasattr(self.var, '_get_module'):
return None
return self.var._get_module()
def __str__(self):
return ''.join([str(self.var), '[', str(self.msb), ':', str(self.lsb), ']'])
def __call__(self, value, blk=False, ldelay=None, rdelay=None):
return self.write(value, blk=blk, ldelay=ldelay, rdelay=rdelay)
@staticmethod
def op(var, msb, lsb):
mask = 0
for i in range(msb - lsb + 1):
mask = (mask << 1) | 0x1
return (var >> lsb) & mask
class Cat(_SpecialOperator):
attr_names = ('vars',)
def __init__(self, *vars):
_SpecialOperator.__init__(self)
self.vars = tuple(vars)
self.assign_value = None
self.subst = []
def write(self, value, blk=False, ldelay=None, rdelay=None):
return _write_subst(self, value, blk, ldelay, rdelay)
def read(self):
return self
def get_width(self):
values = [get_width(v) for v in self.vars]
ret = values[0]
for v in values[1:]:
ret = ret + v
return ret
def assign(self, value):
module = self._get_module()
if module is None:
raise ValueError("This Cat has no parent module information")
return module.Assign(self.write(value))
def _add_assign(self, s):
if self.assign_value is not None:
raise ValueError('already assigned')
self.assign_value = s
def _get_assign(self):
return self.assign_value
def _add_subst(self, s):
self.subst.append(s)
def _get_subst(self):
return self.subst
def _get_module(self):
for var in self.vars:
if hasattr(var, '_get_module'):
return var._get_module()
return None
def __str__(self):
ret = []
ret.append('{')
for v in self.vars:
ret.append(str(v))
ret.append(', ')
ret.pop()
ret.append('}')
return ''.join(ret)
def __call__(self, value, blk=False, ldelay=None, rdelay=None):
return self.write(value, blk=blk, ldelay=ldelay, rdelay=rdelay)
@staticmethod
def op(vars, widths):
ret = 0
for var, width in zip(vars, widths):
ret = (ret << width) | var
return ret
class Repeat(_SpecialOperator):
attr_names = ('var', 'times')
def __init__(self, var, times):
_SpecialOperator.__init__(self)
self.var = var
self.times = times
def get_width(self):
return get_width(self.var) * self.times
def __str__(self):
return ''.join(['{', str(self.times), '{', str(self.var), '}}'])
@staticmethod
def op(var, width, times):
ret = 0
for i in range(times):
ret = (ret << width) | var
return ret
class Cond(_SpecialOperator):
def __init__(self, condition, true_value, false_value):
_SpecialOperator.__init__(self)
self.condition = condition
self.true_value = true_value
self.false_value = false_value
self.signed = get_signed(
self.true_value) or get_signed(self.false_value)
def get_width(self):
t = get_width(self.true_value)
f = get_width(self.false_value)
return max_width(t, f)
def __str__(self):
return ''.join(['(', str(self.condition), ')?',
str(self.true_value), ' : ', str(self.false_value)])
@staticmethod
def op(condition, true_value, false_value):
if condition:
return true_value
else:
return false_value
def Mux(condition, true_value, false_value):
# return the result immediately if the condition can be resolved now
if isinstance(condition, (bool, int, float, str, list, tuple)):
return true_value if condition else false_value
return Cond(condition, true_value, false_value)
def Complement2(var):
if isinstance(var, (int, bool, float)):
return abs(var)
return Unot(var) + Int(1)
def Abs(var):
return Mux(Sign(var), Complement2(var), var)
def Sign(var):
if isinstance(var, (int, bool, float)):
return var < 0
return var < Int(0, signed=True)
class Sensitive(VeriloggenNode):
def __init__(self, name):
VeriloggenNode.__init__(self)
self.name = name
class Posedge(Sensitive):
pass
class Negedge(Sensitive):
pass
class SensitiveAll(Sensitive):
def __init__(self):
Sensitive.__init__(self, 'all')
class Subst(VeriloggenNode):
def __init__(self, left, right, blk=False, ldelay=None, rdelay=None):
VeriloggenNode.__init__(self)
self._type_check_left(left)
self._type_check_right(right)
self.left = left
self.right = right
self.blk = blk
self.ldelay = ldelay
self.rdelay = rdelay
self.left._add_subst(self)
def _type_check_left(self, left):
if not isinstance(left, VeriloggenNode):
raise TypeError(
"left must be VeriloggenNode, not '%s'" % str(type(left)))
def _type_check_right(self, right):
if not isinstance(right, (VeriloggenNode, int, float, bool, str)):
raise TypeError(
"right must be VeriloggenNode, not '%s'" % str(type(right)))
def overwrite_right(self, right):
self.right = right
def __str__(self):
return ''.join([str(self.left), ' <- ', str(self.right)])
class Always(VeriloggenNode):
def __init__(self, *sensitivity):
VeriloggenNode.__init__(self)
self.sensitivity = tuple(sensitivity)
self.statement = None
def set_statement(self, *statement):
if self.statement is not None:
raise ValueError("Statement is already assigned.")
self.statement = tuple(statement)
return self
def __call__(self, *statement):
return self.set_statement(*statement)
class Assign(VeriloggenNode):
def __init__(self, statement):
VeriloggenNode.__init__(self)
self.statement = statement
statement.left._add_assign(self)
def overwrite_right(self, v):
self.statement.overwrite_right(v)
class Initial(VeriloggenNode):
def __init__(self, *statement):
VeriloggenNode.__init__(self)
self.statement = tuple(statement)
def add(self, *statement):
if self.statement is None:
return self.set_statement(*statement)
self.statement = tuple(self.statement + statement)
return self
class If(VeriloggenNode):
def __init__(self, condition):
VeriloggenNode.__init__(self)
self.condition = condition
self.true_statement = None
self.false_statement = None
self.root = self
self.next_call = None
def set_true_statement(self, *statement):
self.true_statement = tuple(statement)
return self.root
def set_false_statement(self, *statement):
self.false_statement = tuple(statement)
return self.root
def Else(self, *statement):
if self.next_call is not None:
return self.next_call.Else(*statement)
if self.false_statement is None:
return self.set_false_statement(*statement)
raise ValueError("False statement is already assigned.")
def Elif(self, condition):
next_If = If(condition)
next_If.root = self.root
self.Else(next_If)
self.next_call = next_If
return self
def __call__(self, *args):
if self.next_call is not None:
return self.next_call(*args)
if self.true_statement is None:
return self.set_true_statement(*args)
if self.false_statement is None:
return self.set_false_statement(*args)
raise ValueError(
"True statement and False statement are already assigned.")
class For(VeriloggenNode):
def __init__(self, pre, condition, post):
VeriloggenNode.__init__(self)
self.pre = pre
self.condition = condition
self.post = post
self.statement = None
def set_statement(self, *statement):
self.statement = tuple(statement)
return self
def add(self, *statement):
if self.statement is None:
return self.set_statement(*statement)
self.statement = tuple(self.statement + statement)
return self
def __call__(self, *args):
if self.statement is None:
return self.set_statement(*args)
raise ValueError("Statement body is already assigned.")
class While(VeriloggenNode):
def __init__(self, condition):
VeriloggenNode.__init__(self)
self.condition = condition
self.statement = None
def set_statement(self, *statement):
self.statement = tuple(statement)
return self
def add(self, *statement):
if self.statement is None:
return self.set_statement(*statement)
self.statement = tuple(self.statement + statement)
return self
def __call__(self, *args):
if self.statement is None:
return self.set_statement(*args)
raise ValueError("Statement body is already assigned.")
class Case(VeriloggenNode):
def __init__(self, comp):
VeriloggenNode.__init__(self)
self.comp = comp
self.statement = None
self.last = False
def _type_check_statement(self, *statement):
for s in statement:
if not isinstance(s, When):
raise TypeError(
"Case statement requires When() object as statement list.")
if self.last:
raise ValueError("When() with None condition must be last.")
if s.condition is None:
self.last = True
def set_statement(self, *statement):
self._type_check_statement(*statement)
self.statement = tuple(statement)
return self
def add(self, *statement):
if self.statement is None:
return self.set_statement(*statement)
self._type_check_statement(*statement)
self.statement = tuple(self.statement + statement)
return self
def __call__(self, *args):
if self.statement is None:
return self.set_statement(*args)
raise ValueError("Case statement list is already assigned.")
class Casex(Case):
pass
class When(VeriloggenNode):
def __init__(self, *condition):
VeriloggenNode.__init__(self)
self._type_check_condition(*condition)
self.condition = None if len(condition) == 0 or condition[
0] is None else tuple(condition)
self.statement = None
def _type_check_condition(self, *args):
if len(args) == 0:
return
if len(args) == 1 and args[0] is None:
return
for i, a in enumerate(args):
if a is None:
raise ValueError(
"None condition must not mixed in When() statement.")
if isinstance(a, (_Numeric, bool, int, float, str)):
continue
raise TypeError(
"Condition must be _Numeric object, not '%s'" % str(type(a)))
def _type_check_statement(self, *args):
pass
def set_statement(self, *statement):
self._type_check_statement(*statement)
self.statement = tuple(statement)
return self
def add(self, *statement):
if self.statement is None:
return self.set_statement(*statement)
self._type_check_statement(*statement)
self.statement = tuple(self.statement + statement)
return self
def __call__(self, *args):
if self.statement is None:
return self.set_statement(*args)
raise ValueError("Statement body is already assigned.")
def PatternIf(*patterns):
root = None
prev = None
length = len(patterns)
if len(patterns) == 1 and isinstance(patterns, (tuple, list)):
patterns = patterns[0]
for i, (cond, stmt) in enumerate(patterns):
if not isinstance(stmt, (tuple, list)):
stmt = tuple([stmt])
body = If(cond)(stmt) if cond is not None else stmt
if root is None:
root = body
else:
prev.Else(body)
prev = body
if cond is None:
if i < length - 1:
raise ValueError("Too many patterns after None condition.")
break
return root
def PatternMux(*patterns):
prev = None
if len(patterns) == 1 and isinstance(patterns, (tuple, list)):
patterns = patterns[0]
for i, (cond, stmt) in enumerate(reversed(patterns)):
if prev is None and cond is not None:
raise ValueError('Last pattern requires a None condition.')
if prev is not None and cond is None:
raise ValueError('Non-last pattern requires a condition.')
prev = Mux(cond, stmt, prev) if cond is not None else stmt
return prev
class ScopeIndex(VeriloggenNode):
def __init__(self, name, index):
VeriloggenNode.__init__(self)
self.name = name
self.index = index
class Scope(_Numeric):
def __init__(self, *args):
_Numeric.__init__(self)
self.args = tuple(args)
if not args:
raise ValueError("Scope requires at least one argument.")
def get_width(self):
try:
w = get_width(self.args[-1])
return w
except:
raise ValueError('could not identify get_width.')
class SystemTask(_Numeric):
def __init__(self, cmd, *args):
_Numeric.__init__(self)
cmd = raw_value(cmd)
self.cmd = cmd
self.args = tuple(args)
def get_width(self):
if self.cmd == 'signed':
return get_width(self.args[0])
raise TypeError("get_width() is not supported.")
def Systask(cmd, *args):
return SingleStatement(SystemTask(cmd, *args))
# frequently-used system task
def Display(*args):
return Systask('display', *args)
def Write(*args):
return Systask('write', *args)
def Finish():
return Systask('finish')
def Signed(value):
return SystemTask('signed', value)
class Event(VeriloggenNode):
def __init__(self, *sensitivity):
VeriloggenNode.__init__(self)
self.sensitivity = sensitivity
class Wait(VeriloggenNode):
def __init__(self, condition):
VeriloggenNode.__init__(self)
self.condition = condition
self.statement = None
def set_statement(self, *statement):
if self.statement is not None:
raise ValueError("Statement is already assigned.")
self.statement = tuple(statement)
return self
def __call__(self, *statement):
return self.set_statement(*statement)
class Forever(VeriloggenNode):
def __init__(self, *statement):
VeriloggenNode.__init__(self)
self.statement = tuple(statement)
class Delay(VeriloggenNode):
def __init__(self, value):
VeriloggenNode.__init__(self)
self.value = value
class SingleStatement(VeriloggenNode):
def __init__(self, statement):
VeriloggenNode.__init__(self)
self.statement = statement
class EmbeddedCode(VeriloggenNode):
def __init__(self, code):
VeriloggenNode.__init__(self)
code = raw_value(code)
self.code = code
class EmbeddedNumeric(EmbeddedCode, _Numeric):
def __init__(self, code):
EmbeddedCode.__init__(self, code)
numerical_types = (_Numeric, int, bool, float, str)
| [
"[email protected]"
] | |
cb3e782d2e8d4c07ddb117999aa1faf47756683f | eb59f8212f40bd7c316e1ef3be03bf7da3dde65f | /annotated2_0/scr_useea.py | d58536a905383f09f108651629f2610863a69e57 | [] | no_license | shtkn/frameDataParser | 764cc3197051966717990f7ca3eb2f02639cf438 | 690d44d4bf188a14c4e5ebebd95bdc75b827f5e5 | refs/heads/master | 2021-07-05T00:52:53.316670 | 2020-10-03T18:16:52 | 2020-10-03T18:16:52 | 187,556,058 | 0 | 0 | null | 2019-11-25T05:36:06 | 2019-05-20T02:40:24 | Python | UTF-8 | Python | false | false | 72,440 | py | @State
def EffNmlAtk5A():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_071_00', 5) # 1-5
sprite('Action_071_01', 5) # 6-10
sprite('Action_071_02', 1) # 11-11
@State
def EffNmlAtk5A_2nd():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_084_00', 5) # 1-5
sprite('Action_084_01', 5) # 6-10
sprite('Action_084_02', 5) # 11-15
@State
def EffNmlAtk5A_3rd():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_082_00', 5) # 1-5
sprite('Action_082_01', 5) # 6-10
sprite('Action_082_02', 5) # 11-15
sprite('Action_082_03', 1) # 16-16
@State
def EffNmlAtk5A_4th_AirShadow():
def upon_IMMEDIATE():
Unknown3026(-16777216)
teleportRelativeX(26000)
Unknown1007(50000)
Unknown23022(1)
Unknown2035(1)
sprite('Action_364_03', 2) # 1-2 **attackbox here**
Unknown3001(128)
Unknown3004(-20)
sprite('Action_364_03', 2) # 3-4 **attackbox here**
physicsXImpulse(25000)
physicsYImpulse(21000)
setGravity(1900)
sprite('Action_364_04', 6) # 5-10 **attackbox here**
@State
def EffNmlAtk5A_4th_LandZanzo():
def upon_IMMEDIATE():
Unknown2005()
Unknown1007(200000)
physicsXImpulse(100000)
Unknown2035(1)
sprite('Action_101_00', 4) # 1-4
sprite('Action_101_01', 4) # 5-8
sprite('Action_101_02', 4) # 9-12
sprite('Action_101_03', 4) # 13-16
sprite('Action_101_04', 4) # 17-20
sprite('Action_101_05', 4) # 21-24
sprite('Action_101_06', 2) # 25-26
@State
def EffNmlAtk5A_4th_Dummy_Zanzo():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_082_00', 5) # 1-5
sprite('Action_082_01', 5) # 6-10
sprite('Action_082_02', 5) # 11-15
sprite('Action_082_03', 1) # 16-16
@State
def EffNmlAtk5A_4th_AtkSub():
def upon_IMMEDIATE():
Unknown1007(100000)
sprite('Action_379_00', 3) # 1-3 **attackbox here**
sprite('Action_379_01', 3) # 4-6 **attackbox here**
sprite('Action_379_02', 3) # 7-9
sprite('Action_379_03', 3) # 10-12
@State
def EffNmlAtk5B_2nd_LandShadow():
def upon_IMMEDIATE():
Unknown3026(-16777216)
teleportRelativeX(75000)
Unknown2035(1)
sprite('Action_270_00', 6) # 1-6
Unknown3001(128)
Unknown3004(-10)
sprite('Action_270_01', 6) # 7-12
sprite('Action_270_02', 6) # 13-18
@State
def EffNmlAtk5B_2nd_Zanzo():
def upon_IMMEDIATE():
Unknown2054(1)
sprite('Action_382_00', 4) # 1-4
sprite('Action_382_01', 4) # 5-8
sprite('Action_382_02', 4) # 9-12
sprite('Action_382_03', 1) # 13-13
@State
def EffNmlAtk5B_2nd_Zanzo2():
def upon_IMMEDIATE():
Unknown2054(1)
Unknown1007(120000)
sprite('Action_376_00', 2) # 1-2
sprite('Action_376_01', 2) # 3-4
sprite('Action_376_02', 2) # 5-6
sprite('Action_376_03', 2) # 7-8
sprite('Action_376_04', 2) # 9-10
sprite('Action_376_05', 2) # 11-12
sprite('Action_376_06', 2) # 13-14
sprite('Action_376_07', 2) # 15-16
@State
def EffNmlAtk5B_3rd_Zanzo():
def upon_IMMEDIATE():
Unknown2054(1)
sprite('Action_383_00', 4) # 1-4
sprite('Action_383_01', 4) # 5-8
sprite('Action_383_02', 4) # 9-12
sprite('Action_383_03', 1) # 13-13
@State
def EffNmlAtk5B_3rd_Zanzo2():
def upon_IMMEDIATE():
Unknown2054(1)
Unknown2005()
sprite('Action_219_00', 2) # 1-2
sprite('Action_219_01', 2) # 3-4
sprite('Action_219_02', 2) # 5-6
sprite('Action_219_03', 2) # 7-8
sprite('Action_219_04', 2) # 9-10
sprite('Action_219_05', 2) # 11-12
sprite('Action_219_06', 2) # 13-14
sprite('Action_219_07', 1) # 15-15
@State
def EffReversal_Zanzo():
def upon_IMMEDIATE():
Unknown2054(1)
Unknown1072(-15000)
sprite('Action_383_00', 4) # 1-4
sprite('Action_383_01', 4) # 5-8
sprite('Action_383_02', 4) # 9-12
sprite('Action_383_03', 1) # 13-13
@State
def EffNmlAtk5B_4th_AirZanzo():
def upon_IMMEDIATE():
Unknown2054(1)
sprite('Action_218_00', 2) # 1-2
sprite('Action_218_01', 2) # 3-4
sprite('Action_218_02', 2) # 5-6
sprite('Action_218_03', 2) # 7-8
sprite('Action_218_04', 2) # 9-10
sprite('Action_218_05', 2) # 11-12
sprite('Action_218_06', 2) # 13-14
sprite('Action_218_07', 1) # 15-15
@State
def EffNmlAtk5B_4th_LandZanzo1():
sprite('Action_224_00', 6) # 1-6
Unknown3004(-20)
Unknown2035(1)
sprite('Action_224_01', 6) # 7-12
sprite('Action_224_02', 6) # 13-18
@State
def EffNmlAtk5B_4th_LandZanzo2():
def upon_IMMEDIATE():
Unknown2054(1)
Unknown2035(1)
sprite('Action_226_00', 4) # 1-4
sprite('Action_226_01', 4) # 5-8
sprite('Action_226_02', 4) # 9-12
sprite('Action_226_03', 1) # 13-13
@State
def EffNmlAtk5B_4th_AssistZanzo1():
def upon_IMMEDIATE():
Unknown2054(1)
Unknown23022(1)
Unknown3026(-16777216)
Unknown2035(1)
sprite('Action_045_01', 6) # 1-6
Unknown3004(-20)
sprite('Action_045_01', 6) # 7-12
sprite('Action_045_01', 6) # 13-18
@State
def EffNmlAtk5B_3rd_Kick():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_223_00', 4) # 1-4
sprite('Action_223_01', 4) # 5-8
sprite('Action_223_02', 4) # 9-12
@State
def EffConfuse_AtkMatome():
def upon_IMMEDIATE():
Unknown2054(1)
def upon_43():
if (SLOT_48 == 100):
Unknown1086(22)
Unknown1007(200000)
GFX_0('EffConfuse_AtkEff', 100)
GFX_0('EffConfuse_AtkEffSub1', 100)
GFX_0('EffConfuse_AtkEffSub2', 100)
GFX_0('EffConfuse_AtkEffSub3', 100)
if (SLOT_48 == 101):
Unknown1086(23)
Unknown1007(200000)
GFX_0('EffConfuse_AtkEff', 100)
GFX_0('EffConfuse_AtkEffSub1', 100)
GFX_0('EffConfuse_AtkEffSub2', 100)
GFX_0('EffConfuse_AtkEffSub3', 100)
sprite('null', 30) # 1-30
@State
def EffConfuse_AtkEff():
def upon_IMMEDIATE():
Unknown2054(1)
random_(2, 0, 50)
if SLOT_ReturnVal:
_gotolabel(1)
label(0)
sprite('Action_375_00', 4) # 1-4
sprite('Action_375_01', 4) # 5-8
sprite('Action_375_02', 4) # 9-12
sprite('Action_375_03', 4) # 13-16
sprite('Action_375_04', 4) # 17-20
sprite('Action_375_05', 4) # 21-24
sprite('Action_375_06', 4) # 25-28
ExitState()
label(1)
sprite('Action_375_08', 4) # 29-32
sprite('Action_375_09', 4) # 33-36
sprite('Action_375_10', 4) # 37-40
sprite('Action_375_11', 4) # 41-44
sprite('Action_375_12', 4) # 45-48
sprite('Action_375_13', 4) # 49-52
sprite('Action_375_14', 4) # 53-56
sprite('Action_375_15', 4) # 57-60
@State
def EffConfuse_AtkEffSub1():
def upon_IMMEDIATE():
Unknown2003(0)
teleportRelativeX(-320000)
Unknown1007(-150000)
Unknown2054(1)
sprite('null', 10) # 1-10
sprite('Action_378_00', 4) # 11-14 **attackbox here**
sprite('Action_378_01', 4) # 15-18 **attackbox here**
sprite('Action_378_02', 4) # 19-22
sprite('Action_378_03', 4) # 23-26
@State
def EffConfuse_AtkEffSub2():
def upon_IMMEDIATE():
Unknown2003(0)
teleportRelativeX(12000)
Unknown1007(150000)
Unknown2054(1)
sprite('null', 10) # 1-10
sprite('Action_378_04', 4) # 11-14 **attackbox here**
sprite('Action_378_05', 4) # 15-18 **attackbox here**
sprite('Action_378_06', 4) # 19-22
sprite('Action_378_07', 4) # 23-26
@State
def EffConfuse_AtkEffSub3():
def upon_IMMEDIATE():
Unknown2003(0)
teleportRelativeX(320000)
Unknown1007(-110000)
Unknown2054(1)
sprite('null', 10) # 1-10
sprite('Action_378_08', 4) # 11-14 **attackbox here**
sprite('Action_378_09', 4) # 15-18 **attackbox here**
sprite('Action_378_10', 4) # 19-22
sprite('Action_378_11', 4) # 23-26
@State
def EffNmlAtk5B():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_083_00', 5) # 1-5
sprite('Action_083_01', 5) # 6-10
sprite('Action_083_02', 5) # 11-15
sprite('Action_083_03', 1) # 16-16
@State
def EffNmlAtk2B():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_080_00', 6) # 1-6
sprite('Action_080_01', 6) # 7-12
sprite('Action_080_02', 1) # 13-13
@State
def EffNmlAtk5C():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_092_00', 5) # 1-5
sprite('Action_092_01', 5) # 6-10
sprite('Action_092_02', 5) # 11-15
sprite('Action_092_03', 1) # 16-16
@State
def EffNmlAtk5C_Chace2nd():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_093_00', 5) # 1-5
sprite('Action_093_01', 5) # 6-10
sprite('Action_093_02', 5) # 11-15
sprite('Action_093_03', 1) # 16-16
@State
def EffNmlAtkAIR5A():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_086_00', 5) # 1-5
sprite('Action_086_01', 5) # 6-10
sprite('Action_086_02', 5) # 11-15
sprite('Action_086_03', 1) # 16-16
@State
def EffNmlAtkAIR5B():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_087_00', 5) # 1-5
sprite('Action_087_01', 5) # 6-10
sprite('Action_087_02', 5) # 11-15
sprite('Action_087_03', 1) # 16-16
@State
def EffNmlAtkAIR5C_Shadow():
def upon_IMMEDIATE():
teleportRelativeX(50000)
Unknown1007(200000)
sprite('Action_125_00', 2) # 1-2
Unknown4004('6566666563745f3239350000000000000000000000000000000000000000000064000000')
Unknown36(1)
teleportRelativeX(-50000)
Unknown1072(60000)
Unknown35()
sprite('Action_125_01', 2) # 3-4
sprite('Action_125_02', 2) # 5-6
sprite('Action_125_03', 2) # 7-8
sprite('Action_125_04', 2) # 9-10
sprite('Action_125_05', 2) # 11-12
sprite('Action_125_06', 2) # 13-14
sprite('Action_125_07', 1) # 15-15
@State
def EffNmlAtkThow():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
sprite('Action_098_00', 3) # 1-3
sprite('Action_098_01', 3) # 4-6
sprite('Action_098_02', 3) # 7-9
sprite('Action_098_03', 3) # 10-12
sprite('Action_098_03', 3) # 13-15
@State
def EffAirBackDash():
sprite('Action_219_00', 2) # 1-2
sprite('Action_219_01', 2) # 3-4
sprite('Action_219_02', 2) # 5-6
sprite('Action_219_03', 2) # 7-8
sprite('Action_219_04', 2) # 9-10
sprite('Action_219_05', 2) # 11-12
sprite('Action_219_06', 2) # 13-14
sprite('Action_219_07', 2) # 15-16
@State
def EffReversalAdd():
def upon_IMMEDIATE():
Unknown1072(150000)
Unknown1007(100000)
teleportRelativeX(100000)
sprite('Action_219_00', 2) # 1-2
sprite('Action_219_01', 2) # 3-4
sprite('Action_219_02', 2) # 5-6
sprite('Action_219_03', 2) # 7-8
sprite('Action_219_04', 2) # 9-10
sprite('Action_219_05', 2) # 11-12
sprite('Action_219_06', 2) # 13-14
sprite('Action_219_07', 2) # 15-16
@State
def EffAssalut_Blade():
def upon_IMMEDIATE():
Unknown1007(250000)
physicsXImpulse(60000)
Unknown2054(1)
sprite('Action_100_00', 3) # 1-3
sprite('Action_100_01', 3) # 4-6
sprite('Action_100_02', 3) # 7-9
sprite('Action_100_03', 3) # 10-12
sprite('Action_100_04', 3) # 13-15
sprite('Action_100_05', 3) # 16-18
sprite('Action_100_06', 1) # 19-19
@State
def EffAssalut_BladeEx():
def upon_IMMEDIATE():
Unknown1007(250000)
physicsXImpulse(150000)
Unknown2054(1)
sprite('Action_100_00', 3) # 1-3
sprite('Action_100_01', 3) # 4-6
sprite('Action_100_02', 3) # 7-9
sprite('Action_100_03', 3) # 10-12
sprite('Action_100_04', 3) # 13-15
sprite('Action_100_05', 3) # 16-18
sprite('Action_100_06', 1) # 19-19
@State
def EffAssalut_Zanzo():
def upon_IMMEDIATE():
Unknown2054(1)
sprite('Action_171_00', 6) # 1-6
Unknown3004(-40)
sprite('Action_171_01', 2) # 7-8
@State
def EffAirAssalut_Add():
def upon_IMMEDIATE():
Unknown4010(3)
Unknown4007(3)
Unknown4009(3)
sprite('Action_388_00', 3) # 1-3
sprite('Action_388_01', 2) # 4-5
sprite('Action_388_02', 1) # 6-6
@State
def EffAirAssalut_GripSlush():
def upon_IMMEDIATE():
teleportRelativeX(55000)
Unknown1007(-75000)
sprite('Action_091_00', 5) # 1-5
sprite('Action_091_01', 7) # 6-12
sprite('Action_091_02', 6) # 13-18
sprite('Action_091_03', 1) # 19-19
@State
def EffAirAssalut_GripAtkEff():
sprite('Action_103_00', 5) # 1-5
sprite('Action_103_01', 2) # 6-7
sprite('Action_103_02', 3) # 8-10
sprite('Action_103_03', 7) # 11-17
sprite('Action_103_04', 3) # 18-20
sprite('Action_103_05', 1) # 21-21
@State
def Shot_Zanzo():
sprite('Action_089_00', 5) # 1-5
sprite('Action_089_01', 5) # 6-10
sprite('Action_089_02', 5) # 11-15
sprite('Action_089_03', 5) # 16-20
sprite('Action_089_04', 5) # 21-25
@State
def Shot_HitEff():
def upon_IMMEDIATE():
def upon_43():
if (SLOT_48 == 100):
Unknown1086(22)
Unknown1007(200000)
Unknown26('Shot_HitEffSub')
GFX_0('Shot_HitEffSub', 100)
Unknown23029(1, 210, 0)
if (SLOT_48 == 101):
Unknown1086(23)
Unknown1007(200000)
Unknown26('Shot_HitEffSub')
GFX_0('Shot_HitEffSub', 100)
Unknown23029(1, 211, 0)
random_(2, 0, 50)
if SLOT_ReturnVal:
_gotolabel(1)
label(0)
sprite('Action_112_00', 3) # 1-3
sprite('Action_112_01', 3) # 4-6
sprite('Action_112_02', 3) # 7-9
sprite('Action_112_03', 3) # 10-12
sprite('Action_112_04', 3) # 13-15
sprite('Action_112_05', 3) # 16-18
sprite('Action_112_06', 3) # 19-21
ExitState()
label(1)
sprite('Action_112_08', 3) # 22-24
sprite('Action_112_09', 3) # 25-27
sprite('Action_112_10', 3) # 28-30
sprite('Action_112_11', 3) # 31-33
sprite('Action_112_12', 3) # 34-36
sprite('Action_112_13', 3) # 37-39
sprite('Action_112_14', 3) # 40-42
sprite('Action_112_15', 3) # 43-45
@State
def Shot_HitEffSub():
def upon_IMMEDIATE():
Unknown2055(51)
def upon_43():
if (SLOT_48 == 210):
clearUponHandler(43)
SLOT_51 = 0
if (SLOT_48 == 211):
clearUponHandler(43)
SLOT_51 = 1
def upon_CLEAR_OR_EXIT():
if SLOT_51:
Unknown1086(23)
else:
Unknown1086(22)
Unknown1007(200000)
sprite('null', 15) # 1-15
label(999)
random_(2, 0, 33)
if SLOT_ReturnVal:
_gotolabel(2)
random_(2, 0, 50)
if SLOT_ReturnVal:
_gotolabel(1)
label(0)
sprite('Action_111_00', 3) # 16-18
sprite('Action_111_01', 3) # 19-21
sprite('Action_111_02', 3) # 22-24
sprite('Action_111_03', 3) # 25-27
loopRest()
gotoLabel(999)
label(1)
sprite('Action_111_06', 3) # 28-30
sprite('Action_111_07', 3) # 31-33
sprite('Action_111_08', 3) # 34-36
sprite('Action_111_09', 3) # 37-39
loopRest()
gotoLabel(999)
label(2)
sprite('Action_111_06', 3) # 40-42
sprite('Action_111_07', 3) # 43-45
sprite('Action_111_08', 3) # 46-48
sprite('Action_111_09', 3) # 49-51
loopRest()
gotoLabel(999)
@Subroutine
def Shot_Atk_InitParam():
AttackLevel_(3)
Damage(1000)
blockstun(11)
AttackP1(60)
AttackP2(95)
GroundedHitstunAnimation(1)
AirHitstunAnimation(1)
AirPushbackY(12000)
AirUntechableTime(25)
Unknown11001(0, 25, 25)
Unknown11050('080000000000000000000000000000000000000000000000000000000000000000000000')
Unknown9266(16)
Unknown23089('0100000001000000010000000100000001000000000000000100000000000000')
Unknown2019(-1000)
Unknown2006()
Unknown48('19000000020000003a000000020000000200000038000000')
if SLOT_58:
AttackP1(70)
def upon_CLEAR_OR_EXIT():
Unknown1019(110)
YAccel(110)
SLOT_54 = (SLOT_54 + 1)
if (SLOT_54 >= 3):
SLOT_54 = 0
GFX_0('Shot_Hasen', 100)
GFX_0('Shot_Hasens', 100)
loopRelated(17, 90)
def upon_17():
Unknown13(25)
def upon_ON_HIT_OR_BLOCK():
SFX_3('SE242')
def upon_78():
Unknown2038(1)
GFX_0('Shot_HitEff', 104)
Unknown23029(1, 100, 0)
def upon_82():
Unknown2038(1)
GFX_0('Shot_HitEff', 104)
Unknown23029(1, 101, 0)
def upon_LANDING():
clearUponHandler(2)
clearUponHandler(53)
Unknown23090(25)
def upon_53():
clearUponHandler(2)
clearUponHandler(53)
Unknown23090(25)
def upon_54():
GFX_0('Shot_AtkKoware', 100)
Unknown13(25)
@State
def Shot_Atk():
def upon_IMMEDIATE():
Unknown2010()
callSubroutine('Shot_Atk_InitParam')
def upon_43():
if (SLOT_48 == 208):
Unknown11042(1)
sprite('Action_139_00', 3) # 1-3
Unknown1111(80000, 22)
Unknown1108(1000)
Unknown1073(90000)
Unknown1019(7)
YAccel(7)
SFX_3('SE_ShotBall')
label(0)
sprite('Action_139_01', 3) # 4-6 **attackbox here**
sprite('Action_139_02', 3) # 7-9 **attackbox here**
sprite('Action_139_03', 3) # 10-12 **attackbox here**
sprite('Action_139_04', 3) # 13-15 **attackbox here**
sprite('Action_139_05', 3) # 16-18 **attackbox here**
sprite('Action_139_06', 3) # 19-21 **attackbox here**
gotoLabel(0)
@State
def Shot_Hasen():
def upon_IMMEDIATE():
Unknown4006(2)
Unknown2019(-998)
Unknown48('19000000020000000c00000002000000020000000c000000')
Unknown48('19000000020000000d00000002000000020000000d000000')
Unknown1019(80)
YAccel(80)
def upon_CLEAR_OR_EXIT():
if (not Unknown46(2)):
clearUponHandler(3)
Unknown1084(1)
random_(2, 0, 50)
if SLOT_ReturnVal:
_gotolabel(1)
label(0)
sprite('Action_109_00', 6) # 1-6
sprite('Action_109_01', 6) # 7-12
sprite('Action_109_02', 15) # 13-27
sprite('Action_109_03', 1) # 28-28
ExitState()
label(1)
sprite('Action_109_05', 6) # 29-34
sprite('Action_109_06', 6) # 35-40
sprite('Action_109_07', 15) # 41-55
sprite('Action_109_08', 1) # 56-56
@State
def Shot_Hasens():
def upon_IMMEDIATE():
Unknown4006(2)
Unknown2019(-997)
Unknown48('19000000020000000c00000002000000020000000c000000')
Unknown48('19000000020000000d00000002000000020000000d000000')
Unknown1019(80)
YAccel(80)
def upon_CLEAR_OR_EXIT():
if (not Unknown46(2)):
clearUponHandler(3)
Unknown1084(1)
random_(2, 0, 50)
if SLOT_ReturnVal:
_gotolabel(1)
label(0)
sprite('Action_110_00', 6) # 1-6
sprite('Action_110_01', 6) # 7-12
sprite('Action_110_02', 15) # 13-27
sprite('Action_110_03', 1) # 28-28
ExitState()
label(1)
sprite('Action_110_05', 6) # 29-34
sprite('Action_110_06', 6) # 35-40
sprite('Action_110_07', 15) # 41-55
sprite('Action_110_08', 1) # 56-56
@State
def Shot_AtkKoware():
def upon_IMMEDIATE():
teleportRelativeX(-50000)
Unknown1096(500)
sprite('Action_079_00', 5) # 1-5
sprite('Action_079_01', 5) # 6-10
sprite('Action_079_02', 5) # 11-15
sprite('Action_079_03', 5) # 16-20
sprite('Action_079_04', 5) # 21-25
sprite('Action_079_05', 5) # 26-30
@State
def ShotEx_AtkMatome():
def upon_IMMEDIATE():
Unknown2010()
Unknown11092(1)
SLOT_51 = 3
def upon_CLEAR_OR_EXIT():
if (SLOT_2 <= 0):
SLOT_2 = 15
if SLOT_51:
GFX_0('ShotEx_Atk', 100)
SLOT_51 = (SLOT_51 + (-1))
if (not SLOT_51):
clearUponHandler(3)
Unknown23029(2, 206, 0)
Unknown2038(-1)
sprite('null', 360) # 1-360
@State
def ShotEx_Atk():
def upon_IMMEDIATE():
Unknown2010()
callSubroutine('Shot_Atk_InitParam')
Unknown23182(2)
Unknown30065(0)
MinimumDamagePct(10)
sprite('Action_139_00', 3) # 1-3
Unknown1111(80000, 22)
Unknown1108(1000)
Unknown1073(90000)
Unknown1019(5)
YAccel(5)
SFX_3('SE_ShotBall')
label(0)
sprite('Action_139_01', 3) # 4-6 **attackbox here**
sprite('Action_139_02', 3) # 7-9 **attackbox here**
sprite('Action_139_03', 3) # 10-12 **attackbox here**
sprite('Action_139_04', 3) # 13-15 **attackbox here**
sprite('Action_139_05', 3) # 16-18 **attackbox here**
sprite('Action_139_06', 3) # 19-21 **attackbox here**
gotoLabel(0)
@Subroutine
def ShotCharge_Param():
Unknown2019(-999)
Unknown2053(1)
Unknown23013(1)
Unknown23022(1)
loopRelated(17, 240)
def upon_17():
Unknown13(25)
def upon_CLEAR_OR_EXIT():
Unknown2038(1)
if (not SLOT_51):
if (SLOT_2 <= 10):
Unknown1019(110)
YAccel(110)
else:
SLOT_51 = 1
SLOT_2 = 0
elif (not SLOT_52):
if (SLOT_2 <= 10):
Unknown1019(90)
YAccel(90)
else:
Unknown4007(0)
Unknown23022(0)
Unknown1084(1)
SLOT_52 = 1
SLOT_2 = 0
elif (not SLOT_53):
if (SLOT_2 >= 70):
Unknown13(1)
Unknown23022(1)
if (not SLOT_57):
SLOT_53 = 1
SLOT_2 = 0
if (not SLOT_55):
SLOT_55 = 1
GFX_0('Shot_Atk', 100)
Unknown38(5, 1)
if SLOT_56:
Unknown23029(1, 208, 0)
else:
SLOT_2 = 0
if (not SLOT_56):
SLOT_56 = 1
GFX_0('ShotEx_AtkMatome', 100)
Unknown38(5, 1)
elif (SLOT_2 >= 10):
if (not SLOT_58):
clearUponHandler(3)
sendToLabel(5)
else:
clearUponHandler(3)
sendToLabel(15)
def upon_43():
if (SLOT_48 == 200):
physicsXImpulse(6500)
physicsYImpulse(-6000)
if (SLOT_48 == 201):
physicsXImpulse(4000)
physicsYImpulse(6000)
if (SLOT_48 == 202):
SLOT_57 = 1
physicsXImpulse(6000)
physicsYImpulse(4000)
if (SLOT_48 == 203):
physicsXImpulse(6500)
physicsYImpulse(-4200)
if (SLOT_48 == 204):
physicsXImpulse(-4500)
physicsYImpulse(-4200)
if (SLOT_48 == 205):
SLOT_57 = 1
physicsXImpulse(9000)
physicsYImpulse(-8000)
if (SLOT_48 == 206):
SLOT_2 = 0
SLOT_53 = 1
if (SLOT_48 == 207):
SLOT_56 = 1
physicsXImpulse(13000)
physicsYImpulse(6000)
Unknown4007(3)
if (SLOT_48 == 212):
Unknown4007(0)
Unknown23090(25)
Unknown23089('0100000001000000010000000000000000000000000000000100000000000000')
Unknown23091(1)
def upon_53():
Unknown23090(25)
def upon_54():
clearUponHandler(3)
clearUponHandler(53)
if (not SLOT_58):
Unknown1084(1)
Unknown23090(5)
sendToLabel(3)
else:
Unknown1084(1)
Unknown23090(5)
sendToLabel(13)
@Subroutine
def ShotChargeColor():
if (SLOT_95 == 0):
sendToLabel(0)
if (SLOT_95 == 1):
SLOT_58 = 1
sendToLabel(10)
if (SLOT_95 == 2):
sendToLabel(0)
if (SLOT_95 == 3):
SLOT_58 = 1
sendToLabel(10)
@State
def Shot_Charge():
def upon_IMMEDIATE():
Unknown2010()
callSubroutine('ShotCharge_Param')
callSubroutine('ShotChargeColor')
label(0)
sprite('Action_149_00', 2) # 1-2
SFX_3('SE074_Sparking')
sprite('Action_149_01', 2) # 3-4
GFX_0('Shot_LightEffMatome', 100)
sprite('Action_149_02', 2) # 5-6
sprite('Action_149_03', 2) # 7-8
sprite('Action_149_04', 2) # 9-10
sprite('Action_149_05', 2) # 11-12
sprite('Action_149_06', 2) # 13-14
label(1)
sprite('Action_149_07', 2) # 15-16
sprite('Action_149_08', 2) # 17-18
sprite('Action_149_09', 2) # 19-20
sprite('Action_149_10', 2) # 21-22
sprite('Action_149_11', 2) # 23-24
sprite('Action_149_12', 2) # 25-26
sprite('Action_149_13', 2) # 27-28
sprite('Action_149_06', 2) # 29-30
gotoLabel(1)
label(2)
sprite('Action_149_14', 2) # 31-32
sprite('Action_149_15', 2) # 33-34
sprite('Action_149_16', 2) # 35-36
sprite('Action_149_17', 2) # 37-38
sprite('Action_149_18', 2) # 39-40
sprite('Action_149_19', 2) # 41-42
sprite('Action_149_20', 2) # 43-44
sprite('Action_149_21', 2) # 45-46
gotoLabel(2)
label(3)
sprite('Action_149_22', 5) # 47-51
sprite('Action_149_23', 2) # 52-53
sprite('Action_149_24', 3) # 54-56 **attackbox here**
sprite('Action_149_25', 3) # 57-59 **attackbox here**
sprite('Action_149_26', 3) # 60-62 **attackbox here**
sprite('Action_149_27', 3) # 63-65 **attackbox here**
sprite('Action_149_28', 4) # 66-69 **attackbox here**
sprite('Action_149_29', 1) # 70-70 **attackbox here**
ExitState()
label(5)
sprite('Action_149_05', 2) # 71-72
sprite('Action_149_04', 2) # 73-74
sprite('Action_149_03', 2) # 75-76
sprite('Action_149_02', 2) # 77-78
sprite('Action_149_01', 2) # 79-80
sprite('Action_149_00', 2) # 81-82
ExitState()
label(10)
sprite('Action_150_00', 2) # 83-84
SFX_3('SE074_Sparking')
sprite('Action_150_01', 2) # 85-86
GFX_0('Shot_LightEffMatome', 100)
sprite('Action_150_02', 2) # 87-88
sprite('Action_150_03', 2) # 89-90
sprite('Action_150_04', 2) # 91-92
sprite('Action_150_05', 2) # 93-94
sprite('Action_150_06', 2) # 95-96
label(11)
sprite('Action_150_07', 2) # 97-98
sprite('Action_150_08', 2) # 99-100
sprite('Action_150_09', 2) # 101-102
sprite('Action_150_10', 2) # 103-104
sprite('Action_150_11', 2) # 105-106
sprite('Action_150_12', 2) # 107-108
sprite('Action_150_13', 2) # 109-110
sprite('Action_150_06', 2) # 111-112
gotoLabel(11)
label(12)
sprite('Action_150_14', 2) # 113-114
sprite('Action_150_15', 2) # 115-116
sprite('Action_150_16', 2) # 117-118
sprite('Action_150_17', 2) # 119-120
sprite('Action_150_18', 2) # 121-122
sprite('Action_150_19', 2) # 123-124
sprite('Action_150_20', 2) # 125-126
sprite('Action_150_21', 2) # 127-128
gotoLabel(12)
label(13)
sprite('Action_150_22', 5) # 129-133
sprite('Action_150_23', 2) # 134-135
sprite('Action_150_24', 3) # 136-138 **attackbox here**
sprite('Action_150_25', 3) # 139-141 **attackbox here**
sprite('Action_150_26', 3) # 142-144 **attackbox here**
sprite('Action_150_27', 3) # 145-147 **attackbox here**
sprite('Action_150_28', 4) # 148-151 **attackbox here**
sprite('Action_150_29', 1) # 152-152 **attackbox here**
label(15)
sprite('Action_150_05', 2) # 153-154
sprite('Action_150_04', 2) # 155-156
sprite('Action_150_03', 2) # 157-158
sprite('Action_150_02', 2) # 159-160
sprite('Action_150_01', 2) # 161-162
sprite('Action_150_00', 2) # 163-164
@State
def ShotEx_Charge():
def upon_IMMEDIATE():
Unknown2010()
callSubroutine('ShotCharge_Param')
callSubroutine('ShotChargeColor')
label(0)
sprite('Action_143_00', 2) # 1-2
SFX_3('SE074_Sparking')
sprite('Action_143_01', 2) # 3-4
GFX_0('Shot_LightEffMatome', 100)
sprite('Action_143_02', 2) # 5-6
sprite('Action_143_03', 2) # 7-8
sprite('Action_143_04', 2) # 9-10
sprite('Action_143_05', 2) # 11-12
sprite('Action_143_06', 2) # 13-14
label(1)
sprite('Action_143_07', 2) # 15-16
sprite('Action_143_08', 2) # 17-18
sprite('Action_143_09', 2) # 19-20
sprite('Action_143_10', 2) # 21-22
sprite('Action_143_11', 2) # 23-24
sprite('Action_143_12', 2) # 25-26
sprite('Action_143_13', 2) # 27-28
sprite('Action_143_06', 2) # 29-30
gotoLabel(1)
label(2)
sprite('Action_143_14', 2) # 31-32
sprite('Action_143_15', 2) # 33-34
sprite('Action_143_16', 2) # 35-36
sprite('Action_143_17', 2) # 37-38
sprite('Action_143_18', 2) # 39-40
sprite('Action_143_19', 2) # 41-42
sprite('Action_143_20', 2) # 43-44
sprite('Action_143_21', 2) # 45-46
gotoLabel(2)
label(3)
sprite('Action_143_22', 5) # 47-51
sprite('Action_143_23', 2) # 52-53
sprite('Action_143_24', 3) # 54-56 **attackbox here**
sprite('Action_143_25', 3) # 57-59 **attackbox here**
sprite('Action_143_26', 3) # 60-62 **attackbox here**
sprite('Action_143_27', 3) # 63-65 **attackbox here**
sprite('Action_143_28', 4) # 66-69 **attackbox here**
sprite('Action_143_29', 1) # 70-70 **attackbox here**
ExitState()
label(5)
sprite('Action_143_05', 2) # 71-72
sprite('Action_143_04', 2) # 73-74
sprite('Action_143_03', 2) # 75-76
sprite('Action_143_02', 2) # 77-78
sprite('Action_143_01', 2) # 79-80
sprite('Action_143_00', 2) # 81-82
ExitState()
label(10)
sprite('Action_144_00', 2) # 83-84
SFX_3('SE074_Sparking')
sprite('Action_144_01', 2) # 85-86
GFX_0('Shot_LightEffMatome', 100)
sprite('Action_144_02', 2) # 87-88
sprite('Action_144_03', 2) # 89-90
sprite('Action_144_04', 2) # 91-92
sprite('Action_144_05', 2) # 93-94
sprite('Action_144_06', 2) # 95-96
label(11)
sprite('Action_144_07', 2) # 97-98
sprite('Action_144_08', 2) # 99-100
sprite('Action_144_09', 2) # 101-102
sprite('Action_144_10', 2) # 103-104
sprite('Action_144_11', 2) # 105-106
sprite('Action_144_12', 2) # 107-108
sprite('Action_144_13', 2) # 109-110
sprite('Action_144_06', 2) # 111-112
gotoLabel(11)
label(12)
sprite('Action_144_14', 2) # 113-114
sprite('Action_144_15', 2) # 115-116
sprite('Action_144_16', 2) # 117-118
sprite('Action_144_17', 2) # 119-120
sprite('Action_144_18', 2) # 121-122
sprite('Action_144_19', 2) # 123-124
sprite('Action_144_20', 2) # 125-126
sprite('Action_144_21', 2) # 127-128
gotoLabel(12)
label(13)
sprite('Action_144_22', 5) # 129-133
sprite('Action_144_23', 2) # 134-135
sprite('Action_144_24', 3) # 136-138 **attackbox here**
sprite('Action_144_25', 3) # 139-141 **attackbox here**
sprite('Action_144_26', 3) # 142-144 **attackbox here**
sprite('Action_144_27', 3) # 145-147 **attackbox here**
sprite('Action_144_28', 4) # 148-151 **attackbox here**
sprite('Action_144_29', 1) # 152-152 **attackbox here**
ExitState()
label(15)
sprite('Action_144_05', 2) # 153-154
sprite('Action_144_04', 2) # 155-156
sprite('Action_144_03', 2) # 157-158
sprite('Action_144_02', 2) # 159-160
sprite('Action_144_01', 2) # 161-162
sprite('Action_144_00', 2) # 163-164
@State
def Shot_LightEffMatome():
def upon_IMMEDIATE():
Unknown4010(2)
Unknown4007(2)
Unknown2019(-998)
label(0)
sprite('null', 60) # 1-60
GFX_0('Shot_LightEff', 100)
sprite('null', 60) # 61-120
GFX_0('Shot_LightEff', 100)
gotoLabel(0)
@State
def Shot_LightEff():
sprite('Action_117_00', 3) # 1-3
sprite('Action_117_01', 3) # 4-6
sprite('Action_117_02', 3) # 7-9
sprite('Action_117_03', 3) # 10-12
sprite('Action_117_04', 3) # 13-15
sprite('Action_117_05', 3) # 16-18
sprite('Action_117_06', 3) # 19-21
sprite('Action_117_07', 1) # 22-22
@State
def UltimateRush_Camera():
def upon_IMMEDIATE():
Unknown20000(1)
Unknown20003(1)
Unknown2053(0)
Unknown2034(0)
EnableCollision(0)
def upon_45():
Unknown1086(22)
teleportRelativeY(0)
def upon_43():
if (SLOT_48 == 1001):
Unknown13(25)
if (SLOT_48 == 1003):
sendToLabel(1)
if (SLOT_48 == 1004):
sendToLabel(0)
loopRelated(17, 420)
def upon_17():
Unknown13(25)
label(0)
sprite('null', 40) # 1-40
sprite('null', 32767) # 41-32807
label(1)
sprite('null', 23) # 32808-32830
@State
def UltimateRush_AtkDmy():
def upon_IMMEDIATE():
Unknown2011()
Unknown23056('')
AttackLevel_(4)
Damage(262)
AttackP1(48)
AttackP2(100)
Unknown11064(1)
Hitstop(0)
AirUntechableTime(90)
MinimumDamagePct(8)
GroundedHitstunAnimation(13)
AirHitstunAnimation(13)
Unknown11001(0, 15, 15)
Unknown30048(1)
Unknown9016(1)
Unknown11023(1)
Unknown11069('UltimateRush_AtkDmy')
def upon_45():
Unknown1086(22)
def upon_43():
if (SLOT_48 == 1002):
Damage(100)
Unknown30048(0)
MinimumDamagePct(100)
AttackP1(100)
AttackP2(100)
sprite('null', 6) # 1-6
sprite('Action_156_atk', 7) # 7-13 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 14-20 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 21-27 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 28-34 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 35-39 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 40-44 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 45-49 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 50-54 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 10) # 55-64 **attackbox here**
RefreshMultihit()
Unknown11069('UltimateRush_FinishShadow')
sprite('Action_156_atk', 10) # 65-74 **attackbox here**
Unknown23029(3, 1000, 0)
@State
def UltimateRushOD_AtkDmy():
def upon_IMMEDIATE():
Unknown2011()
Unknown23056('')
AttackLevel_(4)
Damage(262)
AttackP1(48)
AttackP2(100)
Unknown11064(1)
Hitstop(0)
AirUntechableTime(90)
MinimumDamagePct(8)
GroundedHitstunAnimation(13)
AirHitstunAnimation(13)
Unknown11001(0, 15, 15)
Unknown30048(1)
Unknown9016(1)
Unknown11023(1)
Unknown11069('UltimateRushOD_AtkDmy')
def upon_45():
Unknown1086(22)
def upon_43():
if (SLOT_48 == 1002):
Damage(100)
Unknown30048(0)
MinimumDamagePct(100)
AttackP1(100)
AttackP2(100)
sprite('null', 6) # 1-6
sprite('Action_156_atk', 7) # 7-13 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 14-20 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 21-27 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 28-34 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 35-41 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 42-48 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 49-55 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 56-62 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 7) # 63-69 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 70-74 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 75-79 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 80-84 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 5) # 85-89 **attackbox here**
RefreshMultihit()
sprite('Action_156_atk', 10) # 90-99 **attackbox here**
RefreshMultihit()
Unknown11069('UltimateRushOD_FinishShadow')
sprite('Action_156_atk', 10) # 100-109 **attackbox here**
Unknown23029(3, 1000, 0)
@State
def UltimateRushDDD_Zanzo1():
def upon_IMMEDIATE():
Unknown2054(1)
Unknown23022(1)
Unknown3026(-16777216)
sprite('Action_045_01', 20) # 1-20
Unknown3004(-12)
@State
def UltimateRush_Shadow():
def upon_IMMEDIATE():
Unknown23015(1)
Unknown1086(22)
Unknown1007(-150000)
sprite('Action_158_00', 3) # 1-3
sprite('Action_158_01', 3) # 4-6
sprite('Action_158_02', 3) # 7-9
sprite('Action_158_03', 3) # 10-12
sprite('Action_158_04', 3) # 13-15
sprite('Action_158_05', 3) # 16-18
sprite('Action_158_06', 3) # 19-21
sprite('Action_158_07', 3) # 22-24
sprite('null', 15) # 25-39
sprite('Action_159_00', 2) # 40-41
sprite('Action_159_01', 3) # 42-44
sprite('Action_159_02', 3) # 45-47
sprite('Action_159_03', 3) # 48-50
sprite('Action_159_04', 3) # 51-53
sprite('Action_159_05', 3) # 54-56
sprite('Action_159_06', 3) # 57-59
sprite('Action_159_07', 3) # 60-62
@State
def UltimateRushOD_Shadow():
def upon_IMMEDIATE():
Unknown23015(1)
Unknown1086(22)
Unknown1096(2000)
Unknown1007(-350000)
sprite('Action_158_00', 3) # 1-3
sprite('Action_158_01', 3) # 4-6
sprite('Action_158_02', 3) # 7-9
sprite('Action_158_03', 3) # 10-12
sprite('Action_158_04', 3) # 13-15
sprite('Action_158_05', 3) # 16-18
sprite('Action_158_06', 3) # 19-21
sprite('Action_158_07', 3) # 22-24
sprite('Action_158_00', 3) # 25-27
sprite('Action_158_01', 3) # 28-30
sprite('Action_158_02', 3) # 31-33
sprite('Action_158_03', 3) # 34-36
sprite('Action_158_04', 3) # 37-39
sprite('Action_158_05', 3) # 40-42
sprite('Action_158_06', 3) # 43-45
sprite('Action_158_07', 3) # 46-48
sprite('Action_158_00', 3) # 49-51
sprite('Action_158_01', 3) # 52-54
sprite('Action_158_02', 3) # 55-57
sprite('Action_158_03', 3) # 58-60
sprite('Action_158_04', 3) # 61-63
sprite('Action_158_05', 3) # 64-66
sprite('Action_158_06', 3) # 67-69
sprite('Action_158_07', 3) # 70-72
sprite('Action_158_00', 3) # 73-75
sprite('Action_158_01', 3) # 76-78
sprite('Action_158_02', 3) # 79-81
sprite('Action_158_03', 3) # 82-84
sprite('Action_158_04', 3) # 85-87
sprite('Action_158_05', 3) # 88-90
sprite('Action_158_06', 3) # 91-93
sprite('Action_158_07', 3) # 94-96
sprite('null', 15) # 97-111
Unknown1096(1500)
Unknown1086(22)
sprite('Action_159_00', 2) # 112-113
sprite('Action_159_01', 3) # 114-116
sprite('Action_159_02', 3) # 117-119
sprite('Action_159_03', 3) # 120-122
sprite('Action_159_04', 3) # 123-125
sprite('Action_159_05', 3) # 126-128
sprite('Action_159_06', 3) # 129-131
sprite('Action_159_07', 3) # 132-134
@State
def UltimateRush_FinishShadow():
def upon_IMMEDIATE():
Unknown2011()
Unknown23056('')
AttackLevel_(5)
Damage(2608)
MinimumDamagePct(24)
AttackP1(48)
AttackP2(100)
Hitstop(0)
AirUntechableTime(90)
Unknown9310(1)
AirPushbackX(0)
AirPushbackY(35000)
GroundedHitstunAnimation(9)
AirHitstunAnimation(9)
Unknown9016(1)
Unknown11064(0)
Unknown30048(1)
Unknown4009(3)
Unknown1086(22)
teleportRelativeY(0)
Unknown2005()
Unknown3026(-16777216)
Unknown11069('UltimateRush_Exe2')
def upon_43():
if (SLOT_48 == 1002):
Damage(500)
Unknown30048(0)
MinimumDamagePct(100)
AttackP1(100)
AttackP2(100)
Unknown11069('UltimateRushDDD_Exe')
sprite('Action_160_00', 5) # 1-5 **attackbox here**
RefreshMultihit()
sprite('Action_160_01', 5) # 6-10 **attackbox here**
sprite('Action_160_02', 5) # 11-15 **attackbox here**
sprite('Action_160_03', 5) # 16-20 **attackbox here**
sprite('Action_160_04', 5) # 21-25 **attackbox here**
Unknown3004(-20)
sprite('Action_160_05', 5) # 26-30 **attackbox here**
sprite('Action_160_06', 5) # 31-35 **attackbox here**
sprite('Action_160_07', 13) # 36-48 **attackbox here**
Unknown3004(-60)
@State
def UltimateRushOD_FinishShadow():
def upon_IMMEDIATE():
Unknown2011()
Unknown23056('')
AttackLevel_(5)
Damage(3258)
MinimumDamagePct(24)
AttackP1(48)
AttackP2(100)
Hitstop(0)
AirUntechableTime(90)
Unknown9310(1)
AirPushbackX(0)
AirPushbackY(35000)
GroundedHitstunAnimation(9)
AirHitstunAnimation(9)
Unknown9016(1)
Unknown11064(0)
Unknown30048(1)
Unknown4009(3)
Unknown1086(22)
teleportRelativeY(0)
Unknown2005()
Unknown3026(-16777216)
Unknown11069('UltimateRushOD_Exe2')
def upon_43():
if (SLOT_48 == 1002):
Damage(500)
Unknown30048(0)
MinimumDamagePct(100)
AttackP1(100)
AttackP2(100)
Unknown11069('UltimateRushDDDOD_Exe')
sprite('Action_160_00', 5) # 1-5 **attackbox here**
RefreshMultihit()
sprite('Action_160_01', 5) # 6-10 **attackbox here**
sprite('Action_160_02', 5) # 11-15 **attackbox here**
sprite('Action_160_03', 5) # 16-20 **attackbox here**
sprite('Action_160_04', 5) # 21-25 **attackbox here**
Unknown3004(-20)
sprite('Action_160_05', 5) # 26-30 **attackbox here**
sprite('Action_160_06', 5) # 31-35 **attackbox here**
sprite('Action_160_07', 13) # 36-48 **attackbox here**
Unknown3004(-60)
@State
def UltimateThrow_Camera():
def upon_IMMEDIATE():
Unknown20000(1)
Unknown20003(1)
def upon_CLEAR_OR_EXIT():
Unknown1086(22)
Unknown1007(250000)
sprite('null', 300) # 1-300
@State
def UltimateThrow_PauseShadow():
def upon_IMMEDIATE():
Unknown4009(3)
Unknown2019(500)
sprite('Action_167_00', 16) # 1-16
sprite('Action_167_01', 10) # 17-26
sprite('Action_167_02', 5) # 27-31
sprite('Action_167_03', 3) # 32-34
sprite('Action_167_04', 1) # 35-35
@State
def UltimateThrow_MirrorShadow1():
def upon_IMMEDIATE():
Unknown23022(1)
sendToLabelUpon(2, 1)
Unknown4009(3)
Unknown2005()
Unknown3026(-16777216)
Unknown3004(-10)
sprite('Action_245_11', 1) # 1-1 **attackbox here**
physicsXImpulse(-18000)
physicsYImpulse(16000)
setGravity(4500)
sprite('Action_145_00', 2) # 2-3
sprite('Action_145_01', 2) # 4-5
sprite('Action_145_02', 2) # 6-7
GFX_0('Shot_Zanzo', 0)
physicsXImpulse(-9000)
Unknown1043()
sprite('Action_145_03', 2) # 8-9
GFX_0('UltimateThrowOD_Shot_Charge', 0)
Unknown23029(1, 1015, 0)
sprite('Action_145_04', 4) # 10-13
Recovery()
sprite('Action_145_05', 6) # 14-19
sprite('Action_145_06', 8) # 20-27
label(0)
sprite('Action_245_16', 3) # 28-30
sprite('Action_245_17', 3) # 31-33
loopRest()
gotoLabel(0)
label(1)
sprite('Action_245_18', 5) # 34-38
Unknown1084(1)
sprite('Action_245_19', 5) # 39-43
sprite('Action_245_20', 4) # 44-47
@State
def UltimateThrow_MirrorShadow2():
def upon_IMMEDIATE():
Unknown23022(1)
sendToLabelUpon(2, 1)
Unknown4009(3)
Unknown2005()
Unknown3026(-16777216)
Unknown3004(-10)
def upon_43():
if (SLOT_48 == 1010):
Unknown2038(1)
sprite('Action_245_11', 1) # 1-1 **attackbox here**
physicsXImpulse(-18000)
physicsYImpulse(16000)
setGravity(4500)
sprite('Action_145_00', 2) # 2-3
sprite('Action_145_01', 2) # 4-5
sprite('Action_145_02', 2) # 6-7
GFX_0('Shot_Zanzo', 0)
physicsXImpulse(-9000)
Unknown1043()
sprite('Action_145_03', 2) # 8-9
GFX_0('UltimateThrowOD_Shot_Charge', 0)
Unknown23029(1, 1016, 0)
sprite('Action_145_04', 4) # 10-13
Recovery()
sprite('Action_145_05', 6) # 14-19
sprite('Action_145_06', 8) # 20-27
label(0)
sprite('Action_245_16', 3) # 28-30
sprite('Action_245_17', 3) # 31-33
loopRest()
gotoLabel(0)
label(1)
sprite('Action_245_18', 5) # 34-38
Unknown1084(1)
sprite('Action_245_19', 5) # 39-43
sprite('Action_245_20', 4) # 44-47
@State
def UltimateThrow_MirrorShadow3():
def upon_IMMEDIATE():
Unknown23022(1)
sendToLabelUpon(2, 1)
Unknown4009(3)
Unknown2005()
Unknown3026(-16777216)
Unknown3004(-10)
sprite('Action_245_11', 1) # 1-1 **attackbox here**
physicsXImpulse(-18000)
physicsYImpulse(16000)
setGravity(4500)
sprite('Action_145_00', 2) # 2-3
sprite('Action_145_01', 2) # 4-5
sprite('Action_145_02', 2) # 6-7
GFX_0('Shot_Zanzo', 0)
physicsXImpulse(-9000)
Unknown1043()
sprite('Action_145_03', 2) # 8-9
GFX_0('UltimateThrowOD_Shot_Charge', 0)
Unknown38(5, 1)
Unknown23029(5, 1017, 0)
Unknown23029(5, 1011, 0)
sprite('Action_145_04', 4) # 10-13
Recovery()
sprite('Action_145_05', 6) # 14-19
sprite('Action_145_06', 8) # 20-27
label(0)
sprite('Action_245_16', 3) # 28-30
sprite('Action_245_17', 3) # 31-33
loopRest()
gotoLabel(0)
label(1)
sprite('Action_245_18', 5) # 34-38
Unknown1084(1)
sprite('Action_245_19', 5) # 39-43
sprite('Action_245_20', 4) # 44-47
@State
def UltimateThrowOD_Shot_Charge():
def upon_IMMEDIATE():
Unknown2010()
callSubroutine('ShotChargeColor')
def upon_CLEAR_OR_EXIT():
Unknown2038(1)
if (not SLOT_51):
if (SLOT_2 <= 10):
Unknown1019(110)
YAccel(110)
else:
SLOT_51 = 1
SLOT_2 = 0
elif (not SLOT_52):
if (SLOT_2 <= 10):
Unknown1019(90)
YAccel(90)
else:
Unknown1084(1)
clearUponHandler(3)
def upon_43():
if (SLOT_48 == 1015):
SLOT_57 = 1
physicsXImpulse(7000)
physicsYImpulse(2000)
if (SLOT_48 == 1016):
SLOT_57 = 1
physicsXImpulse(16000)
physicsYImpulse(-500)
if (SLOT_48 == 1017):
SLOT_57 = 1
physicsXImpulse(4500)
physicsYImpulse(3500)
if (SLOT_48 == 206):
if (not SLOT_58):
sendToLabel(5)
else:
sendToLabel(15)
if (SLOT_48 == 1011):
SLOT_54 = 1
loopRelated(17, 45)
def upon_17():
clearUponHandler(17)
GFX_0('UltimateThrowOD_Shot_AtkMatome', 100)
if SLOT_IsInOverdrive2:
Unknown23029(1, 1013, 0)
Unknown23022(1)
label(0)
sprite('Action_143_00', 2) # 1-2
SFX_3('SE074_Sparking')
sprite('Action_143_01', 2) # 3-4
GFX_0('Shot_LightEffMatome', 100)
sprite('Action_143_02', 2) # 5-6
sprite('Action_143_03', 2) # 7-8
sprite('Action_143_04', 2) # 9-10
sprite('Action_143_05', 2) # 11-12
sprite('Action_143_06', 2) # 13-14
label(1)
sprite('Action_143_07', 2) # 15-16
sprite('Action_143_08', 2) # 17-18
sprite('Action_143_09', 2) # 19-20
sprite('Action_143_10', 2) # 21-22
sprite('Action_143_11', 2) # 23-24
sprite('Action_143_12', 2) # 25-26
sprite('Action_143_13', 2) # 27-28
sprite('Action_143_06', 2) # 29-30
gotoLabel(1)
label(2)
sprite('Action_143_14', 2) # 31-32
sprite('Action_143_15', 2) # 33-34
sprite('Action_143_16', 2) # 35-36
sprite('Action_143_17', 2) # 37-38
sprite('Action_143_18', 2) # 39-40
sprite('Action_143_19', 2) # 41-42
sprite('Action_143_20', 2) # 43-44
sprite('Action_143_21', 2) # 45-46
gotoLabel(2)
label(3)
sprite('Action_143_22', 5) # 47-51
sprite('Action_143_23', 2) # 52-53
sprite('Action_143_24', 3) # 54-56 **attackbox here**
sprite('Action_143_25', 3) # 57-59 **attackbox here**
sprite('Action_143_26', 3) # 60-62 **attackbox here**
sprite('Action_143_27', 3) # 63-65 **attackbox here**
sprite('Action_143_28', 4) # 66-69 **attackbox here**
sprite('Action_143_29', 1) # 70-70 **attackbox here**
ExitState()
label(5)
sprite('Action_143_05', 2) # 71-72
sprite('Action_143_04', 2) # 73-74
sprite('Action_143_03', 2) # 75-76
sprite('Action_143_02', 2) # 77-78
sprite('Action_143_01', 2) # 79-80
sprite('Action_143_00', 2) # 81-82
ExitState()
label(10)
sprite('Action_144_00', 2) # 83-84
SFX_3('SE074_Sparking')
sprite('Action_144_01', 2) # 85-86
GFX_0('Shot_LightEffMatome', 100)
sprite('Action_144_02', 2) # 87-88
sprite('Action_144_03', 2) # 89-90
sprite('Action_144_04', 2) # 91-92
sprite('Action_144_05', 2) # 93-94
sprite('Action_144_06', 2) # 95-96
label(11)
sprite('Action_144_07', 2) # 97-98
sprite('Action_144_08', 2) # 99-100
sprite('Action_144_09', 2) # 101-102
sprite('Action_144_10', 2) # 103-104
sprite('Action_144_11', 2) # 105-106
sprite('Action_144_12', 2) # 107-108
sprite('Action_144_13', 2) # 109-110
sprite('Action_144_06', 2) # 111-112
gotoLabel(11)
label(12)
sprite('Action_144_14', 2) # 113-114
sprite('Action_144_15', 2) # 115-116
sprite('Action_144_16', 2) # 117-118
sprite('Action_144_17', 2) # 119-120
sprite('Action_144_18', 2) # 121-122
sprite('Action_144_19', 2) # 123-124
sprite('Action_144_20', 2) # 125-126
sprite('Action_144_21', 2) # 127-128
gotoLabel(12)
label(13)
sprite('Action_144_22', 5) # 129-133
sprite('Action_144_23', 2) # 134-135
sprite('Action_144_24', 3) # 136-138 **attackbox here**
sprite('Action_144_25', 3) # 139-141 **attackbox here**
sprite('Action_144_26', 3) # 142-144 **attackbox here**
sprite('Action_144_27', 3) # 145-147 **attackbox here**
sprite('Action_144_28', 4) # 148-151 **attackbox here**
sprite('Action_144_29', 1) # 152-152 **attackbox here**
ExitState()
label(15)
sprite('Action_144_05', 2) # 153-154
sprite('Action_144_04', 2) # 155-156
sprite('Action_144_03', 2) # 157-158
sprite('Action_144_02', 2) # 159-160
sprite('Action_144_01', 2) # 161-162
sprite('Action_144_00', 2) # 163-164
@State
def UltimateThrowOD_Shot_AtkMatome():
def upon_IMMEDIATE():
Unknown2011()
Unknown23056('')
Unknown11092(1)
SLOT_51 = 3
def upon_CLEAR_OR_EXIT():
if (SLOT_2 <= 3):
SLOT_2 = 15
if SLOT_51:
GFX_0('UltimateThrowOD_Shot', 100)
SLOT_51 = (SLOT_51 + (-1))
if (not SLOT_51):
if SLOT_58:
Unknown23029(1, 1014, 0)
clearUponHandler(3)
Unknown23029(2, 206, 0)
Unknown2038(-1)
def upon_43():
if (SLOT_48 == 1013):
SLOT_58 = 1
sprite('null', 360) # 1-360
@State
def UltimateThrowOD_Shot():
def upon_IMMEDIATE():
Unknown2011()
callSubroutine('Shot_Atk_InitParam')
Unknown23056('')
Unknown13024(0)
Unknown11064(1)
Unknown23182(2)
Damage(300)
AttackP1(50)
AttackP2(100)
AirUntechableTime(100)
MinimumDamagePct(10)
Unknown11069('UltimateThrowOD_Shot')
def upon_43():
if (SLOT_48 == 1014):
Unknown11069('UltimateThrow_FinishAtkDmy')
sprite('Action_139_00', 3) # 1-3
Unknown1111(80000, 22)
Unknown1108(1000)
Unknown1073(90000)
Unknown1019(5)
YAccel(5)
label(0)
sprite('Action_139_01', 3) # 4-6 **attackbox here**
sprite('Action_139_02', 3) # 7-9 **attackbox here**
sprite('Action_139_03', 3) # 10-12 **attackbox here**
sprite('Action_139_04', 3) # 13-15 **attackbox here**
sprite('Action_139_05', 3) # 16-18 **attackbox here**
sprite('Action_139_06', 3) # 19-21 **attackbox here**
gotoLabel(0)
@State
def UltimateThrow_FinishBlade():
def upon_IMMEDIATE():
Unknown23056('')
Unknown2005()
Unknown23015(1)
Unknown1096(2500)
Unknown1072(180000)
Unknown1086(22)
Unknown23033(50)
sprite('Action_419_00', 4) # 1-4 **attackbox here**
GFX_0('UltimateThrow_FinishAtkDmy', 100)
sprite('Action_419_01', 4) # 5-8 **attackbox here**
sprite('Action_419_02', 8) # 9-16
sprite('Action_419_03', 4) # 17-20
Unknown1100(-300)
sprite('Action_419_06', 12) # 21-32
@State
def UltimateThrow_FinishAtkDmy():
def upon_IMMEDIATE():
Unknown2011()
Unknown23056('')
AttackLevel_(4)
Damage(7500)
MinimumDamagePct(20)
AttackP1(50)
AttackP2(100)
AirPushbackX(0)
AirPushbackY(-185000)
YImpluseBeforeWallbounce(0)
Hitstop(0)
AirUntechableTime(100)
Unknown9310(20)
PushbackX(0)
Unknown9016(1)
Unknown11023(1)
Unknown9190(1)
Unknown9118(2)
Unknown11056(3)
Unknown1086(22)
sprite('Action_156_atk', 2) # 1-2 **attackbox here**
StartMultihit()
sprite('Action_156_atk', 6) # 3-8 **attackbox here**
RefreshMultihit()
SFX_3('SE_BigBomb')
@State
def AstralStartCamera():
def upon_IMMEDIATE():
Unknown23032(50)
Unknown20000(1)
sprite('null', 30) # 1-30
@State
def AstralExeCamera():
def upon_IMMEDIATE():
Unknown20000(1)
Unknown20003(1)
Unknown2053(0)
EnableCollision(0)
Unknown2034(0)
Unknown1086(22)
def upon_43():
if (SLOT_48 == 5001):
sendToLabel(1)
label(0)
sprite('null', 32767) # 1-32767
def upon_CLEAR_OR_EXIT():
if (SLOT_105 <= 1300):
SLOT_105 = (SLOT_105 + 3)
else:
Unknown1084(1)
SLOT_105 = 1300
clearUponHandler(3)
label(1)
sprite('null', 32767) # 32768-65534
clearUponHandler(3)
Unknown1000(0)
Unknown23029(3, 5002, 0)
Unknown20009(1150)
Unknown26('AstralBlade_First')
Unknown26('AstralBlade')
@State
def AstralBlade_First():
def upon_IMMEDIATE():
Unknown1072(105000)
Unknown1007(250000)
def upon_43():
(SLOT_48 == 5000)
Unknown2038(1)
sprite('Action_419_00', 4) # 1-4 **attackbox here**
sprite('Action_419_01', 4) # 5-8 **attackbox here**
sprite('Action_419_02', 4) # 9-12
sprite('Action_419_03', 4) # 13-16
label(0)
sprite('Action_419_04', 4) # 17-20
sprite('Action_419_05', 4) # 21-24
if SLOT_2:
_gotolabel(0)
label(1)
sprite('Action_419_06', 4) # 25-28
@State
def AstralBlade_Matome():
def upon_IMMEDIATE():
Unknown2012()
AttackLevel_(4)
Damage(500)
MinimumDamagePct(100)
Hitstop(0)
AirUntechableTime(100)
PushbackX(0)
Unknown11001(0, 40, 40)
Unknown11064(1)
Unknown9016(1)
Unknown11023(1)
Unknown1086(22)
sprite('Action_156_atk', 45) # 1-45 **attackbox here**
StartMultihit()
sprite('Action_156_atk', 15) # 46-60 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(230000)
Unknown23032(52)
Unknown23033(100)
Unknown35()
sprite('Action_156_atk', 15) # 61-75 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(1510000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 15) # 76-90 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(1900000)
Unknown23032(0)
Unknown23033(40)
Unknown35()
sprite('Action_156_atk', 15) # 91-105 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(320000)
Unknown23032(65)
Unknown23033(50)
Unknown35()
sprite('Action_156_atk', 12) # 106-117 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(1750000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 12) # 118-129 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(1740000)
Unknown23032(30)
Unknown23033(40)
Unknown35()
sprite('Action_156_atk', 12) # 130-141 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(1515000)
Unknown23032(3)
Unknown23033(90)
Unknown35()
sprite('Action_156_atk', 12) # 142-153 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(750000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 12) # 154-165 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(210000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 8) # 166-173 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(650000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 8) # 174-181 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(260000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 8) # 182-189 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(750000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 8) # 190-197 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(210000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 8) # 198-205 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(650000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 6) # 206-211 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(260000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 6) # 212-217 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(600000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 6) # 218-223 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(310000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 6) # 224-229 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(800000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 4) # 230-233 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(260000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 4) # 234-237 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(700000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 4) # 238-241 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(310000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 4) # 242-245 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(310000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 4) # 246-249 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(1650000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 4) # 250-253 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(1260000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 4) # 254-257 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(600000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 2) # 258-259 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(700000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 2) # 260-261 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(20000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 2) # 262-263 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(80000)
Unknown23032(65)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 2) # 264-265 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(10000)
Unknown23032(45)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 2) # 266-267 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(80000)
Unknown23032(25)
Unknown23033(30)
Unknown35()
sprite('Action_156_atk', 2) # 268-269 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown1072(100000)
Unknown23032(10)
Unknown23033(15)
Unknown35()
sprite('Action_156_atk', 17) # 270-286 **attackbox here**
RefreshMultihit()
GFX_0('AstralBlade', 100)
Unknown36(1)
Unknown2005()
Unknown1072(160000)
Unknown23032(3)
Unknown23033(107)
Unknown35()
sprite('Action_156_atk', 3) # 287-289 **attackbox here**
RefreshMultihit()
GFX_0('AstralLastBlade', 100)
Unknown36(1)
Unknown23032(60)
Unknown23033(50)
Unknown35()
sprite('Action_156_atk', 30) # 290-319 **attackbox here**
RefreshMultihit()
AirHitstunAnimation(5)
GroundedHitstunAnimation(5)
hitstun(999)
@State
def AstralBlade():
def upon_IMMEDIATE():
Unknown2005()
Unknown23015(1)
sprite('Action_419_00', 4) # 1-4 **attackbox here**
sprite('Action_419_01', 4) # 5-8 **attackbox here**
sprite('Action_419_02', 4) # 9-12
sprite('Action_419_03', 4) # 13-16
label(0)
sprite('Action_419_04', 4) # 17-20
sprite('Action_419_05', 4) # 21-24
gotoLabel(0)
label(1)
sprite('Action_419_06', 4) # 25-28
@State
def AstralLastBlade():
def upon_IMMEDIATE():
Unknown2005()
Unknown23015(4)
Unknown1096(1500)
sprite('Action_421_00', 4) # 1-4 **attackbox here**
sprite('Action_421_01', 4) # 5-8
sprite('Action_421_02', 4) # 9-12
sprite('Action_421_03', 30) # 13-42
Unknown1096(8000)
Unknown21015('41737472616c45786543616d65726100000000000000000000000000000000008913000000000000')
@State
def AstralFinishCutIn():
def upon_IMMEDIATE():
Unknown23015(1)
Unknown2019(-1000)
Unknown6001(1)
Unknown1000(640000)
teleportRelativeY(-640000)
Unknown3026(-16777216)
if SLOT_38:
Unknown1000(-640000)
sprite('Action_426_00', 1) # 1-1
Unknown3001(0)
Unknown36(22)
Unknown1084(1)
Unknown3026(-16777216)
Unknown3038(1)
Unknown3001(0)
Unknown35()
sprite('Action_426_00', 5) # 2-6
Unknown3004(30)
Unknown36(22)
Unknown3004(9)
Unknown35()
sprite('Action_426_01', 15) # 7-21
Unknown3025(-1, 15)
sprite('Action_426_01', 15) # 22-36
physicsXImpulse(-12000)
Unknown1028(300)
Unknown36(22)
Unknown3038(0)
Unknown1000(10)
physicsXImpulse(-18000)
Unknown1028(-450)
Unknown35()
sprite('Action_426_02', 21) # 37-57
sprite('Action_426_02', 28) # 58-85
Unknown1084(1)
Unknown36(22)
Unknown1084(1)
Unknown35()
sprite('Action_426_03', 7) # 86-92
sprite('Action_426_04', 7) # 93-99
sprite('Action_426_05', 30) # 100-129
GFX_0('AstralFinishAtk', 100)
sprite('Action_426_06', 45) # 130-174
Unknown3025(-16777216, 90)
def upon_CLEAR_OR_EXIT():
Unknown36(22)
Unknown3026(-16777216)
Unknown35()
sprite('Action_426_06', 45) # 175-219
GFX_0('AstWhiteOut', 100)
sprite('Action_426_07', 1) # 220-220
clearUponHandler(3)
sprite('Action_426_07', 1) # 221-221
@State
def AstralFinishAtk():
def upon_IMMEDIATE():
Unknown2012()
Damage(25500)
MinimumDamagePct(100)
Unknown11064(3)
Hitstop(0)
Unknown11001(0, 0, 0)
Unknown9130(16)
Unknown9142(100)
GroundedHitstunAnimation(2)
AirHitstunAnimation(2)
PushbackX(0)
Unknown11050('050000000000000000000000000000000000000000000000000000000000000000000000')
Unknown11023(1)
Unknown11086(1)
Unknown23151(22, 103)
def upon_45():
Unknown2038(1)
if (SLOT_2 >= 3):
SLOT_2 = 0
Unknown36(22)
Unknown51(1)
Unknown3026(-16777216)
Unknown35()
else:
Unknown36(22)
Unknown51(0)
Unknown3026(-16777216)
Unknown35()
sprite('Action_423_00', 4) # 1-4 **attackbox here**
SFX_3('SE_BigBomb')
sprite('Action_423_01', 4) # 5-8
sprite('Action_423_02', 4) # 9-12
sprite('Action_423_03', 4) # 13-16
sprite('Action_423_04', 4) # 17-20
@State
def AstWhiteOut():
def upon_IMMEDIATE():
Unknown23015(4)
Unknown3033()
Unknown3001(0)
Unknown1096(100000000)
Unknown1056(20000)
sprite('vr_white', 15) # 1-15
Unknown3004(20)
sprite('vr_white', 40) # 16-55
Unknown3001(255)
Unknown3004(0)
sprite('vr_white', 50) # 56-105
Unknown23029(3, 5003, 0)
Unknown36(22)
Unknown3025(-1, 1)
Unknown35()
sprite('vr_white', 60) # 106-165
Unknown3004(-5)
@State
def AstralBG():
def upon_IMMEDIATE():
Unknown23015(2)
Unknown2007()
Unknown6001(1)
Unknown1000(-640000)
teleportRelativeY(-320000)
sprite('Action_422_00', 4) # 1-4
sprite('Action_422_01', 4) # 5-8
sprite('Action_422_02', 4) # 9-12
sprite('Action_422_03', 4) # 13-16
sprite('Action_422_04', 32767) # 17-32783
sprite('Action_422_05', 4) # 32784-32787
@State
def AstralStartCutIn():
def upon_IMMEDIATE():
Unknown4011(3)
Unknown4010(3)
Unknown2054(1)
Unknown2019(-4000)
Unknown23015(5)
Unknown6001(1)
Unknown1000(625000)
teleportRelativeY(-640000)
if SLOT_38:
Unknown1000(-655000)
sprite('Action_999_01', 2) # 1-2
sprite('Action_999_02', 2) # 3-4
sprite('Action_999_03', 3) # 5-7
sprite('Action_999_04', 2) # 8-9
sprite('Action_999_05', 4) # 10-13
sprite('Action_999_06', 3) # 14-16
sprite('Action_999_07', 3) # 17-19
sprite('Action_999_08', 2) # 20-21
sprite('Action_999_09', 3) # 22-24
sprite('Action_999_10', 4) # 25-28
sprite('Action_999_11', 6) # 29-34
sprite('Action_999_12', 3) # 35-37
sprite('Action_999_13', 10) # 38-47
sprite('Action_999_14', 3) # 48-50
teleportRelativeX(50000)
sprite('Action_999_15', 3) # 51-53 **attackbox here**
sprite('Action_999_16', 3) # 54-56
sprite('Action_999_17', 3) # 57-59
sprite('Action_999_18', 3) # 60-62 **attackbox here**
physicsXImpulse(65000)
Unknown3001(200)
Unknown3004(-20)
Unknown1099(100)
@State
def Win_Knife():
def upon_IMMEDIATE():
def upon_CLEAR_OR_EXIT():
Unknown1065(-21)
Unknown2038(1)
if (SLOT_2 >= 4):
Unknown2037(0)
SFX_3('SE041')
sprite('Action_097_00', 1) # 1-1
Unknown1074(-4500)
sprite('Action_097_01', 1) # 2-2
sprite('Action_097_02', 1) # 3-3
sprite('Action_097_03', 1) # 4-4
Unknown23144('0300000000000000000000000000000000000000000000000000000000000000320000000000000014000000')
sprite('Action_097_04', 1) # 5-5
sprite('Action_097_06', 1) # 6-6
sprite('Action_097_07', 1) # 7-7
sprite('Action_097_08', 1) # 8-8
sprite('Action_097_09', 1) # 9-9
sprite('Action_097_10', 1) # 10-10
Unknown23144('0300000000000000000000000000000000000000000000000000000000000000320000000000000014000000')
sprite('Action_097_11', 1) # 11-11
sprite('Action_097_13', 1) # 12-12
sprite('Action_097_14', 1) # 13-13
sprite('Action_097_15', 1) # 14-14
sprite('Action_097_16', 1) # 15-15
sprite('Action_097_17', 1) # 16-16
sprite('Action_097_18', 1) # 17-17
Unknown23144('0300000000000000000000000000000000000000000000000000000000000000320000000000000014000000')
sprite('Action_097_19', 1) # 18-18
sprite('Action_097_21', 1) # 19-19
Unknown1074(4500)
sprite('Action_097_22', 1) # 20-20
sprite('Action_097_23', 1) # 21-21
sprite('Action_097_24', 1) # 22-22
sprite('Action_097_25', 1) # 23-23
sprite('Action_097_26', 1) # 24-24
sprite('Action_097_27', 1) # 25-25
Unknown23144('0300000000000000000000000000000000000000000000000000000000000000320000000000000014000000')
sprite('Action_097_28', 1) # 26-26
sprite('Action_097_30', 1) # 27-27
sprite('Action_097_31', 1) # 28-28
sprite('Action_097_32', 1) # 29-29
sprite('Action_097_33', 1) # 30-30
sprite('Action_097_34', 1) # 31-31
sprite('Action_097_35', 1) # 32-32
sprite('Action_097_36', 1) # 33-33
Unknown23144('0300000000000000000000000000000000000000000000000000000000000000320000000000000014000000')
sprite('Action_097_37', 1) # 34-34
sprite('Action_097_39', 1) # 35-35
sprite('Action_097_40', 1) # 36-36
sprite('Action_097_41', 1) # 37-37
Unknown1074(0)
clearUponHandler(3)
sprite('Action_097_42', 1) # 38-38
sprite('Action_097_43', 1) # 39-39
sprite('Action_097_44', 1) # 40-40
sprite('Action_097_45', 1) # 41-41
sprite('Action_097_46', 1) # 42-42
@State
def Win_Knife_Equip():
sprite('Action_104_00', 4) # 1-4
SFX_3('')
sprite('Action_104_01', 4) # 5-8
sprite('Action_104_02', 4) # 9-12
sprite('Action_104_03', 4) # 13-16
| [
"[email protected]"
] | |
fb54d19b3e0e115daed7e8ea028298023bd94bc5 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02925/s813842519.py | fd514890376add5cc9ff63723b435deab183d427 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 831 | py | n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
l = [i for i in range(n)]
pos = [0] * n
res = 0
cnt = 0
while True:
res += 1
flag = True
tmp = l.copy()
l = []
used = [False] * n
for v in tmp:
if used[v] or pos[v] == n - 1:
continue
opp = a[v][pos[v]] - 1
if used[opp] or pos[opp] == n - 1:
continue
if a[opp][pos[opp]] - 1 == v:
pos[v] += 1
pos[opp] += 1
l.append(v)
l.append(opp)
used[v] = True
used[opp] = True
flag = False
if pos[v] == n - 1:
cnt += 1
if pos[opp] == n - 1:
cnt += 1
if flag:
print(-1)
break
if cnt == n:
print(res)
break | [
"[email protected]"
] | |
b3c32db3186b4caf7016dabb7784a1f42ab8e00a | 32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd | /benchmark/antennapod/testcase/firstcases/testcase6_004.py | 9e861b2631f1cd4c20da6b5730e18a08b29e1c30 | [] | no_license | Prefest2018/Prefest | c374d0441d714fb90fca40226fe2875b41cf37fc | ac236987512889e822ea6686c5d2e5b66b295648 | refs/heads/master | 2021-12-09T19:36:24.554864 | 2021-12-06T12:46:14 | 2021-12-06T12:46:14 | 173,225,161 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,080 | py | #coding=utf-8
import os
import subprocess
import time
import traceback
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import NoSuchElementException, WebDriverException
desired_caps = {
'platformName' : 'Android',
'deviceName' : 'Android Emulator',
'platformVersion' : '4.4',
'appPackage' : 'de.danoeh.antennapod',
'appActivity' : 'de.danoeh.antennapod.activity.SplashActivity',
'resetKeyboard' : True,
'androidCoverage' : 'de.danoeh.antennapod/de.danoeh.antennapod.JacocoInstrumentation',
'noReset' : True
}
def command(cmd, timeout=5):
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
time.sleep(timeout)
p.terminate()
return
def getElememt(driver, str) :
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str)
return element
def getElememtBack(driver, str1, str2) :
for i in range(0, 2, 1):
try:
element = driver.find_element_by_android_uiautomator(str1)
except NoSuchElementException:
time.sleep(1)
else:
return element
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str2)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str2)
return element
def swipe(driver, startxper, startyper, endxper, endyper) :
size = driver.get_window_size()
width = size["width"]
height = size["height"]
try:
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
except WebDriverException:
time.sleep(1)
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
return
# testcase004
try :
starttime = time.time()
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
element = getElememt(driver, "new UiSelector().resourceId(\"de.danoeh.antennapod:id/refresh_item\").className(\"android.widget.TextView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageButton\").description(\"Open menu\")")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Queue\")", "new UiSelector().className(\"android.widget.TextView\").instance(5)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"de.danoeh.antennapod:id/refresh_item\").className(\"android.widget.TextView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().resourceId(\"de.danoeh.antennapod:id/queue_lock\").className(\"android.widget.TextView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"More options\")")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Clear Queue\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Send…\")", "new UiSelector().className(\"android.widget.Button\").instance(1)")
TouchAction(driver).tap(element).perform()
driver.press_keycode(4)
element = getElememtBack(driver, "new UiSelector().text(\"OK\")", "new UiSelector().className(\"android.widget.Button\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageButton\").description(\"Open menu\")")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Settings\")", "new UiSelector().className(\"android.widget.TextView\").instance(12)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageButton\").description(\"Navigate up\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageButton\").description(\"Open menu\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"de.danoeh.antennapod:id/imgvCover\").className(\"android.widget.ImageView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememtBack(driver, "new UiSelector().text(\"5 seconds\")", "new UiSelector().className(\"android.widget.CheckedTextView\")")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Confirm\")", "new UiSelector().className(\"android.widget.Button\").instance(1)")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Queue\")", "new UiSelector().className(\"android.widget.TextView\").instance(6)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"More options\")")
TouchAction(driver).long_press(element).release().perform()
driver.press_keycode(4)
except Exception, e:
print 'FAIL'
print 'str(e):\t\t', str(e)
print 'repr(e):\t', repr(e)
print traceback.format_exc()
else:
print 'OK'
finally:
cpackage = driver.current_package
endtime = time.time()
print 'consumed time:', str(endtime - starttime), 's'
command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"6_004\"")
jacocotime = time.time()
print 'jacoco time:', str(jacocotime - endtime), 's'
driver.quit()
if (cpackage != 'de.danoeh.antennapod'):
cpackage = "adb shell am force-stop " + cpackage
os.popen(cpackage) | [
"[email protected]"
] | |
a868589ab22d6b001a1e0a8c4cd3b53b2b965c0e | 10d89b6e07a7c72c385eb1d1c60a3e0ed9f9fc3c | /boss/report/views/movie_sum.py | 5d816002dcf23fdd6d97d0c4b852eaccb658a172 | [] | no_license | cash2one/pt | 2a4998a6627cf1604fb64ea8ac62ff1c227f0296 | 8a8c12375610182747099e5e60e15f1a9bb3f953 | refs/heads/master | 2021-01-20T00:36:43.779028 | 2016-11-07T03:27:18 | 2016-11-07T03:27:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,978 | py | #coding: utf-8
"""
服务质量追踪-电影票
"""
from report_pub import *
def get_movie_sum_data(start_date, end_date, app, ver, channel):
if not start_date:
start_date = None
if not end_date:
end_date = None
if not app:
app = None
if not ver:
ver = None
if not channel:
channel = None
cursor = connections['report'].cursor()
cursor.execute("call `SP_T_RP_D_MOVIE_RANKS`(%s, %s, %s, %s, %s)",
[start_date, end_date, ver, channel, app])
objs = cursor.fetchall()
data = []
for obj in objs:
data.append(
[
str(obj[0]),
str(obj[1]),
str(obj[2]),
str(obj[3]),
str(obj[4]),
str(obj[5]),
str(obj[6]),
str(obj[7]),
]
)
if not data:
data.append([Const.NONE] * 8)
else:
data.sort(key=lambda o: o[0], reverse=True)
return data
@login_required
@permission_required(u'man.%s' % ReportConst.BA_PRODUCT_ANALYSIS_MOVIE_REPORT, raise_exception=True)
@add_common_var
def movie_sum(request, template_name):
app = request.GET.get("app")
report_check_app(request, app)
vers = get_app_versions(app)
channels = get_app_channels(app)
product_type = get_product_type(ReportConst.MOVIE)
cps = get_cp_info(product_type)
return report_render(request, template_name,{
"currentdate": get_datestr(0, "%Y-%m-%d"),
"vers": vers,
"channels": channels
})
@login_required
@permission_required(u'man.%s' % ReportConst.BA_PRODUCT_ANALYSIS_MOVIE_REPORT, raise_exception=True)
def movie_sum_ajax(request):
start_date = request.POST.get("start_date")
end_date = request.POST.get("end_date")
app = request.POST.get("app")
report_check_app(request, app)
ver = request.POST.get("ver")
channel = request.POST.get("channel")
result = get_movie_sum_data(start_date, end_date, app, ver, channel)
return HttpResponse(json.dumps(result))
@login_required
@permission_required(u'man.%s' % ReportConst.BA_PRODUCT_ANALYSIS_MOVIE_REPORT, raise_exception=True)
def movie_sum_csv(request):
start_date = request.GET.get("start_date")
end_date = request.GET.get("end_date")
app = request.GET.get("app")
report_check_app(request, app)
ver = request.GET.get("ver")
channel = request.GET.get("channel")
filename = '电影票汇总报表(%s-%s).csv' % (str(start_date), str(end_date))
csv_data = [["电影名称",
"订单总数",
"订单支付数",
"订单支付率",
"订单支付成功数",
"订单支付成功率",
"订单支付失败数",
"订单支付失败率"]]
csv_data.extend(get_movie_sum_data(start_date, end_date, app, ver, channel))
return get_csv_response(filename, csv_data) | [
"[email protected]"
] | |
901df2bd27ecb8f459e0b79373f18de62a4fec93 | e21599d08d2df9dac2dee21643001c0f7c73b24f | /practice/concurrency/threadpool_executor.py | 5de7abb753749c293b03937824f0c77e6414843f | [] | no_license | herolibra/PyCodeComplete | c7bf2fb4ce395737f8c67749148de98a36a71035 | 4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b | refs/heads/master | 2022-07-17T05:39:03.554760 | 2020-05-03T07:00:14 | 2020-05-03T07:00:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 707 | py | #!/usr/bin/env python
# coding=utf-8
import time
import requests
from concurrent.futures import ProcessPoolExecutor
def visit_url(url):
response = requests.request('GET', url)
return response.content
if __name__ == '__main__':
start = time.time()
# 创建需要处理的URL序列
urls = ['http://api.bilibili.com/x/web-interface/archive/stat?aid={0}'.format(i) for i in range(1, 1001)]
with ProcessPoolExecutor(max_workers=20) as executor:
# result = executor.map(visit_url, urls)
for num, result in zip(range(1, 1001), executor.map(visit_url, urls)):
print('video ({}) = {}'.format(num, result))
print('COST: {}'.format(time.time() - start)) | [
"[email protected]"
] | |
7f6f5cb399c032bf7955265b384a932ad7e4bdbd | 3fa7203b6180ab9a8955642f1373f3e436514a1e | /projects/apexlearningcenter/gdata-python-client/setup.py | a057292cc6d08e7313830bbdba294277ff4a9563 | [
"Apache-2.0"
] | permissive | Opportunitylivetv/blog | ce55db2f03dba42286b403f8df0839f6f75b7eea | 01e99810d977d8ddbb7a99b7f8f6d0c4276f3cd7 | refs/heads/master | 2021-07-25T21:40:01.599864 | 2017-11-08T22:10:51 | 2017-11-08T22:10:51 | 110,347,355 | 1 | 1 | null | 2017-11-11T13:26:21 | 2017-11-11T13:26:21 | null | UTF-8 | Python | false | false | 1,987 | py | #!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# 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.
from distutils.core import setup
setup(
name='gdata.py',
version='1.0.10.1',
description='Python client library for Google data APIs',
long_description = """\
The Google data Python client library makes it easy to access data
through the Google data APIs. This library provides data model and
service modules for the the following Google data services:
- Google Calendar data API
- Google Spreadsheets data API
- Google Document List data APIs
- Google Base data API
- Google Apps Provisioning API
- Picasa Web Albums Data API
- Google Code Search Data API
- core Google data API functionality
The core Google data code provides sufficient functionality to use this
library with any Google data API (even if a module hasn't been written for
it yet). For example, this client can be used with the Picasa Web Albums data
API, the Blogger API, and the YouTube API. This library may also be used with
any Atom Publishing Protocol service.
""",
author='Jeffrey Scudder',
author_email='[email protected]',
license='Apache 2.0',
url='http://code.google.com/p/gdata-python-client/',
packages=['atom', 'gdata', 'gdata.calendar', 'gdata.base',
'gdata.spreadsheet', 'gdata.apps', 'gdata.docs', 'gdata.codesearch',
'gdata.photos', 'gdata.exif', 'gdata.geo', 'gdata.media'],
package_dir = {'gdata':'src/gdata', 'atom':'src/atom'}
)
| [
"[email protected]"
] | |
b46a9f045a08dbe61856a95eec669f548997abff | 074ce641fe9ab26835e4bfa77bdcac4aed92fcc7 | /locations/spiders/bojangles.py | 0e584c803734199752d1f60be07cccbd6260fee0 | [
"MIT"
] | permissive | zerebubuth/all-the-places | 173623ef00be2517bda26aff568a342ba1168c74 | a8b5931ca2e727194a6eb622357998dddccf1bb4 | refs/heads/master | 2021-07-04T04:02:54.306426 | 2017-08-02T16:17:46 | 2017-08-02T16:17:46 | 105,061,033 | 0 | 0 | null | 2017-09-27T19:35:12 | 2017-09-27T19:35:12 | null | UTF-8 | Python | false | false | 4,326 | py | # -*- coding: utf-8 -*-
import json
import scrapy
import re
from scrapy.utils.url import urljoin_rfc
from scrapy.utils.response import get_base_url
from locations.items import GeojsonPointItem
class BojanglesSpider(scrapy.Spider):
name = "bojangles"
allowed_domains = ["locations.bojangles.com"]
start_urls = (
'http://locations.bojangles.com/',
)
def store_hours(self, store_hours):
day_groups = []
this_day_group = None
for day_info in store_hours:
day = day_info['day'][:2].title()
hour_intervals = []
for interval in day_info['intervals']:
f_time = str(interval['start']).zfill(4)
t_time = str(interval['end']).zfill(4)
hour_intervals.append('{}:{}-{}:{}'.format(
f_time[0:2],
f_time[2:4],
t_time[0:2],
t_time[2:4],
))
hours = ','.join(hour_intervals)
if not this_day_group:
this_day_group = {
'from_day': day,
'to_day': day,
'hours': hours
}
elif this_day_group['hours'] != hours:
day_groups.append(this_day_group)
this_day_group = {
'from_day': day,
'to_day': day,
'hours': hours
}
elif this_day_group['hours'] == hours:
this_day_group['to_day'] = day
day_groups.append(this_day_group)
opening_hours = ""
if len(day_groups) == 1 and day_groups[0]['hours'] in ('00:00-23:59', '00:00-00:00'):
opening_hours = '24/7'
else:
for day_group in day_groups:
if day_group['from_day'] == day_group['to_day']:
opening_hours += '{from_day} {hours}; '.format(**day_group)
elif day_group['from_day'] == 'Su' and day_group['to_day'] == 'Sa':
opening_hours += '{hours}; '.format(**day_group)
else:
opening_hours += '{from_day}-{to_day} {hours}; '.format(**day_group)
opening_hours = opening_hours[:-2]
return opening_hours
def parse_store(self, response):
properties = {
'addr:full': response.xpath('//span[@itemprop="streetAddress"]/text()')[0].extract(),
'addr:city': response.xpath('//span[@itemprop="addressLocality"]/text()')[0].extract(),
'addr:state': response.xpath('//span[@itemprop="addressRegion"]/text()')[0].extract(),
'addr:postcode': response.xpath('//span[@itemprop="postalCode"]/text()')[0].extract(),
'ref': response.url,
'website': response.url,
}
phone = response.xpath('//a[@class="c-phone-number-link c-phone-main-number-link"]/text()')[0].extract()
if phone:
properties['phone'] = phone
hours = json.loads(response.xpath('//div[@class="c-location-hours-today js-location-hours"]/@data-days')[0].extract())
opening_hours = self.store_hours(hours) if hours else None
if opening_hours:
properties['opening_hours'] = opening_hours
lon_lat = [
float(response.xpath('//span/meta[@itemprop="longitude"]/@content')[0].extract()),
float(response.xpath('//span/meta[@itemprop="latitude"]/@content')[0].extract()),
]
yield GeojsonPointItem(
properties=properties,
lon_lat=lon_lat,
)
def parse(self, response):
base_url = get_base_url(response)
urls = response.xpath('//a[@class="c-directory-list-content-item-link"]/@href').extract()
for path in urls:
if len(path.split('/')) > 2:
# If there's only one store, the URL will be longer than <state code>.html
yield scrapy.Request(urljoin_rfc(base_url, path), callback=self.parse_store)
else:
yield scrapy.Request(urljoin_rfc(base_url, path))
urls = response.xpath('//a[@class="c-location-grid-item-link"]/@href').extract()
for path in urls:
yield scrapy.Request(urljoin_rfc(base_url, path), callback=self.parse_store)
| [
"[email protected]"
] | |
a927f9c813867b753eff1fe9ffff2a4ca4958e48 | f65c074b9d47a86488ea82bccf3bcea2c089b576 | /Matc_links/Matc_links/items.py | ab239cf684765f22c9935412ffce36888c35f3d9 | [
"MIT"
] | permissive | Nouldine/CrawlerSystems | 32aea71bf4f24f7f5f3430fa93576d4524bf0448 | 7bba8ba3ec76e10f70a35700602812ee6f039b63 | refs/heads/master | 2020-09-15T12:18:50.117873 | 2020-01-23T14:50:45 | 2020-01-23T14:50:45 | 223,441,439 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 354 | py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
class MatcLinksItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
links = scrapy.Field()
pass
| [
"[email protected]"
] | |
7d0c1a071fb41cdfe747f02f3ff8aacdd1540482 | 5864f03e60b18b6ba6d5f666f5656193a423be2a | /5.3-random.py | a810965241b091e21e408279cdb5a52e425e4457 | [] | no_license | c4collins/python-standard-library-examples | 1ca66176cee9dab606afc8cd70f806f7c261ef81 | ef812ca846692243604a0fc119b6eece4025f148 | refs/heads/master | 2021-01-01T17:05:21.504397 | 2018-01-18T21:15:06 | 2018-01-18T21:15:06 | 8,157,627 | 22 | 9 | null | null | null | null | UTF-8 | Python | false | false | 7,582 | py | ## 5.3 Random
# Uses the Mersenne Twister algorithm
import random, os, itertools, time, decimal, math
import cPickle as pickle
## 5.3.1 Generating Random numbers
for i in xrange(5):
print '%04.3f' % random.random(),
print
# uniform() will generate numbers within a specified range
for i in xrange(5):
print '%04.3f' % random.uniform(1,100),
print
# Seeding gives the same set of 'random' data each time
random.seed(1)
for i in xrange(5):
print '%04.3f' % random.random(),
print
random.seed(1)
for i in xrange(5):
print '%04.3f' % random.random(),
print
random.seed(1)
for i in xrange(5):
print '%04.3f' % random.random(),
print '\n'
## 5.3.3 Saving State
if os.path.exists('data/5.3.3-state.dat'):
#Restore the previously saved state
print "Found '5.3.3-state.dat', initializing random module"
with open('data/5.3.3-state.dat', 'rb') as f:
state = pickle.load(f)
random.setstate(state)
else:
# Use a known start state
print "No '5.3.3-state.dat', seeding"
random.seed(1)
# Produce random values
for i in xrange(3):
print '%04.3f' % random.random(),
print '\n'
# Save state for next time
with open('data/5.3.3-state.dat', 'wb') as f:
pickle.dump(random.getstate(), f)
# Produce more random values
print "After saving state:"
for i in xrange(3):
print '%04.3f' % random.random(),
print '\n'
# Random integers
print '[1, 100]:',
for i in xrange(3):
print random.randint(1,100),
print '\n[-5 ,5]:',
for i in xrange(3):
print random.randint(-5, 5),
print
for i in xrange(3):
print random.randrange(0, 101, 5), # random.randrange(min, max, step)
print '\n'
## 5.3.5 Picking Random Items
for j in xrange(2):
outcomes = { 'heads':0, 'tails':0, }
sides = outcomes.keys()
random.seed() # reset the seed to a random value
for i in xrange(10000):
outcomes[ random.choice(sides) ] += 1
for key in sides:
print key,':',outcomes[key]
print
## 5.3.6 Permutations
FACE_CARDS = ('J', 'Q', 'K', 'A')
SUITS = ('H', 'D', 'C', 'S')
def new_deck():
return list( itertools.product(
itertools.chain( xrange(2, 11), FACE_CARDS ),
SUITS
))
def show_deck(deck):
p_deck = deck[:]
while p_deck:
row = p_deck[:13]
p_deck = p_deck[13:]
for j in row:
print '%2s%s' % j,
print
# Make a new deck, with the cards in order
deck = new_deck()
print "\nInitial deck:"
show_deck(deck)
# Shuffle and sisplay the shuffled deck
random.shuffle(deck)
print "\nShuffled Deck:"
show_deck(deck)
# Deal 4 hands of 5 cards
hands = [ [], [], [], [] ]
for i in xrange(5):
for h in hands:
h.append(deck.pop())
# Show the hands
print "\nHands:"
for n, h in enumerate(hands):
print '%d:' % (n+1)
for c in h:
print '%2s%s' % c,
print
# Show remaining deck
print "\nRemaining deck:"
show_deck(deck)
## 5.3.6 Sampling
with open('/usr/share/dict/words', 'rt') as f:
words = f.readlines()
words = [w.rstrip() for w in words ]
for w in random.sample(words, 5):
print w,
print "\n"
## 5.3.8 Multiple Simultaneous Generators
# Each instance of Random can have these properties set on it's own, and can be utilized separately
print "Default Initialization:\n"
r1 = random.Random()
r2 = random.Random()
for i in xrange(3):
print '%04.3f %04.3f' % (r1.random(), r2.random())
print "\nSame seed:\n"
seed = time.time()
r1 = random.Random(seed)
r2 = random.Random(seed)
for i in xrange(3):
print '%04.3f %04.3f' % (r1.random(), r2.random())
print "\nForce jumpahead on r2:\n"
r2.jumpahead(1024)
for i in xrange(3):
print '%04.3f %04.3f' % (r1.random(), r2.random())
## 5.3.9 SystemRandom
# SystemRandom has the same API as Random, but uses os.urandom() to generate values
# this means seed() and setstate() do nothing because the randomness is coming from the system
print "Default Initialization:\n"
r1 = random.SystemRandom()
r2 = random.SystemRandom()
for i in xrange(3):
print '%04.3f %04.3f' % (r1.random(), r2.random())
print "\nSame seed:\n"
seed = time.time()
r1 = random.SystemRandom(seed)
r2 = random.SystemRandom(seed)
for i in xrange(3):
print '%04.3f %04.3f' % (r1.random(), r2.random())
## 5.3.10 Nonuniform Distributions
# Set up context for rounding
c = decimal.getcontext().copy()
c.rounding = 'ROUND_UP'
c.prec = 2
## Normal
mu = 7.5 # mean
sigma = 2.0 # std. deviation
print "\nNormal(mu=%d, sigma=%d):" % (mu, sigma)
normal = []
for i in xrange(20):
normal.append(c.create_decimal( random.normalvariate( mu, sigma ) ))
normal = sorted(normal)
for n in normal:
print "%02.1d" % n,
## Gauss-Normal
print "\n(Gauss) Normal(mu=%d, sigma=%d):" % (mu, sigma)
gauss = []
for i in xrange(20):
gauss.append(c.create_decimal( random.gauss( mu, sigma ) ))
gauss = sorted(gauss)
for g in gauss:
print "%02.1d" % g,
## Log-Normal
print "\n(Logarithmic) Normal(mu=%d, sigma=%d):" % (mu, sigma)
lognormal = []
for i in xrange(15):
lognormal.append(c.create_decimal( random.lognormvariate( mu, sigma ) ))
lognormal = sorted(lognormal)
for l in lognormal:
print "%02.1d" % l,
## Triangular
low = 0
high = 10
mode = 7.5
print "\nTriangular(low=%d, high=%d, mode=%d)" % ( low, high, mode)
triangular = []
for i in xrange(20):
triangular.append( c.create_decimal( random.triangular( low, high, mode ) ) )
triangular = sorted(triangular)
for t in triangular:
print "%02.1d" % t,
## Exponential
lambd = 1.0 / 7.5 # lambd is (1.0 / the desired mean)
print "\nExponential(lambd=%0.4r)" % ( lambd )
exponential = []
for i in xrange(20):
exponential.append( c.create_decimal( random.expovariate( lambd ) ) )
exponential = sorted(exponential)
for e in exponential:
print "%02.1d" % e,
## Pareto distribution
alpha = 1 # shape parameter
print "\n(Long Tail) Pareto(alpha=%d)" % ( alpha )
pareto = []
for i in xrange(20):
pareto.append( c.create_decimal( random.paretovariate( alpha ) ) )
pareto = sorted(pareto)
for p in pareto:
print "%02.1d" % p,
## Angular (Von Mises)
mu = math.pi * 1.5 # radians between 0 and 2*pi
kappa = 1.5 # concentration, must be >= 0
print "\n(Von Mises) Angular(mu=%d, kappa=%d)" % ( mu, kappa )
angular = []
for i in xrange(20):
angular.append( c.create_decimal( random.vonmisesvariate( mu, kappa ) ) )
angular = sorted(angular)
for a in angular:
print "%02.1d" % a,
## Beta distribution
alpha = 1
beta = 2
print "\nBeta(alpha=%d, beta=%d)" % ( alpha, beta )
beta_v = []
for i in xrange(20):
beta_v.append( random.betavariate( alpha, beta ) )
beta_v = sorted(beta_v)
for b in beta_v:
print c.create_decimal(b),
## Gamma distribution
print "\nGamma(alpha=%d, beta=%d)" % ( alpha, beta )
gamma = []
for i in xrange(20):
gamma.append( random.gammavariate( alpha, beta ) )
gamma = sorted(gamma)
for g in gamma:
print c.create_decimal(g),
## Weibull distribution
print "\nWeibull(alpha=%d, beta=%d)" % ( alpha, beta )
weibull = []
for i in xrange(20):
weibull.append( random.weibullvariate( alpha, beta ) )
weibull = sorted(weibull)
for w in weibull:
print c.create_decimal(w), | [
"[email protected]"
] | |
46eb89357e79a72c0d54fe04daaea91db1801d5d | 3c01d7928029e74a19d646f5a40b3bf099b281a7 | /typeshed/stdlib/_thread.pyi | 2425703121b5dd5c8b5f33b5571063d7ac4de438 | [
"MIT"
] | permissive | arpancodes/protectsql | f3ced238c103fca72615902a9cb719c44ee2b5ba | 6392bb7a86d1f62b86faf98943a302f7ea3fce4c | refs/heads/main | 2023-08-07T16:33:57.496144 | 2021-09-24T19:44:51 | 2021-09-24T19:44:51 | 409,894,807 | 0 | 1 | MIT | 2021-09-24T19:44:52 | 2021-09-24T08:46:02 | Python | UTF-8 | Python | false | false | 1,427 | pyi | import sys
from threading import Thread
from types import TracebackType
from typing import Any, Callable, NoReturn, Optional, Tuple, Type
error = RuntimeError
def _count() -> int: ...
_dangling: Any
class LockType:
def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ...
def release(self) -> None: ...
def locked(self) -> bool: ...
def __enter__(self) -> bool: ...
def __exit__(
self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
) -> None: ...
def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ...
def interrupt_main() -> None: ...
def exit() -> NoReturn: ...
def allocate_lock() -> LockType: ...
def get_ident() -> int: ...
def stack_size(size: int = ...) -> int: ...
TIMEOUT_MAX: float
if sys.version_info >= (3, 8):
def get_native_id() -> int: ... # only available on some platforms
class _ExceptHookArgs(Tuple[Type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]]):
@property
def exc_type(self) -> Type[BaseException]: ...
@property
def exc_value(self) -> BaseException | None: ...
@property
def exc_traceback(self) -> TracebackType | None: ...
@property
def thread(self) -> Thread | None: ...
_excepthook: Callable[[_ExceptHookArgs], Any]
| [
"[email protected]"
] | |
a2fab96aa42133cf1bef5480f1a3154ef1479005 | 6923f79f1eaaba0ab28b25337ba6cb56be97d32d | /programming_computer_vision_with_python/cvbook-contrib/rof.py | cca76f74204c8c254b9909d2168401a571270eac | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | burakbayramli/books | 9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0 | 5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95 | refs/heads/master | 2023-08-17T05:31:08.885134 | 2023-08-14T10:05:37 | 2023-08-14T10:05:37 | 72,460,321 | 223 | 174 | null | 2022-10-24T12:15:06 | 2016-10-31T17:24:00 | Jupyter Notebook | UTF-8 | Python | false | false | 1,102 | py | import numpy
def denoise(im, U_init, tolerance=0.1, tau=0.125, tv_weight=30):
"""Denoises |im| using the ROF image denoising model.
Note: If tv_weight is set to something large, tolerance needs to be
lowered."""
# THe code is from Jan Erik Solem's book; it's based on:
# Chambolle 2005, eq 11 on p14 "Total variation minimization and a class of
# binary MRF models"
# http://www.cmap.polytechnique.fr/preprint/repository/578.pdf
m, n = im.shape
U = U_init
Px = numpy.zeros((m, n))
Py = numpy.zeros((m, n))
error = 1
while error > tolerance:
Uold = U
GradUx = numpy.roll(U, -1, axis=1) - U
GradUy = numpy.roll(U, -1, axis=0) - U
PxNew = Px + (tau / tv_weight) * GradUx
PyNew = Py + (tau / tv_weight) * GradUy
NormNew = numpy.maximum(1, numpy.sqrt(PxNew**2 + PyNew**2))
Px = PxNew / NormNew
Py = PyNew / NormNew
RxPx = numpy.roll(Px, 1, axis=1)
RyPy = numpy.roll(Py, 1, axis=0)
DivP = (Px - RxPx) + (Py - RyPy)
U = im + tv_weight * DivP
error = numpy.linalg.norm(U - Uold) / numpy.sqrt(n * m)
return U, im - U
| [
"[email protected]"
] | |
d376851a61e7d1f753b45331107716086f934b7e | fa9bae32c203323dfb345d9a415d4eaecb27a931 | /33. Search in Rotated Sorted Array.py | e6cd02b083ea61bcdaa241d139c7425c617c6ff7 | [] | no_license | IUIUN/The-Best-Time-Is-Now | 48a0c2e9d449aa2f4b6e565868a227b6d555bf29 | fab660f98bd36715d1ee613c4de5c7fd2b69369e | refs/heads/master | 2020-09-14T12:06:24.074973 | 2020-02-15T06:55:08 | 2020-02-15T06:55:08 | 223,123,743 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 772 | py | class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums:
return -1
left, right = 0, len(nums) - 1
if nums[left] ==target:
return left
if nums[right] ==target:
return right
while left +1 < right:
mid = left + (right- left)//2
if target == nums[mid]:
return mid
if nums[left] < nums[mid]:
if nums[left] < target <nums[mid]:
right = mid
else:
left = mid
else:
if nums[mid] < target < nums[right]:
left = mid
else:
right = mid
return -1
| [
"[email protected]"
] | |
54894be402b8fc5a0c43e67ef20cae3642449ae9 | 5e84763c16bd6e6ef06cf7a129bb4bd29dd61ec5 | /blimgui/dist/sdl2/test/audio_test.py | 569d249f8a32b6a76e411c269fc60885af4c9d7d | [
"MIT"
] | permissive | juso40/bl2sdk_Mods | 8422a37ca9c2c2bbf231a2399cbcb84379b7e848 | 29f79c41cfb49ea5b1dd1bec559795727e868558 | refs/heads/master | 2023-08-15T02:28:38.142874 | 2023-07-22T21:48:01 | 2023-07-22T21:48:01 | 188,486,371 | 42 | 110 | MIT | 2022-11-20T09:47:56 | 2019-05-24T20:55:10 | Python | UTF-8 | Python | false | false | 16,668 | py | import os
import sys
import ctypes
import pytest
import sdl2
from sdl2 import SDL_Init, SDL_Quit, SDL_InitSubSystem, SDL_QuitSubSystem, \
SDL_INIT_AUDIO
from sdl2.audio import FORMAT_NAME_MAP
from sdl2.error import SDL_GetError, SDL_ClearError
# NOTE: This module is missing a lot of tests, but is also going to be tricky
# to write more tests for.
# Get original audio driver, if one was set in the environment
original_driver = os.getenv("SDL_AUDIODRIVER", None)
@pytest.fixture
def with_sdl_audio():
# Reset original audio driver in the environment (if there was one)
if original_driver:
os.environ["SDL_AUDIODRIVER"] = original_driver
# Initialize SDL2 with video and audio subsystems
sdl2.SDL_Quit()
sdl2.SDL_ClearError()
ret = sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO | sdl2.SDL_INIT_AUDIO)
assert sdl2.SDL_GetError() == b""
assert ret == 0
yield
sdl2.SDL_Quit()
# Reset original audio driver in environment
os.environ.pop("SDL_AUDIODRIVER", None)
if original_driver:
os.environ["SDL_AUDIODRIVER"] = original_driver
@pytest.fixture
def with_default_driver(with_sdl_audio):
driver = sdl2.SDL_GetCurrentAudioDriver()
if driver == None or sdl2.SDL_GetNumAudioDevices(False) == 0:
sdl2.SDL_QuitSubSystem(SDL_INIT_AUDIO)
os.environ["SDL_AUDIODRIVER"] = b'dummy'
sdl2.SDL_InitSubSystem(SDL_INIT_AUDIO)
driver = sdl2.SDL_GetCurrentAudioDriver()
yield driver
def _get_audio_drivers():
drivers = []
for index in range(sdl2.SDL_GetNumAudioDrivers()):
name = sdl2.SDL_GetAudioDriver(index)
drivers.append(name.decode('utf-8'))
return drivers
# Test macro functions
def test_SDL_AUDIO_BITSIZE():
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_U8) == 8
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_S8) == 8
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_U16LSB) == 16
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_S16LSB) == 16
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_U16MSB) == 16
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_S16MSB) == 16
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_U16) == 16
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_S16) == 16
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_S32LSB) == 32
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_S32MSB) == 32
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_S32) == 32
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_F32LSB) == 32
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_F32MSB) == 32
assert sdl2.SDL_AUDIO_BITSIZE(sdl2.AUDIO_F32) == 32
def test_SDL_AUDIO_ISFLOAT():
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_U8)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_S8)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_U16LSB)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_S16LSB)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_U16MSB)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_S16MSB)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_U16)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_S16)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_S32LSB)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_S32MSB)
assert not sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_S32)
assert sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_F32LSB)
assert sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_F32MSB)
assert sdl2.SDL_AUDIO_ISFLOAT(sdl2.AUDIO_F32)
def test_SDL_AUDIO_ISBIGENDIAN():
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_U8)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_S8)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_U16LSB)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_S16LSB)
assert sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_U16MSB)
assert sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_S16MSB)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_U16)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_S16)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_S32LSB)
assert sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_S32MSB)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_S32)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_F32LSB)
assert sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_F32MSB)
assert not sdl2.SDL_AUDIO_ISBIGENDIAN(sdl2.AUDIO_F32)
def test_SDL_AUDIO_ISSIGNED():
assert not sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_U8)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_S8)
assert not sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_U16LSB)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_S16LSB)
assert not sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_U16MSB)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_S16MSB)
assert not sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_U16)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_S16)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_S32LSB)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_S32MSB)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_S32)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_F32LSB)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_F32MSB)
assert sdl2.SDL_AUDIO_ISSIGNED(sdl2.AUDIO_F32)
def test_SDL_AUDIO_ISINT():
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_U8)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_S8)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_U16LSB)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_S16LSB)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_U16MSB)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_S16MSB)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_U16)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_S16)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_S32LSB)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_S32MSB)
assert sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_S32)
assert not sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_F32LSB)
assert not sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_F32MSB)
assert not sdl2.SDL_AUDIO_ISINT(sdl2.AUDIO_F32)
def test_SDL_AUDIO_ISLITTLEENDIAN():
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_U8)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_S8)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_U16LSB)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_S16LSB)
assert not sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_U16MSB)
assert not sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_S16MSB)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_U16)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_S16)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_S32LSB)
assert not sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_S32MSB)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_S32)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_F32LSB)
assert not sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_F32MSB)
assert sdl2.SDL_AUDIO_ISLITTLEENDIAN(sdl2.AUDIO_F32)
def test_SDL_AUDIO_ISUNSIGNED():
assert sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_U8)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_S8)
assert sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_U16LSB)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_S16LSB)
assert sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_U16MSB)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_S16MSB)
assert sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_U16)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_S16)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_S32LSB)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_S32MSB)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_S32)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_F32LSB)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_F32MSB)
assert not sdl2.SDL_AUDIO_ISUNSIGNED(sdl2.AUDIO_F32)
# Test structs and objects
@pytest.mark.skip("not implemented")
def test_SDL_AudioSpec():
pass
@pytest.mark.skip("not implemented")
def test_SDL_AudioCVT():
pass
@pytest.mark.skip("not implemented")
def test_SDL_AudioStream():
pass
# Test actual function bindings
@pytest.mark.skip("not implemented")
def test_SDL_AudioInitQuit():
pass
def test_SDL_GetNumAudioDrivers(with_sdl_audio):
count = sdl2.SDL_GetNumAudioDrivers()
assert count >= 1
def test_SDL_GetAudioDriver(with_sdl_audio):
founddummy = False
drivercount = sdl2.SDL_GetNumAudioDrivers()
for index in range(drivercount):
drivername = sdl2.SDL_GetAudioDriver(index)
assert isinstance(drivername, (str, bytes))
if drivername == b"dummy":
founddummy = True
assert founddummy
def test_SDL_GetCurrentAudioDriver(with_sdl_audio):
success = 0
# Reset audio subsystem
SDL_Quit()
SDL_Init(0)
for index in range(sdl2.SDL_GetNumAudioDrivers()):
drivername = sdl2.SDL_GetAudioDriver(index)
os.environ["SDL_AUDIODRIVER"] = drivername.decode("utf-8")
# Certain drivers fail without bringing up the correct
# return value, such as the esd, if it is not running.
SDL_InitSubSystem(SDL_INIT_AUDIO)
driver = sdl2.SDL_GetCurrentAudioDriver()
SDL_QuitSubSystem(SDL_INIT_AUDIO)
# Do not handle wrong return values.
if driver is not None:
assert drivername == driver
success += 1
assert success >= 1
def test_SDL_OpenCloseAudio(with_sdl_audio):
# TODO: Add test that checks which audio formats are supported for each
# audio device?
fmt = sdl2.AUDIO_F32 if sys.platform == "darwin" else sdl2.AUDIO_U16
reqspec = sdl2.SDL_AudioSpec(44100, fmt, 2, 1024)
spec = sdl2.SDL_AudioSpec(0, 0, 0, 0)
ret = sdl2.SDL_OpenAudio(reqspec, ctypes.byref(spec))
assert ret == 0
assert spec.format > 0 # Can't guarantee we'll get requested format
assert spec.freq == reqspec.freq
assert spec.channels == reqspec.channels
sdl2.SDL_CloseAudio()
def test_SDL_GetNumAudioDevices(with_sdl_audio):
outnum = sdl2.SDL_GetNumAudioDevices(False)
assert outnum >= 1
innum = sdl2.SDL_GetNumAudioDevices(True)
assert innum >= 0
def test_SDL_GetAudioDeviceName(with_sdl_audio):
# NOTE: Check & print errors for drivers that failed to load?
backends = []
devices = {}
# Reset audio subsystem
SDL_Quit()
SDL_Init(0)
for drivername in _get_audio_drivers():
# Get input/output device names for each audio driver
backends.append(drivername)
os.environ["SDL_AUDIODRIVER"] = drivername
# Need to reinitialize subsystem for each driver
SDL_InitSubSystem(SDL_INIT_AUDIO)
driver = sdl2.SDL_GetCurrentAudioDriver()
if driver is not None:
driver = driver.decode("utf-8")
devices[driver] = {'input': [], 'output': []}
outnum = sdl2.SDL_GetNumAudioDevices(False)
innum = sdl2.SDL_GetNumAudioDevices(True)
for x in range(outnum):
name = sdl2.SDL_GetAudioDeviceName(x, False)
assert name is not None
devices[driver]['output'].append(name.decode('utf-8'))
for x in range(innum):
name = sdl2.SDL_GetAudioDeviceName(x, True)
assert name is not None
devices[driver]['input'].append(name.decode('utf-8'))
SDL_QuitSubSystem(SDL_INIT_AUDIO)
print("Audio backends supported by current SDL2 binary:")
print(backends)
print("\nAvailable audio drivers and devices:")
for driver in devices.keys():
print(driver)
print(" - input: {0}".format(str(devices[driver]['input'])))
print(" - output: {0}".format(str(devices[driver]['output'])))
@pytest.mark.skipif(sdl2.dll.version < 2016, reason="not available")
def test_SDL_GetAudioDeviceSpec(with_default_driver):
driver = with_default_driver
drivername = driver.decode('utf-8')
# Get name and spec of first output device
outspec = sdl2.SDL_AudioSpec(0, 0, 0, 0)
outname = sdl2.SDL_GetAudioDeviceName(0, False).decode('utf-8')
ret = sdl2.SDL_GetAudioDeviceSpec(0, False, ctypes.byref(outspec))
assert ret == 0
# Validate frequency and channel count were set
hz = outspec.freq
fmt = FORMAT_NAME_MAP[outspec.format] if outspec.format > 0 else 'unknown'
chans = outspec.channels
bufsize = outspec.samples if outspec.samples > 0 else 'unknown'
if driver != b"dummy":
assert hz > 0
assert chans > 0
# Print out device spec info
msg = "Audio device spec for {0} with '{1}' driver:"
msg2 = "{0} Hz, {1} channels, {2} format, {3} sample buffer size"
print(msg.format(outname, drivername))
print(msg2.format(hz, chans, fmt, bufsize))
@pytest.mark.skipif(sdl2.dll.version < 2240, reason="not available")
def test_SDL_GetDefaultAudioInfo(with_default_driver):
driver = with_default_driver
drivername = driver.decode('utf-8')
# Get name and spec of first output device
outspec = sdl2.SDL_AudioSpec(0, 0, 0, 0)
outname = ctypes.c_char_p()
ret = sdl2.SDL_GetDefaultAudioInfo(ctypes.byref(outname), ctypes.byref(outspec), 0)
# If method isn't implemented for the current back end, just skip
if ret < 0 and b"not supported" in sdl2.SDL_GetError():
pytest.skip("not supported by driver")
assert ret == 0
# Validate frequency and channel count were set
hz = outspec.freq
fmt = FORMAT_NAME_MAP[outspec.format] if outspec.format > 0 else 'unknown'
chans = outspec.channels
bufsize = outspec.samples if outspec.samples > 0 else 'unknown'
assert hz > 0
assert chans > 0
# Print out device spec info
outname = outname.value.decode('utf-8')
msg = "Default audio spec for {0} with '{1}' driver:"
msg2 = "{0} Hz, {1} channels, {2} format, {3} sample buffer size"
print(msg.format(outname, drivername))
print(msg2.format(hz, chans, fmt, bufsize))
def test_SDL_OpenCloseAudioDevice(with_sdl_audio):
#TODO: Add tests for callback
fmt = sdl2.AUDIO_F32 if sys.platform == "darwin" else sdl2.AUDIO_U16
reqspec = sdl2.SDL_AudioSpec(44100, fmt, 2, 1024)
outnum = sdl2.SDL_GetNumAudioDevices(0)
for x in range(outnum):
spec = sdl2.SDL_AudioSpec(0, 0, 0, 0)
name = sdl2.SDL_GetAudioDeviceName(x, 0)
assert name is not None
deviceid = sdl2.SDL_OpenAudioDevice(
name, 0, reqspec, ctypes.byref(spec),
sdl2.SDL_AUDIO_ALLOW_ANY_CHANGE
)
err = SDL_GetError()
assert deviceid >= 2
assert isinstance(spec, sdl2.SDL_AudioSpec)
assert spec.format in sdl2.AUDIO_FORMATS
assert spec.freq > 0
assert spec.channels > 0
assert spec.samples > 0
sdl2.SDL_CloseAudioDevice(deviceid)
@pytest.mark.skip("not implemented")
def test_SDL_GetAudioStatus(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_GetAudioDeviceStatus(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_PauseAudio(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_PauseAudioDevice(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_LoadWAV_RW(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_LoadWAV(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_FreeWAV(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_BuildAudioCVT(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_ConvertAudio(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_MixAudio(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_MixAudioFormat(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_LockUnlockAudio(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_LockUnlockAudioDevice(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_QueueAudio(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_GetQueuedAudioSize(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_ClearQueuedAudio(self):
pass
@pytest.mark.skip("not implemented")
def test_SDL_DequeueAudio(self):
pass
@pytest.mark.skip("not implemented")
@pytest.mark.skipif(sdl2.dll.version < 2007, reason="not available")
def test_SDL_NewAudioStream():
pass
@pytest.mark.skip("not implemented")
@pytest.mark.skipif(sdl2.dll.version < 2007, reason="not available")
def test_SDL_AudioStreamPut():
pass
@pytest.mark.skip("not implemented")
@pytest.mark.skipif(sdl2.dll.version < 2007, reason="not available")
def test_SDL_AudioStreamGet():
pass
@pytest.mark.skip("not implemented")
@pytest.mark.skipif(sdl2.dll.version < 2007, reason="not available")
def test_SDL_AudioStreamAvailable():
pass
@pytest.mark.skip("not implemented")
@pytest.mark.skipif(sdl2.dll.version < 2007, reason="not available")
def test_SDL_AudioStreamClear():
pass
@pytest.mark.skip("not implemented")
@pytest.mark.skipif(sdl2.dll.version < 2007, reason="not available")
def test_SDL_FreeAudioStream():
pass
| [
"[email protected]"
] | |
9dda382f321a6bd1b6fe598188a36bf543a1a2e8 | 026f12a5fdd4b3bfee00713091267aaef71047c1 | /end/demo4/hualiservice/trade/admin.py | daf8549e21a189ea882ce11a3ab0e6af12b56ab1 | [] | no_license | zzy0371/py1911project | 64c64413ea0107926ae81479adc27da87ee04767 | 7ce2a2acfc1dade24e6e7f8763fceb809fabd7a1 | refs/heads/master | 2023-01-08T07:51:13.388203 | 2020-03-19T03:31:33 | 2020-03-19T03:31:33 | 239,649,431 | 0 | 1 | null | 2023-01-05T09:04:53 | 2020-02-11T01:22:35 | JavaScript | UTF-8 | Python | false | false | 170 | py | from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Cart)
admin.site.register(Order)
admin.site.register(OrderDetail)
| [
"[email protected]"
] | |
28fde1cc01caebb7f303b02bcf82fa3c46c163d1 | e23a4f57ce5474d468258e5e63b9e23fb6011188 | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DynamicProgramming/132_PalindromePartitioningII.py | 207d00a98abde367cada73c26aa59d47492dee70 | [] | no_license | syurskyi/Python_Topics | 52851ecce000cb751a3b986408efe32f0b4c0835 | be331826b490b73f0a176e6abed86ef68ff2dd2b | refs/heads/master | 2023-06-08T19:29:16.214395 | 2023-05-29T17:09:11 | 2023-05-29T17:09:11 | 220,583,118 | 3 | 2 | null | 2023-02-16T03:08:10 | 2019-11-09T02:58:47 | Python | UTF-8 | Python | false | false | 1,820 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
"""
Dynamic Programming:
cuts[i]: minimum cuts needed for a palindrome partitioning of s[i:], so we want cuts[0].
To get cuts[i-1], we scan j from i-1 to len(s)-1.
Once we comes to a is_palindrome[i-1][j]==true:
if j==len(s)-1, the string s[i-1:] is a Pal, cuts[i-1] is 0;
else: the current cut num (first cut s[i-1:j+1] and then cut the rest
s[j+1:]) is 1+cuts[j+1], compare it to the exisiting cuts[i-1], repalce if smaller.
is_palindrome[i][j]: whether s[i:j+1] is palindrome.
Here we need not to compute the is_palindrome in advance.
We use "Dynamic Programming" too, the formula is very intuitive:
is_palindrome[i][j] = true if (is_palindrome[i+1][j-1] and s[i] == s[j]) else false
A better O(n) space solution can be found here:
https://discuss.leetcode.com/topic/2840/my-solution-does-not-need-a-table-for-palindrome-is-it-right-it-uses-only-o-n-space
"""
def minCut(self, s):
if not s:
return 0
s_len = len(s)
is_palindrome = [[False for i in range(s_len)]
for j in range(s_len)]
cuts = [s_len - 1 - i for i in range(s_len)]
for i in range(s_len - 1, -1, -1):
for j in range(i, s_len):
# if self.is_palindrome(i, j):
if ((j - i < 2 and s[i] == s[j]) or (s[i] == s[j] and is_palindrome[i + 1][j - 1])):
is_palindrome[i][j] = True
if j == s_len - 1:
cuts[i] = 0
else:
cuts[i] = min(cuts[i], 1 + cuts[j + 1])
else:
pass
return cuts[0]
"""
""
"aab"
"aabb"
"aabaa"
"acbca"
"acbbca"
"""
| [
"[email protected]"
] | |
46ff6bb671dba2e977cd92127af3a8fdffa5e7eb | 2cd06e44dd79b45708ddf010c31289458d850b94 | /test/functional/p2p_leak.py | 17143f418ca822b3cde05e7a2d2f0874b7260b7b | [
"MIT"
] | permissive | adymoloca/flocoin | bc66233e5b3b1af294ca6719b4a26f8829d682e4 | d9244577577dede975c852f6fcfe1afba4d71a57 | refs/heads/master | 2023-08-21T23:51:28.266695 | 2021-10-06T01:40:10 | 2021-10-06T01:40:10 | 408,609,250 | 0 | 0 | MIT | 2021-09-30T10:11:53 | 2021-09-20T21:45:28 | C++ | UTF-8 | Python | false | false | 7,392 | py | #!/usr/bin/env python3
# Copyright (c) 2017-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test message sending before handshake completion.
Before receiving a VERACK, a node should not send anything but VERSION/VERACK
and feature negotiation messages (WTXIDRELAY, SENDADDRV2).
This test connects to a node and sends it a few messages, trying to entice it
into sending us something it shouldn't."""
import time
from test_framework.messages import (
msg_getaddr,
msg_ping,
msg_version,
)
from test_framework.p2p import (
P2PInterface,
P2P_SUBVERSION,
P2P_SERVICES,
P2P_VERSION_RELAY,
)
from test_framework.test_framework import FlocoinTestFramework
from test_framework.util import (
assert_equal,
assert_greater_than_or_equal,
)
PEER_TIMEOUT = 3
class LazyPeer(P2PInterface):
def __init__(self):
super().__init__()
self.unexpected_msg = False
self.ever_connected = False
self.got_wtxidrelay = False
self.got_sendaddrv2 = False
def bad_message(self, message):
self.unexpected_msg = True
print("should not have received message: %s" % message.msgtype)
def on_open(self):
self.ever_connected = True
# Does not respond to "version" with "verack"
def on_version(self, message): self.bad_message(message)
def on_verack(self, message): self.bad_message(message)
def on_inv(self, message): self.bad_message(message)
def on_addr(self, message): self.bad_message(message)
def on_getdata(self, message): self.bad_message(message)
def on_getblocks(self, message): self.bad_message(message)
def on_tx(self, message): self.bad_message(message)
def on_block(self, message): self.bad_message(message)
def on_getaddr(self, message): self.bad_message(message)
def on_headers(self, message): self.bad_message(message)
def on_getheaders(self, message): self.bad_message(message)
def on_ping(self, message): self.bad_message(message)
def on_mempool(self, message): self.bad_message(message)
def on_pong(self, message): self.bad_message(message)
def on_feefilter(self, message): self.bad_message(message)
def on_sendheaders(self, message): self.bad_message(message)
def on_sendcmpct(self, message): self.bad_message(message)
def on_cmpctblock(self, message): self.bad_message(message)
def on_getblocktxn(self, message): self.bad_message(message)
def on_blocktxn(self, message): self.bad_message(message)
def on_wtxidrelay(self, message): self.got_wtxidrelay = True
def on_sendaddrv2(self, message): self.got_sendaddrv2 = True
# Peer that sends a version but not a verack.
class NoVerackIdlePeer(LazyPeer):
def __init__(self):
self.version_received = False
super().__init__()
def on_verack(self, message): pass
# When version is received, don't reply with a verack. Instead, see if the
# node will give us a message that it shouldn't. This is not an exhaustive
# list!
def on_version(self, message):
self.version_received = True
self.send_message(msg_ping())
self.send_message(msg_getaddr())
class P2PVersionStore(P2PInterface):
version_received = None
def on_version(self, msg):
# Responds with an appropriate verack
super().on_version(msg)
self.version_received = msg
class P2PLeakTest(FlocoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [[f"-peertimeout={PEER_TIMEOUT}"]]
def create_old_version(self, nversion):
old_version_msg = msg_version()
old_version_msg.nVersion = nversion
old_version_msg.strSubVer = P2P_SUBVERSION
old_version_msg.nServices = P2P_SERVICES
old_version_msg.relay = P2P_VERSION_RELAY
return old_version_msg
def run_test(self):
self.log.info('Check that the node doesn\'t send unexpected messages before handshake completion')
# Peer that never sends a version, nor any other messages. It shouldn't receive anything from the node.
no_version_idle_peer = self.nodes[0].add_p2p_connection(LazyPeer(), send_version=False, wait_for_verack=False)
# Peer that sends a version but not a verack.
no_verack_idle_peer = self.nodes[0].add_p2p_connection(NoVerackIdlePeer(), wait_for_verack=False)
# Pre-wtxidRelay peer that sends a version but not a verack and does not support feature negotiation
# messages which start at nVersion == 70016
pre_wtxidrelay_peer = self.nodes[0].add_p2p_connection(NoVerackIdlePeer(), send_version=False, wait_for_verack=False)
pre_wtxidrelay_peer.send_message(self.create_old_version(70015))
# Wait until the peer gets the verack in response to the version. Though, don't wait for the node to receive the
# verack, since the peer never sent one
no_verack_idle_peer.wait_for_verack()
pre_wtxidrelay_peer.wait_for_verack()
no_version_idle_peer.wait_until(lambda: no_version_idle_peer.ever_connected)
no_verack_idle_peer.wait_until(lambda: no_verack_idle_peer.version_received)
pre_wtxidrelay_peer.wait_until(lambda: pre_wtxidrelay_peer.version_received)
# Mine a block and make sure that it's not sent to the connected peers
self.nodes[0].generate(nblocks=1)
# Give the node enough time to possibly leak out a message
time.sleep(PEER_TIMEOUT + 2)
# Make sure only expected messages came in
assert not no_version_idle_peer.unexpected_msg
assert not no_version_idle_peer.got_wtxidrelay
assert not no_version_idle_peer.got_sendaddrv2
assert not no_verack_idle_peer.unexpected_msg
assert no_verack_idle_peer.got_wtxidrelay
assert no_verack_idle_peer.got_sendaddrv2
assert not pre_wtxidrelay_peer.unexpected_msg
assert not pre_wtxidrelay_peer.got_wtxidrelay
assert not pre_wtxidrelay_peer.got_sendaddrv2
# Expect peers to be disconnected due to timeout
assert not no_version_idle_peer.is_connected
assert not no_verack_idle_peer.is_connected
assert not pre_wtxidrelay_peer.is_connected
self.log.info('Check that the version message does not leak the local address of the node')
p2p_version_store = self.nodes[0].add_p2p_connection(P2PVersionStore())
ver = p2p_version_store.version_received
# Check that received time is within one hour of now
assert_greater_than_or_equal(ver.nTime, time.time() - 3600)
assert_greater_than_or_equal(time.time() + 3600, ver.nTime)
assert_equal(ver.addrFrom.port, 0)
assert_equal(ver.addrFrom.ip, '0.0.0.0')
assert_equal(ver.nStartingHeight, 201)
assert_equal(ver.relay, 1)
self.log.info('Check that old peers are disconnected')
p2p_old_peer = self.nodes[0].add_p2p_connection(P2PInterface(), send_version=False, wait_for_verack=False)
with self.nodes[0].assert_debug_log(['peer=4 using obsolete version 31799; disconnecting']):
p2p_old_peer.send_message(self.create_old_version(31799))
p2p_old_peer.wait_for_disconnect()
if __name__ == '__main__':
P2PLeakTest().main()
| [
"[email protected]"
] | |
9578af48e44f55f45d0eac8073ab379d3a7704ac | dc83706c0fc77dca0dde8f5d8de0c53dd746bd59 | /cachier/scripts/cli.py | c467b07ac8cef327a7cab774a89c4f8a48456cc3 | [
"MIT"
] | permissive | ofirnk/cachier | 5a773d38c6093a276a7ce735e5173461e86bcc60 | 0d4a914806e5a6d048dc4189c9f6176105f8954f | refs/heads/master | 2023-06-20T07:09:09.761919 | 2021-07-22T07:56:52 | 2021-07-22T07:56:52 | 388,360,470 | 0 | 0 | MIT | 2021-07-22T07:15:51 | 2021-07-22T06:57:58 | null | UTF-8 | Python | false | false | 429 | py | """A command-line interface for cachier."""
import click
from cachier.core import _set_max_workers
@click.group()
def cli():
"""A command-line interface for cachier."""
@cli.command("Limits the number of worker threads used by cachier.")
@click.argument('max_workers', nargs=1, type=int)
def set_max_workers(max_workers):
"""Limits the number of worker threads used by cachier."""
_set_max_workers(max_workers)
| [
"[email protected]"
] | |
ea81c1667ac5b76d19d935cf2e009a85fbf12b9f | 610ac1da64200c109b9ac48d162058fdd85801aa | /Exception handling/runtimeerror2.py | 09a54c4a09a30824641f60a4979d524c33d96794 | [] | no_license | rajdharmkar/Python2.7 | 3d88e7c76c92bbba7481bce7a224ccc8670b3abb | 9c6010e8afd756c16e426bf8c3a40ae2cefdadfe | refs/heads/master | 2021-05-03T18:56:36.249812 | 2019-10-08T00:17:46 | 2019-10-08T00:17:46 | 120,418,397 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 76 | py | a = input('Enter a number:')
b = input('Enter a number:')
c = a*b
print c | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.