blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
295fd8f0cd83c7bab2343e031e45924340617e17
9342a741739e00d231d8a476bf551d6d7f886dd6
/src/rnn_classifier/test.py
db82a28751b8b809b10ddef281ca6a2a81a70052
[]
no_license
salmedina/Vehice_Action_Classifier
b23fe5bfdcf448c6a07b04e8f96fc95fb087302e
4d8d11ea81ad50b28bfcb10f360d7f6f4cfea061
refs/heads/master
2020-03-29T20:28:56.427539
2019-11-07T19:15:10
2019-11-07T19:15:10
150,314,452
0
0
null
null
null
null
UTF-8
Python
false
false
976
py
import sys from myconfig import * sys.path.append(diva_util_path) from diva_util import * seglen = 40 for vid in train_vid_list: actlst = parse_diva_act_yaml(train_annot_path+vid+'.activities.yml') geomlst = parse_diva_geom_yaml(train_annot_path+vid+'.geom.yml') geom_id_dict = get_geom_id_list(geomlst) typedict = parse_diva_type_yaml(train_annot_path+vid+'.types.yml') ### extract all ground truth tracklet for act in actlst: if 'meta' in act.keys(): continue if act['act2'] not in VEHICLE_ACT_NAMES: continue span, bb_lst = get_act_tubelet(act, geom_id_dict) print(len(bb_lst)) ### extract detection result trackdict = read_mot_as_defaultdict(car_trk_dir+vid+'.txt') for k in trackdict.keys(): start = min([t for t, box in trackdict[k]]) end = max([t for t, box in trackdict[k]]) for t in range(start, end, seglen/2): s,e = t, min(t+seglen, end)
[ "benken.tyhu@gmail.com" ]
benken.tyhu@gmail.com
5f5eae5db39e8c4718c5b27e5925778f98491218
2719a9cdfea21b5dc00faa2388e295a767652c56
/find_duplicate_files_test.py
f69aff7ae94d70b8d478bfd38ef22d3f1ff39695
[]
no_license
NoemiMolnar/duplicate-finder
d74648409d5539e29b08681127b0b99f1213dcbb
bcbc4ae3c6a6633d143430ec87d395ea92ea2e20
refs/heads/master
2020-04-01T02:10:28.618050
2018-10-13T08:52:05
2018-10-13T08:52:05
152,767,790
0
0
null
null
null
null
UTF-8
Python
false
false
1,380
py
#!/usr/bin/env python """ This module contains test(s) for the find duplicate files module. """ import unittest from get_file_content import get_file_content from find_duplicate_files import find_duplicate_files from output_simple_list import output_simple_list from output_grouped_list import output_grouped_list class TestCompareFiles(unittest.TestCase): """ This class contains test(s) for the find duplicate files module. """ def test_simple_output(self): """ This method tests the find suplicate files functions with the output simple list method. """ directory_path = '/media/noemi/96667C6D667C504B/files' duplicate_files_test_data = ['603 (another copy)', '603', '603 (copy)'] duplicate_files = find_duplicate_files(get_file_content, directory_path, output_simple_list) self.assertEqual(duplicate_files, duplicate_files_test_data) def test_grouped_output(self): """ This method tests the find suplicate files functions with the output grouped list method. """ directory = '/media/noemi/96667C6D667C504B/files' duplicate_files_test_data = [['603', '603 (another copy)', '603 (copy)']] duplicate_files = find_duplicate_files(get_file_content, directory, output_grouped_list) self.assertEqual(duplicate_files, duplicate_files_test_data)
[ "noemi.m.molnar@gmail.com" ]
noemi.m.molnar@gmail.com
dcbee15b406d40c38ef6ce0dec541398d089e4d7
8668830f34ce260565217ea3b49e090778780b44
/firestorm/tests/test_ad_rep_invite.py
fe126c8036952fa2492bb012f029a19ed764b682
[]
no_license
wcirillo/ten
72baf94da958b2ee6f34940c1fc3116660436762
a780ccdc3350d4b5c7990c65d1af8d71060c62cc
refs/heads/master
2016-09-06T13:39:03.966370
2015-07-02T12:37:36
2015-07-02T12:37:36
15,700,975
0
0
null
null
null
null
UTF-8
Python
false
false
3,381
py
""" Unit tests for AdRepInviteTask. """ import datetime import logging from django.core import mail from common.test_utils import EnhancedTestCase from firestorm.factories.ad_rep_factory import AD_REP_FACTORY from firestorm.factories.ad_rep_lead_factory import AD_REP_LEAD_FACTORY from firestorm.tasks.ad_rep_invite import AD_REP_INVITE_TASK LOG = logging.getLogger('ten.%s' % __name__) LOG.setLevel(logging.ERROR) class TestAdRepInviteTask(EnhancedTestCase): """ Test case for AdRepInviteTask. """ def test_email_good(self): """ Assert ad rep leads created yesterday receive an invite email. """ ad_rep_leads = list( AD_REP_LEAD_FACTORY.create_ad_rep_leads(create_count=2)) for ad_rep_lead in ad_rep_leads: ad_rep_lead.create_datetime -= datetime.timedelta(1) ad_rep_lead.save() AD_REP_INVITE_TASK.run() self.assertEqual(len(mail.outbox), 2) ad_rep_lead_1_found = False ad_rep_lead_2_found = False for email in mail.outbox: if ad_rep_leads[0].first_name in email.alternatives[0][0]: ad_rep_lead_1_found = True self.assertTrue(ad_rep_leads[0].first_name in email.body) elif ad_rep_leads[1].first_name in email.alternatives[0][0]: ad_rep_lead_2_found = True self.assertTrue(ad_rep_leads[1].first_name in email.body) self.assertTrue(ad_rep_lead_1_found and ad_rep_lead_2_found) def test_ad_rep_signature(self): """ Assert the referring ad rep of a lead is included in the signature. """ ad_rep_lead = AD_REP_LEAD_FACTORY.create_ad_rep_lead() ad_rep_lead.ad_rep = AD_REP_FACTORY.create_ad_rep() ad_rep_lead.save() mail_prior = len(mail.outbox) AD_REP_INVITE_TASK.run(test_mode=[ad_rep_lead]) LOG.debug(mail.outbox[mail_prior].alternatives[0][0]) LOG.debug(mail.outbox[mail_prior].body) self.assertEqual(len(mail.outbox), mail_prior + 1) self.assertTrue(ad_rep_lead.ad_rep.first_name in mail.outbox[mail_prior].alternatives[0][0]) self.assertTrue(ad_rep_lead.ad_rep.last_name in mail.outbox[mail_prior].alternatives[0][0]) self.assertTrue(ad_rep_lead.ad_rep.email in mail.outbox[mail_prior].alternatives[0][0]) self.assertTrue(ad_rep_lead.ad_rep.url in mail.outbox[mail_prior].alternatives[0][0]) self.assertTrue(ad_rep_lead.ad_rep.first_name in mail.outbox[mail_prior].body) self.assertTrue(ad_rep_lead.ad_rep.last_name in mail.outbox[mail_prior].body) self.assertTrue(ad_rep_lead.ad_rep.email in mail.outbox[mail_prior].body) self.assertTrue(ad_rep_lead.ad_rep.url in mail.outbox[mail_prior].body) def test_email_task_already_ran(self): """ Assert task will not run twice on the same day (without rerun flag) """ ad_rep_lead = AD_REP_LEAD_FACTORY.create_ad_rep_lead() self.assertEqual(len(mail.outbox), 0) AD_REP_INVITE_TASK.run(test_mode=[ad_rep_lead]) self.assertEqual(len(mail.outbox), 1) # Run again. result = AD_REP_INVITE_TASK.run(test_mode=[ad_rep_lead]) self.assertEqual(result, 'Aborted:: AdRepInviteTask already ran today')
[ "williamcirillo@gmail.com" ]
williamcirillo@gmail.com
40b0bd0357b079a2561206ad0c89d01228a7601a
43a2e1acd93905e1ad244ab06b9383122cfcd507
/train.py
eaf298688275ef8b7247e1688b5507d1d68901ae
[ "Apache-2.0" ]
permissive
OceanChip/PaddlePaddle-MobileFaceNets
f41dbcceb39543133f87aa495481c0d8c0435bf9
535e18bbb65d94af3bb1924e7192f3632094f2e5
refs/heads/master
2023-08-11T23:10:22.960985
2021-09-22T06:54:00
2021-09-22T06:54:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,901
py
import argparse import functools import os import re import shutil import time from datetime import datetime, timedelta import paddle import paddle.distributed as dist from paddle.io import DataLoader from paddle.metric import accuracy from paddle.static import InputSpec from visualdl import LogWriter from utils.rec_mv1_enhance import MobileFaceNet from utils.resnet import resnet_face34 from utils.metrics import ArcNet from utils.reader import CustomDataset from utils.utils import add_arguments, print_arguments, get_lfw_list from utils.utils import get_features, get_feature_dict, test_performance parser = argparse.ArgumentParser(description=__doc__) add_arg = functools.partial(add_arguments, argparser=parser) add_arg('gpus', str, '0', '训练使用的GPU序号,使用英文逗号,隔开,如:0,1') add_arg('batch_size', int, 128, '训练的批量大小') add_arg('num_workers', int, 4, '读取数据的线程数量') add_arg('num_epoch', int, 50, '训练的轮数') add_arg('learning_rate', float, 1e-3, '初始学习率的大小') add_arg('use_model', str, 'mobilefacenet', '所使用的模型,支持 mobilefacenet,resnet_face34') add_arg('train_root_path', str, 'dataset/images', '训练数据的根目录') add_arg('test_list_path', str, 'dataset/lfw_test.txt', '测试数据的数据列表路径') add_arg('save_model', str, 'models/', '模型保存的路径') add_arg('resume', str, None, '恢复训练,当为None则不使用恢复模型') add_arg('pretrained_model', str, None, '预训练模型的路径,当为None则不使用预训练模型') args = parser.parse_args() # 评估模型 @paddle.no_grad() def test(model): model.eval() # 获取测试数据 img_paths = get_lfw_list(args.test_list_path) features = get_features(model, img_paths, batch_size=args.batch_size) fe_dict = get_feature_dict(img_paths, features) accuracy, _ = test_performance(fe_dict, args.test_list_path) model.train() return accuracy # 保存模型 def save_model(args, epoch, model, metric_fc, optimizer): model_params_path = os.path.join(args.save_model, args.use_model, 'params', 'epoch_%d' % epoch) if not os.path.exists(model_params_path): os.makedirs(model_params_path) # 保存模型参数 paddle.save(model.state_dict(), os.path.join(model_params_path, 'model.pdparams')) paddle.save(metric_fc.state_dict(), os.path.join(model_params_path, 'metric_fc.pdparams')) paddle.save(optimizer.state_dict(), os.path.join(model_params_path, 'optimizer.pdopt')) # 删除旧的模型 old_model_path = os.path.join(args.save_model, args.use_model, 'params', 'epoch_%d' % (epoch - 3)) if os.path.exists(old_model_path): shutil.rmtree(old_model_path) def train(args): # 设置支持多卡训练 if len(args.gpus.split(',')) > 1: dist.init_parallel_env() if dist.get_rank() == 0: shutil.rmtree('log', ignore_errors=True) # 日志记录器 writer = LogWriter(logdir='log') # 获取数据 train_dataset = CustomDataset(args.train_root_path, is_train=True) # 设置支持多卡训练 if len(args.gpus.split(',')) > 1: batch_sampler = paddle.io.DistributedBatchSampler(train_dataset, batch_size=args.batch_size, shuffle=True) else: batch_sampler = paddle.io.BatchSampler(train_dataset, batch_size=args.batch_size, shuffle=True) train_loader = DataLoader(dataset=train_dataset, batch_sampler=batch_sampler, num_workers=args.num_workers) print("[%s] 总数据类别为:%d" % (datetime.now(), train_dataset.num_classes)) # 获取模型,贴心的作者同时提供了resnet的模型,以满足不同情况的使用 if args.use_model == 'resnet_face34': model = resnet_face34() else: model = MobileFaceNet() metric_fc = ArcNet(feature_dim=512, class_dim=train_dataset.num_classes) if dist.get_rank() == 0: paddle.summary(model, input_size=(None, 3, 112, 112)) # 设置支持多卡训练 if len(args.gpus.split(',')) > 1: model = paddle.DataParallel(model) metric_fc = paddle.DataParallel(metric_fc) # 初始化epoch数 last_epoch = 0 # 学习率衰减 scheduler = paddle.optimizer.lr.StepDecay(learning_rate=args.learning_rate, step_size=1, gamma=0.83, verbose=True) # 设置优化方法 optimizer = paddle.optimizer.Adam(parameters=model.parameters() + metric_fc.parameters(), learning_rate=scheduler, weight_decay=paddle.regularizer.L2Decay(5e-4)) # 加载预训练模型 if args.pretrained_model is not None: model_dict = model.state_dict() model_state_dict = paddle.load(os.path.join(args.pretrained_model, 'model.pdparams')) # 特征层 for name, weight in model_dict.items(): if name in model_state_dict.keys(): if weight.shape != list(model_state_dict[name].shape): print('{} not used, shape {} unmatched with {} in model.'. format(name, list(model_state_dict[name].shape), weight.shape)) model_state_dict.pop(name, None) else: print('Lack weight: {}'.format(name)) model.set_dict(model_state_dict) print('[%s] Rank %d 成功加载 model 参数' % (datetime.now(), dist.get_rank())) # 恢复训练 if args.resume is not None: model.set_state_dict(paddle.load(os.path.join(args.resume, 'model.pdparams'))) metric_fc.set_state_dict(paddle.load(os.path.join(args.resume, 'metric_fc.pdparams'))) optimizer_state = paddle.load(os.path.join(args.resume, 'optimizer.pdopt')) optimizer.set_state_dict(optimizer_state) # 获取预训练的epoch数 last_epoch = optimizer_state['LR_Scheduler']['last_epoch'] print('[%s] Rank %d 成功加载模型参数和优化方法参数' % (datetime.now(), dist.get_rank())) # 获取损失函数 loss = paddle.nn.CrossEntropyLoss() train_step = 0 test_step = 0 sum_batch = len(train_loader) * (args.num_epoch - last_epoch) # 开始训练 for epoch in range(last_epoch, args.num_epoch): loss_sum = [] accuracies = [] for batch_id, (img, label) in enumerate(train_loader()): start = time.time() feature = model(img) output = metric_fc(feature, label) # 计算损失值 los = loss(output, label) los.backward() optimizer.step() optimizer.clear_grad() # 计算准确率 label = paddle.reshape(label, shape=(-1, 1)) acc = accuracy(input=paddle.nn.functional.softmax(output), label=label) accuracies.append(acc.numpy()[0]) loss_sum.append(los.numpy()[0]) # 多卡训练只使用一个进程打印 if batch_id % 100 == 0 and dist.get_rank() == 0: eta_sec = ((time.time() - start) * 1000) * (sum_batch - (epoch - last_epoch) * len(train_loader) - batch_id) eta_str = str(timedelta(seconds=int(eta_sec / 1000))) print('[%s] Train epoch %d, batch: %d/%d, loss: %f, accuracy: %f, eta: %s' % ( datetime.now(), epoch, batch_id, len(train_loader), sum(loss_sum) / len(loss_sum), sum(accuracies) / len(accuracies), eta_str)) writer.add_scalar('Train loss', los, train_step) train_step += 1 loss_sum = [] if batch_id % 20000 == 0 and batch_id != 0 and dist.get_rank() == 0: save_model(args, args.num_epoch, model, metric_fc, optimizer) # 多卡训练只使用一个进程执行评估和保存模型 if dist.get_rank() == 0: print('='*70) acc = test(model) print('[%s] Test %d, accuracy: %f' % (datetime.now(), epoch, acc)) print('='*70) writer.add_scalar('Test acc', acc, test_step) # 记录学习率 writer.add_scalar('Learning rate', scheduler.last_lr, epoch) test_step += 1 save_model(args, epoch, model, metric_fc, optimizer) scheduler.step() if dist.get_rank() == 0: save_model(args, args.num_epoch, model, metric_fc, optimizer) if __name__ == '__main__': print_arguments(args) if len(args.gpus.split(',')) > 1: dist.spawn(train, args=(args,), gpus=args.gpus, nprocs=len(args.gpus.split(','))) else: os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus train(args)
[ "yeyupiaoling@foxmail.com" ]
yeyupiaoling@foxmail.com
e2011cfe0770056ee9f383b010dd491f4fe48bc4
8d90176f719e4bb61efa75803d62fe9e54a90f6e
/jscad/urls.py
1b08ae02932e81aed9964690bb4fb84d8551a50a
[]
no_license
chriscauley/modifi3d
969f2c52d3cd263db6b918c5747d25d07a00b63d
74dc12f9fba16f17cd6456595ddd275b9c9045cc
refs/heads/master
2021-01-23T02:39:38.332483
2019-09-09T12:30:49
2019-09-09T12:30:49
23,629,099
1
0
null
null
null
null
UTF-8
Python
false
false
198
py
from django.conf import settings from django.conf.urls import patterns, include, url urlpatterns = patterns( 'jscad.views', url(r'item/(\d+)/([^/]+).jscad','item_source',name='item_source'), )
[ "chris@lablackey.com" ]
chris@lablackey.com
fcb9745bc425c7d4fe22ae9dabb2a51a33e692b1
9d1d106b813efe5c1b04d241d0faa49c229b9548
/tensorflow-triplet-loss/data/transfer_from_np_to_tfrecord.py
acafa416a24dfe2844290a6e62a00c5911b2e572
[ "MIT" ]
permissive
younglittlefat/deep_learning
1205d3179a32a49c9bd99958792c7d3fecffd7e9
4ba845fd1bcc88139abfb73deefe31d2ffda33ad
refs/heads/master
2021-05-06T20:36:34.391666
2018-05-17T00:56:45
2018-05-17T00:56:45
112,330,215
0
0
null
null
null
null
UTF-8
Python
false
false
2,575
py
import sys import os import codecs import tensorflow as tf import numpy as np tfrecord_dir = "./tfrecords" def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def convert(filename, filepath, label): filename = filename.split(".")[0] + '.tfrecords' writer = tf.python_io.TFRecordWriter(os.path.join(tfrecord_dir, filename)) #with open(filepath, "rb") as f: # data_arr = np.load(f) data_arr = np.load(filepath) data_arr = data_arr.reshape(-1) example = tf.train.Example(features=tf.train.Features(feature={ 'label': _int64_feature(int(label)), 'data': _bytes_feature(data_arr.tobytes())})) #'data': _float_feature(data_arr.tolist())})) writer.write(example.SerializeToString()) writer.close() def convert_all_features(label_file): data_dir = "/home/younglittlefat/deep_learning/video_classification/video_features" with open(label_file, "r") as f: for line in f: if line.startswith(codecs.BOM_UTF8): line = line[len(codecs.BOM_UTF8):] filename, label = line.strip().split(" ") label = int(label) filename = filename.split(".")[0] + ".npy" filepath = os.path.join(data_dir, filename) convert(filename, filepath, label) def check_tfrecord(path): def _parse_function(example_proto): features = { 'label': tf.FixedLenFeature([],tf.int64), #'data': tf.FixedLenFeature([],tf.float32) 'data': tf.FixedLenFeature([],tf.string) } parsed_features = tf.parse_single_example(example_proto, features) data = tf.decode_raw(parsed_features["data"], tf.float32) data = tf.reshape(data, [30, 1024]) return data, parsed_features["label"] filenames = [path] dataset = tf.data.TFRecordDataset(filenames) dataset = dataset.map(_parse_function) iterator = dataset.make_one_shot_iterator() one_element = iterator.get_next() with tf.Session() as sess: print sess.run(one_element) if __name__ == "__main__": #convert("20171023_18047378.npy", "/home/younglittlefat/deep_learning/video_classification/video_features/20171023_18047378.npy", 25) #convert_all_features("label") check_tfrecord("./tfrecords/20171023_18047378.tfrecords")
[ "younglittlefat@gmail.com" ]
younglittlefat@gmail.com
e8b6718f19be532b98435b092f2507b9db975a06
d5be74d2de6fa0ded61d6c3ee7c91a403c0f90db
/quantarhei/utils/vectors.py
d3051f6c330212a837c95f778baa6133d189a8d8
[ "MIT" ]
permissive
tmancal74/quantarhei
43cf9d4be857b8e6db1274ebb8a384f1545cd9ad
fa3042d809005d47106e53609e6a63aa780c477c
refs/heads/master
2023-05-11T06:57:36.368595
2023-05-02T13:10:18
2023-05-02T13:10:18
63,804,925
20
22
MIT
2022-12-21T14:10:00
2016-07-20T18:30:25
Python
UTF-8
Python
false
false
536
py
# -*- coding: utf-8 -*- import numpy from .types import check_numpy_array X = (1.0,0.0,0.0) Y = (0.0,1.0,0.0) Z = (0.0,0.0,1.0) Dxy = (1.0,1.0,0.0)/numpy.sqrt(2) Axy = (-1.0,1.0,0.0)/numpy.sqrt(2) def normalize2(vec,norm=1.0): """ Normalizes a vector to a specified size """ vec = check_numpy_array(vec) vel = numpy.sqrt(numpy.dot(vec,vec)) out = (vec/vel)*norm return out def norm(vec): """Returns the vector norm (scalar product with itself) """ vel = numpy.sqrt(numpy.dot(vec,vec)) return vel
[ "tmancal74@gmail.com" ]
tmancal74@gmail.com
78381c91182aa366096be702631b720cff9241bc
4e04c150e529c8435bbed0287207397a776be7ea
/ball_blast/MeetY1Project/game.py
1bbea6db345ff5933ccdd46be17c13af99d333f7
[]
no_license
rayan20-meet/project
5cb87749f9eeda38087db39a57515a7e4ab2cfcf
e2fb2d0d1162e68dcfece7d6e59596db91f26fcf
refs/heads/master
2020-04-26T19:36:44.451253
2019-03-04T16:27:36
2019-03-04T16:27:36
173,780,722
0
0
null
null
null
null
UTF-8
Python
false
false
2,064
py
from turtle import * import random import math from blast import Blast from shoot import Shoot from tal_maya_ball_blast import Ball import time import turtle turtle.hideturtle() bg = turtle.Screen() bg.setup(800,800) bg.bgpic("/home/student/Desktop/space-game-background.v1.gif") turtle.bgpic("/home/student/Desktop/space-game-background.v1.gif") tracer(0,2) frame = 1 shots=[] running = True blast_1= Blast(-200,-300,70) def movearound(): blast_1.goto(getcanvas().winfo_pointerx() - screen_width*2, -300) x = blast_1.pos()[0] y = blast_1.pos()[1] + blast_1.r - 0.5 if frame % 10 == 0: shoot = Shoot(x, y, 10) shots.append(shoot) screen_width = getcanvas().winfo_width()/2 screen_height = getcanvas().winfo_height()/2 first_r = 100 first_y = (screen_height - first_r )- 10 first_x = random.randint(-screen_width + first_r+3, screen_width-first_r-3) first_ball = Ball(first_x, first_y, first_r, 0, color) Ball.Balls.append(first_ball) # b = (screen_height*2 + 5)/math.fabs(dy) def collide(shoot_a, ball_a): if shoot_a is ball_a: return False d= math.sqrt(math.pow(shoot_a.pos()[0]-ball_a.pos()[0],2)+math.pow(shoot_a.pos()[1]-ball_a.pos()[1],2)) if shoot_a.r+ball_a.r<= d: return False else: print(len(Ball.Balls)) return True #import threading # def instantiateBall(): # threading.Timer(2.0, instantiateBall).start() # new_ball = Ball(first_x, first_y, first_r, 0) # Ball.Balls.append(new_ball) # instantiateBall() while running: first_r = 100 first_y = (screen_height - first_r )- 10 first_x = random.randint(-screen_width + first_r+3, screen_width-first_r-3) movearound() for shoot in shots: shoot.move() for b in Ball.Balls: b.move(screen_width, screen_height) for shoot_a in shots: if collide(shoot_a, b): print("collision") b.split() if b in Ball.Balls: Ball.Balls.remove(b) b.reset() shoot_a.reset() shots.remove(shoot_a) if shoot_a.ycor() >= screen_height: shots.remove(shoot_a) del shoot_a frame += 1 time.sleep(0.001) update() turtle.mainloop()
[ "noreply@github.com" ]
rayan20-meet.noreply@github.com
bda08816a833d5480975d0bb2b57d8a1697e6210
b334e50581f1f61b0b05627ce63645128069f230
/python/14_Longest_Common_Prefix.py
1893e5d197445f1bfa5e8fc8bc73e2d0cea032a7
[]
no_license
evanwangxx/leetcode
7846a61e272fd807ce850582d32f0b4d7a33d26d
25c4b7d04c3482a8e3625bed66d110a61b572aa0
refs/heads/master
2021-06-07T06:24:40.671226
2020-04-17T09:50:05
2020-04-17T09:50:05
152,075,218
0
0
null
null
null
null
UTF-8
Python
false
false
1,113
py
# Write a function to find the longest common prefix string amongst an array of strings. # # If there is no common prefix, return an empty string "". # # Example 1: # # Input: ["flower","flow","flight"] # Output: "fl" # Example 2: # # Input: ["dog","racecar","car"] # Output: "" # Explanation: There is no common prefix among the input strings. class Solution: @staticmethod def find_common_between_string(cs, y): if not cs or not y: return "" cm = "" for i in range(min(len(cs), len(y))): if cs[i] == y[i]: cm += cs[i] else: return cm return cm def longestCommonPrefix(self, strs: [str]) -> str: if not strs: return "" common_prefix = strs[0] for i in range(1, len(strs)): this = strs[i] common_prefix = self.find_common_between_string(common_prefix, this) return common_prefix t1 = ["flower", "flow", "flight"] t2 = ["dog", "racecar", "car"] print(Solution().longestCommonPrefix(t1)) print(Solution().longestCommonPrefix(t2))
[ "neptunewang@tencent.com" ]
neptunewang@tencent.com
8a04359094b0c1b7015d695ae3b6b99155ad5e0c
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/M/mcallister73/foi_response_statistics_for_nhs_trusts.py
cbf8d1bfbf2042cb16a7d965252a0f9078b09076
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,002
py
import scraperwiki import BeautifulSoup import re import sys from scraperwiki import datastore # FOI request statistics for nhs trusts from WhatDoTheyKnow.com # # function to extract the request statistics def extract_dictionary(next_html): #print "extract_dictionary" nhstrust_statistics = {"total_num_requests":0, "successful":0, "partially_successful":0, "rejected":0, "waiting_response":0, "waiting_classification":0, "waiting_clarification":0, "waiting_response_overdue":0, "waiting_response_very_overdue":0, "not_held":0, "requires_admin":0, "internal_review":0, "user_withdrawn":0, "error_message":0, "gone_postal":0} while True: #print "next_html = " + str(next_html) # classify each request for request_span in next_html.findAll(attrs={'class' : re.compile("^bottomline")}): nhstrust_statistics["total_num_requests"] +=1 type_of_request = re.split('\W+', request_span['class'])[1] type_of_request = re.sub("icon_", "", type_of_request) # add it to the dictionary, checking if it exists try: nhstrust_statistics[type_of_request] += 1 except: print "Ooops - no " + type_of_request + " entry in dictionary! Stopping scraping..." sys.exit(0) # print "Number " + str(nhstrust_statistics["total_num_requests"]) + ": " + type_of_request # once the for loop is finished, check whether there are additional pages for this nhstrust: # look for "next" link and loop again if so if next_html.find("a", "next_page") is None: return nhstrust_statistics #print "next page found" next_link = base_url + next_html.find("a", "next_page")['href'] temp_html = scraperwiki.scrape(next_link) next_html = BeautifulSoup.BeautifulSoup(temp_html) # base URLs and initial scrape base_url = 'http://www.whatdotheyknow.com' home_url = base_url + '/body/list/nhstrust' scraped_html = scraperwiki.scrape(home_url) list_of_nhstrust = BeautifulSoup.BeautifulSoup(scraped_html) # extract the link to each nhstrust page, start processing for each_nhstrust in list_of_nhstrust.findAll("span", "head")[:300]: # extract the nhs trust name and page nhstrust_link = each_nhstrust.a nhstrust_name = nhstrust_link.string nhstrust_page = base_url + nhstrust_link['href'] # now scrape the nhstrust page temp_html = scraperwiki.scrape(nhstrust_page) next_html = BeautifulSoup.BeautifulSoup(temp_html) nhstrust_statistics = extract_dictionary(next_html) # before saving data, check the numbers add up, in case we missed any requests count = sum(nhstrust_statistics.itervalues()) num_requests = nhstrust_statistics["total_num_requests"] if count/2 != num_requests: print "May have missed requests: count is %s and total_num_requests is %s, stopping scraping" % (count, nhstrust_statistics["total_num_requests"]) sys.exit(0) # when all is complete, save to datastore data = { 'nhstrust name' : nhstrust_name, 'nhstrust page' : nhstrust_page, 'Total requests' : nhstrust_statistics["total_num_requests"], 'Successful' : nhstrust_statistics["successful"], 'Partly successful' : nhstrust_statistics["partially_successful"], 'Rejected' : nhstrust_statistics["rejected"], 'Awaiting response' : nhstrust_statistics["waiting_response"], 'Awaiting classification' : nhstrust_statistics["waiting_classification"], 'Awaiting clarification' : nhstrust_statistics["waiting_clarification"], 'Overdue' : nhstrust_statistics["waiting_response_overdue"], 'Long overdue' : nhstrust_statistics["waiting_response_very_overdue"], 'Info not held' : nhstrust_statistics["not_held"], 'Requires admin' : nhstrust_statistics["requires_admin"], 'Internal review' : nhstrust_statistics["internal_review"], 'Withdrawn by user' : nhstrust_statistics["user_withdrawn"], 'Error message' : nhstrust_statistics["error_message"], 'Handled by post' : nhstrust_statistics["gone_postal"], } scraperwiki.sqlite.save(unique_keys=['nhstrust name' ], data=data) #'Total requests', 'Successful', 'Partially successful', #'Rejected', 'Awaiting response', 'Awaiting classification', #'Awaiting clarification', 'Overdue', 'Long overdue', #'Info not held', 'Requires admin', 'Internal review', #'Withdrawn by user', 'Error message', 'Handled by post'], data=data) import scraperwiki import BeautifulSoup import re import sys from scraperwiki import datastore # FOI request statistics for nhs trusts from WhatDoTheyKnow.com # # function to extract the request statistics def extract_dictionary(next_html): #print "extract_dictionary" nhstrust_statistics = {"total_num_requests":0, "successful":0, "partially_successful":0, "rejected":0, "waiting_response":0, "waiting_classification":0, "waiting_clarification":0, "waiting_response_overdue":0, "waiting_response_very_overdue":0, "not_held":0, "requires_admin":0, "internal_review":0, "user_withdrawn":0, "error_message":0, "gone_postal":0} while True: #print "next_html = " + str(next_html) # classify each request for request_span in next_html.findAll(attrs={'class' : re.compile("^bottomline")}): nhstrust_statistics["total_num_requests"] +=1 type_of_request = re.split('\W+', request_span['class'])[1] type_of_request = re.sub("icon_", "", type_of_request) # add it to the dictionary, checking if it exists try: nhstrust_statistics[type_of_request] += 1 except: print "Ooops - no " + type_of_request + " entry in dictionary! Stopping scraping..." sys.exit(0) # print "Number " + str(nhstrust_statistics["total_num_requests"]) + ": " + type_of_request # once the for loop is finished, check whether there are additional pages for this nhstrust: # look for "next" link and loop again if so if next_html.find("a", "next_page") is None: return nhstrust_statistics #print "next page found" next_link = base_url + next_html.find("a", "next_page")['href'] temp_html = scraperwiki.scrape(next_link) next_html = BeautifulSoup.BeautifulSoup(temp_html) # base URLs and initial scrape base_url = 'http://www.whatdotheyknow.com' home_url = base_url + '/body/list/nhstrust' scraped_html = scraperwiki.scrape(home_url) list_of_nhstrust = BeautifulSoup.BeautifulSoup(scraped_html) # extract the link to each nhstrust page, start processing for each_nhstrust in list_of_nhstrust.findAll("span", "head")[:300]: # extract the nhs trust name and page nhstrust_link = each_nhstrust.a nhstrust_name = nhstrust_link.string nhstrust_page = base_url + nhstrust_link['href'] # now scrape the nhstrust page temp_html = scraperwiki.scrape(nhstrust_page) next_html = BeautifulSoup.BeautifulSoup(temp_html) nhstrust_statistics = extract_dictionary(next_html) # before saving data, check the numbers add up, in case we missed any requests count = sum(nhstrust_statistics.itervalues()) num_requests = nhstrust_statistics["total_num_requests"] if count/2 != num_requests: print "May have missed requests: count is %s and total_num_requests is %s, stopping scraping" % (count, nhstrust_statistics["total_num_requests"]) sys.exit(0) # when all is complete, save to datastore data = { 'nhstrust name' : nhstrust_name, 'nhstrust page' : nhstrust_page, 'Total requests' : nhstrust_statistics["total_num_requests"], 'Successful' : nhstrust_statistics["successful"], 'Partly successful' : nhstrust_statistics["partially_successful"], 'Rejected' : nhstrust_statistics["rejected"], 'Awaiting response' : nhstrust_statistics["waiting_response"], 'Awaiting classification' : nhstrust_statistics["waiting_classification"], 'Awaiting clarification' : nhstrust_statistics["waiting_clarification"], 'Overdue' : nhstrust_statistics["waiting_response_overdue"], 'Long overdue' : nhstrust_statistics["waiting_response_very_overdue"], 'Info not held' : nhstrust_statistics["not_held"], 'Requires admin' : nhstrust_statistics["requires_admin"], 'Internal review' : nhstrust_statistics["internal_review"], 'Withdrawn by user' : nhstrust_statistics["user_withdrawn"], 'Error message' : nhstrust_statistics["error_message"], 'Handled by post' : nhstrust_statistics["gone_postal"], } scraperwiki.sqlite.save(unique_keys=['nhstrust name' ], data=data) #'Total requests', 'Successful', 'Partially successful', #'Rejected', 'Awaiting response', 'Awaiting classification', #'Awaiting clarification', 'Overdue', 'Long overdue', #'Info not held', 'Requires admin', 'Internal review', #'Withdrawn by user', 'Error message', 'Handled by post'], data=data)
[ "pallih@kaninka.net" ]
pallih@kaninka.net
66039f29a268cb937080c45a942f5a73faf09f85
a907bc8de9186fad3139a02cccc2c47031fd4484
/setup.py
a5fdfa0bd2b700af566484563afe0692c490b32a
[ "BSD-2-Clause" ]
permissive
turtlebender/troposphere
2da1c6bf1e7da4d36080d2cb759e911ca1d4bfb3
55aba0bd23b61a41612a4ccf52ddf68dbd8c9bee
refs/heads/master
2021-01-15T19:34:40.541812
2013-03-27T20:13:20
2013-03-27T20:13:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
383
py
from setuptools import setup setup( name='troposphere', version='0.2.6', description="AWS CloudFormation creation library", author="Mark Peek", author_email="mark@peek.org", url="https://github.com/cloudtools/troposphere", license="New BSD license", packages=['troposphere'], scripts=['scripts/cfn'], test_suite="tests", use_2to3=True, )
[ "mark@peek.org" ]
mark@peek.org
d46380d79d1478b600e2897568e1074c816c7e9d
95186364f23ba4944854236a4ce08fcdc52a597e
/python/4일차/입력프로그램.py
7c582f300c7badfcf0213c1452c3781a33231b20
[]
no_license
GriTRini/study
acd1a9d9a45dbd7045aa8121811a64d65a382af3
4031ccf93d0c1e91ab708f1d17df9dbc9cb3a071
refs/heads/main
2023-07-31T07:01:33.376363
2021-09-04T14:30:26
2021-09-04T14:30:26
370,933,659
0
0
null
null
null
null
UTF-8
Python
false
false
151
py
f = open('out.txt', 'w', encoding='utf-8') for i in range(3): num = input('num : ') f.write(num + '\n') print('파일저장완료') f.close()
[ "cd2918@naver.com" ]
cd2918@naver.com
03ca9f7cb52cd83a5598fad32ace8d825b7a8fcf
fc4845bb92eb0f3a0f0b0e40f296491c3f32e865
/automlkiller/models/clustering/spectral_cluster.py
505025096f1b901433b184a78252ff2845d527f1
[ "Apache-2.0" ]
permissive
toandaominh1997/automlkiller
df082d9bf43dcc88eb626bb2b83521afaf3bc91d
c5f451cfb05d8287bec0d26a9b14e2c1b452861c
refs/heads/master
2023-01-20T20:26:15.731197
2020-11-29T17:26:52
2020-11-29T17:26:52
315,043,727
0
0
null
null
null
null
UTF-8
Python
false
false
570
py
from sklearn.cluster import SpectralClustering from automlkiller.models.model_factory import ModelFactory from automlkiller.utils.distributions import np_list_arange, UniformDistribution, IntUniformDistribution @ModelFactory.register('clustering-spectralclustering') class SpectralClusteringContainer(KMeans): def __init__(self, **kwargs): super().__init__() tune_grid = {} tune_distributions = {} self.tune_grid = tune_grid self.tune_distributions = tune_distributions self.estimator = SpectralClustering(**kwargs)
[ "toandm2@onemount.com" ]
toandm2@onemount.com
f86f6d6d1d76ec9702ef7edc02f26812a837efbd
e5e4d5061bb9e39c808f20edb92e0b35fd6c07e2
/syn.py
f0ac2903b298a1d94fd6279000ad2697c64b7115
[]
no_license
SilamArasu/Wikipedia-Link-Retrieval
90b7d53aec1ea4596ec553d7f702a2ae2230129f
b26109561fe3ca407e2ee6a45267e4ff90d70391
refs/heads/master
2020-07-06T23:53:06.475093
2020-03-29T06:09:19
2020-03-29T06:09:19
203,177,520
0
0
null
null
null
null
UTF-8
Python
false
false
517
py
import nltk from nltk.corpus import wordnet # Gets related terms from the nltk wordnet library def related_terms(word): synonyms = set() for syn in wordnet.synsets(word): for l in syn.lemmas(): synonyms.append(l.name()) return set(synonyms) # Computes the degree of similarity between two words def comp(a,b): w1 = wordnet.synset(a+'.n.01') # n here denotes the tag noun w2 = wordnet.synset(b+'.n.01') a = w1.wup_similarity(w2) if(a>0.5): return True else: False
[ "45484418+SilamArasu@users.noreply.github.com" ]
45484418+SilamArasu@users.noreply.github.com
debc1d83d1618bdefb8a383823b854b36686475f
54784ef24d64fff27e90a08edabe82b2545a538d
/ros/src/tl_detector/light_publisher.py
1a7c0671d243b6148f39e280f621eb1baaf8d067
[ "MIT" ]
permissive
RTarkunde/CarND-Capstone
3c87ec00e30845706bccc06913e9255e353ee60d
83926a7ecdd3310b683524d63c936771f5832ed3
refs/heads/master
2022-11-24T13:49:44.341508
2019-09-18T03:02:17
2019-09-18T03:02:17
209,309,438
0
0
MIT
2022-11-22T00:23:20
2019-09-18T13:00:37
Makefile
UTF-8
Python
false
false
1,917
py
#!/usr/bin/env python import rospy import tf import cv2 import time from styx_msgs.msg import TrafficLightArray, TrafficLight from std_msgs.msg import Header from geometry_msgs.msg import PoseStamped, Quaternion, TwistStamped import numpy as np import rospkg import math class TLPublisher(object): def __init__(self): rospy.logwarn("entry: TLPublisher::init") rospy.init_node('tl_publisher') self.traffic_light_pubs = rospy.Publisher('/vehicle/traffic_lights', TrafficLightArray, queue_size=1) light = self.create_light(20.991, 22.837, 1.524, 0.08, 3) lights = TrafficLightArray() lights.header = light.header lights.lights = [light] self.lights = lights self.loop() def loop(self): rate = rospy.Rate(50) while not rospy.is_shutdown(): self.traffic_light_pubs.publish(self.lights) rate.sleep() def create_light(self, x, y, z, yaw, state): rospy.logwarn("entry: create_light") light = TrafficLight() light.header = Header() light.header.stamp = rospy.Time.now() light.header.frame_id = '/world' light.pose = self.create_pose(x, y, z, yaw) light.state = state return light def create_pose(self, x, y, z, yaw=0.): rospy.logwarn("entry: create_pose") pose = PoseStamped() pose.header = Header() pose.header.stamp = rospy.Time.now() pose.header.frame_id = '/world' pose.pose.position.x = x pose.pose.position.y = y pose.pose.position.z = z q = tf.transformations.quaternion_from_euler(0., 0., math.pi * yaw/180.) pose.pose.orientation = Quaternion(*q) return pose if __name__ == '__main__': try: TLPublisher() except rospy.ROSInterruptException: rospy.logerr('Could not start traffic publisher node.')
[ "rtarkund@yahoo.com" ]
rtarkund@yahoo.com
67aa6f59d838dc4cc4ed7a426a38f713a2c81d59
3e721fca7d38ce657ceb79093588c9b57811bc06
/proyect/aplicacion1/apps.py
7180dcf9a9f9dc2024258343b8e6bf43c396ca6e
[]
no_license
Michell15678932/Primera-Evaluaci-n-de-Desarrollo-de-Aplicaciones-WEB-II
1d83620972fd7f8a8ec207813e9ead276885cbfb
3daca4efe78bbe92f53d2d2337c4192c8f06ec37
refs/heads/master
2023-07-29T17:12:11.720597
2021-09-11T23:44:27
2021-09-11T23:44:27
404,900,856
0
0
null
null
null
null
UTF-8
Python
false
false
154
py
from django.apps import AppConfig class Aplicacion1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'aplicacion1'
[ "mickiro789@gmail.com" ]
mickiro789@gmail.com
350a39c673f7e277a4f6070fa5d8cf3309c25e14
1bdc5a480d54eac55f2779bc018fc48603f357e1
/train.py
898f0a25df140b14f451f0ee87aa8602c55b2fde
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
abcSup/captionamerica
4d099078eadd4f729431ad442ae323f43d7c6a35
e34e5f794a7e1b519b6f876720325c97cedc4a85
refs/heads/master
2022-02-20T10:39:16.123327
2019-09-19T00:56:14
2019-09-19T00:56:14
105,931,954
1
0
null
null
null
null
UTF-8
Python
false
false
1,773
py
from os.path import join import numpy as np import h5py from keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping from configuration import Config from model import get_model from data_generator import DataGenerator from data_generator import CustomSequence num_train_epoch = 30 num_finetune_epoch = 200 #data_dir = './data' #h5file = join(data_dir, 'train_data.h5') #data = h5py.File(h5file, 'r') #seq_generator = CustomSequence(data, batch_size) config = Config() model = get_model(config) data = DataGenerator(config) checkpoint = ModelCheckpoint('./checkpoint/_weight.hdf5', monitor='loss', mode='min', save_best_only=True, verbose=1) tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=False) model.fit_generator(data.generator(), config.num_batch, epochs=num_train_epoch, initial_epoch=0, callbacks=[tensorboard, checkpoint], workers=1, use_multiprocessing=False) # Fine-tuning config.fine_tune = True model = get_model(config) checkpoint = ModelCheckpoint('./checkpoint/train_weight.hdf5', monitor='loss', mode='min', save_best_only=True, verbose=1) earlystop = EarlyStopping(monitor='loss', patience=10, verbose=0, mode='min') model.load_weights('./checkpoint/_weight.hdf5') model.fit_generator(data.generator(), config.num_batch, epochs=num_finetune_epoch, initial_epoch=num_train_epoch, callbacks=[checkpoint, tensorboard, earlystop], workers=1, use_multiprocessing=False)
[ "kristan97@hotmail.com" ]
kristan97@hotmail.com
d57f37d1606004d68e120ce8b75611161043cf5e
f7876d3c40b01c8dfe564d650729fb7eb5d8dbf6
/birthdaybot/persistence.py
9e27399039241e211cfc002c8475d8307f59e81c
[]
no_license
ShinyShingi/BirthdayTelegramBot
64c535c6f3fce8d74b250bd7e66e9cc72323e999
1b51a95c98d334cbe732433178b4239c3f740d19
refs/heads/master
2023-03-20T20:18:18.635957
2020-07-29T14:31:30
2020-07-29T14:31:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,628
py
""" This method implements the inheritance from the BasePersistence class to provide the persistence of the bot. """ from birthdaybot.db.database import Database from telegram.ext import BasePersistence from collections import defaultdict from copy import deepcopy class BotPersistence(BasePersistence): def __init__(self, database: Database, store_user_data=True, store_chat_data=True, store_bot_data=True, on_flush=False): super(BotPersistence, self).__init__(store_user_data=store_user_data, store_chat_data=store_chat_data, store_bot_data=store_bot_data) self.database = database self.on_flush = on_flush self.user_data = None self.chat_data = None self.bot_data = None self.conversations = None def get_user_data(self): """Returns the user_data from the pickle file if it exsists or an empty defaultdict. Returns: :obj:`defaultdict`: The restored user data. """ if self.user_data: pass else: data = self.database.get_user_data() if not data: data = defaultdict(dict) else: data = defaultdict(dict, data) self.user_data = data return deepcopy(self.user_data) def get_chat_data(self) -> dict: """ Returns the chat_data from the database. :return: The restored chat data. """ if self.chat_data: pass else: data = self.database.get_chat_data() if not data: data = defaultdict(dict) else: data = defaultdict(dict, data) self.chat_data = data return deepcopy(self.chat_data) def get_conversations(self, name): if self.conversations: pass else: data = self.database.get_conversations() if not data: data = {} self.conversations = data return self.conversations.get(name, {}).copy() def update_chat_data(self, chat_id, data): """ Will update the chat_data (if changed) and save the data into the database. :param chat_id: The chat the data might have been changed for. :param data: The :attr:`telegram.ext.dispatcher.chat_data` [chat_id]. """ if self.chat_data is None: self.chat_data = defaultdict(dict) if self.chat_data.get(chat_id) == data: return self.chat_data[chat_id] = data if not self.on_flush: self.database.update_chat_data(self.chat_data) def update_user_data(self, user_id, data): """Will update the user_data (if changed) and depending on :attr:`on_flush` save the pickle file. Args: user_id (:obj:`int`): The user the data might have been changed for. data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.user_data` [user_id]. """ if self.user_data is None: self.user_data = defaultdict(dict) if self.user_data.get(user_id) == data: return self.user_data[user_id] = data if not self.on_flush: self.database.update_user_data(self.user_data) def update_conversation(self, name: str, key: tuple, new_state: int): """ Will update the conversations for the given handler and depending on :attr:`on_flush` save data in the database. :param name: The handlers name. :param key: The key the state is changed for. :param new_state: The new state for the given key. """ # Since, this bot can't be invited into a group, it has just chat_id (as key) and will have no name if self.conversations.setdefault(name, {}).get(key) == new_state: return self.conversations[name][key] = new_state if not self.on_flush: self.database.update_conversations(self.conversations) def flush(self): if self.user_data: self.database.update_user_data(self.user_data) if self.chat_data: self.database.update_chat_data(self.chat_data) if self.bot_data: pass if self.conversations: self.database.update_conversations(self.conversations) self.database.connection.close() def update_bot_data(self, data): pass def get_bot_data(self): pass
[ "kofffsh@gmail.com" ]
kofffsh@gmail.com
fa628e6b45e49100d2e7a8eac3793aac4082bf30
900a7285b2fc4d203717e09c88e8afe5bba9144f
/axonius_api_client/tests/tests_api/tests_assets/test_fields.py
7e7c0fdd1955ccdfcb4009f8fc0bd000728adb8b
[ "MIT" ]
permissive
geransmith/axonius_api_client
5694eb60964141b3473d57e9a97929d4bff28110
09fd564d62f0ddf7aa44db14a509eaafaf0c930f
refs/heads/master
2022-11-23T01:43:52.205716
2020-06-12T14:15:38
2020-06-12T14:15:38
280,499,094
0
0
MIT
2020-07-17T18:35:48
2020-07-17T18:35:47
null
UTF-8
Python
false
false
18,743
py
# -*- coding: utf-8 -*- """Test suite for assets.""" import pytest from axonius_api_client.constants import AGG_ADAPTER_ALTS, AGG_ADAPTER_NAME from axonius_api_client.exceptions import ApiError, NotFoundError from ...meta import (FIELD_FORMATS, NORM_TYPES, SCHEMA_FIELD_FORMATS, SCHEMA_TYPES) def load_test_data(apiobj): """Pass.""" apiobj.TEST_DATA = getattr(apiobj, "TEST_DATA", {}) if not apiobj.TEST_DATA.get("fields_map"): apiobj.TEST_DATA["fields_map"] = apiobj.fields.get() return apiobj class FieldsPrivate: """Pass.""" def test_private_get(self, apiobj): """Pass.""" fields = apiobj.fields._get() self.val_raw_fields(fields=fields) assert not fields def val_raw_fields(self, fields): """Pass.""" assert isinstance(fields, dict) schema = fields.pop("schema") assert isinstance(schema, dict) generic = fields.pop("generic") assert isinstance(generic, list) self.val_raw_adapter_fields(adapter="generic", adapter_fields=generic) generic_schema = schema.pop("generic") assert isinstance(generic_schema, dict) self.val_raw_schema(adapter="generic", schema=generic_schema) specific = fields.pop("specific") assert isinstance(specific, dict) specific_schema = schema.pop("specific") assert isinstance(specific_schema, dict) for adapter, adapter_fields in specific.items(): self.val_raw_adapter_fields(adapter=adapter, adapter_fields=adapter_fields) adapter_schema = specific_schema.pop(adapter) self.val_raw_schema(adapter=adapter, schema=adapter_schema) assert not fields assert not schema def val_raw_schema(self, adapter, schema): """Pass.""" assert isinstance(schema, dict) items = schema.pop("items") assert isinstance(items, list) required = schema.pop("required") assert isinstance(required, list) stype = schema.pop("type") assert stype == "array" assert not schema, list(schema) for req in required: assert isinstance(req, str) for item in items: assert item self.val_raw_items(adapter=adapter, items=item) def val_raw_adapter_fields(self, adapter, adapter_fields): """Pass.""" assert isinstance(adapter_fields, list) for field in adapter_fields: assert isinstance(field, dict) name = field.pop("name") assert isinstance(name, str) and name title = field.pop("title") assert isinstance(title, str) and title ftype = field.pop("type") assert isinstance(ftype, str) and ftype assert ftype in SCHEMA_TYPES description = field.pop("description", "") assert isinstance(description, str) sort = field.pop("sort", False) assert isinstance(sort, bool) unique = field.pop("unique", False) assert isinstance(unique, bool) branched = field.pop("branched", False) assert isinstance(branched, bool) dynamic = field.pop("dynamic", False) assert isinstance(dynamic, bool) fformat = field.pop("format", "") assert isinstance(fformat, str) assert fformat in FIELD_FORMATS or fformat == "" enums = field.pop("enum", []) assert isinstance(enums, list) for enum in enums: assert isinstance(enum, str) or isinstance(enum, int) items = field.pop("items", {}) assert isinstance(items, dict) self.val_raw_items(adapter=f"{adapter}:{name}", items=items) assert not field, list(field) def val_raw_items(self, adapter, items): """Pass.""" assert isinstance(items, dict) if items: ftype = items.pop("type") assert isinstance(ftype, str) assert ftype in SCHEMA_TYPES description = items.pop("description", "") assert isinstance(description, str) title = items.pop("title", "") assert isinstance(title, str) name = items.pop("name", "") assert isinstance(name, str) sort = items.pop("sort", False) assert isinstance(sort, bool) unique = items.pop("unique", False) assert isinstance(unique, bool) branched = items.pop("branched", False) assert isinstance(branched, bool) dynamic = items.pop("dynamic", False) assert isinstance(dynamic, bool) hidden = items.pop("hidden", False) assert isinstance(hidden, bool) iformat = items.pop("format", "") assert isinstance(iformat, str) assert iformat in SCHEMA_FIELD_FORMATS or iformat == "" val_source(obj=items) enums = items.pop("enum", []) assert isinstance(enums, list) for enum in enums: assert isinstance(enum, str) or isinstance(enum, int) sub_items = items.pop("items", []) assert isinstance(sub_items, list) or isinstance(sub_items, dict) assert not items, list(items) if isinstance(sub_items, dict): self.val_raw_items(adapter=adapter, items=sub_items) else: for sub_item in sub_items: self.val_raw_items(adapter=adapter, items=sub_item) def test_private_prettify_schemas(self, apiobj): """Pass.""" fields_map = apiobj.TEST_DATA["fields_map"] schemas = fields_map[AGG_ADAPTER_NAME] pretty = apiobj.fields._prettify_schemas(schemas=schemas) assert isinstance(pretty, list) for p in pretty: assert isinstance(p, str) assert "->" in p class FieldsPublic: """Pass.""" def test_get(self, apiobj): """Pass.""" fields_map = apiobj.fields.get() assert isinstance(fields_map, dict) assert isinstance(fields_map[AGG_ADAPTER_NAME], list) self.val_parsed_fields(fields_map=fields_map) def val_parsed_fields(self, fields_map): """Pass.""" assert isinstance(fields_map, dict) for adapter, schemas in fields_map.items(): assert not adapter.endswith("_adapter") assert isinstance(schemas, list) for schema in schemas: self.val_parsed_schema(schema=schema, adapter=adapter) def val_parsed_schema(self, schema, adapter): """Pass.""" assert isinstance(schema, dict) name = schema.pop("name") assert isinstance(name, str) and name ftype = schema.pop("type") assert isinstance(ftype, str) and ftype assert ftype in SCHEMA_TYPES fformat = schema.pop("format", "") assert isinstance(fformat, str) assert fformat in FIELD_FORMATS or fformat == "" adapter_name = schema.pop("adapter_name") assert isinstance(adapter_name, str) and adapter_name adapter_name_raw = schema.pop("adapter_name_raw") assert isinstance(adapter_name_raw, str) and adapter_name_raw adapter_prefix = schema.pop("adapter_prefix") assert isinstance(adapter_prefix, str) and adapter_prefix adapter_title = schema.pop("adapter_title") assert isinstance(adapter_title, str) and adapter_title column_name = schema.pop("column_name") assert isinstance(column_name, str) and column_name column_title = schema.pop("column_title") assert isinstance(column_title, str) and column_title name_base = schema.pop("name_base") assert isinstance(name_base, str) and name_base name_qual = schema.pop("name_qual") assert isinstance(name_qual, str) and name_qual title = schema.pop("title") assert isinstance(title, str) and title type_norm = schema.pop("type_norm") assert isinstance(type_norm, str) and type_norm assert type_norm in NORM_TYPES parent = schema.pop("parent") assert isinstance(parent, str) and parent is_root = schema.pop("is_root") assert isinstance(is_root, bool) is_list = schema.pop("is_list") assert isinstance(is_list, bool) selectable = schema.pop("selectable", False) assert isinstance(selectable, bool) description = schema.pop("description", "") assert isinstance(description, str) sort = schema.pop("sort", False) assert isinstance(sort, bool) unique = schema.pop("unique", False) assert isinstance(unique, bool) branched = schema.pop("branched", False) assert isinstance(branched, bool) dynamic = schema.pop("dynamic", False) assert isinstance(dynamic, bool) is_complex = schema.pop("is_complex") assert isinstance(is_complex, bool) enums = schema.pop("enum", []) assert isinstance(enums, list) for enum in enums: assert isinstance(enum, str) or isinstance(enum, int) sub_fields = schema.pop("sub_fields", []) assert isinstance(sub_fields, list) if is_complex: if name != "all": assert sub_fields for sub_field in sub_fields: self.val_parsed_schema(adapter=f"{adapter}:{name}", schema=sub_field) else: items = schema.pop("items", {}) dynamic = items.pop("dynamic", False) assert isinstance(dynamic, bool) iformat = items.pop("format", "") assert isinstance(iformat, str) assert iformat in SCHEMA_FIELD_FORMATS or iformat == "" itype = items.pop("type", "") assert isinstance(itype, str) assert itype in SCHEMA_TYPES or itype == "" val_source(obj=items) enums = items.pop("enum", []) assert isinstance(enums, list) for enum in enums: assert isinstance(enum, str) or isinstance(enum, int) assert not items assert not schema, list(schema) def test_get_adapter_name(self, apiobj): """Pass.""" search = AGG_ADAPTER_ALTS[0] exp = AGG_ADAPTER_NAME adapter = apiobj.fields.get_adapter_name( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) assert adapter == exp def test_get_adapter_name_error(self, apiobj): """Pass.""" search = "badwolf" with pytest.raises(NotFoundError): apiobj.fields.get_adapter_name( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) def test_get_adapter_names_single(self, apiobj): """Pass.""" search = AGG_ADAPTER_ALTS[0] exp = [AGG_ADAPTER_NAME] adapters = apiobj.fields.get_adapter_names( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) assert adapters == exp def test_get_adapter_names_multi(self, apiobj): """Pass.""" search = "a" adapters = apiobj.fields.get_adapter_names( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) assert AGG_ADAPTER_NAME in adapters assert len(adapters) > 1 def test_get_adapter_names_error(self, apiobj): """Pass.""" search = "badwolf" with pytest.raises(NotFoundError): apiobj.fields.get_adapter_names( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) def test_get_field_schema(self, apiobj): """Pass.""" search = "last_seen" exp = [ x for x in apiobj.TEST_DATA["fields_map"][AGG_ADAPTER_NAME] if x["name_base"] == search ][0] result = apiobj.fields.get_field_schema( value=search, schemas=apiobj.TEST_DATA["fields_map"][AGG_ADAPTER_NAME] ) assert exp == result def test_get_field_names_re(self, apiobj): """Pass.""" search = ["seen"] result = apiobj.fields.get_field_names_re( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) assert "specific_data.data.last_seen" in result def test_get_field_names_eq(self, apiobj): """Pass.""" search = ["specific_data.data.id", "last_seen"] exp = [] for i in search: exp += [ x["name_qual"] for x in apiobj.TEST_DATA["fields_map"][AGG_ADAPTER_NAME] if x["name_base"] == i or x["name_qual"] == i ] result = apiobj.fields.get_field_names_eq( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) assert exp == result def test_get_field_schemas(self, apiobj): """Pass.""" search = "l" exp = [ x for x in apiobj.TEST_DATA["fields_map"][AGG_ADAPTER_NAME] if ( search in x["name_base"] or search in x["name_qual"] or search in x["name"] ) and x.get("selectable", False) ] result = apiobj.fields.get_field_schemas( value=search, schemas=apiobj.TEST_DATA["fields_map"][AGG_ADAPTER_NAME] ) assert exp == result def test_get_field_schema_error(self, apiobj): """Pass.""" search = "badwolf" with pytest.raises(NotFoundError): apiobj.fields.get_field_schema( value=search, schemas=apiobj.TEST_DATA["fields_map"][AGG_ADAPTER_NAME], ) # def test_get_field_schemas_error(self, apiobj): # """Pass.""" # search = "badwolf" # with pytest.raises(NotFoundError): # apiobj.fields.get_field_schemas( # value=search, schemas=apiobj.TEST_DATA["fields_map"][AGG_ADAPTER_NAME], # ) @pytest.mark.parametrize( "test_data", [ (f"{AGG_ADAPTER_NAME}:host", (AGG_ADAPTER_NAME, ["host"])), ( f"{AGG_ADAPTER_NAME}:host, ip, other", (AGG_ADAPTER_NAME, ["host", "ip", "other"]), ), ("host, ip, other", (AGG_ADAPTER_NAME, ["host", "ip", "other"])), ("adapter1:host, ip, other", ("adapter1", ["host", "ip", "other"])), (":host", (AGG_ADAPTER_NAME, ["host"])), ], scope="class", ) def test_split_search(self, apiobj, test_data): """Pass.""" search, exp = test_data result = apiobj.fields.split_search(value=search) assert result == exp @pytest.mark.parametrize( "test_data", [ (f"{AGG_ADAPTER_NAME}:host", [(AGG_ADAPTER_NAME, ["host"])]), ( f"{AGG_ADAPTER_NAME}:host, ip, other", [(AGG_ADAPTER_NAME, ["host", "ip", "other"])], ), ("host, ip, other", [(AGG_ADAPTER_NAME, ["host", "ip", "other"])]), ("adapter1:host, ip, other", [("adapter1", ["host", "ip", "other"])]), ( [f"{AGG_ADAPTER_NAME}:host", "adapter1:host, ip, other"], [(AGG_ADAPTER_NAME, ["host"]), ("adapter1", ["host", "ip", "other"])], ), ], scope="class", ) def test_split_searches(self, apiobj, test_data): """Pass.""" searches, exp = test_data result = apiobj.fields.split_searches(value=searches) assert result == exp def test_split_search_error(self, apiobj): """Pass.""" search = f"{AGG_ADAPTER_NAME}:" with pytest.raises(ApiError): apiobj.fields.split_search(value=search) def test_get_field_name_manual(self, apiobj): """Pass.""" search = "test" result = apiobj.fields.get_field_name( value=search, fields_map=apiobj.TEST_DATA["fields_map"], field_manual=True, ) assert search == result def test_get_field_name_error(self, apiobj): """Pass.""" search = "bad,wolf" with pytest.raises(ApiError): apiobj.fields.get_field_name( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) def test_get_field_name(self, apiobj): """Pass.""" search = "last_seen" exp = "specific_data.data.last_seen" result = apiobj.fields.get_field_name( value=search, fields_map=apiobj.TEST_DATA["fields_map"] ) assert result == exp def test_validate(self, apiobj): """Pass.""" exp = apiobj.fields_default + [ "specific_data.data", "specific_data.data.last_seen", "specific_data.data.first_fetch_time", ] result = apiobj.fields.validate( fields=["last_seen"], fields_regex=["^first_fetch_time$"], fields_manual=["specific_data.data"], fields_default=True, ) assert result == exp def test_validate_defaults(self, apiobj): """Pass.""" exp = apiobj.fields_default result = apiobj.fields.validate( fields=None, fields_regex=None, fields_manual=None, fields_default=True ) assert exp == result def test_validate_error(self, apiobj): """Pass.""" with pytest.raises(ApiError): apiobj.fields.validate( fields=None, fields_regex=None, fields_manual=None, fields_default=False, ) class TestFieldsDevices(FieldsPrivate, FieldsPublic): """Pass.""" @pytest.fixture(scope="class") def apiobj(self, api_devices): """Pass.""" return load_test_data(api_devices) class TestFieldsUsers(FieldsPrivate, FieldsPublic): """Pass.""" @pytest.fixture(scope="class") def apiobj(self, api_users): """Pass.""" return load_test_data(api_users) def val_source(obj): """Pass.""" source = obj.pop("source", {}) assert isinstance(source, dict) if source: source_key = source.pop("key") assert isinstance(source_key, str) source_options = source.pop("options") assert isinstance(source_options, dict) options_allow = source_options.pop("allow-custom-option") assert isinstance(options_allow, bool) assert not source, source assert not source_options, source_options
[ "jimbosan@gmail.com" ]
jimbosan@gmail.com
85586a9aa388a3da1afb95388a12ea3118e794e6
ea215e23733a02cb1f5e35a593cdfbc1f9a1c26f
/python语法基础/06.匿名函数、文件操作/08-读入数据.py
326aefde725dd9559ffecde059815cb81ef946a9
[]
no_license
XiaoqingWang/python_code
288ce365aa0b90a475306e2b3c6a9f90748d7b3a
cbe623c9316e7ae83277482b2ef3e4a47f04a753
refs/heads/master
2020-03-30T05:51:14.213923
2018-01-28T08:16:58
2018-01-28T08:16:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
71
py
f = open("xxx.txt", "r") content = f.read() print(content) f.close()
[ "1216938752@qq.com" ]
1216938752@qq.com
196b422eb35ab2bb9e2b625a3517a0eb98868d34
9afbcb367de9bf055d531d285bc299a9ca3040fe
/django_session/app01/views.py
0c8261d29e36376540f9346f423e2e2196894c87
[]
no_license
mysqlplus163/aboutPython
a41a5bc2efd43b53d4acf96e7477e80c022cf657
fa7c3e6f123158011d8726b28bfcd0dee02fa853
refs/heads/master
2020-03-21T05:06:19.949902
2018-03-14T16:04:54
2018-03-14T16:04:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
499
py
from django.shortcuts import render, redirect, HttpResponse # Create your views here. def login(request): print("login...") if request.method == "POST": print(request.POST) request.session["user"] = request.POST.get("username") return redirect("/index/") else: return render(request, "login.html") def index(request): if request.session.get("user", None): return render(request, "index.html") else: return HttpResponse("gun")
[ "liwenzhou7@gmail.com" ]
liwenzhou7@gmail.com
69bcfdf83c33919af92c429df5abbb676d5fa80e
ffa1663df6c89fd2342ff11e180374ea6b50c50a
/30_days_of_code_challenge/day_4_class_vs_instance.py
75affb0db15a1ac60e7478bac5b6f2ea7ec568f4
[]
no_license
mandybawa/HackerRank
d919a08fd4de60bcb8068bc290c88d240aa1fbd1
6ddf4396f0eb4e6241162573634ab12d7e64cfb1
refs/heads/master
2020-12-04T21:32:32.049760
2020-02-11T12:50:20
2020-02-11T12:51:46
231,908,728
0
0
null
null
null
null
UTF-8
Python
false
false
2,723
py
# Task: # Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. # The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative # if a negative argument is passed as, the constructor should set to age to 0 # and print Age is not valid, setting age to 0.. In addition, you must # write the following instance methods: # 1. yearPasses() should increase the age instance variable by 1 # 2. amIOld() should perform the following conditional actions: # If age < 13 print You are young.. # If age >= 13 and age < 18 print You are a teenager.. # Otherwise, print You are old.. # To help you learn by example and complete this challenge, much of the code is provided for you, # but you'll be writing everything in the future. The code that creates each instance of your Person class # is in the main method. Don't worry if you don't understand it all quite yet! # Note: Do not remove or alter the stub code in the editor. # Input Format: # Input is handled for you by the stub code in the editor. # The first line contains an integer, T (the number of test cases), and the T subsequent lines each contain an integer denoting the # age of a Person instance. # Output Format: # Complete the method definitions provided in the editor so they meet the specifications outlined above # the code to test your work is already in the editor. If your methods are implemented correctly, each test case will print 2 or 3 # lines(depending on whether or not a valid initialAge as passed to the # constructor). # Sample Input: # 4 # -1 # 10 # 16 # 18 # Sample Output: # Age is not valid, setting age to 0. # You are young. # You are young. # You are young. # You are a teenager. # You are a teenager. # You are old. # You are old. # You are old. # Solution: class Person: def __init__(self, initialAge): if initialAge < 0: self.initial_age = 0 print("Age is not valid, setting age to 0.") else: self.initial_age = initialAge def amIOld(self): # Do some computations in here and print out the correct statement to # the console if self.initial_age in range(0, 13): print("You are young.") elif self.initial_age in range(13, 18): print("You are a teenager.") else: print("You are old.") def yearPasses(self): # Increment the age of the person in here self.initial_age += 1 t = int(input()) for i in range(0, t): age = int(input()) p = Person(age) p.amIOld() for j in range(0, 3): p.yearPasses() p.amIOld() print("")
[ "mandeepkaur@constellation.ai" ]
mandeepkaur@constellation.ai
c686e702e0087727365ef2bd4566c0817162c4d9
9b2eb0d6b673ac4945f9698c31840b847f790a58
/pkg/test/test_query_details.py
142ecb411b374b9eb5230324a05514b3e97d53c3
[ "Apache-2.0" ]
permissive
Apteco/apteco-api
6d21c9f16e58357da9ce64bac52f1d2403b36b7c
e8cf50a9cb01b044897025c74d88c37ad1612d31
refs/heads/master
2023-07-10T23:25:59.000038
2023-07-07T14:52:29
2023-07-07T14:52:29
225,371,142
2
0
null
null
null
null
UTF-8
Python
false
false
1,857
py
# coding: utf-8 """ Apteco API An API to allow access to Apteco Marketing Suite resources # noqa: E501 The version of the OpenAPI document: v2 Contact: support@apteco.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import datetime import apteco_api from apteco_api.models.query_details import QueryDetails # noqa: E501 from apteco_api.rest import ApiException class TestQueryDetails(unittest.TestCase): """QueryDetails unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test QueryDetails include_option is a boolean, when False only required params are included, when True both required and optional params are included """ # model = apteco_api.models.query_details.QueryDetails() # noqa: E501 if include_optional : return QueryDetails( description = '0', counts = [ apteco_api.models.query_detail_count.QueryDetailCount( table_name = '0', table_description = '0', count_value = 56, ) ], properties = [ apteco_api.models.property.Property( name = '0', property_value = '0', hidden = True, ) ] ) else : return QueryDetails( ) def testQueryDetails(self): """Test QueryDetails""" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__ == '__main__': unittest.main()
[ "tim.morris@apteco.com" ]
tim.morris@apteco.com
4ea5e2cf870de6176f770c5f8c3b3935d8803997
283076c1bb3a5610308f262a6091b6ca996ada53
/lib/kseval/models/starcraft.py
56495e4128f2f81e5103004e97aeb765bd0b2b29
[]
no_license
amirbachar/kickscore-kdd19
09c5f676c1cf7366dc90d00e7e837117531bd472
8a30b9cc8667dc1c203d0893c05df5d4d5fd50c2
refs/heads/master
2022-01-20T05:31:23.415728
2019-07-25T19:58:01
2019-07-25T19:58:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,544
py
import abc import kickscore as ks import numpy as np from .base import PredictiveModel, iterate_dataset from math import log SETTINGS = { "wol": { "path": "kdd-starcraft-wol.txt", "idx1": 30828, "idx2": 43159, }, "hots": { "path": "kdd-starcraft-hots.txt", "idx1": 14291, "idx2": 20007, }, } class StarCraftModel(PredictiveModel, metaclass=abc.ABCMeta): def __init__(self, dataset, obs_type="probit", method="ep", max_iter=100, lr=1.0): self.ks_model = ks.BinaryModel(obs_type=obs_type) self.fit_params = {"method": method, "max_iter": max_iter, "lr": lr} self.dataset = dataset def fit(self, *, cutoff=None): path = SETTINGS[self.dataset]["path"] idx1 = SETTINGS[self.dataset]["idx1"] for i, obs in enumerate(iterate_dataset(path)): if i == idx1: break feats1, feats2 = self.make_features(obs["winner"], obs["loser"]) self.ks_model.observe(winners=feats1, losers=feats2, t=0.0) converged = self.ks_model.fit(**self.fit_params) return converged def evaluate(self): path = SETTINGS[self.dataset]["path"] idx2 = SETTINGS[self.dataset]["idx2"] log_loss = 0 accuracy = 0 n_obs = 0 for i, obs in enumerate(iterate_dataset(path)): if i >= idx2: feats1, feats2 = self.make_features(obs["winner"], obs["loser"]) pw, _ = self.ks_model.probabilities(feats1, feats2, t=0.0) log_loss += -log(pw) accuracy += 1.0 if pw > 0.5 else 0.0 n_obs += 1 return n_obs, log_loss, accuracy @abc.abstractmethod def make_features(self, winner, loser): """Make feature vectors for the two players.""" @property def log_likelihood(self): path = SETTINGS[self.dataset]["path"] idx1 = SETTINGS[self.dataset]["idx1"] idx2 = SETTINGS[self.dataset]["idx2"] loglike = 0 for i, obs in enumerate(iterate_dataset(path)): if idx1 <= i < idx2: feats1, feats2 = self.make_features(obs["winner"], obs["loser"]) pw, _ = self.ks_model.probabilities(feats1, feats2, t=0.0) loglike += log(pw) return loglike @classmethod def get_dates(cls, begin=None): raise NotImplementedError() class ConstantModel(StarCraftModel): def __init__(self, *, dataset, cvar): super().__init__(dataset) self._ckern = ks.kernel.Constant(var=cvar) def make_features(self, winner, loser): for item in (winner, loser): if item not in self.ks_model.item: self.ks_model.add_item(item, kernel=self._ckern) return [winner], [loser] class IntransitiveModel(StarCraftModel): def __init__(self, *, dataset, cvar, xvar): super().__init__(dataset, lr=0.8) self._ckern = ks.kernel.Constant(var=cvar) self._xkern = ks.kernel.Constant(var=xvar) def make_features(self, winner, loser): for item in (winner, loser): if item not in self.ks_model.item: self.ks_model.add_item(item, kernel=self._ckern) x = "{}-{}".format(*sorted((winner, loser))) if x not in self.ks_model.item: self.ks_model.add_item(x, kernel=self._xkern) if winner < loser: return [winner, x], [loser] else: return [winner], [loser, x]
[ "lucas@maystre.ch" ]
lucas@maystre.ch
25e20bb0b3030b740809685abdf8aec701ccc499
9df5fa4c65df58e30aa23736d44309c228bd2bf7
/CSTraining/CodingSchool/Bootcamp - Intuition/bfs.py
a394fc1bafd3da7474033b7e4f6eda70bfa95f52
[]
no_license
mwijaya3/Training
db385bbf7001c27fc2be24290c6ae90595c9b96d
1fdbf995be056a04c96cb834f321e35e1c9e3752
refs/heads/master
2020-04-19T08:32:29.977548
2018-09-20T19:59:43
2018-09-20T19:59:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,808
py
class Node(dict): """ Definition for a node in a graph """ # Visit State UNVISITED = 0 # not visited or on frontier (while) FRONTIER = 1 # on frontier, waiting to be visited (gray) VISITED = 2 # visited (black) def __init__(self, key): """ constructor initializing the fields as key=value pairs in dictionary """ super().__init__(key=key,neighbors=[],visited=self.UNVISITED) def neighbor(self, neighbor): """ Add a neighbor to this node """ # list the node as a neighbor of this node self["neighbors"].append(neighbor) # set this node as a neighbor of the node neighbor["neighbors"].append(self) def bfs(root): """ Breadth first search of a graph """ # Create a queue for frontier nodes (nodes to be visited next) frontier = [] # Add the root node to the frontier ( Enqueue ) frontier.append(root) root["visited"] = root.FRONTIER # Traverse each node in the frontier list while len(frontier) != 0: # visit the next node ( Dequeue ) visit = frontier[0] del frontier[0] visit["visited"] = visit.VISITED print(visit[ "key" ] ) # Add the node's neighbors (if not visited and not on frontier list) # to the frontier list nodes = visit["neighbors"] for node in nodes: # not in visited or unvisited list if node["visited"] == node.UNVISITED: frontier.append(node) # Enqueue node["visited"] = node.FRONTIER # Test Driver nodes = [None] * 6; for i in range(0, 6): nodes[i] = Node(i) nodes[0].neighbor(nodes[1]) nodes[0].neighbor(nodes[2]) nodes[0].neighbor(nodes[3]) nodes[1].neighbor(nodes[2]) nodes[1].neighbor(nodes[3]) nodes[3].neighbor(nodes[4]) nodes[3].neighbor(nodes[5]) nodes[4].neighbor(nodes[5]) print("BFS: 0 1 2 3 4 5") bfs(nodes[0]) for i in range(0, 6): nodes[i]["visited"] = nodes[i].UNVISITED
[ "aferlitsch@gmail.com" ]
aferlitsch@gmail.com
5fd74abcb614eb1436c05ade8440cd438a2c2b1b
8dc64db8a0d7ddb8778c8eae2dac9075b9a90e2b
/env/Lib/site-packages/dns/rdtypes/__init__.py
c3af264e48fd7718c7e7c6d108b48e0ba35844f7
[ "MIT" ]
permissive
theXtroyer1221/Cloud-buffer
c3992d1b543a1f11fde180f6f7d988d28b8f9684
37eabdd78c15172ea980b59d1aff65d8628cb845
refs/heads/master
2022-11-22T22:37:10.453923
2022-02-25T01:15:57
2022-02-25T01:15:57
240,901,269
1
1
MIT
2022-09-04T14:48:02
2020-02-16T14:00:32
HTML
UTF-8
Python
false
false
1,072
py
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS rdata type classes""" __all__ = [ 'ANY', 'IN', 'CH', 'dnskeybase', 'dsbase', 'euibase', 'mxbase', 'nsbase', 'svcbbase', 'tlsabase', 'txtbase', 'util' ]
[ "jaddou2005@gmail.com" ]
jaddou2005@gmail.com
77e8c1d9be9b563cc355464958f3da7249df01d7
921acb2b2faa5f5e3a0614b136d8782412d15e94
/wave_native_cdk/wave_native_stack.py
fffb687a77d0b6ad1053e89a62ec7cec37b8b011
[]
no_license
rdghosal/WaveNativeCDK
422c2849bcdf0000ad04fca05574cba031dd7c25
525bba990ff404133aeed6a70f7e9fa4435eeb44
refs/heads/master
2021-01-07T00:01:44.928020
2020-02-19T03:07:25
2020-02-19T03:07:25
241,520,141
0
0
null
null
null
null
UTF-8
Python
false
false
1,428
py
import os from aws_cdk import aws_rds, aws_ec2, aws_s3, aws_s3_assets, aws_elasticbeanstalk, core class WaveNativeStack(core.Stack): def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your stack goes here # Configure VPC for Elastic Beanstalk (EB) + RDS subnet vpc = aws_ec2.Vpc(self, "wave-native_vpc") # Configure RDS # TODO: add master_username, engine, instance_class rds = aws_rds.DatabaseInstance( self, "wave-native_rds", database_name="wave-native", vpc=vpc ) # Configure Bucket and upload app files as S3 asset s3_bucket = aws_s3.Bucket(self, "wave-native_s3") s3_asset = aws_s3_assets.Assets( self, "wave-native.zip", path=os.path.join(os.getcwd(), "wave-native.zip") ) # Instantiate source_bundle for EB source_bundle = aws_elasticbeanstalk.CfnApplicationVersion.SourceBundleProperty() source_bundle.S3Bucket = s3_bucket.s3BucketName source_bundle.S3Key = s3_asset.s3ObjectKey # Configure EB # TODO: add EB to VPC eb = aws_elasticbeanstalk.CfnApplicationVersion( self, "wave-native_eb", application_name="WaveNative", source_bundle=source_bundle )
[ "rdghosal@gmail.com" ]
rdghosal@gmail.com
73bb40f773a6186cf0f1432517bb00476cc09595
1b6e89a5b4ca98378325cf6b16661b9519f164b7
/run_file.py
67ba6e526c90ef773493848ea01b8e2a9cce2023
[]
no_license
msDikshaGarg/KNN-Perceptron-MLP
bbcd11058d1f14d3fb247a1d250df6688c33c953
339613a4d019fafdc13c09d6f39f7445ef4e3b8f
refs/heads/main
2022-12-24T07:13:22.561701
2020-10-07T01:51:28
2020-10-07T01:51:28
301,885,039
1
0
null
null
null
null
UTF-8
Python
false
false
2,702
py
import classifiers as models import numpy as np import sys if(sys.version_info[0] < 3): raise Exception("This assignment must be completed using Python 3") #==========================================================Data========================================================== # Number of Instances: # 569 # Number of Attributes: # 30 numeric, predictive attributes and the class # Attribute Information: # radius (mean of distances from center to points on the perimeter) # texture (standard deviation of gray-scale values) # perimeter # area # smoothness (local variation in radius lengths) # compactness (perimeter^2 / area - 1.0) # concavity (severity of concave portions of the contour) # concave points (number of concave portions of the contour) # symmetry # fractal dimension (“coastline approximation” - 1) # The mean, standard error, and “worst” or largest (mean of the three largest values) of these features were computed for each image, resulting in 30 features # Class Distribution: # 212 - Malignant (0), 357 - Benign (1) #======================================================================================================================== def train_test_split(X, y, test_ratio): tr = int(y.size*test_ratio) return X[:tr], X[tr:], y[:tr], y[tr:] def load_data(path): data = np.genfromtxt(path, delimiter=',', dtype=float) return data[:,:-1], data[:,-1].astype(int) X, y = load_data("breast_cancer_dataset.csv") X_train, X_test, y_train, y_test = train_test_split(X, y, 0.75) #Initialization #KNN k = 3 knn = models.KNN(k) #Perceptron lr = .001 w = np.random.normal(0, .1, size=X_train.shape[1]) #Each column represents all the weights going into an output node b = np.random.normal(0, .1, size=1) perceptron = models.Perceptron(w, b, lr) #MLP lr = .0001 w1 = np.random.normal(0, .1, size=(X_train.shape[1], 10)) w2 = np.random.normal(0, .1, size=(10,1)) b1 = np.random.normal(0, .1, size=(1,10)) b2 = np.random.normal(0, .1, size=(1,1)) mlp = models.MLP(w1, b1, w2, b2, lr) #Train steps = 100*y_train.size knn.train(X_train, y_train) perceptron.train(X_train, y_train, steps) mlp.train(X_train, y_train, steps) #Check weights (For grading) # perceptron.w # perceptron.b # mlp.w1 # mlp.b1 # mlp.w2 # mlp.b2 #Evaluate def evaluate(solutions, real): if(solutions.shape != real.shape): raise ValueError("Output is wrong shape.") predictions = np.array(solutions) labels = np.array(real) return (predictions == labels).sum() / float(labels.size) solutions = knn.predict(X_test) print(evaluate(solutions, y_test)) solutions = perceptron.predict(X_test) print(evaluate(solutions, y_test)) solutions = mlp.predict(X_test) print(evaluate(solutions, y_test))
[ "noreply@github.com" ]
msDikshaGarg.noreply@github.com
a9948b4ec7caf4566893e720ced1dd75cfd40472
49bf70e32aff3c9eec3385aa7db32014cca5255c
/graph/env.py
8cce220c61627789f88c80cef1a8a594772932f0
[ "MIT" ]
permissive
felipefelixarias/a2cat-vn-pytorch
2919b58b245dfd598949ea8ce3bfd8d5acdee82c
6e1b97c58be2405ef860718a91ecd2b07bc4b65f
refs/heads/master
2022-11-07T11:36:56.847076
2020-05-07T03:07:56
2020-05-07T03:07:56
254,767,673
0
0
MIT
2020-04-11T01:08:43
2020-04-11T01:08:42
null
UTF-8
Python
false
false
8,216
py
import gym import gym.spaces from graph.util import step, is_valid_state, load_graph, enumerate_positions, sample_initial_state, sample_initial_position, direction_to_change import numpy as np from operator import add import random class OrientedGraphEnv(gym.Env): def __init__(self, graph, goal, rewards = [1.0, 0.0, 0.0]): self.goal = goal if isinstance(graph, str): with open(graph, 'rb') as f: self.graph = load_graph(f) else: self.graph = graph self.observation_space = gym.spaces.Box(0.0, 1.0, self.graph.observation_shape, np.float32) if self.graph.dtype == np.float32 or self.graph.dtype == np.uint8: pass else: raise Exception('Unsupported observation type') self.action_space = gym.spaces.Discrete(4) self.state = None self.largest_distance = np.max(self.graph.graph) self.complexity = None self.rewards = rewards @property def unwrapped(self): return self def set_complexity(self, complexity = None): self.complexity = complexity def reset(self): optimal_distance = None if self.complexity is not None: optimal_distance = self.complexity * (self.largest_distance + 4 - 1) + 1 state = sample_initial_state(self.graph, self.goal, optimal_distance = optimal_distance) self.state = state return self.observe(self.state) def observe(self, state): observation = self.graph.render(state[:2], state[2]) if self.graph.dtype == np.uint8: return observation.astype(np.float32) / 255.0 return observation def step(self, action): nstate = step(self.state, action) if not is_valid_state(self.graph.maze, nstate): # We can either end the episode with failure # Or continue with negative reward return self.observe(self.state), self.rewards[2], False, dict(state = self.state) else: self.state = nstate if self.state[:2] == self.goal: return self.observe(self.state), self.rewards[0], True, dict(state = self.state, win = True) else: return self.observe(self.state), self.rewards[1], False, dict(state = self.state) def render(self, mode = 'human'): if mode == 'human': import matplotlib.pyplot as plt plt.imshow(self.observe(self.state)) plt.show() class SimpleGraphEnv(gym.Env): def __init__(self, graph, rewards = [1.0, 0.0, 0.0]): if isinstance(graph, str): with open(graph, 'rb') as f: self.graph = load_graph(f) else: self.graph = graph self.goal = self.graph.goal self.observation_space = gym.spaces.Box(0.0, 1.0, self.graph.observation_shape, np.float32) if self.graph.dtype == np.float32 or self.graph.dtype == np.uint8: pass else: raise Exception('Unsupported observation type') self.action_space = gym.spaces.Discrete(4) self.state = None self.largest_distance = np.max(self.graph.graph) self.complexity = None self._rewards = rewards @property def unwrapped(self): return self def set_complexity(self, complexity = None): self.complexity = complexity def reset(self): optimal_distance = None if self.complexity is not None: optimal_distance = self.complexity * (self.largest_distance - 1) + 1 state = sample_initial_position(self.graph, self.goal, optimal_distance = optimal_distance) self.state = state return self.observe(self.state) def observe(self, state): observation = self.graph.render(state) if self.graph.dtype == np.uint8: return observation.astype(np.float32) / 255.0 return observation def step(self, action): if action is None or action == -1: # Return the latest observation return self.observe(self.state), 0.0, False, dict() nstate = tuple(map(add, self.state, direction_to_change(action))) if not is_valid_state(self.graph.maze, nstate): # We can either end the episode with failure # Or continue with negative reward return self.observe(self.state), self._rewards[2], False, dict(state = self.state) else: self.state = nstate if self.state[:2] == self.goal: return self.observe(self.state), self._rewards[0], True, dict(state = self.state, win = True) else: return self.observe(self.state), self._rewards[1], False, dict(state = self.state) def render(self, mode = 'human'): if mode == 'human': import matplotlib.pyplot as plt plt.imshow(self.observe(self.state)) plt.show() elif mode == 'rgbarray': array = (self.observe(self.state) * 255).astype(np.uint8) import cv2 return cv2.resize(array, (300, 300), interpolation = cv2.INTER_NEAREST) class MultipleGraphEnv(gym.Env): def __init__(self, graphs, rewards = [1.0, 0.0, 0.0]): if isinstance(graphs[0], str): self.graphs = [] for g in graphs: with open(g, 'rb') as f: self.graphs.append(load_graph(f)) else: self.graphs = graphs self.observation_space = gym.spaces.Box(0.0, 1.0, self.graphs[0].observation_shape, np.float32) if self.graphs[0].dtype == np.float32 or self.graphs[0].dtype == np.uint8: pass else: raise Exception('Unsupported observation type') self.action_space = gym.spaces.Discrete(4) self.state = None self.largest_distances = [np.max(x.graph) for x in self.graphs] self.graph_number = None self.complexity = None self._rewards = rewards @property def unwrapped(self): return self def set_complexity(self, complexity = None): self.complexity = complexity def reset(self): self.graph_number = random.randrange(len(self.graphs)) optimal_distance = None if self.complexity is not None: optimal_distance = self.complexity * (self.largest_distances[self.graph_number] - 1) + 1 state = sample_initial_position(self.graphs[self.graph_number], self.graphs[self.graph_number].goal, optimal_distance = optimal_distance) self.state = state return self.observe(self.state) def observe(self, state): observation = self.graphs[self.graph_number].render(state) if self.graphs[0].dtype == np.uint8: return observation.astype(np.float32) / 255.0 return observation def step(self, action): if action is None or action == -1: # Return the latest observation return self.observe(self.state), 0.0, False, dict() nstate = tuple(map(add, self.state, direction_to_change(action))) if not is_valid_state(self.graphs[self.graph_number].maze, nstate): # We can either end the episode with failure # Or continue with negative reward return self.observe(self.state), self._rewards[2], False, dict(state = self.state) else: self.state = nstate if self.state[:2] == self.graphs[self.graph_number].goal: return self.observe(self.state), self._rewards[0], True, dict(state = self.state, win = True) else: return self.observe(self.state), self._rewards[1], False, dict(state = self.state) def render(self, mode = 'human'): if mode == 'human': import matplotlib.pyplot as plt plt.imshow(self.observe(self.state)) plt.show() elif mode == 'rgbarray': array = (self.observe(self.state) * 255).astype(np.uint8) import cv2 return cv2.resize(array, (300, 300), interpolation = cv2.INTER_NEAREST)
[ "jonas.kulhanek@live.com" ]
jonas.kulhanek@live.com
f038a680df255cdd84a21bae4b91b3abf65afb7e
ba4b91646add81d34617415be5792891b552f772
/ir_config_parameter_multi_company/models/ir_property.py
df3d75322980ddd6d6bd2389c9f7bc0bb9b284c4
[]
no_license
ShaheenHossain/multi_webstie
f718911b116d73b092a5e8e05cacd58c8f028d1d
23f50ab1fb314af69d844f80f1fd082bc15f96f3
refs/heads/master
2020-08-31T23:31:41.823364
2019-10-31T16:47:56
2019-10-31T16:47:56
218,814,415
0
1
null
null
null
null
UTF-8
Python
false
false
330
py
from eagle import models, api class IrProperty(models.Model): _inherit = 'ir.property' @api.multi def write(self, vals): res = super(IrProperty, self).write(vals) field = self.env.ref('base.field_ir_config_parameter__value') self._update_db_value_website_dependent(field) return res
[ "rapidgrps@gmail.com" ]
rapidgrps@gmail.com
e04a21c7d6887b03bbc9c20dc1a7a5e7b7df95d5
4e465ecc24ea243fa7556cb5526c405e9d1dad17
/nb_back/serializers.py
f38dc76c8c5f58d8e20f437b232e0b7b51c5acb1
[]
no_license
ismaelpontes/webdevbook-noticias-backend
e9cd571f48d36236a7c2e7746aa036c33cd6eec2
226cf9e89e358ff821962f0c26094876f7016f41
refs/heads/master
2021-09-28T00:43:08.259700
2018-11-12T22:10:09
2018-11-12T22:10:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,938
py
from rest_framework import serializers from rest_framework.fields import empty from .models import * from django.contrib.auth.models import User, Group import logging logger = logging.getLogger('noticias-back') class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('url', 'id', 'name') class UserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True, read_only=True) groups_ids = serializers.PrimaryKeyRelatedField(queryset=Group.objects.all(), many=True, write_only=True, required=False) password = serializers.CharField(write_only=True) class Meta: model = User fields = ('url', 'id', 'username', 'email', 'password', 'is_superuser', 'groups', 'groups_ids') def create(self, validated_data): groups = validated_data.pop('groups_ids', None) instance = User(**validated_data) instance.save() if groups: for group in groups: instance.groups.add(group) instance.save() return instance def update(self, instance, validated_data): groups = validated_data.pop('groups_ids', None) if groups is not None: instance.groups.clear() for group in groups: instance.groups.add(group) instance.save() return instance class CategoriaSerializer(serializers.ModelSerializer): class Meta: model = Categoria fields = ('url', 'id', 'nome', 'slug', 'descricao') class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('url', 'id', 'nome', 'slug') class PessoaSerializer(serializers.ModelSerializer): usuario_id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), pk_field=serializers.IntegerField(), write_only=True, required=False) usuario = UserSerializer(read_only=True) class Meta: model = Pessoa fields = ('url', 'id', 'nome', 'email', 'usuario', 'usuario_id') def create(self, validated_data): usuario = validated_data.pop('usuario_id', None) instance = Pessoa(**validated_data) if usuario: instance.usuario = usuario instance.save() return instance def update(self, instance, validated_data): usuario = validated_data.pop('usuario_id', None) if usuario: instance.usuario = usuario for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() return instance class NoticiaSerializer(serializers.ModelSerializer): autor = PessoaSerializer(read_only=True) autor_id = serializers.PrimaryKeyRelatedField(queryset=Pessoa.objects.all(), pk_field=serializers.IntegerField(), write_only=True) categoria = CategoriaSerializer(read_only=True) categoria_id = serializers.PrimaryKeyRelatedField(queryset=Categoria.objects.all(), write_only=True, required=False) tags = TagSerializer(many=True, read_only=True) tags_ids = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all(), write_only=True, required=False) class Meta: model = Noticia fields = ('url', 'id', 'titulo', 'resumo', 'conteudo', 'autor', 'autor_id', 'data', 'data_cadastro', 'publicada', 'destaque', 'foto', 'categoria', 'categoria_id', 'tags', 'tags_ids') read_only_fields = ('foto',) def create(self, validated_data): autor = validated_data.pop('autor_id', None) categoria = validated_data.pop('categoria_id', None) tags = validated_data.pop('tags_ids', None) instance = Noticia(**validated_data) instance.autor = autor instance.save() if categoria: instance.categoria = categoria if tags: for tag in tags: instance.tags.add(tag) instance.save() return instance def update(self, instance, validated_data): autor = validated_data.pop('autor_id', None) categoria = validated_data.pop('categoria_id', None) tags = validated_data.pop('tags_ids', None) instance.autor = autor instance.categoria = categoria if tags is not None: instance.tags.clear() for tag in tags: instance.tags.add(tag) for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() return instance class NoticiaFotoSerializer(serializers.ModelSerializer): class Meta: model = Noticia fields = ['foto']
[ "jgomes@ceulp.edu.br" ]
jgomes@ceulp.edu.br
43b8fb8293d1f2261578ead6092373bcd434cd23
efe72fe75338af2146e6249261866420bb758b37
/app/routers/users.py
f03b74ff541d7db143a31017294ff9c2def00637
[]
no_license
nerdburn/cred-python-api
ad451b0ca50b8138a31dce88decb0419f3d19958
35fc015101e36b38e62fe1222e634872efdb1059
refs/heads/master
2022-11-10T18:51:48.281008
2020-06-20T06:28:40
2020-06-20T06:28:40
273,591,977
0
0
null
null
null
null
UTF-8
Python
false
false
4,332
py
from datetime import datetime, timedelta import jwt from jwt import PyJWTError from fastapi import Depends, FastAPI, HTTPException, status, APIRouter from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from passlib.context import CryptContext from pydantic import BaseModel, EmailStr router = APIRouter() # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "e0e91efefee94d972c359d60640ce88247f76e646761a22865d2597ff58b2eb0" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 fake_users_db = { "shawn@nerdburn.com": { "full_name": "Shawn Adrian", "email": "shawn@nerdburn.com", "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", "disabled": False, }, "stephanie@blossomeffect.com": { "full_name": "Stephanie Kawahara", "email": "stephanie@blossomeffect.com", "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", "disabled": False, } } class Token(BaseModel): access_token: str token_type: str # not sure why we can't just use User here? # maybe something to do with JWT class TokenData(BaseModel): username: str = None class User(BaseModel): email: EmailStr full_name: str = None hashed_password: str = None disabled: bool = None pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password): return pwd_context.hash(password) def get_user(db, username: str): if username in db: user_dict = db[username] return User(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user def create_access_token(data: dict, expires_delta: timedelta = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except PyJWTError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: raise credentials_exception return user async def get_current_active_user(current_user: User = Depends(get_current_user)): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user @router.post("/token", response_model=Token) async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={"sub": user.email}, expires_delta=access_token_expires ) return {"access_token": access_token, "token_type": "bearer"} @router.get("/users/me/", response_model=User) async def read_users_me(current_user: User = Depends(get_current_active_user)): return current_user @router.get("/users/me/items/") async def read_own_items(current_user: User = Depends(get_current_active_user)): return [{"item_id": "Foo", "owner": current_user.email}]
[ "shawn@nerdburn.com" ]
shawn@nerdburn.com
d41a3fdee01878c3167ab8b9dce19207a3b9225e
79bc99d3f30eacccac49ac07df0ed98b8bf7a3aa
/search_endpoint.py
b9a2180cd8aad55d12d5bcd63570893d3a3ca8a9
[]
no_license
nggih/sofwerx
0c404787123257a242aa00125f293dc1f98465a4
c05b01809538063332c7c4f8a2cf006cc3317f6f
refs/heads/master
2020-12-30T13:21:11.547696
2017-05-13T22:21:50
2017-05-13T22:21:50
91,205,925
1
1
null
null
null
null
UTF-8
Python
false
false
507
py
import os import requests from requests.auth import HTTPBasicAuth # our demo filter that filters by geometry, date and cloud cover from demo_filters import Vessel_Search # Search API request object search_endpoint_request = { "item_types": ["PSScene3Band"], "filter": Vessel_Search, "satellite_id": "1005" } result = \ requests.post( 'https://api.planet.com/data/v1/quick-search', auth=HTTPBasicAuth(os.environ['PLANET_API_KEY'], ''), json=search_endpoint_request) print result.text
[ "noreply@github.com" ]
nggih.noreply@github.com
87d344c58c39f29ed1036e5883d70eed3ce97045
7b2199662df445cb992ea536cd8fcfc1e9558ff7
/03-Theano/106-Linear-Regression.py
7b8ceb5e35a8334c5fc21140485a842d63ebfb02
[]
no_license
bansheng/tf_note
f5371cd6e879568452ad3fe11bb74cfa95261b7c
1a0d1609b0583ac728eecd7bf1ff927d43c38703
refs/heads/master
2020-05-02T04:32:47.355741
2019-09-09T12:03:02
2019-09-09T12:03:02
177,752,300
0
0
null
null
null
null
UTF-8
Python
false
false
2,046
py
import theano import theano.tensor as T import numpy as np import matplotlib.pyplot as plt class Layer(object): def __init__(self, inputs, in_size, out_size, activation_function=None): self.W = theano.shared(np.random.normal(0, 1, (in_size, out_size))) self.b = theano.shared(np.zeros((out_size, )) + 0.1) self.Wx_plus_b = T.dot(inputs, self.W) + self.b self.activation_function = activation_function if activation_function is None: self.outputs = self.Wx_plus_b else: self.outputs = self.activation_function(self.Wx_plus_b) # Make up some fake data x_data = np.linspace(-1, 1, 300)[:, np.newaxis] noise = np.random.normal(0, 0.05, x_data.shape) y_data = np.square(x_data) - 0.5 + noise # y = x^2 - 0.5 + whitenoise # 散点图显示 # show the fake data # plt.scatter(x_data, y_data) # plt.show() # determine the inputs dtype x = T.dmatrix("x") y = T.dmatrix("y") # add layers l1 = Layer(x, 1, 10, T.nnet.relu) l2 = Layer(l1.outputs, 10, 1, None) # compute the cost cost = T.mean(T.square(l2.outputs - y)) # compute the gradients gW1, gb1, gW2, gb2 = T.grad(cost, [l1.W, l1.b, l2.W, l2.b]) # apply gradient descent learning_rate = 0.05 train = theano.function( inputs=[x, y], outputs=cost, updates=[(l1.W, l1.W - learning_rate * gW1), (l1.b, l1.b - learning_rate * gb1), (l2.W, l2.W - learning_rate * gW2), (l2.b, l2.b - learning_rate * gb2)]) # prediction predict = theano.function(inputs=[x], outputs=l2.outputs) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.scatter(x_data, y_data) plt.ion() plt.show() for i in range(1000): # training err = train(x_data, y_data) if i % 50 == 0: # to visualize the result and improvement try: ax.lines.remove(lines[0]) except Exception: pass prediction_value = predict(x_data) # plot the prediction lines = ax.plot(x_data, prediction_value, 'r-', lw=5) plt.pause(.5)
[ "dyadongcs@gmail.com" ]
dyadongcs@gmail.com
0b0cdf32484388667f0ad71e7e44f924843ee956
090fbd7c125cf3e2747c22a981f90fc0035bd1dc
/cse4309/hw6/value_iteration.py
704aa77b807c50e677c2b24b45b056eacd447888
[]
no_license
addonovan/school
e661e1e32a06d95b82088c3b5bbac69450ce0f7c
3594ca4decfeacfef75cdc6b593bb893f0efd06c
refs/heads/master
2021-05-25T12:07:45.259361
2020-03-14T04:25:27
2020-03-14T04:25:27
127,382,457
0
0
null
2020-03-14T04:25:28
2018-03-30T04:44:57
MATLAB
UTF-8
Python
false
false
4,155
py
# Austin Donovan # add1620 from enum import Enum import math import numpy as np import os.path from random import randint import sys from environment import Environment, TileType from robot import Robot, Action # # Value Iteration # def action_utility(utilities, state, action): """ Calcualtes the overall utility of performing the given `action` in the current `state`, knowing all of the states' previously calculated `utilities`. """ base_robot = Robot(environment, state) # based on all possibilities from trying to perform the action at # the current position, calculate all of the resultant states' # utilities. Then weight them based on the probability of those # states being reached given the current action. accumulator = 0 for (action_set, probability) in action.movement_possibilities(): new_robot = base_robot.move(action_set[action]) new_utility = utilities[new_robot.state()] accumulator += probability * new_utility return accumulator def state_utility(utilities, environment, state): """ Calculates the utility of being in the given `state` in the current `environment`, knowing the states' previously calculated `utilities`. """ tile = environment.tile_at(state) # terminal states end the agent's action, so their utilities are # simply their rewards if tile.terminal(): return tile.reward() # If the tile can't be entered at all, then it has no utility # whatsoever (these are blocked tiles) elif not tile.enterable(): return 0 base_utility = environment.tile_at(state).reward() best_action_utility = max([ action_utility(utilities, state, action) for action in [Action.Up, Action.Down, Action.Left, Action.Right] ]) return base_utility + (gamma * best_action_utility) def value_iteration(environment, iteration_count): """ Performs the value iteration algorithm `iteration_count` times for the given `environment`, then returns the resultant vector of utilities for all states. """ states = environment.state_list() utilities = { state: 0 for state in states } # run the policy update `iteration_count` times for _ in range(0, iteration_count): utilities_copy = utilities.copy() for state in states: utilities[state] = state_utility(utilities_copy, environment, state) return utilities # # General Overhead # def read_argv(): """ Reads the command line arguments and returns a 4-tuple of: `(environment_file, default_reward, gamma, iteration_count)` """ if len(sys.argv) < 3: print("Usage: <environment_file> <default_reward> <gamma> <iteration_count>") if len(sys.argv) == 1: print("No arguments, will run hardcoded data instead") environment_file = "data/environment1.txt" default_reward = -0.04 gamma = 1.0 iteration_count = 20 print(f'value_iterations.py "{environment_file}" "{default_reward}" "{gamma}" "{iteration_count}"') return (environment_file, default_reward, gamma, iteration_count) else: exit(-1) environment_file = sys.argv[1] if not os.path.isfile(environment_file): print(f"No such file: {environment_file} (training file)") exit(-2) default_reward = float(sys.argv[2]) gamma = float(sys.argv[3]) iteration_count = int(sys.argv[4]) if iteration_count < 1: print(f"<iteration_count> ({iteration_count}) must be at least 1") exit(-5) return (environment_file, default_reward, gamma, iteration_count) # # Script # (environment_file, default_reward, gamma, iteration_count) = read_argv() environment = Environment(environment_file, default_reward) state_utilities = value_iteration(environment, iteration_count) def print_tile(state, more_tiles_following): print(f"{state_utilities[state]:6.3f}", end = "") if more_tiles_following: print(",", end = "") environment.for_each_tile(print_tile, print)
[ "noreply@github.com" ]
addonovan.noreply@github.com
5c37c15f7ee2829109dffaecabcd2ab49cbc3cfa
1f7aa6f21e113535e799cdb84b943a5fe9725890
/reconciliation_scripts/match.py
cbaceb845be4868d18bc8b1c2eec635faaf013ca
[]
no_license
ezl/recs
14911bdfc9e35e95b9b9427c5046ba94effe41bd
906c5ffd7d325b218b81aa56746c00134822099b
refs/heads/master
2020-06-04T03:23:26.457283
2011-02-15T02:04:29
2011-02-15T02:04:29
1,366,869
0
0
null
null
null
null
UTF-8
Python
false
false
5,473
py
from optionscity import OptionsCity from newedge import NewEdgeWebsite oc = OptionsCity(host="10.51.132.92", user="eric", passwd="ziu", db="optionscity") OC_positions = oc.get_positions() OC_trades = oc.get_trades() ne = NewEdgeWebsite(userid="ERICLIU", password="Newedge1") ne.connect() NE_positions = ne.retrieve_positions() NE_trades = ne.retrieve_trades() # position matching def total_position(instrument, positions): """Input a list of positions, where each position is a list [instrument_name, position]""" return sum([i[1] for i in filter(lambda x: x[0]==instrument, positions)]) def outer_join_positions(oc, ne): """Join OC and NE positions into one list. Inputs: lists of oc parsed positins and ne parsed positions format for each list is [ [instrument1, pos1], [instrument2, pos2], ..., [instrumentX, posX], ] Returns: list of both format is list of [instrument1, oc_pos, ne_pos] Fxn makes assumption that no instruments are repeated. """ instruments = set([i[0] for i in oc] + [i[0] for i in ne]) joined_positions = [[i, total_position(i, oc), total_position(i, ne)] for i in instruments] return joined_positions # save these suckers for reference OC_positions_full, NE_positions_full = OC_positions, NE_positions joined = outer_join_positions(OC_positions, NE_positions) position_exceptions = filter(lambda x: x[1] != x[2], joined) # trade matching def total_trade_and_cash(instrument, trades): """a trade in the trades list() looks like: [instrument_name, quantity, price]""" return (sum([i[1] for i in filter(lambda x: x[0]==instrument, trades)]), sum([i[1] * i[2] for i in filter(lambda x: x[0]==instrument, trades)]) ) def match_exact(oc, ne, matches=[]): oc.sort() ne.sort() oc = list(oc) ne = list(ne) """Remove exact matching legs from lists. Returns 2 lists""" for trade in list(oc): if trade in ne: matches.append((oc.pop(oc.index(trade)), ne.pop(ne.index(trade)))) return oc, ne, matches def match_split_qty(oc, ne, matched_oc_split_qty=[], matched_ne_split_qty=[]): """Match if a strike is the same but split or priced differently. For example: -500@16 == -100@16 plus -400@16 -200@24.5 == -100@24.4 plus -100@24.6 """ oc = list(oc) ne = list(ne) instruments = set([i[0] for i in oc] + [i[0] for i in ne]) for i in instruments: oc_net_traded, oc_net_cash = total_trade_and_cash(i, oc) ne_net_traded, ne_net_cash = total_trade_and_cash(i, ne) if oc_net_traded == ne_net_traded and oc_net_cash == ne_net_cash: # strike matches, lets take this sucker out matched_oc_split_qty.extend(filter(lambda x: x[0]==i, oc)) matched_ne_split_qty.extend(filter(lambda x: x[0]==i, ne)) oc = filter(lambda x: not x[0]==i, oc) ne = filter(lambda x: not x[0]==i, ne) return oc, ne, matched_oc_split_qty, matched_ne_split_qty def match_spread_legs(oc, ne, matched_oc_legs=[], matched_ne_legs=[]): """See if cash for matching positions matches. If so, they're spreads. This is a brutally inefficient process and 1 bad leg can screw it up.""" oc = list(oc) ne = list(ne) instruments = set([i[0] for i in oc] + [i[0] for i in ne]) potential_oc_legs = [] potential_ne_legs = [] for i in instruments: oc_net_traded, oc_net_cash = total_trade_and_cash(i, oc) ne_net_traded, ne_net_cash = total_trade_and_cash(i, ne) if oc_net_traded == ne_net_traded: # the quantity for a given instrument matches. # create a synthetic cash + position line item # remove individual legs from original sets potential_oc_legs.append([i, oc_net_traded, oc_net_cash]) potential_ne_legs.append([i, ne_net_traded, ne_net_cash]) # now we have all the matching legs. see if the net prices match if sum([i[2] for i in potential_oc_legs]) == sum([i[2] for i in potential_ne_legs]): # woohoo, cash matches! These are spread legs! # lets take them out of the system. matching_instruments = [i[0] for i in potential_oc_legs] for i in matching_instruments: # add the line item to matching_legs matched_oc_legs.extend(filter(lambda x: x[0]==i, oc)) matched_ne_legs.extend(filter(lambda x: x[0]==i, ne)) # remove the line item from oc and ne oc = filter(lambda x: not x[0]==i, oc) ne = filter(lambda x: not x[0]==i, ne) return oc, ne, matched_oc_legs, matched_ne_legs def are_spreads(oc, ne): """Determine if the contents of 2 lists are equivalent. Takes 2 lists of Trade objects, then determines if they are equivalent. If the cash matches and the quantities of each instrument are the same, it is a spread. """ pass # save these suckers for reference OC_trades_full, NE_trades_full = OC_trades, NE_trades OC_trades, NE_trades, exact_matches = match_exact(OC_trades, NE_trades) OC_trades, NE_trades, OC_matched_split_qty, NE_matched_split_qty = match_split_qty(OC_trades, NE_trades) OC_trades, NE_trades, OC_matched_legs, NE_matched_legs = match_spread_legs(OC_trades, NE_trades)
[ "ericzliu@gmail.com" ]
ericzliu@gmail.com
7acf4162defb50b77e972102390709cfca2861f2
e1fb5b619359d5e91d99c555c7c47b65995c63d2
/client.py
9fab4168694c9b9c18c7c795afed00969361698f
[ "MIT" ]
permissive
kacao/async_square
76526747e3d281b82c9c7fe5fa0a042f374932a9
075c5810e96bef27bba8334ba3410ca441eca2de
refs/heads/master
2020-08-02T16:09:18.978424
2019-09-28T00:58:14
2019-09-28T00:58:14
211,423,508
0
0
null
null
null
null
UTF-8
Python
false
false
489
py
import aiohttp import asyncio class Client: def __init__(self, api_key): self.api_key = api_key self.headers = { 'Authorization': 'Bearer %s' % config["api_key"], 'Content-Type': 'application/json' } async def fetch(self, url, params, session=None): if session == None: session = aiohttp.ClientSession() res = session.get(url, headers=self.headers, params=params) return await res.json()
[ "khanhncao@gmail.com" ]
khanhncao@gmail.com
f4c32a719ecb906620f028665698a70cf5f1af9a
e10551916a2dfc6f8fdbdece8e2b45d82f249bc1
/document_service/app/db_connection.py
5c1e3012af9d138ed5142091599bbe85d560f73b
[]
no_license
overmesgit/cogent
71367836583a8544fbd3d8fc946a7b5134cf5f3a
90c68853ffd929c5be76b9bb383330b74595e5e0
refs/heads/master
2023-08-15T18:38:38.646959
2021-10-11T03:20:19
2021-10-11T03:20:19
414,568,002
0
0
null
null
null
null
UTF-8
Python
false
false
85
py
import os from redis import Redis redis_con = Redis(host=os.environ['REDIS_HOST'])
[ "artem.bezu@localfolio.co.jp" ]
artem.bezu@localfolio.co.jp
f2313a933a7f5f4937398e9152afab0eee0d1305
e2fd4132181dffadffa6f00dc4417f0e6517aa7b
/index.py
e3d95469fb248b4bccea91207e6c4bd58692d2ff
[]
no_license
bruno-leal/covid19-portugal-dash
7ecba3f3b4e1cba3268bd9bbddc8713d546f2cf4
90dac9973cfefeb02ede23c42491e948e1726a98
refs/heads/master
2022-11-30T19:54:35.095849
2020-08-11T19:05:09
2020-08-11T19:05:09
264,713,087
0
0
null
null
null
null
UTF-8
Python
false
false
2,496
py
import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output from app import app, server from views import home, national, regional, local, maps import data_handler as dh app.layout = dbc.Container( [ dcc.Location(id='url', refresh=False), dbc.NavbarSimple( children=[ dbc.NavItem(dbc.NavLink("Início", href="/")), dbc.DropdownMenu( children=[ # dbc.DropdownMenuItem("Evolução", header=True), dbc.DropdownMenuItem("Nacional", href="/national"), dbc.DropdownMenuItem("Regiões", href="/regional"), dbc.DropdownMenuItem("Concelhos", href="/local"), ], nav=True, in_navbar=True, label="Evolução", ), dbc.NavItem(dbc.NavLink("Mapas", href="/maps")), ], dark=True, color="primary", className="p-2" ), dbc.Spinner(children=[html.Div(id='page-content')], color="light"), html.Br(), html.Hr(), html.Footer( [ dbc.Row( [ dbc.Col( html.P( [ "Fonte dos dados: ", html.A(children=["relatórios dários da DGS"], href="https://covid19.min-saude.pt/relatorio-de-situacao", target="_blank"), " (última actualização: {})".format(dh.get_last_update_date()), "." ] ), width={"size": 6, "order": 1}, ), dbc.Col( html.P( [ "Autor: ", html.A(children=["Bruno Leal"], href="https://github.com/bruno-leal/covid19-portugal-dash", target="_blank"), ] ), width={"size": 3, "order": "last", "offset": 3}, ) ] ), html.P( [ "Icon made by ", html.A(children=["Freepik"], href="https://www.flaticon.com/authors/freepik", title="Freepik", target="_blank"), " from ", html.A(children=["www.flaticon.com"], href="https://www.flaticon.com/", title="Flaticon", target="_blank"), "." ] ) ] ) ], fluid=True ) @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if (pathname == "/"): return home.get_contents() elif (pathname == '/national'): return national.get_contents() elif (pathname == '/regional'): return regional.get_contents() elif (pathname == '/local'): return local.get_contents() elif (pathname == '/maps'): return maps.get_contents() else: return '404' if __name__ == '__main__': app.run_server(debug=True)
[ "bruno.leal@brivcase.com" ]
bruno.leal@brivcase.com
fe4d5b1e385462a8b5231489ed0e541c2bc0eb15
afc1abc145d150b32b6447f551cd5f5d8381fba2
/leapday/models.py
0d8c7bd0601d5587c6d9935ab51fe59c9a01fbda
[ "MIT" ]
permissive
Zerack/zoll.me
3ca3d4ebef73de3d7aba073a641dffe26431d2ee
4781c4f5e712137a4726ce4c4d30015e364756c5
refs/heads/master
2020-04-14T16:58:41.768025
2013-08-05T22:59:52
2013-08-05T22:59:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,131
py
''' James D. Zoll 4/15/2013 Purpose: Defines models for the Leap Day application. License: This is a public work. ''' from django.db import models # Note that this is pretty heavily denormalized for better query performance. # Updates are done by a timed job, and can afford to be slow. class Good(models.Model): numeric_key = models.IntegerField() key = models.CharField(max_length=100) level = models.IntegerField(null=True) display_name = models.CharField(max_length=100) multiplier = models.FloatField(null=True) base_value = models.IntegerField(null=True) num_ingredients = models.IntegerField(null=True) description = models.CharField(max_length=1000) shopkeeper = models.CharField(max_length=100,null=True) occupation = models.CharField(max_length=1000,null=True) ingredient_0 = models.CharField(max_length=100,null=True) ingredient_1 = models.CharField(max_length=100,null=True) ingredient_2 = models.CharField(max_length=100,null=True) ingredient_3 = models.CharField(max_length=100,null=True) ingredient_4 = models.CharField(max_length=100,null=True)
[ "zolljd@gmail.com" ]
zolljd@gmail.com
14fc026351f132c8a3d1c72d56af027c3c0bf164
529ac67742e194405c792307d037293484c9c9ed
/08.深度卷积生成对抗网络-DCGAN/keras_02.STL.py
d386193dea749edffa439737f6273e514368abdd
[]
no_license
DingXiaoKe/BeginnerDL
810707a7b54413ecef78d7cbc050cbeee62a5c8b
bf9fc82b0c5f3db99d905f6441e16638a7125e45
refs/heads/master
2020-03-11T06:22:34.505354
2018-04-16T20:35:21
2018-04-16T20:35:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,198
py
from keras.layers import Input, Dense, LeakyReLU, Reshape,Conv2DTranspose, Conv2D,Flatten,Dropout,\ BatchNormalization, Activation, UpSampling2D, MaxPooling2D, ZeroPadding2D, Cropping2D from keras.models import Model,load_model, Sequential from keras.optimizers import SGD,RMSprop, Adam from keras.utils import multi_gpu_model import numpy as np import pickle from matplotlib import pyplot as plt from keras.preprocessing import image from lib.config.STLConfig import STLConfig from lib.datareader.DataReaderForClassification import DataReader from lib.utils.progressbar.ProgressBar import ProgressBar from keras.initializers import RandomNormal conv_init = RandomNormal(0, 0.02) gamma_init = RandomNormal(1., 0.02) config = STLConfig() def builder_generator(isize=96, nz=100, nc=3, ngf=64): # cngf= ngf//2 # tisize = isize # while tisize > 5: # cngf = cngf * 2 # tisize = tisize // 2 # _ = inputs = Input(shape=(nz,)) # _ = Reshape((1,1,nz))(_) # _ = Conv2DTranspose(filters=cngf, kernel_size=tisize, strides=1, use_bias=False, # kernel_initializer = conv_init, # name = 'initial.{0}-{1}.convt'.format(nz, cngf))(_) # _ = BatchNormalization(axis=1, epsilon=1.01e-5, name = 'initial.{0}.batchnorm'.format(cngf))(_, training=1) # _ = Activation("relu", name = 'initial.{0}.relu'.format(cngf))(_) # csize, cndf = tisize, cngf # # while csize < isize//2: # in_feat = cngf # out_feat = cngf//2 # _ = Conv2DTranspose(filters=out_feat, kernel_size=4, strides=2, use_bias=False, # kernel_initializer = conv_init, # name = 'pyramid.{0}-{1}.convt'.format(in_feat, out_feat) # ) (_) # _ = Cropping2D(cropping=1, name = 'pyramid.{0}.cropping'.format(in_feat) )(_) # _ = BatchNormalization(axis=1, epsilon=1.01e-5, name = 'pyramid.{0}.batchnorm'.format(out_feat))(_, training=1) # _ = Activation("relu", name = 'pyramid.{0}.relu'.format(out_feat))(_) # csize, cngf = csize*2, cngf//2 # _ = Conv2DTranspose(filters=nc, kernel_size=4, strides=2, use_bias=False, # kernel_initializer = conv_init, # name = 'final.{0}-{1}.convt'.format(cngf, nc) # )(_) # _ = Cropping2D(cropping=1, name = 'final.{0}.cropping'.format(nc) )(_) # outputs = Activation("tanh", name = 'final.{0}.tanh'.format(nc))(_) # return Model(inputs=inputs, outputs=outputs) noise = Input(shape=(nz,)) network = Dense(units=1024)(noise) network = Activation('tanh')(network) network = Dense(units=128*8*8)(network) network = BatchNormalization()(network) network = Activation('tanh')(network) network = Reshape(target_shape=(8,8,128))(network) network = UpSampling2D()(network) network = Conv2DTranspose(filters=64, kernel_size=4, strides=2, padding='same')(network) network = BatchNormalization()(network) network = Activation('tanh')(network) network = Conv2DTranspose(filters=3, kernel_size=4, strides=3, padding='same')(network) network = Activation('tanh')(network) model = Model(inputs=noise, outputs=network) return model def builder_discriminator(isize = 96, nc = 3, ndf = 64): # inputs = Input(shape=(isize, isize, nc)) # network = ZeroPadding2D(name = 'initial.padding.{0}'.format(nc))(inputs) # network = Conv2D(filters=ndf, kernel_size=4, strides=2, use_bias=False, # kernel_initializer = conv_init, # name = 'initial.conv.{0}-{1}'.format(nc, ndf) # ) (network) # network = LeakyReLU(alpha=0.2, name = 'initial.relu.{0}'.format(ndf))(network) # csize, cndf = isize // 2, ndf # while csize > 5: # in_feat = cndf # out_feat = cndf*2 # network = ZeroPadding2D(name = 'pyramid.{0}.padding'.format(in_feat))(network) # network = Conv2D(filters=out_feat, kernel_size=4, strides=2, use_bias=False, # kernel_initializer = conv_init, # name = 'pyramid.{0}-{1}.conv'.format(in_feat, out_feat) # ) (network) # network = BatchNormalization(name = 'pyramid.{0}.batchnorm'.format(out_feat), # axis=1, epsilon=1.01e-5)(network, training=1) # network = LeakyReLU(alpha=0.2, name = 'pyramid.{0}.relu'.format(out_feat))(network) # csize, cndf = csize//2, cndf*2 # network = Conv2D(filters=1, kernel_size=csize, strides=1, use_bias=False, # name = 'final.{0}-{1}.conv'.format(cndf, 1) # ) (network) # outputs = Flatten()(network) # return Model(inputs=inputs, outputs=outputs) img = Input(shape=(96,96,3)) network = Conv2D(32, kernel_size=2, strides=2, padding='same')(img) network = Activation('relu')(network) network = MaxPooling2D(pool_size=(2,2))(network) network = Conv2D(64, kernel_size=3, strides=2, padding="same")(network) # network = ZeroPadding2D(padding=((0,1),(0,1)))(network) network = Activation('relu')(network) network = BatchNormalization(momentum=0.8)(network) network = Conv2D(128, kernel_size=3, strides=2, padding="same")(network) network = Activation('relu')(network) network = BatchNormalization(momentum=0.8)(network) network = MaxPooling2D(pool_size=(2,2))(network) network = Conv2D(256, kernel_size=3, strides=1, padding="same")(network) network = Activation('relu')(network) network = Flatten()(network) network = Dense(1, activation='sigmoid')(network) model = Model(inputs=img, outputs=network) return model PHRASE = "TRAIN" GPU_NUM = 1 batchSize = 50 epochs = 60 randomDim = 100 if PHRASE == "TRAIN": # adam = Adam(lr=0.0002, beta_1=0.5) reader = DataReader("../ganData/STL/") imageList, labelList = reader.readData(image_shape=(config.IMAGE_SIZE, config.IMAGE_SIZE, config.IMAGE_CHANNEL), subFolder='1') discriminator = builder_discriminator() # discriminator = multi_gpu_model(discriminator, GPU_NUM) discriminator.compile(optimizer=SGD(lr=0.003),#RMSprop(lr=0.0003, clipvalue=1.0, decay=1e-8), loss='binary_crossentropy') discriminator.trainable = False generator = builder_generator(nz=randomDim) generator.compile(optimizer=SGD(lr=0.003),#RMSprop(lr=0.0003, clipvalue=1.0, decay=1e-8), loss='binary_crossentropy') ganInput = Input(shape=(randomDim,)) ganOutput = discriminator(generator(ganInput)) dcgan = Model(inputs=ganInput, outputs=ganOutput) if GPU_NUM > 1: dcgan = multi_gpu_model(dcgan, GPU_NUM) dcgan.compile(loss='binary_crossentropy', optimizer= SGD(lr=0.003)#RMSprop(lr=0.0003, clipvalue=1.0, decay=1e-8) ) dLosses = [] aLosses = [] dloss = 0 aloss = 0 x_train = imageList y_train = labelList x_train = (x_train.reshape( (x_train.shape[0],) + (config.IMAGE_SIZE, config.IMAGE_SIZE, config.IMAGE_CHANNEL)).astype('float32')) / 255 batchCount = x_train.shape[0] // batchSize print('Epochs:', epochs) print('Batch size:', batchSize) print('Batches per epoch:', batchCount) progBar = ProgressBar(epochs, batchCount, "D Loss:%.3f;G Loss:%.3f") samples_image = [] start = 0 for epoch in range(1, (epochs + 1)): for _ in range(batchCount): noise = np.random.normal(size=(batchSize, 100)) generatedImages = generator.predict(noise) imageBatch = x_train[np.random.randint(0, x_train.shape[0], size=batchSize)] combined_images = np.concatenate([generatedImages, imageBatch]) labels = np.concatenate([np.ones((batchSize, 1)), np.zeros((batchSize, 1))]) labels += 0.05 * np.random.random(labels.shape) d_loss = discriminator.train_on_batch(combined_images, labels) noise = np.random.normal(size=[batchSize, 100]) yGen = np.zeros(batchSize) aloss = dcgan.train_on_batch(noise, yGen) progBar.show(d_loss, aloss) dLosses.append(dloss) aLosses.append(aloss) if epoch == 1 or epoch % 5 == 0: samples_image.append(generatedImages) img = image.array_to_img(generatedImages[0] * 255., scale=False) img.save('generated_airplane' + str(epoch) + '.png') with open('train_samples.pkl', 'wb') as f: pickle.dump(samples_image, f) generator.save('stl_generator.h5') else: generator = load_model("cifar_generator.h5") noise = np.random.normal(size=[batchSize, 100]) generated_images = generator.predict(noise) plt.figure(num='astronaut',figsize=(8,8)) # generated_images = generated_images * 2 - 1 for index, img in enumerate(generated_images): img = image.array_to_img(img * 255., scale=False) plt.subplot(10,10,index+1) plt.imshow(img) plt.show()
[ "jeffcobile@gmail.com" ]
jeffcobile@gmail.com
217fb8aa600423c6be4bfa3ca278726e03d69d72
ba7550a0182ac08f319cc7826f539d18669bc726
/Step7_Area_CSV/Cre_Bax/Creat_SGZ_Area_CSV_Cre_Bax.py
92cdef0391c616131e88bd449aab62cba8689e1a
[]
no_license
keriber/Hilar-Prox1-Cells-Quantification
75c5d1c8ef1bc30ceb6f758975a6cc674259d124
474015d775c938d295df32ee694342a623778072
refs/heads/master
2021-01-22T05:05:27.535527
2015-07-12T16:16:33
2015-07-12T16:16:33
22,692,094
0
0
null
null
null
null
UTF-8
Python
false
false
1,137
py
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 14:52:00 2013 @author: kbermudez-hernandez """ import os import numpy as np from pandas import Series, DataFrame import pandas as pd import re #Code to make list of files and vdevide them in slide1 and slide2 path = "G:\Keria\Quntification_CreBax\SGZ\Area" os.chdir(path)#change directory from pandas import Series, DataFrame FileNames=[] Values = [] for file in os.listdir(path): if file.endswith(".txt"): FileNames.append(os.path.basename(file)[:-4]) Value = pd.read_table(file,sep='\t') Values.append(Value) Data = dict(zip(FileNames,Values)) globals().update(Data) for file in FileNames: Data[file] = Data[file].rename(columns= {'Label':'SectionsID', 'Area':'SGZ Area'}) #Data[file]['Hilar Area']= Data[file]['Hilar Area'] * 0.136342782003905 Data[file].SectionsID = Data[file].SectionsID.str[:-4] X = Data[file].SectionsID.str[0:2] Data[file].index = X Data[file].index.name ='Sections' for file in FileNames: Data[file].to_csv(file + '_Area'+'.csv') ##Data[file].index = X.astype(int)
[ "keria.bermudez@gmail.com" ]
keria.bermudez@gmail.com
647371f8a58889fce870589d6546fc9869a0ae28
8a79b2d419c803fa96aad9106a0fbc1adf7c95e0
/todo/migrations/0002_auto_20200805_0853.py
ffff244dcc9806989a3102e508912430b943ea4b
[]
no_license
BADGUY0592/todolist-in-django
d88c78817c0beb83af18960153a1afa32269efc0
73ad4d22b2f5c7691e4dfd394ac2681035e6ea10
refs/heads/master
2022-12-02T14:25:01.100453
2020-08-15T03:10:29
2020-08-15T03:10:29
283,126,342
0
0
null
null
null
null
UTF-8
Python
false
false
390
py
# Generated by Django 3.1rc1 on 2020-08-05 03:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('todo', '0001_initial'), ] operations = [ migrations.AlterField( model_name='todo', name='datecompleted', field=models.DateTimeField(blank=True, null=True), ), ]
[ "thebadguyisbck@gmail.com" ]
thebadguyisbck@gmail.com
b6abacc8432bcbfde3c88b03c2c32d3875ec5160
a2b84976da28ebca5ba20eba895d4f0748a16aca
/Model/ModelMFR/Surveillance/mobile_part_data.py
d5a5979629b8574cc47039ebe9afca73a9d5ae8f
[]
no_license
Igor9rov/TrackingAndIdentificationModel
f128439a856a370b520dd89c54b92dbea06aba7f
4812a46681535e7f75e2bcdda902c73b4f229d90
refs/heads/master
2020-07-25T22:19:59.588998
2020-01-24T19:31:53
2020-01-24T19:31:53
208,440,378
0
0
null
null
null
null
UTF-8
Python
false
false
2,243
py
from math import cos, sin, pi import numpy as np class MobilePartData: """Класс, содержащий данные по подвижной части антенны""" __slots__ = ("gamma", "eps", "beta", "corrupted_beta", "matrix_gamma", "matrix_eps", "matrix_beta", "matrix_corrupted_beta", "transform_matrix", "corrupted_transform_matrix") def __init__(self, error_beta: int = 0) -> None: # Пересчёт ошибки по углу в радианы error_beta_rad = error_beta * pi / (180 * 60) # Угол скручивания антенны gamma = 0. # Угол наклона антенны eps = pi / 6 # Азимут оси антенны beta = 0. # Азимут оси антенные с ошибками corrupted_beta = beta + error_beta_rad # Матрицы поворота по каждому из углов matrix_gamma = np.array([[1., 0., 0.], [0., cos(gamma), sin(gamma)], [0., -sin(gamma), cos(gamma)]]) matrix_eps = np.array([[cos(eps), sin(eps), 0.], [-sin(eps), cos(eps), 0.], [0., 0., 1.]]) matrix_beta = np.array([[cos(beta), 0., sin(beta)], [0., 1., 0.], [-sin(beta), 0., cos(beta)]]) matrix_corrupted_beta = np.array([[cos(corrupted_beta), 0., sin(corrupted_beta)], [0., 1., 0.], [-sin(corrupted_beta), 0., cos(corrupted_beta)]]) # Матрица, отвечающая за подвижную часть антенны self.transform_matrix = matrix_gamma @ matrix_eps @ matrix_beta # Матрица, отвечающая за подвижную часть антенны, определённая с ошибками self.corrupted_transform_matrix = matrix_gamma @ matrix_eps @ matrix_corrupted_beta
[ "devyatyarov@phystech.edu" ]
devyatyarov@phystech.edu
5ee440a12b0c08aa32db9a6bbcfae676730daa78
3e4b2c0b97b11fe9837fbf5d17a708fce6cf69b9
/Search/public/NeuroML2_To_HTML/convert.py
98c99491b4d55bb7231d09f3b8f11d3c2c11b9b9
[]
no_license
JustasB/neuroml-db
48a2c3337a8bd09cba70170aa10526c6d10712f3
382f56ab732a5ce71050d981a208f0f869c93fa5
refs/heads/master
2020-12-07T15:17:16.727888
2015-06-10T01:23:56
2015-06-10T01:23:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
324
py
import lxml.etree as ET import sys try: infile = sys.argv[1] except: print "Usage: convert.py _fileToConvert_" sys.exit(1) xsl_file = 'NeuroML2_To_HTML.xsl' dom = ET.parse(infile) xslt = ET.parse(xsl_file) transform = ET.XSLT(xslt) newdom = transform(dom) print(ET.tostring(newdom, pretty_print=True))
[ "birgiolasj@yahoo.com" ]
birgiolasj@yahoo.com
907bec29fd5d18481e0d83c1bc35cc3a3287219d
0a5c895fa540bf5cef6b4388fd691ac532cd4fd2
/stocktools/urls.py
fd4bc4bb844c390ad3d972d9d98574022107a371
[]
no_license
BenTheNetizen/StockTools
6223c5ffdf9e107132dd4864d31542ca773a8e83
12ddfcf58c54f51feb81039fb78f8654bdedd5ad
refs/heads/main
2023-04-13T03:29:51.872839
2021-04-16T04:52:39
2021-04-16T04:52:39
351,594,919
0
0
null
null
null
null
UTF-8
Python
false
false
961
py
"""stocktools URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/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 from django.urls import include from django.views.generic import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('stockscraper/', include('stockscraper.urls')), path('', RedirectView.as_view(url='stockscraper/', permanent=True)), ]
[ "benisin5@gmail.com" ]
benisin5@gmail.com
d9cf6b8204ba6f43386bd06b984cb51ac0edbaa6
f046c23d73d3e60e97ea90d6961edad1139a6f8d
/Chrome_Extension_Tests/__init__.py
78c7b143a88a7899a1de1a06c524ed7966c96d79
[]
no_license
reidzesna/Zang_Products_Auto_Test_Python
01bb3fe82d2874e9d0cb2c56764f9acdef3cca3b
072983c5f38da2fd5e023991d860dcd329cb31cb
refs/heads/master
2021-01-20T07:41:47.391009
2017-09-07T11:36:02
2017-09-07T11:36:02
90,029,500
0
2
null
null
null
null
UTF-8
Python
false
false
50
py
''' Created on May 17, 2017 @author: qcadmin '''
[ "qcadmin@ReidZ-PC.ex2010.local" ]
qcadmin@ReidZ-PC.ex2010.local
755db2aff05eab3ccb6b05364252ec809845698e
b6166f9494b1e5867b0fd23b70d2479de7d2effc
/transform.py
2b82a57a78c917273c74c7e414ca911e41324d0f
[]
no_license
SummerStoneS/depp_426
b7f74af51c9c04274d78c40b71d97c071d4e56a0
83f2a79242298080dbed0180104b263dfe3ad6b0
refs/heads/master
2020-03-13T10:29:14.428323
2018-05-03T09:34:02
2018-05-03T09:34:02
131,084,410
0
0
null
null
null
null
UTF-8
Python
false
false
5,383
py
import pandas as pd from time import sleep from amap import AMap from tqdm import tqdm import numpy as np import datetime import re """ get_location: 将所有取货地址按照中文地址名字转化成经纬度,查不到的返回np.nan split_location: 把上一步经纬度列解析成经度和纬度两列 转换时间 """ orders_columns = ['订单号', '最早接货时间', '最晚接货时间', '开单体积', '接货地址'] static_cars_columns = ["车牌号", "净空"] dynamic_cars_columns = ["车牌号", '订单号', '经度', '纬度', '净空', '取货状态'] def get_location(source_data, use_col='接货地址'): """ :param source_data: :param use_col: :param save_file: :return: 根据接货地址,调用高德api,返回一列新增的经纬度列 """ data = source_data[use_col].drop_duplicates() # 避免查询重复的地址 # api = AMap('d928d8749358e9245c9cec5c06aa9d06') # 高德地图的key api = AMap('b9cacaf85e70270ab2f15e81b2a942ce') # xulei的API result = [] for item in tqdm(data): try: resp = api.geocode(item, '上海') result.append(resp['location']) except: result.append(np.nan) # 没有找到地址的返回nan # print(item) sleep(0.05) location = pd.Series(result, name='经纬度') data = data.reset_index(drop=True) data = pd.concat([data, location], axis=1) if "经纬度" in source_data.columns: del source_data['经纬度'] location_data = pd.merge(source_data, data, left_on=use_col, right_on=use_col, how='left') return location_data def split_location(raw_data, use_col='经纬度'): """ :param raw_data: :param use_col: :return: 原数据增加经度一列,纬度一列 """ raw_data['纬度'] = raw_data[use_col].apply(lambda x: x.split(',')[1]).astype(float) raw_data['经度'] = raw_data[use_col].apply(lambda x: x.split(',')[0]).astype(float) return raw_data def log(msg): with open("log.txt", "a") as f: f.write(msg) f.write("\n") def convert_time(x): """ :param x: 时间 :return: 计算距离当日0点的秒数,满足Jsprit对输入时间的要求 """ b = datetime.datetime(1899, 12, 30, tzinfo=datetime.timezone.utc) + datetime.timedelta( days=x) time = b.time() return time.hour * 60 * 60 + time.minute * 60 + time.second # 距离当天零点对应的秒数 def convert_date(x, type='weekday'): b = datetime.datetime(1899, 12, 30, tzinfo=datetime.timezone.utc) + datetime.timedelta(days=x) if type == 'weekday': return b.weekday() else: return b def format_time(x): """ :param x: Jsprit 跑出来的5位数时间 :return: 转换成%H:%M:%S """ x = float(x) if x != 0: hours = x / 60 / 60 hour = int(hours) minutes = (hours - int(hours)) * 60 minute = int(minutes) seconds = (minutes - minute) * 60 second = int(seconds) return "{}:{}:{}".format(hour, minute, second) else: return np.nan def fill_na_for_notnumber(col): try: a = float(col) except: a = np.nan return a def check_columns(data, type='orders'): """ :param data: 待接单信息或者是车辆信息 :param type: :return: 检查该有的列名是不是都有 """ if type == 'orders': included_cols = orders_columns elif type == 'static_cars': included_cols = static_cars_columns elif type == 'dynamic_cars': included_cols = dynamic_cars_columns flag = None for column_name in included_cols: if column_name not in data.columns: log("{}没有{}列,请检查列名".format(type, column_name)) flag = 1 if flag: raise ValueError else: return data[included_cols] def transform_orders(orders): orders = check_columns(orders) orders['开单体积'] = orders['开单体积'].apply(fill_na_for_notnumber) # 处理没有体积信息的订单 orders['开单体积'] = orders['开单体积'].fillna(0.4) return orders def convert_plate_number(data, use_col='车牌号'): """ :param data: :param use_col: 车牌号 :return: 去掉车牌号前的“沪”字 """ data[use_col] = data[use_col].apply(lambda x: re.sub(u'[\u4E00-\u9FA5]+', '', x)) def transform_cars(cars, type='static'): if type == 'static': cars = check_columns(cars, type='static_cars') # 检查列名 cars_info = cars[['车牌号', '净空']].drop_duplicates().reset_index(drop=True) # 车牌号不能重复 if len(cars_info) != len(cars): log("有重复的车牌号,请修改后再次上传") raise ValueError elif type == 'dynamic': cars = check_columns(cars, type='dynamic_cars') cars_info = cars cars_info['净空'] = cars_info['净空'].apply(fill_na_for_notnumber) # 处理没有净空的车 cars_info['净空'].fillna(14, inplace=True) convert_plate_number(cars_info, use_col='车牌号') # 去掉车牌号前的“沪”字 return cars_info if __name__ == '__main__': pass
[ "sruo688@163.com" ]
sruo688@163.com
503e6216af7bcfa3315bb2a4a4b0598830b093ae
65e0a2c39f3397d28af194951cf7b83d850e44b4
/.vscode-oss/extensions/ms-python.python-2019.4.11987/pythonFiles/lib/python/ptvsd/_vendored/pydevd/_pydevd_bundle/_debug_adapter/pydevd_schema.py
c381f3f979ddbcd62518899b2baa46f98fa38817
[ "MIT" ]
permissive
arjunchandran/newrepo
45abce0d80c841ba8b7034a79cb1496c467d852f
e89f8fb734b09c4b2eb857bbf0e52d9fd5de91e5
refs/heads/master
2021-01-05T12:27:23.081811
2020-02-17T04:57:24
2020-02-17T04:57:24
241,023,306
0
0
null
null
null
null
UTF-8
Python
false
false
470,678
py
# Automatically generated code. # Do not edit manually. # Generated by running: __main__pydevd_gen_debug_adapter_protocol.py from .pydevd_base_schema import BaseSchema, register, register_request, register_response, register_event @register class ProtocolMessage(BaseSchema): """ Base class of requests, responses, and events. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "description": "Message type.", "_enum": [ "request", "response", "event" ] } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, type, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: Message type. :param integer seq: Sequence number. """ self.type = type self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) seq = self.seq dct = { 'type': type, 'seq': seq, } dct.update(self.kwargs) return dct @register class Request(BaseSchema): """ A client or debug adapter initiated request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "description": "The command to execute." }, "arguments": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Object containing arguments for the command." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, command, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: The command to execute. :param integer seq: Sequence number. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] arguments: Object containing arguments for the command. """ self.type = 'request' self.command = command self.seq = seq self.arguments = arguments self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command seq = self.seq arguments = self.arguments dct = { 'type': type, 'command': command, 'seq': seq, } if arguments is not None: dct['arguments'] = arguments dct.update(self.kwargs) return dct @register class Event(BaseSchema): """ A debug adapter initiated event. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "description": "Type of event." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Event-specific information." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, event, seq=-1, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: Type of event. :param integer seq: Sequence number. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Event-specific information. """ self.type = 'event' self.event = event self.seq = seq self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event seq = self.seq body = self.body dct = { 'type': type, 'event': event, 'seq': seq, } if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register class Response(BaseSchema): """ Response for a request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_response('error') @register class ErrorResponse(BaseSchema): """ On error (whenever 'success' is false), the body can provide more details. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "error": { "$ref": "#/definitions/Message", "description": "An optional, structured error message." } } } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param ErrorResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = ErrorResponseBody() else: self.body = ErrorResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ErrorResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_event('initialized') @register class InitializedEvent(BaseSchema): """ This event indicates that the debug adapter is ready to accept configuration requests (e.g. SetBreakpointsRequest, SetExceptionBreakpointsRequest). A debug adapter is expected to send this event when it is ready to accept configuration requests (but not before the 'initialize' request has finished). The sequence of events/requests is as follows: - adapters sends 'initialized' event (after the 'initialize' request has returned) - frontend sends zero or more 'setBreakpoints' requests - frontend sends one 'setFunctionBreakpoints' request - frontend sends a 'setExceptionBreakpoints' request if one or more 'exceptionBreakpointFilters' have been defined (or if 'supportsConfigurationDoneRequest' is not defined or false) - frontend sends other future configuration requests - frontend sends one 'configurationDone' request to indicate the end of the configuration. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "initialized" ] }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Event-specific information." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param integer seq: Sequence number. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Event-specific information. """ self.type = 'event' self.event = 'initialized' self.seq = seq self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event seq = self.seq body = self.body dct = { 'type': type, 'event': event, 'seq': seq, } if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_event('stopped') @register class StoppedEvent(BaseSchema): """ The event indicates that the execution of the debuggee has stopped due to some condition. This can be caused by a break point previously set, a stepping action has completed, by executing a debugger statement etc. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "stopped" ] }, "body": { "type": "object", "properties": { "reason": { "type": "string", "description": "The reason for the event.\nFor backward compatibility this string is shown in the UI if the 'description' attribute is missing (but it must not be translated).", "_enum": [ "step", "breakpoint", "exception", "pause", "entry", "goto" ] }, "description": { "type": "string", "description": "The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and must be translated." }, "threadId": { "type": "integer", "description": "The thread which was stopped." }, "preserveFocusHint": { "type": "boolean", "description": "A value of true hints to the frontend that this event should not change the focus." }, "text": { "type": "string", "description": "Additional information. E.g. if reason is 'exception', text contains the exception name. This string is shown in the UI." }, "allThreadsStopped": { "type": "boolean", "description": "If 'allThreadsStopped' is true, a debug adapter can announce that all threads have stopped.\n- The client should use this information to enable that all threads can be expanded to access their stacktraces.\n- If the attribute is missing or false, only the thread with the given threadId can be expanded." } }, "required": [ "reason" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param StoppedEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'stopped' if body is None: self.body = StoppedEventBody() else: self.body = StoppedEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != StoppedEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('continued') @register class ContinuedEvent(BaseSchema): """ The event indicates that the execution of the debuggee has continued. Please note: a debug adapter is not expected to send this event in response to a request that implies that execution continues, e.g. 'launch' or 'continue'. It is only necessary to send a 'continued' event if there was no previous request that implied this. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "continued" ] }, "body": { "type": "object", "properties": { "threadId": { "type": "integer", "description": "The thread which was continued." }, "allThreadsContinued": { "type": "boolean", "description": "If 'allThreadsContinued' is true, a debug adapter can announce that all threads have continued." } }, "required": [ "threadId" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param ContinuedEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'continued' if body is None: self.body = ContinuedEventBody() else: self.body = ContinuedEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ContinuedEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('exited') @register class ExitedEvent(BaseSchema): """ The event indicates that the debuggee has exited and returns its exit code. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "exited" ] }, "body": { "type": "object", "properties": { "exitCode": { "type": "integer", "description": "The exit code returned from the debuggee." } }, "required": [ "exitCode" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param ExitedEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'exited' if body is None: self.body = ExitedEventBody() else: self.body = ExitedEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ExitedEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('terminated') @register class TerminatedEvent(BaseSchema): """ The event indicates that debugging of the debuggee has terminated. This does **not** mean that the debuggee itself has exited. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "terminated" ] }, "body": { "type": "object", "properties": { "restart": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "A debug adapter may set 'restart' to true (or to an arbitrary object) to request that the front end restarts the session.\nThe value is not interpreted by the client and passed unmodified as an attribute '__restart' to the 'launch' and 'attach' requests." } } } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param integer seq: Sequence number. :param TerminatedEventBody body: """ self.type = 'event' self.event = 'terminated' self.seq = seq if body is None: self.body = TerminatedEventBody() else: self.body = TerminatedEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != TerminatedEventBody else body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event seq = self.seq body = self.body dct = { 'type': type, 'event': event, 'seq': seq, } if body is not None: dct['body'] = body.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register_event('thread') @register class ThreadEvent(BaseSchema): """ The event indicates that a thread has started or exited. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "thread" ] }, "body": { "type": "object", "properties": { "reason": { "type": "string", "description": "The reason for the event.", "_enum": [ "started", "exited" ] }, "threadId": { "type": "integer", "description": "The identifier of the thread." } }, "required": [ "reason", "threadId" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param ThreadEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'thread' if body is None: self.body = ThreadEventBody() else: self.body = ThreadEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ThreadEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('output') @register class OutputEvent(BaseSchema): """ The event indicates that the target has produced some output. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "output" ] }, "body": { "type": "object", "properties": { "category": { "type": "string", "description": "The output category. If not specified, 'console' is assumed.", "_enum": [ "console", "stdout", "stderr", "telemetry" ] }, "output": { "type": "string", "description": "The output to report." }, "variablesReference": { "type": "number", "description": "If an attribute 'variablesReference' exists and its value is > 0, the output contains objects which can be retrieved by passing 'variablesReference' to the 'variables' request." }, "source": { "$ref": "#/definitions/Source", "description": "An optional source location where the output was produced." }, "line": { "type": "integer", "description": "An optional source location line where the output was produced." }, "column": { "type": "integer", "description": "An optional source location column where the output was produced." }, "data": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Optional data to report. For the 'telemetry' category the data will be sent to telemetry, for the other categories the data is shown in JSON format." } }, "required": [ "output" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param OutputEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'output' if body is None: self.body = OutputEventBody() else: self.body = OutputEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != OutputEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('breakpoint') @register class BreakpointEvent(BaseSchema): """ The event indicates that some information about a breakpoint has changed. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "breakpoint" ] }, "body": { "type": "object", "properties": { "reason": { "type": "string", "description": "The reason for the event.", "_enum": [ "changed", "new", "removed" ] }, "breakpoint": { "$ref": "#/definitions/Breakpoint", "description": "The 'id' attribute is used to find the target breakpoint and the other attributes are used as the new values." } }, "required": [ "reason", "breakpoint" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param BreakpointEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'breakpoint' if body is None: self.body = BreakpointEventBody() else: self.body = BreakpointEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != BreakpointEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('module') @register class ModuleEvent(BaseSchema): """ The event indicates that some information about a module has changed. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "module" ] }, "body": { "type": "object", "properties": { "reason": { "type": "string", "description": "The reason for the event.", "enum": [ "new", "changed", "removed" ] }, "module": { "$ref": "#/definitions/Module", "description": "The new, changed, or removed module. In case of 'removed' only the module id is used." } }, "required": [ "reason", "module" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param ModuleEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'module' if body is None: self.body = ModuleEventBody() else: self.body = ModuleEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ModuleEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('loadedSource') @register class LoadedSourceEvent(BaseSchema): """ The event indicates that some source has been added, changed, or removed from the set of all loaded sources. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "loadedSource" ] }, "body": { "type": "object", "properties": { "reason": { "type": "string", "description": "The reason for the event.", "enum": [ "new", "changed", "removed" ] }, "source": { "$ref": "#/definitions/Source", "description": "The new, changed, or removed source." } }, "required": [ "reason", "source" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param LoadedSourceEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'loadedSource' if body is None: self.body = LoadedSourceEventBody() else: self.body = LoadedSourceEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != LoadedSourceEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('process') @register class ProcessEvent(BaseSchema): """ The event indicates that the debugger has begun debugging a new process. Either one that it has launched, or one that it has attached to. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "process" ] }, "body": { "type": "object", "properties": { "name": { "type": "string", "description": "The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js." }, "systemProcessId": { "type": "integer", "description": "The system process id of the debugged process. This property will be missing for non-system processes." }, "isLocalProcess": { "type": "boolean", "description": "If true, the process is running on the same computer as the debug adapter." }, "startMethod": { "type": "string", "enum": [ "launch", "attach", "attachForSuspendedLaunch" ], "description": "Describes how the debug engine started debugging this process.", "enumDescriptions": [ "Process was launched under the debugger.", "Debugger attached to an existing process.", "A project launcher component has launched a new process in a suspended state and then asked the debugger to attach." ] } }, "required": [ "name" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param ProcessEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'process' if body is None: self.body = ProcessEventBody() else: self.body = ProcessEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ProcessEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_event('capabilities') @register class CapabilitiesEvent(BaseSchema): """ The event indicates that one or more capabilities have changed. Since the capabilities are dependent on the frontend and its UI, it might not be possible to change that at random times (or too late). Consequently this event has a hint characteristic: a frontend can only be expected to make a 'best effort' in honouring individual capabilities but there are no guarantees. Only changed capabilities need to be included, all other capabilities keep their values. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "capabilities" ] }, "body": { "type": "object", "properties": { "capabilities": { "$ref": "#/definitions/Capabilities", "description": "The set of updated capabilities." } }, "required": [ "capabilities" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string event: :param CapabilitiesEventBody body: :param integer seq: Sequence number. """ self.type = 'event' self.event = 'capabilities' if body is None: self.body = CapabilitiesEventBody() else: self.body = CapabilitiesEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != CapabilitiesEventBody else body self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) event = self.event body = self.body seq = self.seq dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register_request('runInTerminal') @register class RunInTerminalRequest(BaseSchema): """ This request is sent from the debug adapter to the client to run a command in a terminal. This is typically used to launch the debuggee in a terminal provided by the client. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "runInTerminal" ] }, "arguments": { "type": "RunInTerminalRequestArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param RunInTerminalRequestArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'runInTerminal' if arguments is None: self.arguments = RunInTerminalRequestArguments() else: self.arguments = RunInTerminalRequestArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != RunInTerminalRequestArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class RunInTerminalRequestArguments(BaseSchema): """ Arguments for 'runInTerminal' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "kind": { "type": "string", "enum": [ "integrated", "external" ], "description": "What kind of terminal to launch." }, "title": { "type": "string", "description": "Optional title of the terminal." }, "cwd": { "type": "string", "description": "Working directory of the command." }, "args": { "type": "array", "items": { "type": "string" }, "description": "List of arguments. The first argument is the command to run." }, "env": { "type": "object", "description": "Environment key-value pairs that are added to or removed from the default environment.", "additionalProperties": { "type": [ "string", "null" ], "description": "Proper values must be strings. A value of 'null' removes the variable from the environment." } } } __refs__ = set(['env']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, cwd, args, kind=None, title=None, env=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string cwd: Working directory of the command. :param array args: List of arguments. The first argument is the command to run. :param string kind: What kind of terminal to launch. :param string title: Optional title of the terminal. :param RunInTerminalRequestArgumentsEnv env: Environment key-value pairs that are added to or removed from the default environment. """ self.cwd = cwd self.args = args self.kind = kind self.title = title if env is None: self.env = RunInTerminalRequestArgumentsEnv() else: self.env = RunInTerminalRequestArgumentsEnv(update_ids_from_dap=update_ids_from_dap, **env) if env.__class__ != RunInTerminalRequestArgumentsEnv else env self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) cwd = self.cwd args = self.args kind = self.kind title = self.title env = self.env dct = { 'cwd': cwd, 'args': args, } if kind is not None: dct['kind'] = kind if title is not None: dct['title'] = title if env is not None: dct['env'] = env.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register_response('runInTerminal') @register class RunInTerminalResponse(BaseSchema): """ Response to 'runInTerminal' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "processId": { "type": "number", "description": "The process ID." }, "shellProcessId": { "type": "number", "description": "The process ID of the terminal shell." } } } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param RunInTerminalResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = RunInTerminalResponseBody() else: self.body = RunInTerminalResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != RunInTerminalResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('initialize') @register class InitializeRequest(BaseSchema): """ The 'initialize' request is sent as the first request from the client to the debug adapter in order to configure it with client capabilities and to retrieve capabilities from the debug adapter. Until the debug adapter has responded to with an 'initialize' response, the client must not send any additional requests or events to the debug adapter. In addition the debug adapter is not allowed to send any requests or events to the client until it has responded with an 'initialize' response. The 'initialize' request may only be sent once. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "initialize" ] }, "arguments": { "type": "InitializeRequestArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param InitializeRequestArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'initialize' if arguments is None: self.arguments = InitializeRequestArguments() else: self.arguments = InitializeRequestArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != InitializeRequestArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class InitializeRequestArguments(BaseSchema): """ Arguments for 'initialize' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "clientID": { "type": "string", "description": "The ID of the (frontend) client using this adapter." }, "clientName": { "type": "string", "description": "The human readable name of the (frontend) client using this adapter." }, "adapterID": { "type": "string", "description": "The ID of the debug adapter." }, "locale": { "type": "string", "description": "The ISO-639 locale of the (frontend) client using this adapter, e.g. en-US or de-CH." }, "linesStartAt1": { "type": "boolean", "description": "If true all line numbers are 1-based (default)." }, "columnsStartAt1": { "type": "boolean", "description": "If true all column numbers are 1-based (default)." }, "pathFormat": { "type": "string", "_enum": [ "path", "uri" ], "description": "Determines in what format paths are specified. The default is 'path', which is the native format." }, "supportsVariableType": { "type": "boolean", "description": "Client supports the optional type attribute for variables." }, "supportsVariablePaging": { "type": "boolean", "description": "Client supports the paging of variables." }, "supportsRunInTerminalRequest": { "type": "boolean", "description": "Client supports the runInTerminal request." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, adapterID, clientID=None, clientName=None, locale=None, linesStartAt1=None, columnsStartAt1=None, pathFormat=None, supportsVariableType=None, supportsVariablePaging=None, supportsRunInTerminalRequest=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string adapterID: The ID of the debug adapter. :param string clientID: The ID of the (frontend) client using this adapter. :param string clientName: The human readable name of the (frontend) client using this adapter. :param string locale: The ISO-639 locale of the (frontend) client using this adapter, e.g. en-US or de-CH. :param boolean linesStartAt1: If true all line numbers are 1-based (default). :param boolean columnsStartAt1: If true all column numbers are 1-based (default). :param string pathFormat: Determines in what format paths are specified. The default is 'path', which is the native format. :param boolean supportsVariableType: Client supports the optional type attribute for variables. :param boolean supportsVariablePaging: Client supports the paging of variables. :param boolean supportsRunInTerminalRequest: Client supports the runInTerminal request. """ self.adapterID = adapterID self.clientID = clientID self.clientName = clientName self.locale = locale self.linesStartAt1 = linesStartAt1 self.columnsStartAt1 = columnsStartAt1 self.pathFormat = pathFormat self.supportsVariableType = supportsVariableType self.supportsVariablePaging = supportsVariablePaging self.supportsRunInTerminalRequest = supportsRunInTerminalRequest self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) adapterID = self.adapterID clientID = self.clientID clientName = self.clientName locale = self.locale linesStartAt1 = self.linesStartAt1 columnsStartAt1 = self.columnsStartAt1 pathFormat = self.pathFormat supportsVariableType = self.supportsVariableType supportsVariablePaging = self.supportsVariablePaging supportsRunInTerminalRequest = self.supportsRunInTerminalRequest dct = { 'adapterID': adapterID, } if clientID is not None: dct['clientID'] = clientID if clientName is not None: dct['clientName'] = clientName if locale is not None: dct['locale'] = locale if linesStartAt1 is not None: dct['linesStartAt1'] = linesStartAt1 if columnsStartAt1 is not None: dct['columnsStartAt1'] = columnsStartAt1 if pathFormat is not None: dct['pathFormat'] = pathFormat if supportsVariableType is not None: dct['supportsVariableType'] = supportsVariableType if supportsVariablePaging is not None: dct['supportsVariablePaging'] = supportsVariablePaging if supportsRunInTerminalRequest is not None: dct['supportsRunInTerminalRequest'] = supportsRunInTerminalRequest dct.update(self.kwargs) return dct @register_response('initialize') @register class InitializeResponse(BaseSchema): """ Response to 'initialize' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "description": "The capabilities of this debug adapter.", "type": "Capabilities" } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param Capabilities body: The capabilities of this debug adapter. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message if body is None: self.body = Capabilities() else: self.body = Capabilities(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != Capabilities else body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register_request('configurationDone') @register class ConfigurationDoneRequest(BaseSchema): """ The client of the debug protocol must send this request at the end of the sequence of configuration requests (which was started by the 'initialized' event). Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "configurationDone" ] }, "arguments": { "type": "ConfigurationDoneArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param integer seq: Sequence number. :param ConfigurationDoneArguments arguments: """ self.type = 'request' self.command = 'configurationDone' self.seq = seq if arguments is None: self.arguments = ConfigurationDoneArguments() else: self.arguments = ConfigurationDoneArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != ConfigurationDoneArguments else arguments self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command seq = self.seq arguments = self.arguments dct = { 'type': type, 'command': command, 'seq': seq, } if arguments is not None: dct['arguments'] = arguments.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register class ConfigurationDoneArguments(BaseSchema): """ Arguments for 'configurationDone' request. Note: automatically generated code. Do not edit manually. """ __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register_response('configurationDone') @register class ConfigurationDoneResponse(BaseSchema): """ Response to 'configurationDone' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('launch') @register class LaunchRequest(BaseSchema): """ The launch request is sent from the client to the debug adapter to start the debuggee with or without debugging (if 'noDebug' is true). Since launching is debugger/runtime specific, the arguments for this request are not part of this specification. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "launch" ] }, "arguments": { "type": "LaunchRequestArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param LaunchRequestArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'launch' if arguments is None: self.arguments = LaunchRequestArguments() else: self.arguments = LaunchRequestArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != LaunchRequestArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class LaunchRequestArguments(BaseSchema): """ Arguments for 'launch' request. Additional attributes are implementation specific. Note: automatically generated code. Do not edit manually. """ __props__ = { "noDebug": { "type": "boolean", "description": "If noDebug is true the launch request should launch the program without enabling debugging." }, "__restart": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Optional data from the previous, restarted session.\nThe data is sent as the 'restart' attribute of the 'terminated' event.\nThe client should leave the data intact." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, noDebug=None, __restart=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean noDebug: If noDebug is true the launch request should launch the program without enabling debugging. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] __restart: Optional data from the previous, restarted session. The data is sent as the 'restart' attribute of the 'terminated' event. The client should leave the data intact. """ self.noDebug = noDebug self.__restart = __restart self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) noDebug = self.noDebug __restart = self.__restart dct = { } if noDebug is not None: dct['noDebug'] = noDebug if __restart is not None: dct['__restart'] = __restart dct.update(self.kwargs) return dct @register_response('launch') @register class LaunchResponse(BaseSchema): """ Response to 'launch' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('attach') @register class AttachRequest(BaseSchema): """ The attach request is sent from the client to the debug adapter to attach to a debuggee that is already running. Since attaching is debugger/runtime specific, the arguments for this request are not part of this specification. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "attach" ] }, "arguments": { "type": "AttachRequestArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param AttachRequestArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'attach' if arguments is None: self.arguments = AttachRequestArguments() else: self.arguments = AttachRequestArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != AttachRequestArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class AttachRequestArguments(BaseSchema): """ Arguments for 'attach' request. Additional attributes are implementation specific. Note: automatically generated code. Do not edit manually. """ __props__ = { "__restart": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Optional data from the previous, restarted session.\nThe data is sent as the 'restart' attribute of the 'terminated' event.\nThe client should leave the data intact." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, __restart=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] __restart: Optional data from the previous, restarted session. The data is sent as the 'restart' attribute of the 'terminated' event. The client should leave the data intact. """ self.__restart = __restart self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) __restart = self.__restart dct = { } if __restart is not None: dct['__restart'] = __restart dct.update(self.kwargs) return dct @register_response('attach') @register class AttachResponse(BaseSchema): """ Response to 'attach' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('restart') @register class RestartRequest(BaseSchema): """ Restarts a debug session. If the capability 'supportsRestartRequest' is missing or has the value false, the client will implement 'restart' by terminating the debug adapter first and then launching it anew. A debug adapter can override this default behaviour by implementing a restart request and setting the capability 'supportsRestartRequest' to true. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "restart" ] }, "arguments": { "type": "RestartArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param integer seq: Sequence number. :param RestartArguments arguments: """ self.type = 'request' self.command = 'restart' self.seq = seq if arguments is None: self.arguments = RestartArguments() else: self.arguments = RestartArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != RestartArguments else arguments self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command seq = self.seq arguments = self.arguments dct = { 'type': type, 'command': command, 'seq': seq, } if arguments is not None: dct['arguments'] = arguments.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register class RestartArguments(BaseSchema): """ Arguments for 'restart' request. Note: automatically generated code. Do not edit manually. """ __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register_response('restart') @register class RestartResponse(BaseSchema): """ Response to 'restart' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('disconnect') @register class DisconnectRequest(BaseSchema): """ The 'disconnect' request is sent from the client to the debug adapter in order to stop debugging. It asks the debug adapter to disconnect from the debuggee and to terminate the debug adapter. If the debuggee has been started with the 'launch' request, the 'disconnect' request terminates the debuggee. If the 'attach' request was used to connect to the debuggee, 'disconnect' does not terminate the debuggee. This behavior can be controlled with the 'terminateDebuggee' argument (if supported by the debug adapter). Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "disconnect" ] }, "arguments": { "type": "DisconnectArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param integer seq: Sequence number. :param DisconnectArguments arguments: """ self.type = 'request' self.command = 'disconnect' self.seq = seq if arguments is None: self.arguments = DisconnectArguments() else: self.arguments = DisconnectArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != DisconnectArguments else arguments self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command seq = self.seq arguments = self.arguments dct = { 'type': type, 'command': command, 'seq': seq, } if arguments is not None: dct['arguments'] = arguments.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register class DisconnectArguments(BaseSchema): """ Arguments for 'disconnect' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "restart": { "type": "boolean", "description": "A value of true indicates that this 'disconnect' request is part of a restart sequence." }, "terminateDebuggee": { "type": "boolean", "description": "Indicates whether the debuggee should be terminated when the debugger is disconnected.\nIf unspecified, the debug adapter is free to do whatever it thinks is best.\nA client can only rely on this attribute being properly honored if a debug adapter returns true for the 'supportTerminateDebuggee' capability." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, restart=None, terminateDebuggee=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean restart: A value of true indicates that this 'disconnect' request is part of a restart sequence. :param boolean terminateDebuggee: Indicates whether the debuggee should be terminated when the debugger is disconnected. If unspecified, the debug adapter is free to do whatever it thinks is best. A client can only rely on this attribute being properly honored if a debug adapter returns true for the 'supportTerminateDebuggee' capability. """ self.restart = restart self.terminateDebuggee = terminateDebuggee self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) restart = self.restart terminateDebuggee = self.terminateDebuggee dct = { } if restart is not None: dct['restart'] = restart if terminateDebuggee is not None: dct['terminateDebuggee'] = terminateDebuggee dct.update(self.kwargs) return dct @register_response('disconnect') @register class DisconnectResponse(BaseSchema): """ Response to 'disconnect' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('terminate') @register class TerminateRequest(BaseSchema): """ The 'terminate' request is sent from the client to the debug adapter in order to give the debuggee a chance for terminating itself. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "terminate" ] }, "arguments": { "type": "TerminateArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param integer seq: Sequence number. :param TerminateArguments arguments: """ self.type = 'request' self.command = 'terminate' self.seq = seq if arguments is None: self.arguments = TerminateArguments() else: self.arguments = TerminateArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != TerminateArguments else arguments self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command seq = self.seq arguments = self.arguments dct = { 'type': type, 'command': command, 'seq': seq, } if arguments is not None: dct['arguments'] = arguments.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register class TerminateArguments(BaseSchema): """ Arguments for 'terminate' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "restart": { "type": "boolean", "description": "A value of true indicates that this 'terminate' request is part of a restart sequence." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, restart=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean restart: A value of true indicates that this 'terminate' request is part of a restart sequence. """ self.restart = restart self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) restart = self.restart dct = { } if restart is not None: dct['restart'] = restart dct.update(self.kwargs) return dct @register_response('terminate') @register class TerminateResponse(BaseSchema): """ Response to 'terminate' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('setBreakpoints') @register class SetBreakpointsRequest(BaseSchema): """ Sets multiple breakpoints for a single source and clears all previous breakpoints in that source. To clear all breakpoint for a source, specify an empty array. When a breakpoint is hit, a 'stopped' event (with reason 'breakpoint') is generated. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "setBreakpoints" ] }, "arguments": { "type": "SetBreakpointsArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param SetBreakpointsArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'setBreakpoints' if arguments is None: self.arguments = SetBreakpointsArguments() else: self.arguments = SetBreakpointsArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != SetBreakpointsArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class SetBreakpointsArguments(BaseSchema): """ Arguments for 'setBreakpoints' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "source": { "description": "The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified.", "type": "Source" }, "breakpoints": { "type": "array", "items": { "$ref": "#/definitions/SourceBreakpoint" }, "description": "The code locations of the breakpoints." }, "lines": { "type": "array", "items": { "type": "integer" }, "description": "Deprecated: The code locations of the breakpoints." }, "sourceModified": { "type": "boolean", "description": "A value of true indicates that the underlying source has been modified which results in new breakpoint locations." } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, source, breakpoints=None, lines=None, sourceModified=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param Source source: The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified. :param array breakpoints: The code locations of the breakpoints. :param array lines: Deprecated: The code locations of the breakpoints. :param boolean sourceModified: A value of true indicates that the underlying source has been modified which results in new breakpoint locations. """ if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.breakpoints = breakpoints if update_ids_from_dap and self.breakpoints: for o in self.breakpoints: SourceBreakpoint.update_dict_ids_from_dap(o) self.lines = lines self.sourceModified = sourceModified self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) source = self.source breakpoints = self.breakpoints lines = self.lines sourceModified = self.sourceModified dct = { 'source': source.to_dict(update_ids_to_dap=update_ids_to_dap), } if breakpoints is not None: dct['breakpoints'] = [SourceBreakpoint.update_dict_ids_to_dap(o) for o in breakpoints] if (update_ids_to_dap and breakpoints) else breakpoints if lines is not None: dct['lines'] = lines if sourceModified is not None: dct['sourceModified'] = sourceModified dct.update(self.kwargs) return dct @register_response('setBreakpoints') @register class SetBreakpointsResponse(BaseSchema): """ Response to 'setBreakpoints' request. Returned is information about each breakpoint created by this request. This includes the actual code location and whether the breakpoint could be verified. The breakpoints returned are in the same order as the elements of the 'breakpoints' (or the deprecated 'lines') array in the arguments. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "breakpoints": { "type": "array", "items": { "$ref": "#/definitions/Breakpoint" }, "description": "Information about the breakpoints. The array elements are in the same order as the elements of the 'breakpoints' (or the deprecated 'lines') array in the arguments." } }, "required": [ "breakpoints" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param SetBreakpointsResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = SetBreakpointsResponseBody() else: self.body = SetBreakpointsResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != SetBreakpointsResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('setFunctionBreakpoints') @register class SetFunctionBreakpointsRequest(BaseSchema): """ Sets multiple function breakpoints and clears all previous function breakpoints. To clear all function breakpoint, specify an empty array. When a function breakpoint is hit, a 'stopped' event (event type 'function breakpoint') is generated. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "setFunctionBreakpoints" ] }, "arguments": { "type": "SetFunctionBreakpointsArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param SetFunctionBreakpointsArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'setFunctionBreakpoints' if arguments is None: self.arguments = SetFunctionBreakpointsArguments() else: self.arguments = SetFunctionBreakpointsArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != SetFunctionBreakpointsArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class SetFunctionBreakpointsArguments(BaseSchema): """ Arguments for 'setFunctionBreakpoints' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "breakpoints": { "type": "array", "items": { "$ref": "#/definitions/FunctionBreakpoint" }, "description": "The function names of the breakpoints." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, breakpoints, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array breakpoints: The function names of the breakpoints. """ self.breakpoints = breakpoints if update_ids_from_dap and self.breakpoints: for o in self.breakpoints: FunctionBreakpoint.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) breakpoints = self.breakpoints dct = { 'breakpoints': [FunctionBreakpoint.update_dict_ids_to_dap(o) for o in breakpoints] if (update_ids_to_dap and breakpoints) else breakpoints, } dct.update(self.kwargs) return dct @register_response('setFunctionBreakpoints') @register class SetFunctionBreakpointsResponse(BaseSchema): """ Response to 'setFunctionBreakpoints' request. Returned is information about each breakpoint created by this request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "breakpoints": { "type": "array", "items": { "$ref": "#/definitions/Breakpoint" }, "description": "Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array." } }, "required": [ "breakpoints" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param SetFunctionBreakpointsResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = SetFunctionBreakpointsResponseBody() else: self.body = SetFunctionBreakpointsResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != SetFunctionBreakpointsResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('setExceptionBreakpoints') @register class SetExceptionBreakpointsRequest(BaseSchema): """ The request configures the debuggers response to thrown exceptions. If an exception is configured to break, a 'stopped' event is fired (with reason 'exception'). Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "setExceptionBreakpoints" ] }, "arguments": { "type": "SetExceptionBreakpointsArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param SetExceptionBreakpointsArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'setExceptionBreakpoints' if arguments is None: self.arguments = SetExceptionBreakpointsArguments() else: self.arguments = SetExceptionBreakpointsArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != SetExceptionBreakpointsArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class SetExceptionBreakpointsArguments(BaseSchema): """ Arguments for 'setExceptionBreakpoints' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "filters": { "type": "array", "items": { "type": "string" }, "description": "IDs of checked exception options. The set of IDs is returned via the 'exceptionBreakpointFilters' capability." }, "exceptionOptions": { "type": "array", "items": { "$ref": "#/definitions/ExceptionOptions" }, "description": "Configuration options for selected exceptions." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, filters, exceptionOptions=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array filters: IDs of checked exception options. The set of IDs is returned via the 'exceptionBreakpointFilters' capability. :param array exceptionOptions: Configuration options for selected exceptions. """ self.filters = filters self.exceptionOptions = exceptionOptions if update_ids_from_dap and self.exceptionOptions: for o in self.exceptionOptions: ExceptionOptions.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) filters = self.filters exceptionOptions = self.exceptionOptions dct = { 'filters': filters, } if exceptionOptions is not None: dct['exceptionOptions'] = [ExceptionOptions.update_dict_ids_to_dap(o) for o in exceptionOptions] if (update_ids_to_dap and exceptionOptions) else exceptionOptions dct.update(self.kwargs) return dct @register_response('setExceptionBreakpoints') @register class SetExceptionBreakpointsResponse(BaseSchema): """ Response to 'setExceptionBreakpoints' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('continue') @register class ContinueRequest(BaseSchema): """ The request starts the debuggee to run again. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "continue" ] }, "arguments": { "type": "ContinueArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param ContinueArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'continue' if arguments is None: self.arguments = ContinueArguments() else: self.arguments = ContinueArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != ContinueArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class ContinueArguments(BaseSchema): """ Arguments for 'continue' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Continue execution for the specified thread (if possible). If the backend cannot continue on a single thread but will continue on all threads, it should set the 'allThreadsContinued' attribute in the response to true." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Continue execution for the specified thread (if possible). If the backend cannot continue on a single thread but will continue on all threads, it should set the 'allThreadsContinued' attribute in the response to true. """ self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId dct = { 'threadId': threadId, } dct.update(self.kwargs) return dct @register_response('continue') @register class ContinueResponse(BaseSchema): """ Response to 'continue' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "allThreadsContinued": { "type": "boolean", "description": "If true, the 'continue' request has ignored the specified thread and continued all threads instead. If this attribute is missing a value of 'true' is assumed for backward compatibility." } } } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param ContinueResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = ContinueResponseBody() else: self.body = ContinueResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ContinueResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('next') @register class NextRequest(BaseSchema): """ The request starts the debuggee to run again for one step. The debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "next" ] }, "arguments": { "type": "NextArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param NextArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'next' if arguments is None: self.arguments = NextArguments() else: self.arguments = NextArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != NextArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class NextArguments(BaseSchema): """ Arguments for 'next' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Execute 'next' for this thread." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Execute 'next' for this thread. """ self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId dct = { 'threadId': threadId, } dct.update(self.kwargs) return dct @register_response('next') @register class NextResponse(BaseSchema): """ Response to 'next' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('stepIn') @register class StepInRequest(BaseSchema): """ The request starts the debuggee to step into a function/method if possible. If it cannot step into a target, 'stepIn' behaves like 'next'. The debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed. If there are multiple function/method calls (or other targets) on the source line, the optional argument 'targetId' can be used to control into which target the 'stepIn' should occur. The list of possible targets for a given source line can be retrieved via the 'stepInTargets' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "stepIn" ] }, "arguments": { "type": "StepInArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param StepInArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'stepIn' if arguments is None: self.arguments = StepInArguments() else: self.arguments = StepInArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != StepInArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class StepInArguments(BaseSchema): """ Arguments for 'stepIn' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Execute 'stepIn' for this thread." }, "targetId": { "type": "integer", "description": "Optional id of the target to step into." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, targetId=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Execute 'stepIn' for this thread. :param integer targetId: Optional id of the target to step into. """ self.threadId = threadId self.targetId = targetId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId targetId = self.targetId dct = { 'threadId': threadId, } if targetId is not None: dct['targetId'] = targetId dct.update(self.kwargs) return dct @register_response('stepIn') @register class StepInResponse(BaseSchema): """ Response to 'stepIn' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('stepOut') @register class StepOutRequest(BaseSchema): """ The request starts the debuggee to run again for one step. The debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "stepOut" ] }, "arguments": { "type": "StepOutArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param StepOutArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'stepOut' if arguments is None: self.arguments = StepOutArguments() else: self.arguments = StepOutArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != StepOutArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class StepOutArguments(BaseSchema): """ Arguments for 'stepOut' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Execute 'stepOut' for this thread." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Execute 'stepOut' for this thread. """ self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId dct = { 'threadId': threadId, } dct.update(self.kwargs) return dct @register_response('stepOut') @register class StepOutResponse(BaseSchema): """ Response to 'stepOut' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('stepBack') @register class StepBackRequest(BaseSchema): """ The request starts the debuggee to run one step backwards. The debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed. Clients should only call this request if the capability 'supportsStepBack' is true. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "stepBack" ] }, "arguments": { "type": "StepBackArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param StepBackArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'stepBack' if arguments is None: self.arguments = StepBackArguments() else: self.arguments = StepBackArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != StepBackArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class StepBackArguments(BaseSchema): """ Arguments for 'stepBack' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Execute 'stepBack' for this thread." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Execute 'stepBack' for this thread. """ self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId dct = { 'threadId': threadId, } dct.update(self.kwargs) return dct @register_response('stepBack') @register class StepBackResponse(BaseSchema): """ Response to 'stepBack' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('reverseContinue') @register class ReverseContinueRequest(BaseSchema): """ The request starts the debuggee to run backward. Clients should only call this request if the capability 'supportsStepBack' is true. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "reverseContinue" ] }, "arguments": { "type": "ReverseContinueArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param ReverseContinueArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'reverseContinue' if arguments is None: self.arguments = ReverseContinueArguments() else: self.arguments = ReverseContinueArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != ReverseContinueArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class ReverseContinueArguments(BaseSchema): """ Arguments for 'reverseContinue' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Execute 'reverseContinue' for this thread." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Execute 'reverseContinue' for this thread. """ self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId dct = { 'threadId': threadId, } dct.update(self.kwargs) return dct @register_response('reverseContinue') @register class ReverseContinueResponse(BaseSchema): """ Response to 'reverseContinue' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('restartFrame') @register class RestartFrameRequest(BaseSchema): """ The request restarts execution of the specified stackframe. The debug adapter first sends the response and then a 'stopped' event (with reason 'restart') after the restart has completed. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "restartFrame" ] }, "arguments": { "type": "RestartFrameArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param RestartFrameArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'restartFrame' if arguments is None: self.arguments = RestartFrameArguments() else: self.arguments = RestartFrameArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != RestartFrameArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class RestartFrameArguments(BaseSchema): """ Arguments for 'restartFrame' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "frameId": { "type": "integer", "description": "Restart this stackframe." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, frameId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer frameId: Restart this stackframe. """ self.frameId = frameId if update_ids_from_dap: self.frameId = self._translate_id_from_dap(self.frameId) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_from_dap(dct['frameId']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) frameId = self.frameId if update_ids_to_dap: if frameId is not None: frameId = self._translate_id_to_dap(frameId) dct = { 'frameId': frameId, } dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_to_dap(dct['frameId']) return dct @register_response('restartFrame') @register class RestartFrameResponse(BaseSchema): """ Response to 'restartFrame' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('goto') @register class GotoRequest(BaseSchema): """ The request sets the location where the debuggee will continue to run. This makes it possible to skip the execution of code or to executed code again. The code between the current location and the goto target is not executed but skipped. The debug adapter first sends the response and then a 'stopped' event with reason 'goto'. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "goto" ] }, "arguments": { "type": "GotoArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param GotoArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'goto' if arguments is None: self.arguments = GotoArguments() else: self.arguments = GotoArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != GotoArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class GotoArguments(BaseSchema): """ Arguments for 'goto' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Set the goto target for this thread." }, "targetId": { "type": "integer", "description": "The location where the debuggee will continue to run." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, targetId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Set the goto target for this thread. :param integer targetId: The location where the debuggee will continue to run. """ self.threadId = threadId self.targetId = targetId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId targetId = self.targetId dct = { 'threadId': threadId, 'targetId': targetId, } dct.update(self.kwargs) return dct @register_response('goto') @register class GotoResponse(BaseSchema): """ Response to 'goto' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('pause') @register class PauseRequest(BaseSchema): """ The request suspenses the debuggee. The debug adapter first sends the response and then a 'stopped' event (with reason 'pause') after the thread has been paused successfully. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "pause" ] }, "arguments": { "type": "PauseArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param PauseArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'pause' if arguments is None: self.arguments = PauseArguments() else: self.arguments = PauseArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != PauseArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class PauseArguments(BaseSchema): """ Arguments for 'pause' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Pause execution for this thread." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Pause execution for this thread. """ self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId dct = { 'threadId': threadId, } dct.update(self.kwargs) return dct @register_response('pause') @register class PauseResponse(BaseSchema): """ Response to 'pause' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('stackTrace') @register class StackTraceRequest(BaseSchema): """ The request returns a stacktrace from the current execution state. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "stackTrace" ] }, "arguments": { "type": "StackTraceArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param StackTraceArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'stackTrace' if arguments is None: self.arguments = StackTraceArguments() else: self.arguments = StackTraceArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != StackTraceArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class StackTraceArguments(BaseSchema): """ Arguments for 'stackTrace' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Retrieve the stacktrace for this thread." }, "startFrame": { "type": "integer", "description": "The index of the first frame to return; if omitted frames start at 0." }, "levels": { "type": "integer", "description": "The maximum number of frames to return. If levels is not specified or 0, all frames are returned." }, "format": { "description": "Specifies details on how to format the stack frames.", "type": "StackFrameFormat" } } __refs__ = set(['format']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, startFrame=None, levels=None, format=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Retrieve the stacktrace for this thread. :param integer startFrame: The index of the first frame to return; if omitted frames start at 0. :param integer levels: The maximum number of frames to return. If levels is not specified or 0, all frames are returned. :param StackFrameFormat format: Specifies details on how to format the stack frames. """ self.threadId = threadId self.startFrame = startFrame self.levels = levels if format is None: self.format = StackFrameFormat() else: self.format = StackFrameFormat(update_ids_from_dap=update_ids_from_dap, **format) if format.__class__ != StackFrameFormat else format self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId startFrame = self.startFrame levels = self.levels format = self.format # noqa (assign to builtin) dct = { 'threadId': threadId, } if startFrame is not None: dct['startFrame'] = startFrame if levels is not None: dct['levels'] = levels if format is not None: dct['format'] = format.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register_response('stackTrace') @register class StackTraceResponse(BaseSchema): """ Response to 'stackTrace' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "stackFrames": { "type": "array", "items": { "$ref": "#/definitions/StackFrame" }, "description": "The frames of the stackframe. If the array has length zero, there are no stackframes available.\nThis means that there is no location information available." }, "totalFrames": { "type": "integer", "description": "The total number of frames available." } }, "required": [ "stackFrames" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param StackTraceResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = StackTraceResponseBody() else: self.body = StackTraceResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != StackTraceResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('scopes') @register class ScopesRequest(BaseSchema): """ The request returns the variable scopes for a given stackframe ID. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "scopes" ] }, "arguments": { "type": "ScopesArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param ScopesArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'scopes' if arguments is None: self.arguments = ScopesArguments() else: self.arguments = ScopesArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != ScopesArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class ScopesArguments(BaseSchema): """ Arguments for 'scopes' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "frameId": { "type": "integer", "description": "Retrieve the scopes for this stackframe." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, frameId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer frameId: Retrieve the scopes for this stackframe. """ self.frameId = frameId if update_ids_from_dap: self.frameId = self._translate_id_from_dap(self.frameId) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_from_dap(dct['frameId']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) frameId = self.frameId if update_ids_to_dap: if frameId is not None: frameId = self._translate_id_to_dap(frameId) dct = { 'frameId': frameId, } dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_to_dap(dct['frameId']) return dct @register_response('scopes') @register class ScopesResponse(BaseSchema): """ Response to 'scopes' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "scopes": { "type": "array", "items": { "$ref": "#/definitions/Scope" }, "description": "The scopes of the stackframe. If the array has length zero, there are no scopes available." } }, "required": [ "scopes" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param ScopesResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = ScopesResponseBody() else: self.body = ScopesResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ScopesResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('variables') @register class VariablesRequest(BaseSchema): """ Retrieves all child variables for the given variable reference. An optional filter can be used to limit the fetched children to either named or indexed children. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "variables" ] }, "arguments": { "type": "VariablesArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param VariablesArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'variables' if arguments is None: self.arguments = VariablesArguments() else: self.arguments = VariablesArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != VariablesArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class VariablesArguments(BaseSchema): """ Arguments for 'variables' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "variablesReference": { "type": "integer", "description": "The Variable reference." }, "filter": { "type": "string", "enum": [ "indexed", "named" ], "description": "Optional filter to limit the child variables to either named or indexed. If ommited, both types are fetched." }, "start": { "type": "integer", "description": "The index of the first variable to return; if omitted children start at 0." }, "count": { "type": "integer", "description": "The number of variables to return. If count is missing or 0, all variables are returned." }, "format": { "description": "Specifies details on how to format the Variable values.", "type": "ValueFormat" } } __refs__ = set(['format']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, variablesReference, filter=None, start=None, count=None, format=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer variablesReference: The Variable reference. :param string filter: Optional filter to limit the child variables to either named or indexed. If ommited, both types are fetched. :param integer start: The index of the first variable to return; if omitted children start at 0. :param integer count: The number of variables to return. If count is missing or 0, all variables are returned. :param ValueFormat format: Specifies details on how to format the Variable values. """ self.variablesReference = variablesReference self.filter = filter self.start = start self.count = count if format is None: self.format = ValueFormat() else: self.format = ValueFormat(update_ids_from_dap=update_ids_from_dap, **format) if format.__class__ != ValueFormat else format if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) variablesReference = self.variablesReference filter = self.filter # noqa (assign to builtin) start = self.start count = self.count format = self.format # noqa (assign to builtin) if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'variablesReference': variablesReference, } if filter is not None: dct['filter'] = filter if start is not None: dct['start'] = start if count is not None: dct['count'] = count if format is not None: dct['format'] = format.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register_response('variables') @register class VariablesResponse(BaseSchema): """ Response to 'variables' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "variables": { "type": "array", "items": { "$ref": "#/definitions/Variable" }, "description": "All (or a range) of variables for the given variable reference." } }, "required": [ "variables" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param VariablesResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = VariablesResponseBody() else: self.body = VariablesResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != VariablesResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('setVariable') @register class SetVariableRequest(BaseSchema): """ Set the variable with the given name in the variable container to a new value. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "setVariable" ] }, "arguments": { "type": "SetVariableArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param SetVariableArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'setVariable' if arguments is None: self.arguments = SetVariableArguments() else: self.arguments = SetVariableArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != SetVariableArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class SetVariableArguments(BaseSchema): """ Arguments for 'setVariable' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "variablesReference": { "type": "integer", "description": "The reference of the variable container." }, "name": { "type": "string", "description": "The name of the variable." }, "value": { "type": "string", "description": "The value of the variable." }, "format": { "description": "Specifies details on how to format the response value.", "type": "ValueFormat" } } __refs__ = set(['format']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, variablesReference, name, value, format=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer variablesReference: The reference of the variable container. :param string name: The name of the variable. :param string value: The value of the variable. :param ValueFormat format: Specifies details on how to format the response value. """ self.variablesReference = variablesReference self.name = name self.value = value if format is None: self.format = ValueFormat() else: self.format = ValueFormat(update_ids_from_dap=update_ids_from_dap, **format) if format.__class__ != ValueFormat else format if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) variablesReference = self.variablesReference name = self.name value = self.value format = self.format # noqa (assign to builtin) if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'variablesReference': variablesReference, 'name': name, 'value': value, } if format is not None: dct['format'] = format.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register_response('setVariable') @register class SetVariableResponse(BaseSchema): """ Response to 'setVariable' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "value": { "type": "string", "description": "The new value of the variable." }, "type": { "type": "string", "description": "The type of the new value. Typically shown in the UI when hovering over the value." }, "variablesReference": { "type": "number", "description": "If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." }, "namedVariables": { "type": "number", "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "number", "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." } }, "required": [ "value" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param SetVariableResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = SetVariableResponseBody() else: self.body = SetVariableResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != SetVariableResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('source') @register class SourceRequest(BaseSchema): """ The request retrieves the source code for a given source reference. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "source" ] }, "arguments": { "type": "SourceArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param SourceArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'source' if arguments is None: self.arguments = SourceArguments() else: self.arguments = SourceArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != SourceArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class SourceArguments(BaseSchema): """ Arguments for 'source' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "source": { "description": "Specifies the source content to load. Either source.path or source.sourceReference must be specified.", "type": "Source" }, "sourceReference": { "type": "integer", "description": "The reference to the source. This is the same as source.sourceReference. This is provided for backward compatibility since old backends do not understand the 'source' attribute." } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, sourceReference, source=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer sourceReference: The reference to the source. This is the same as source.sourceReference. This is provided for backward compatibility since old backends do not understand the 'source' attribute. :param Source source: Specifies the source content to load. Either source.path or source.sourceReference must be specified. """ self.sourceReference = sourceReference if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) sourceReference = self.sourceReference source = self.source dct = { 'sourceReference': sourceReference, } if source is not None: dct['source'] = source.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register_response('source') @register class SourceResponse(BaseSchema): """ Response to 'source' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "content": { "type": "string", "description": "Content of the source reference." }, "mimeType": { "type": "string", "description": "Optional content type (mime type) of the source." } }, "required": [ "content" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param SourceResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = SourceResponseBody() else: self.body = SourceResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != SourceResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('threads') @register class ThreadsRequest(BaseSchema): """ The request retrieves a list of all threads. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "threads" ] }, "arguments": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Object containing arguments for the command." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param integer seq: Sequence number. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] arguments: Object containing arguments for the command. """ self.type = 'request' self.command = 'threads' self.seq = seq self.arguments = arguments self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command seq = self.seq arguments = self.arguments dct = { 'type': type, 'command': command, 'seq': seq, } if arguments is not None: dct['arguments'] = arguments dct.update(self.kwargs) return dct @register_response('threads') @register class ThreadsResponse(BaseSchema): """ Response to 'threads' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "threads": { "type": "array", "items": { "$ref": "#/definitions/Thread" }, "description": "All threads." } }, "required": [ "threads" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param ThreadsResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = ThreadsResponseBody() else: self.body = ThreadsResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ThreadsResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('terminateThreads') @register class TerminateThreadsRequest(BaseSchema): """ The request terminates the threads with the given ids. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "terminateThreads" ] }, "arguments": { "type": "TerminateThreadsArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param TerminateThreadsArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'terminateThreads' if arguments is None: self.arguments = TerminateThreadsArguments() else: self.arguments = TerminateThreadsArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != TerminateThreadsArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class TerminateThreadsArguments(BaseSchema): """ Arguments for 'terminateThreads' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadIds": { "type": "array", "items": { "type": "integer" }, "description": "Ids of threads to be terminated." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadIds=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array threadIds: Ids of threads to be terminated. """ self.threadIds = threadIds self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadIds = self.threadIds dct = { } if threadIds is not None: dct['threadIds'] = threadIds dct.update(self.kwargs) return dct @register_response('terminateThreads') @register class TerminateThreadsResponse(BaseSchema): """ Response to 'terminateThreads' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register_request('modules') @register class ModulesRequest(BaseSchema): """ Modules can be retrieved from the debug adapter with the ModulesRequest which can either return all modules or a range of modules to support paging. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "modules" ] }, "arguments": { "type": "ModulesArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param ModulesArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'modules' if arguments is None: self.arguments = ModulesArguments() else: self.arguments = ModulesArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != ModulesArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class ModulesArguments(BaseSchema): """ Arguments for 'modules' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "startModule": { "type": "integer", "description": "The index of the first module to return; if omitted modules start at 0." }, "moduleCount": { "type": "integer", "description": "The number of modules to return. If moduleCount is not specified or 0, all modules are returned." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, startModule=None, moduleCount=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer startModule: The index of the first module to return; if omitted modules start at 0. :param integer moduleCount: The number of modules to return. If moduleCount is not specified or 0, all modules are returned. """ self.startModule = startModule self.moduleCount = moduleCount self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) startModule = self.startModule moduleCount = self.moduleCount dct = { } if startModule is not None: dct['startModule'] = startModule if moduleCount is not None: dct['moduleCount'] = moduleCount dct.update(self.kwargs) return dct @register_response('modules') @register class ModulesResponse(BaseSchema): """ Response to 'modules' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "modules": { "type": "array", "items": { "$ref": "#/definitions/Module" }, "description": "All modules or range of modules." }, "totalModules": { "type": "integer", "description": "The total number of modules available." } }, "required": [ "modules" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param ModulesResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = ModulesResponseBody() else: self.body = ModulesResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ModulesResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('loadedSources') @register class LoadedSourcesRequest(BaseSchema): """ Retrieves the set of all sources currently loaded by the debugged process. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "loadedSources" ] }, "arguments": { "type": "LoadedSourcesArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param integer seq: Sequence number. :param LoadedSourcesArguments arguments: """ self.type = 'request' self.command = 'loadedSources' self.seq = seq if arguments is None: self.arguments = LoadedSourcesArguments() else: self.arguments = LoadedSourcesArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != LoadedSourcesArguments else arguments self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command seq = self.seq arguments = self.arguments dct = { 'type': type, 'command': command, 'seq': seq, } if arguments is not None: dct['arguments'] = arguments.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register class LoadedSourcesArguments(BaseSchema): """ Arguments for 'loadedSources' request. Note: automatically generated code. Do not edit manually. """ __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register_response('loadedSources') @register class LoadedSourcesResponse(BaseSchema): """ Response to 'loadedSources' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "sources": { "type": "array", "items": { "$ref": "#/definitions/Source" }, "description": "Set of loaded sources." } }, "required": [ "sources" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param LoadedSourcesResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = LoadedSourcesResponseBody() else: self.body = LoadedSourcesResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != LoadedSourcesResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('evaluate') @register class EvaluateRequest(BaseSchema): """ Evaluates the given expression in the context of the top most stack frame. The expression has access to any variables and arguments that are in scope. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "evaluate" ] }, "arguments": { "type": "EvaluateArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param EvaluateArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'evaluate' if arguments is None: self.arguments = EvaluateArguments() else: self.arguments = EvaluateArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != EvaluateArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class EvaluateArguments(BaseSchema): """ Arguments for 'evaluate' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "expression": { "type": "string", "description": "The expression to evaluate." }, "frameId": { "type": "integer", "description": "Evaluate the expression in the scope of this stack frame. If not specified, the expression is evaluated in the global scope." }, "context": { "type": "string", "_enum": [ "watch", "repl", "hover" ], "enumDescriptions": [ "evaluate is run in a watch.", "evaluate is run from REPL console.", "evaluate is run from a data hover." ], "description": "The context in which the evaluate request is run." }, "format": { "description": "Specifies details on how to format the Evaluate result.", "type": "ValueFormat" } } __refs__ = set(['format']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, expression, frameId=None, context=None, format=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string expression: The expression to evaluate. :param integer frameId: Evaluate the expression in the scope of this stack frame. If not specified, the expression is evaluated in the global scope. :param string context: The context in which the evaluate request is run. :param ValueFormat format: Specifies details on how to format the Evaluate result. """ self.expression = expression self.frameId = frameId self.context = context if format is None: self.format = ValueFormat() else: self.format = ValueFormat(update_ids_from_dap=update_ids_from_dap, **format) if format.__class__ != ValueFormat else format if update_ids_from_dap: self.frameId = self._translate_id_from_dap(self.frameId) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_from_dap(dct['frameId']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) expression = self.expression frameId = self.frameId context = self.context format = self.format # noqa (assign to builtin) if update_ids_to_dap: if frameId is not None: frameId = self._translate_id_to_dap(frameId) dct = { 'expression': expression, } if frameId is not None: dct['frameId'] = frameId if context is not None: dct['context'] = context if format is not None: dct['format'] = format.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_to_dap(dct['frameId']) return dct @register_response('evaluate') @register class EvaluateResponse(BaseSchema): """ Response to 'evaluate' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "result": { "type": "string", "description": "The result of the evaluate request." }, "type": { "type": "string", "description": "The optional type of the evaluate result." }, "presentationHint": { "$ref": "#/definitions/VariablePresentationHint", "description": "Properties of a evaluate result that can be used to determine how to render the result in the UI." }, "variablesReference": { "type": "number", "description": "If variablesReference is > 0, the evaluate result is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." }, "namedVariables": { "type": "number", "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "number", "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." } }, "required": [ "result", "variablesReference" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param EvaluateResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = EvaluateResponseBody() else: self.body = EvaluateResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != EvaluateResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('setExpression') @register class SetExpressionRequest(BaseSchema): """ Evaluates the given 'value' expression and assigns it to the 'expression' which must be a modifiable l-value. The expressions have access to any variables and arguments that are in scope of the specified frame. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "setExpression" ] }, "arguments": { "type": "SetExpressionArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param SetExpressionArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'setExpression' if arguments is None: self.arguments = SetExpressionArguments() else: self.arguments = SetExpressionArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != SetExpressionArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class SetExpressionArguments(BaseSchema): """ Arguments for 'setExpression' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "expression": { "type": "string", "description": "The l-value expression to assign to." }, "value": { "type": "string", "description": "The value expression to assign to the l-value expression." }, "frameId": { "type": "integer", "description": "Evaluate the expressions in the scope of this stack frame. If not specified, the expressions are evaluated in the global scope." }, "format": { "description": "Specifies how the resulting value should be formatted.", "type": "ValueFormat" } } __refs__ = set(['format']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, expression, value, frameId=None, format=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string expression: The l-value expression to assign to. :param string value: The value expression to assign to the l-value expression. :param integer frameId: Evaluate the expressions in the scope of this stack frame. If not specified, the expressions are evaluated in the global scope. :param ValueFormat format: Specifies how the resulting value should be formatted. """ self.expression = expression self.value = value self.frameId = frameId if format is None: self.format = ValueFormat() else: self.format = ValueFormat(update_ids_from_dap=update_ids_from_dap, **format) if format.__class__ != ValueFormat else format if update_ids_from_dap: self.frameId = self._translate_id_from_dap(self.frameId) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_from_dap(dct['frameId']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) expression = self.expression value = self.value frameId = self.frameId format = self.format # noqa (assign to builtin) if update_ids_to_dap: if frameId is not None: frameId = self._translate_id_to_dap(frameId) dct = { 'expression': expression, 'value': value, } if frameId is not None: dct['frameId'] = frameId if format is not None: dct['format'] = format.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_to_dap(dct['frameId']) return dct @register_response('setExpression') @register class SetExpressionResponse(BaseSchema): """ Response to 'setExpression' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "value": { "type": "string", "description": "The new value of the expression." }, "type": { "type": "string", "description": "The optional type of the value." }, "presentationHint": { "$ref": "#/definitions/VariablePresentationHint", "description": "Properties of a value that can be used to determine how to render the result in the UI." }, "variablesReference": { "type": "number", "description": "If variablesReference is > 0, the value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." }, "namedVariables": { "type": "number", "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "number", "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." } }, "required": [ "value" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param SetExpressionResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = SetExpressionResponseBody() else: self.body = SetExpressionResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != SetExpressionResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('stepInTargets') @register class StepInTargetsRequest(BaseSchema): """ This request retrieves the possible stepIn targets for the specified stack frame. These targets can be used in the 'stepIn' request. The StepInTargets may only be called if the 'supportsStepInTargetsRequest' capability exists and is true. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "stepInTargets" ] }, "arguments": { "type": "StepInTargetsArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param StepInTargetsArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'stepInTargets' if arguments is None: self.arguments = StepInTargetsArguments() else: self.arguments = StepInTargetsArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != StepInTargetsArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class StepInTargetsArguments(BaseSchema): """ Arguments for 'stepInTargets' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "frameId": { "type": "integer", "description": "The stack frame for which to retrieve the possible stepIn targets." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, frameId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer frameId: The stack frame for which to retrieve the possible stepIn targets. """ self.frameId = frameId if update_ids_from_dap: self.frameId = self._translate_id_from_dap(self.frameId) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_from_dap(dct['frameId']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) frameId = self.frameId if update_ids_to_dap: if frameId is not None: frameId = self._translate_id_to_dap(frameId) dct = { 'frameId': frameId, } dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_to_dap(dct['frameId']) return dct @register_response('stepInTargets') @register class StepInTargetsResponse(BaseSchema): """ Response to 'stepInTargets' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "targets": { "type": "array", "items": { "$ref": "#/definitions/StepInTarget" }, "description": "The possible stepIn targets of the specified source location." } }, "required": [ "targets" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param StepInTargetsResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = StepInTargetsResponseBody() else: self.body = StepInTargetsResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != StepInTargetsResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('gotoTargets') @register class GotoTargetsRequest(BaseSchema): """ This request retrieves the possible goto targets for the specified source location. These targets can be used in the 'goto' request. The GotoTargets request may only be called if the 'supportsGotoTargetsRequest' capability exists and is true. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "gotoTargets" ] }, "arguments": { "type": "GotoTargetsArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param GotoTargetsArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'gotoTargets' if arguments is None: self.arguments = GotoTargetsArguments() else: self.arguments = GotoTargetsArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != GotoTargetsArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class GotoTargetsArguments(BaseSchema): """ Arguments for 'gotoTargets' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "source": { "description": "The source location for which the goto targets are determined.", "type": "Source" }, "line": { "type": "integer", "description": "The line location for which the goto targets are determined." }, "column": { "type": "integer", "description": "An optional column location for which the goto targets are determined." } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, source, line, column=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param Source source: The source location for which the goto targets are determined. :param integer line: The line location for which the goto targets are determined. :param integer column: An optional column location for which the goto targets are determined. """ if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.line = line self.column = column self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) source = self.source line = self.line column = self.column dct = { 'source': source.to_dict(update_ids_to_dap=update_ids_to_dap), 'line': line, } if column is not None: dct['column'] = column dct.update(self.kwargs) return dct @register_response('gotoTargets') @register class GotoTargetsResponse(BaseSchema): """ Response to 'gotoTargets' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "targets": { "type": "array", "items": { "$ref": "#/definitions/GotoTarget" }, "description": "The possible goto targets of the specified location." } }, "required": [ "targets" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param GotoTargetsResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = GotoTargetsResponseBody() else: self.body = GotoTargetsResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != GotoTargetsResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('completions') @register class CompletionsRequest(BaseSchema): """ Returns a list of possible completions for a given caret position and text. The CompletionsRequest may only be called if the 'supportsCompletionsRequest' capability exists and is true. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "completions" ] }, "arguments": { "type": "CompletionsArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param CompletionsArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'completions' if arguments is None: self.arguments = CompletionsArguments() else: self.arguments = CompletionsArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != CompletionsArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class CompletionsArguments(BaseSchema): """ Arguments for 'completions' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "frameId": { "type": "integer", "description": "Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope." }, "text": { "type": "string", "description": "One or more source lines. Typically this is the text a user has typed into the debug console before he asked for completion." }, "column": { "type": "integer", "description": "The character position for which to determine the completion proposals." }, "line": { "type": "integer", "description": "An optional line for which to determine the completion proposals. If missing the first line of the text is assumed." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, text, column, frameId=None, line=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string text: One or more source lines. Typically this is the text a user has typed into the debug console before he asked for completion. :param integer column: The character position for which to determine the completion proposals. :param integer frameId: Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope. :param integer line: An optional line for which to determine the completion proposals. If missing the first line of the text is assumed. """ self.text = text self.column = column self.frameId = frameId self.line = line if update_ids_from_dap: self.frameId = self._translate_id_from_dap(self.frameId) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_from_dap(dct['frameId']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) text = self.text column = self.column frameId = self.frameId line = self.line if update_ids_to_dap: if frameId is not None: frameId = self._translate_id_to_dap(frameId) dct = { 'text': text, 'column': column, } if frameId is not None: dct['frameId'] = frameId if line is not None: dct['line'] = line dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'frameId' in dct: dct['frameId'] = cls._translate_id_to_dap(dct['frameId']) return dct @register_response('completions') @register class CompletionsResponse(BaseSchema): """ Response to 'completions' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "targets": { "type": "array", "items": { "$ref": "#/definitions/CompletionItem" }, "description": "The possible completions for ." } }, "required": [ "targets" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param CompletionsResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = CompletionsResponseBody() else: self.body = CompletionsResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != CompletionsResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register_request('exceptionInfo') @register class ExceptionInfoRequest(BaseSchema): """ Retrieves the details of the exception that caused this event to be raised. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "exceptionInfo" ] }, "arguments": { "type": "ExceptionInfoArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param ExceptionInfoArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'exceptionInfo' if arguments is None: self.arguments = ExceptionInfoArguments() else: self.arguments = ExceptionInfoArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != ExceptionInfoArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class ExceptionInfoArguments(BaseSchema): """ Arguments for 'exceptionInfo' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "Thread for which exception information should be retrieved." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: Thread for which exception information should be retrieved. """ self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId dct = { 'threadId': threadId, } dct.update(self.kwargs) return dct @register_response('exceptionInfo') @register class ExceptionInfoResponse(BaseSchema): """ Response to 'exceptionInfo' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": "object", "properties": { "exceptionId": { "type": "string", "description": "ID of the exception that was thrown." }, "description": { "type": "string", "description": "Descriptive text for the exception provided by the debug adapter." }, "breakMode": { "$ref": "#/definitions/ExceptionBreakMode", "description": "Mode that caused the exception notification to be raised." }, "details": { "$ref": "#/definitions/ExceptionDetails", "description": "Detailed information about the exception." } }, "required": [ "exceptionId", "breakMode" ] } } __refs__ = set(['body']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, body, seq=-1, message=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param ExceptionInfoResponseBody body: :param integer seq: Sequence number. :param string message: Contains error message if success == false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command if body is None: self.body = ExceptionInfoResponseBody() else: self.body = ExceptionInfoResponseBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != ExceptionInfoResponseBody else body self.seq = seq self.message = message self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command body = self.body seq = self.seq message = self.message dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } if message is not None: dct['message'] = message dct.update(self.kwargs) return dct @register class Capabilities(BaseSchema): """ Information about the capabilities of a debug adapter. Note: automatically generated code. Do not edit manually. """ __props__ = { "supportsConfigurationDoneRequest": { "type": "boolean", "description": "The debug adapter supports the 'configurationDone' request." }, "supportsFunctionBreakpoints": { "type": "boolean", "description": "The debug adapter supports function breakpoints." }, "supportsConditionalBreakpoints": { "type": "boolean", "description": "The debug adapter supports conditional breakpoints." }, "supportsHitConditionalBreakpoints": { "type": "boolean", "description": "The debug adapter supports breakpoints that break execution after a specified number of hits." }, "supportsEvaluateForHovers": { "type": "boolean", "description": "The debug adapter supports a (side effect free) evaluate request for data hovers." }, "exceptionBreakpointFilters": { "type": "array", "items": { "$ref": "#/definitions/ExceptionBreakpointsFilter" }, "description": "Available filters or options for the setExceptionBreakpoints request." }, "supportsStepBack": { "type": "boolean", "description": "The debug adapter supports stepping back via the 'stepBack' and 'reverseContinue' requests." }, "supportsSetVariable": { "type": "boolean", "description": "The debug adapter supports setting a variable to a value." }, "supportsRestartFrame": { "type": "boolean", "description": "The debug adapter supports restarting a frame." }, "supportsGotoTargetsRequest": { "type": "boolean", "description": "The debug adapter supports the 'gotoTargets' request." }, "supportsStepInTargetsRequest": { "type": "boolean", "description": "The debug adapter supports the 'stepInTargets' request." }, "supportsCompletionsRequest": { "type": "boolean", "description": "The debug adapter supports the 'completions' request." }, "supportsModulesRequest": { "type": "boolean", "description": "The debug adapter supports the 'modules' request." }, "additionalModuleColumns": { "type": "array", "items": { "$ref": "#/definitions/ColumnDescriptor" }, "description": "The set of additional module information exposed by the debug adapter." }, "supportedChecksumAlgorithms": { "type": "array", "items": { "$ref": "#/definitions/ChecksumAlgorithm" }, "description": "Checksum algorithms supported by the debug adapter." }, "supportsRestartRequest": { "type": "boolean", "description": "The debug adapter supports the 'restart' request. In this case a client should not implement 'restart' by terminating and relaunching the adapter but by calling the RestartRequest." }, "supportsExceptionOptions": { "type": "boolean", "description": "The debug adapter supports 'exceptionOptions' on the setExceptionBreakpoints request." }, "supportsValueFormattingOptions": { "type": "boolean", "description": "The debug adapter supports a 'format' attribute on the stackTraceRequest, variablesRequest, and evaluateRequest." }, "supportsExceptionInfoRequest": { "type": "boolean", "description": "The debug adapter supports the 'exceptionInfo' request." }, "supportTerminateDebuggee": { "type": "boolean", "description": "The debug adapter supports the 'terminateDebuggee' attribute on the 'disconnect' request." }, "supportsDelayedStackTraceLoading": { "type": "boolean", "description": "The debug adapter supports the delayed loading of parts of the stack, which requires that both the 'startFrame' and 'levels' arguments and the 'totalFrames' result of the 'StackTrace' request are supported." }, "supportsLoadedSourcesRequest": { "type": "boolean", "description": "The debug adapter supports the 'loadedSources' request." }, "supportsLogPoints": { "type": "boolean", "description": "The debug adapter supports logpoints by interpreting the 'logMessage' attribute of the SourceBreakpoint." }, "supportsTerminateThreadsRequest": { "type": "boolean", "description": "The debug adapter supports the 'terminateThreads' request." }, "supportsSetExpression": { "type": "boolean", "description": "The debug adapter supports the 'setExpression' request." }, "supportsTerminateRequest": { "type": "boolean", "description": "The debug adapter supports the 'terminate' request." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, supportsConfigurationDoneRequest=None, supportsFunctionBreakpoints=None, supportsConditionalBreakpoints=None, supportsHitConditionalBreakpoints=None, supportsEvaluateForHovers=None, exceptionBreakpointFilters=None, supportsStepBack=None, supportsSetVariable=None, supportsRestartFrame=None, supportsGotoTargetsRequest=None, supportsStepInTargetsRequest=None, supportsCompletionsRequest=None, supportsModulesRequest=None, additionalModuleColumns=None, supportedChecksumAlgorithms=None, supportsRestartRequest=None, supportsExceptionOptions=None, supportsValueFormattingOptions=None, supportsExceptionInfoRequest=None, supportTerminateDebuggee=None, supportsDelayedStackTraceLoading=None, supportsLoadedSourcesRequest=None, supportsLogPoints=None, supportsTerminateThreadsRequest=None, supportsSetExpression=None, supportsTerminateRequest=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean supportsConfigurationDoneRequest: The debug adapter supports the 'configurationDone' request. :param boolean supportsFunctionBreakpoints: The debug adapter supports function breakpoints. :param boolean supportsConditionalBreakpoints: The debug adapter supports conditional breakpoints. :param boolean supportsHitConditionalBreakpoints: The debug adapter supports breakpoints that break execution after a specified number of hits. :param boolean supportsEvaluateForHovers: The debug adapter supports a (side effect free) evaluate request for data hovers. :param array exceptionBreakpointFilters: Available filters or options for the setExceptionBreakpoints request. :param boolean supportsStepBack: The debug adapter supports stepping back via the 'stepBack' and 'reverseContinue' requests. :param boolean supportsSetVariable: The debug adapter supports setting a variable to a value. :param boolean supportsRestartFrame: The debug adapter supports restarting a frame. :param boolean supportsGotoTargetsRequest: The debug adapter supports the 'gotoTargets' request. :param boolean supportsStepInTargetsRequest: The debug adapter supports the 'stepInTargets' request. :param boolean supportsCompletionsRequest: The debug adapter supports the 'completions' request. :param boolean supportsModulesRequest: The debug adapter supports the 'modules' request. :param array additionalModuleColumns: The set of additional module information exposed by the debug adapter. :param array supportedChecksumAlgorithms: Checksum algorithms supported by the debug adapter. :param boolean supportsRestartRequest: The debug adapter supports the 'restart' request. In this case a client should not implement 'restart' by terminating and relaunching the adapter but by calling the RestartRequest. :param boolean supportsExceptionOptions: The debug adapter supports 'exceptionOptions' on the setExceptionBreakpoints request. :param boolean supportsValueFormattingOptions: The debug adapter supports a 'format' attribute on the stackTraceRequest, variablesRequest, and evaluateRequest. :param boolean supportsExceptionInfoRequest: The debug adapter supports the 'exceptionInfo' request. :param boolean supportTerminateDebuggee: The debug adapter supports the 'terminateDebuggee' attribute on the 'disconnect' request. :param boolean supportsDelayedStackTraceLoading: The debug adapter supports the delayed loading of parts of the stack, which requires that both the 'startFrame' and 'levels' arguments and the 'totalFrames' result of the 'StackTrace' request are supported. :param boolean supportsLoadedSourcesRequest: The debug adapter supports the 'loadedSources' request. :param boolean supportsLogPoints: The debug adapter supports logpoints by interpreting the 'logMessage' attribute of the SourceBreakpoint. :param boolean supportsTerminateThreadsRequest: The debug adapter supports the 'terminateThreads' request. :param boolean supportsSetExpression: The debug adapter supports the 'setExpression' request. :param boolean supportsTerminateRequest: The debug adapter supports the 'terminate' request. """ self.supportsConfigurationDoneRequest = supportsConfigurationDoneRequest self.supportsFunctionBreakpoints = supportsFunctionBreakpoints self.supportsConditionalBreakpoints = supportsConditionalBreakpoints self.supportsHitConditionalBreakpoints = supportsHitConditionalBreakpoints self.supportsEvaluateForHovers = supportsEvaluateForHovers self.exceptionBreakpointFilters = exceptionBreakpointFilters if update_ids_from_dap and self.exceptionBreakpointFilters: for o in self.exceptionBreakpointFilters: ExceptionBreakpointsFilter.update_dict_ids_from_dap(o) self.supportsStepBack = supportsStepBack self.supportsSetVariable = supportsSetVariable self.supportsRestartFrame = supportsRestartFrame self.supportsGotoTargetsRequest = supportsGotoTargetsRequest self.supportsStepInTargetsRequest = supportsStepInTargetsRequest self.supportsCompletionsRequest = supportsCompletionsRequest self.supportsModulesRequest = supportsModulesRequest self.additionalModuleColumns = additionalModuleColumns if update_ids_from_dap and self.additionalModuleColumns: for o in self.additionalModuleColumns: ColumnDescriptor.update_dict_ids_from_dap(o) self.supportedChecksumAlgorithms = supportedChecksumAlgorithms if update_ids_from_dap and self.supportedChecksumAlgorithms: for o in self.supportedChecksumAlgorithms: ChecksumAlgorithm.update_dict_ids_from_dap(o) self.supportsRestartRequest = supportsRestartRequest self.supportsExceptionOptions = supportsExceptionOptions self.supportsValueFormattingOptions = supportsValueFormattingOptions self.supportsExceptionInfoRequest = supportsExceptionInfoRequest self.supportTerminateDebuggee = supportTerminateDebuggee self.supportsDelayedStackTraceLoading = supportsDelayedStackTraceLoading self.supportsLoadedSourcesRequest = supportsLoadedSourcesRequest self.supportsLogPoints = supportsLogPoints self.supportsTerminateThreadsRequest = supportsTerminateThreadsRequest self.supportsSetExpression = supportsSetExpression self.supportsTerminateRequest = supportsTerminateRequest self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) supportsConfigurationDoneRequest = self.supportsConfigurationDoneRequest supportsFunctionBreakpoints = self.supportsFunctionBreakpoints supportsConditionalBreakpoints = self.supportsConditionalBreakpoints supportsHitConditionalBreakpoints = self.supportsHitConditionalBreakpoints supportsEvaluateForHovers = self.supportsEvaluateForHovers exceptionBreakpointFilters = self.exceptionBreakpointFilters supportsStepBack = self.supportsStepBack supportsSetVariable = self.supportsSetVariable supportsRestartFrame = self.supportsRestartFrame supportsGotoTargetsRequest = self.supportsGotoTargetsRequest supportsStepInTargetsRequest = self.supportsStepInTargetsRequest supportsCompletionsRequest = self.supportsCompletionsRequest supportsModulesRequest = self.supportsModulesRequest additionalModuleColumns = self.additionalModuleColumns supportedChecksumAlgorithms = self.supportedChecksumAlgorithms supportsRestartRequest = self.supportsRestartRequest supportsExceptionOptions = self.supportsExceptionOptions supportsValueFormattingOptions = self.supportsValueFormattingOptions supportsExceptionInfoRequest = self.supportsExceptionInfoRequest supportTerminateDebuggee = self.supportTerminateDebuggee supportsDelayedStackTraceLoading = self.supportsDelayedStackTraceLoading supportsLoadedSourcesRequest = self.supportsLoadedSourcesRequest supportsLogPoints = self.supportsLogPoints supportsTerminateThreadsRequest = self.supportsTerminateThreadsRequest supportsSetExpression = self.supportsSetExpression supportsTerminateRequest = self.supportsTerminateRequest dct = { } if supportsConfigurationDoneRequest is not None: dct['supportsConfigurationDoneRequest'] = supportsConfigurationDoneRequest if supportsFunctionBreakpoints is not None: dct['supportsFunctionBreakpoints'] = supportsFunctionBreakpoints if supportsConditionalBreakpoints is not None: dct['supportsConditionalBreakpoints'] = supportsConditionalBreakpoints if supportsHitConditionalBreakpoints is not None: dct['supportsHitConditionalBreakpoints'] = supportsHitConditionalBreakpoints if supportsEvaluateForHovers is not None: dct['supportsEvaluateForHovers'] = supportsEvaluateForHovers if exceptionBreakpointFilters is not None: dct['exceptionBreakpointFilters'] = [ExceptionBreakpointsFilter.update_dict_ids_to_dap(o) for o in exceptionBreakpointFilters] if (update_ids_to_dap and exceptionBreakpointFilters) else exceptionBreakpointFilters if supportsStepBack is not None: dct['supportsStepBack'] = supportsStepBack if supportsSetVariable is not None: dct['supportsSetVariable'] = supportsSetVariable if supportsRestartFrame is not None: dct['supportsRestartFrame'] = supportsRestartFrame if supportsGotoTargetsRequest is not None: dct['supportsGotoTargetsRequest'] = supportsGotoTargetsRequest if supportsStepInTargetsRequest is not None: dct['supportsStepInTargetsRequest'] = supportsStepInTargetsRequest if supportsCompletionsRequest is not None: dct['supportsCompletionsRequest'] = supportsCompletionsRequest if supportsModulesRequest is not None: dct['supportsModulesRequest'] = supportsModulesRequest if additionalModuleColumns is not None: dct['additionalModuleColumns'] = [ColumnDescriptor.update_dict_ids_to_dap(o) for o in additionalModuleColumns] if (update_ids_to_dap and additionalModuleColumns) else additionalModuleColumns if supportedChecksumAlgorithms is not None: dct['supportedChecksumAlgorithms'] = [ChecksumAlgorithm.update_dict_ids_to_dap(o) for o in supportedChecksumAlgorithms] if (update_ids_to_dap and supportedChecksumAlgorithms) else supportedChecksumAlgorithms if supportsRestartRequest is not None: dct['supportsRestartRequest'] = supportsRestartRequest if supportsExceptionOptions is not None: dct['supportsExceptionOptions'] = supportsExceptionOptions if supportsValueFormattingOptions is not None: dct['supportsValueFormattingOptions'] = supportsValueFormattingOptions if supportsExceptionInfoRequest is not None: dct['supportsExceptionInfoRequest'] = supportsExceptionInfoRequest if supportTerminateDebuggee is not None: dct['supportTerminateDebuggee'] = supportTerminateDebuggee if supportsDelayedStackTraceLoading is not None: dct['supportsDelayedStackTraceLoading'] = supportsDelayedStackTraceLoading if supportsLoadedSourcesRequest is not None: dct['supportsLoadedSourcesRequest'] = supportsLoadedSourcesRequest if supportsLogPoints is not None: dct['supportsLogPoints'] = supportsLogPoints if supportsTerminateThreadsRequest is not None: dct['supportsTerminateThreadsRequest'] = supportsTerminateThreadsRequest if supportsSetExpression is not None: dct['supportsSetExpression'] = supportsSetExpression if supportsTerminateRequest is not None: dct['supportsTerminateRequest'] = supportsTerminateRequest dct.update(self.kwargs) return dct @register class ExceptionBreakpointsFilter(BaseSchema): """ An ExceptionBreakpointsFilter is shown in the UI as an option for configuring how exceptions are dealt with. Note: automatically generated code. Do not edit manually. """ __props__ = { "filter": { "type": "string", "description": "The internal ID of the filter. This value is passed to the setExceptionBreakpoints request." }, "label": { "type": "string", "description": "The name of the filter. This will be shown in the UI." }, "default": { "type": "boolean", "description": "Initial value of the filter. If not specified a value 'false' is assumed." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, filter, label, default=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string filter: The internal ID of the filter. This value is passed to the setExceptionBreakpoints request. :param string label: The name of the filter. This will be shown in the UI. :param boolean default: Initial value of the filter. If not specified a value 'false' is assumed. """ self.filter = filter self.label = label self.default = default self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) filter = self.filter # noqa (assign to builtin) label = self.label default = self.default dct = { 'filter': filter, 'label': label, } if default is not None: dct['default'] = default dct.update(self.kwargs) return dct @register class Message(BaseSchema): """ A structured message object. Used to return errors from requests. Note: automatically generated code. Do not edit manually. """ __props__ = { "id": { "type": "integer", "description": "Unique identifier for the message." }, "format": { "type": "string", "description": "A format string for the message. Embedded variables have the form '{name}'.\nIf variable name starts with an underscore character, the variable does not contain user data (PII) and can be safely used for telemetry purposes." }, "variables": { "type": "object", "description": "An object used as a dictionary for looking up the variables in the format string.", "additionalProperties": { "type": "string", "description": "Values must be strings." } }, "sendTelemetry": { "type": "boolean", "description": "If true send to telemetry." }, "showUser": { "type": "boolean", "description": "If true show user." }, "url": { "type": "string", "description": "An optional url where additional information about this message can be found." }, "urlLabel": { "type": "string", "description": "An optional label that is presented to the user as the UI for opening the url." } } __refs__ = set(['variables']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, id, format, variables=None, sendTelemetry=None, showUser=None, url=None, urlLabel=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer id: Unique identifier for the message. :param string format: A format string for the message. Embedded variables have the form '{name}'. If variable name starts with an underscore character, the variable does not contain user data (PII) and can be safely used for telemetry purposes. :param MessageVariables variables: An object used as a dictionary for looking up the variables in the format string. :param boolean sendTelemetry: If true send to telemetry. :param boolean showUser: If true show user. :param string url: An optional url where additional information about this message can be found. :param string urlLabel: An optional label that is presented to the user as the UI for opening the url. """ self.id = id self.format = format if variables is None: self.variables = MessageVariables() else: self.variables = MessageVariables(update_ids_from_dap=update_ids_from_dap, **variables) if variables.__class__ != MessageVariables else variables self.sendTelemetry = sendTelemetry self.showUser = showUser self.url = url self.urlLabel = urlLabel self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) id = self.id # noqa (assign to builtin) format = self.format # noqa (assign to builtin) variables = self.variables sendTelemetry = self.sendTelemetry showUser = self.showUser url = self.url urlLabel = self.urlLabel dct = { 'id': id, 'format': format, } if variables is not None: dct['variables'] = variables.to_dict(update_ids_to_dap=update_ids_to_dap) if sendTelemetry is not None: dct['sendTelemetry'] = sendTelemetry if showUser is not None: dct['showUser'] = showUser if url is not None: dct['url'] = url if urlLabel is not None: dct['urlLabel'] = urlLabel dct.update(self.kwargs) return dct @register class Module(BaseSchema): """ A Module object represents a row in the modules view. Two attributes are mandatory: an id identifies a module in the modules view and is used in a ModuleEvent for identifying a module for adding, updating or deleting. The name is used to minimally render the module in the UI. Additional attributes can be added to the module. They will show up in the module View if they have a corresponding ColumnDescriptor. To avoid an unnecessary proliferation of additional attributes with similar semantics but different names we recommend to re-use attributes from the 'recommended' list below first, and only introduce new attributes if nothing appropriate could be found. Note: automatically generated code. Do not edit manually. """ __props__ = { "id": { "type": [ "integer", "string" ], "description": "Unique identifier for the module." }, "name": { "type": "string", "description": "A name of the module." }, "path": { "type": "string", "description": "optional but recommended attributes.\nalways try to use these first before introducing additional attributes.\n\nLogical full path to the module. The exact definition is implementation defined, but usually this would be a full path to the on-disk file for the module." }, "isOptimized": { "type": "boolean", "description": "True if the module is optimized." }, "isUserCode": { "type": "boolean", "description": "True if the module is considered 'user code' by a debugger that supports 'Just My Code'." }, "version": { "type": "string", "description": "Version of Module." }, "symbolStatus": { "type": "string", "description": "User understandable description of if symbols were found for the module (ex: 'Symbols Loaded', 'Symbols not found', etc." }, "symbolFilePath": { "type": "string", "description": "Logical full path to the symbol file. The exact definition is implementation defined." }, "dateTimeStamp": { "type": "string", "description": "Module created or modified." }, "addressRange": { "type": "string", "description": "Address range covered by this module." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, id, name, path=None, isOptimized=None, isUserCode=None, version=None, symbolStatus=None, symbolFilePath=None, dateTimeStamp=None, addressRange=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param ['integer', 'string'] id: Unique identifier for the module. :param string name: A name of the module. :param string path: optional but recommended attributes. always try to use these first before introducing additional attributes. Logical full path to the module. The exact definition is implementation defined, but usually this would be a full path to the on-disk file for the module. :param boolean isOptimized: True if the module is optimized. :param boolean isUserCode: True if the module is considered 'user code' by a debugger that supports 'Just My Code'. :param string version: Version of Module. :param string symbolStatus: User understandable description of if symbols were found for the module (ex: 'Symbols Loaded', 'Symbols not found', etc. :param string symbolFilePath: Logical full path to the symbol file. The exact definition is implementation defined. :param string dateTimeStamp: Module created or modified. :param string addressRange: Address range covered by this module. """ self.id = id self.name = name self.path = path self.isOptimized = isOptimized self.isUserCode = isUserCode self.version = version self.symbolStatus = symbolStatus self.symbolFilePath = symbolFilePath self.dateTimeStamp = dateTimeStamp self.addressRange = addressRange self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) id = self.id # noqa (assign to builtin) name = self.name path = self.path isOptimized = self.isOptimized isUserCode = self.isUserCode version = self.version symbolStatus = self.symbolStatus symbolFilePath = self.symbolFilePath dateTimeStamp = self.dateTimeStamp addressRange = self.addressRange dct = { 'id': id, 'name': name, } if path is not None: dct['path'] = path if isOptimized is not None: dct['isOptimized'] = isOptimized if isUserCode is not None: dct['isUserCode'] = isUserCode if version is not None: dct['version'] = version if symbolStatus is not None: dct['symbolStatus'] = symbolStatus if symbolFilePath is not None: dct['symbolFilePath'] = symbolFilePath if dateTimeStamp is not None: dct['dateTimeStamp'] = dateTimeStamp if addressRange is not None: dct['addressRange'] = addressRange dct.update(self.kwargs) return dct @register class ColumnDescriptor(BaseSchema): """ A ColumnDescriptor specifies what module attribute to show in a column of the ModulesView, how to format it, and what the column's label should be. It is only used if the underlying UI actually supports this level of customization. Note: automatically generated code. Do not edit manually. """ __props__ = { "attributeName": { "type": "string", "description": "Name of the attribute rendered in this column." }, "label": { "type": "string", "description": "Header UI label of column." }, "format": { "type": "string", "description": "Format to use for the rendered values in this column. TBD how the format strings looks like." }, "type": { "type": "string", "enum": [ "string", "number", "boolean", "unixTimestampUTC" ], "description": "Datatype of values in this column. Defaults to 'string' if not specified." }, "width": { "type": "integer", "description": "Width of this column in characters (hint only)." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, attributeName, label, format=None, type=None, width=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string attributeName: Name of the attribute rendered in this column. :param string label: Header UI label of column. :param string format: Format to use for the rendered values in this column. TBD how the format strings looks like. :param string type: Datatype of values in this column. Defaults to 'string' if not specified. :param integer width: Width of this column in characters (hint only). """ self.attributeName = attributeName self.label = label self.format = format self.type = type self.width = width self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) attributeName = self.attributeName label = self.label format = self.format # noqa (assign to builtin) type = self.type # noqa (assign to builtin) width = self.width dct = { 'attributeName': attributeName, 'label': label, } if format is not None: dct['format'] = format if type is not None: dct['type'] = type if width is not None: dct['width'] = width dct.update(self.kwargs) return dct @register class ModulesViewDescriptor(BaseSchema): """ The ModulesViewDescriptor is the container for all declarative configuration options of a ModuleView. For now it only specifies the columns to be shown in the modules view. Note: automatically generated code. Do not edit manually. """ __props__ = { "columns": { "type": "array", "items": { "$ref": "#/definitions/ColumnDescriptor" } } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, columns, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array columns: """ self.columns = columns if update_ids_from_dap and self.columns: for o in self.columns: ColumnDescriptor.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) columns = self.columns dct = { 'columns': [ColumnDescriptor.update_dict_ids_to_dap(o) for o in columns] if (update_ids_to_dap and columns) else columns, } dct.update(self.kwargs) return dct @register class Thread(BaseSchema): """ A Thread Note: automatically generated code. Do not edit manually. """ __props__ = { "id": { "type": "integer", "description": "Unique identifier for the thread." }, "name": { "type": "string", "description": "A name of the thread." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, id, name, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer id: Unique identifier for the thread. :param string name: A name of the thread. """ self.id = id self.name = name self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) id = self.id # noqa (assign to builtin) name = self.name dct = { 'id': id, 'name': name, } dct.update(self.kwargs) return dct @register class Source(BaseSchema): """ A Source is a descriptor for source code. It is returned from the debug adapter as part of a StackFrame and it is used by clients when specifying breakpoints. Note: automatically generated code. Do not edit manually. """ __props__ = { "name": { "type": "string", "description": "The short name of the source. Every source returned from the debug adapter has a name. When sending a source to the debug adapter this name is optional." }, "path": { "type": "string", "description": "The path of the source to be shown in the UI. It is only used to locate and load the content of the source if no sourceReference is specified (or its value is 0)." }, "sourceReference": { "type": "number", "description": "If sourceReference > 0 the contents of the source must be retrieved through the SourceRequest (even if a path is specified). A sourceReference is only valid for a session, so it must not be used to persist a source." }, "presentationHint": { "type": "string", "description": "An optional hint for how to present the source in the UI. A value of 'deemphasize' can be used to indicate that the source is not available or that it is skipped on stepping.", "enum": [ "normal", "emphasize", "deemphasize" ] }, "origin": { "type": "string", "description": "The (optional) origin of this source: possible values 'internal module', 'inlined content from source map', etc." }, "sources": { "type": "array", "items": { "$ref": "#/definitions/Source" }, "description": "An optional list of sources that are related to this source. These may be the source that generated this source." }, "adapterData": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Optional data that a debug adapter might want to loop through the client. The client should leave the data intact and persist it across sessions. The client should not interpret the data." }, "checksums": { "type": "array", "items": { "$ref": "#/definitions/Checksum" }, "description": "The checksums associated with this file." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, name=None, path=None, sourceReference=None, presentationHint=None, origin=None, sources=None, adapterData=None, checksums=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string name: The short name of the source. Every source returned from the debug adapter has a name. When sending a source to the debug adapter this name is optional. :param string path: The path of the source to be shown in the UI. It is only used to locate and load the content of the source if no sourceReference is specified (or its value is 0). :param number sourceReference: If sourceReference > 0 the contents of the source must be retrieved through the SourceRequest (even if a path is specified). A sourceReference is only valid for a session, so it must not be used to persist a source. :param string presentationHint: An optional hint for how to present the source in the UI. A value of 'deemphasize' can be used to indicate that the source is not available or that it is skipped on stepping. :param string origin: The (optional) origin of this source: possible values 'internal module', 'inlined content from source map', etc. :param array sources: An optional list of sources that are related to this source. These may be the source that generated this source. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] adapterData: Optional data that a debug adapter might want to loop through the client. The client should leave the data intact and persist it across sessions. The client should not interpret the data. :param array checksums: The checksums associated with this file. """ self.name = name self.path = path self.sourceReference = sourceReference self.presentationHint = presentationHint self.origin = origin self.sources = sources if update_ids_from_dap and self.sources: for o in self.sources: Source.update_dict_ids_from_dap(o) self.adapterData = adapterData self.checksums = checksums if update_ids_from_dap and self.checksums: for o in self.checksums: Checksum.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) name = self.name path = self.path sourceReference = self.sourceReference presentationHint = self.presentationHint origin = self.origin sources = self.sources adapterData = self.adapterData checksums = self.checksums dct = { } if name is not None: dct['name'] = name if path is not None: dct['path'] = path if sourceReference is not None: dct['sourceReference'] = sourceReference if presentationHint is not None: dct['presentationHint'] = presentationHint if origin is not None: dct['origin'] = origin if sources is not None: dct['sources'] = [Source.update_dict_ids_to_dap(o) for o in sources] if (update_ids_to_dap and sources) else sources if adapterData is not None: dct['adapterData'] = adapterData if checksums is not None: dct['checksums'] = [Checksum.update_dict_ids_to_dap(o) for o in checksums] if (update_ids_to_dap and checksums) else checksums dct.update(self.kwargs) return dct @register class StackFrame(BaseSchema): """ A Stackframe contains the source location. Note: automatically generated code. Do not edit manually. """ __props__ = { "id": { "type": "integer", "description": "An identifier for the stack frame. It must be unique across all threads. This id can be used to retrieve the scopes of the frame with the 'scopesRequest' or to restart the execution of a stackframe." }, "name": { "type": "string", "description": "The name of the stack frame, typically a method name." }, "source": { "description": "The optional source of the frame.", "type": "Source" }, "line": { "type": "integer", "description": "The line within the file of the frame. If source is null or doesn't exist, line is 0 and must be ignored." }, "column": { "type": "integer", "description": "The column within the line. If source is null or doesn't exist, column is 0 and must be ignored." }, "endLine": { "type": "integer", "description": "An optional end line of the range covered by the stack frame." }, "endColumn": { "type": "integer", "description": "An optional end column of the range covered by the stack frame." }, "moduleId": { "type": [ "integer", "string" ], "description": "The module associated with this frame, if any." }, "presentationHint": { "type": "string", "enum": [ "normal", "label", "subtle" ], "description": "An optional hint for how to present this frame in the UI. A value of 'label' can be used to indicate that the frame is an artificial frame that is used as a visual label or separator. A value of 'subtle' can be used to change the appearance of a frame in a 'subtle' way." } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, id, name, line, column, source=None, endLine=None, endColumn=None, moduleId=None, presentationHint=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer id: An identifier for the stack frame. It must be unique across all threads. This id can be used to retrieve the scopes of the frame with the 'scopesRequest' or to restart the execution of a stackframe. :param string name: The name of the stack frame, typically a method name. :param integer line: The line within the file of the frame. If source is null or doesn't exist, line is 0 and must be ignored. :param integer column: The column within the line. If source is null or doesn't exist, column is 0 and must be ignored. :param Source source: The optional source of the frame. :param integer endLine: An optional end line of the range covered by the stack frame. :param integer endColumn: An optional end column of the range covered by the stack frame. :param ['integer', 'string'] moduleId: The module associated with this frame, if any. :param string presentationHint: An optional hint for how to present this frame in the UI. A value of 'label' can be used to indicate that the frame is an artificial frame that is used as a visual label or separator. A value of 'subtle' can be used to change the appearance of a frame in a 'subtle' way. """ self.id = id self.name = name self.line = line self.column = column if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.endLine = endLine self.endColumn = endColumn self.moduleId = moduleId self.presentationHint = presentationHint if update_ids_from_dap: self.id = self._translate_id_from_dap(self.id) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'id' in dct: dct['id'] = cls._translate_id_from_dap(dct['id']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) id = self.id # noqa (assign to builtin) name = self.name line = self.line column = self.column source = self.source endLine = self.endLine endColumn = self.endColumn moduleId = self.moduleId presentationHint = self.presentationHint if update_ids_to_dap: if id is not None: id = self._translate_id_to_dap(id) # noqa (assign to builtin) dct = { 'id': id, 'name': name, 'line': line, 'column': column, } if source is not None: dct['source'] = source.to_dict(update_ids_to_dap=update_ids_to_dap) if endLine is not None: dct['endLine'] = endLine if endColumn is not None: dct['endColumn'] = endColumn if moduleId is not None: dct['moduleId'] = moduleId if presentationHint is not None: dct['presentationHint'] = presentationHint dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'id' in dct: dct['id'] = cls._translate_id_to_dap(dct['id']) return dct @register class Scope(BaseSchema): """ A Scope is a named container for variables. Optionally a scope can map to a source or a range within a source. Note: automatically generated code. Do not edit manually. """ __props__ = { "name": { "type": "string", "description": "Name of the scope such as 'Arguments', 'Locals'." }, "variablesReference": { "type": "integer", "description": "The variables of this scope can be retrieved by passing the value of variablesReference to the VariablesRequest." }, "namedVariables": { "type": "integer", "description": "The number of named variables in this scope.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "integer", "description": "The number of indexed variables in this scope.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "expensive": { "type": "boolean", "description": "If true, the number of variables in this scope is large or expensive to retrieve." }, "source": { "description": "Optional source for this scope.", "type": "Source" }, "line": { "type": "integer", "description": "Optional start line of the range covered by this scope." }, "column": { "type": "integer", "description": "Optional start column of the range covered by this scope." }, "endLine": { "type": "integer", "description": "Optional end line of the range covered by this scope." }, "endColumn": { "type": "integer", "description": "Optional end column of the range covered by this scope." } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, name, variablesReference, expensive, namedVariables=None, indexedVariables=None, source=None, line=None, column=None, endLine=None, endColumn=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string name: Name of the scope such as 'Arguments', 'Locals'. :param integer variablesReference: The variables of this scope can be retrieved by passing the value of variablesReference to the VariablesRequest. :param boolean expensive: If true, the number of variables in this scope is large or expensive to retrieve. :param integer namedVariables: The number of named variables in this scope. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. :param integer indexedVariables: The number of indexed variables in this scope. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. :param Source source: Optional source for this scope. :param integer line: Optional start line of the range covered by this scope. :param integer column: Optional start column of the range covered by this scope. :param integer endLine: Optional end line of the range covered by this scope. :param integer endColumn: Optional end column of the range covered by this scope. """ self.name = name self.variablesReference = variablesReference self.expensive = expensive self.namedVariables = namedVariables self.indexedVariables = indexedVariables if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.line = line self.column = column self.endLine = endLine self.endColumn = endColumn if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) name = self.name variablesReference = self.variablesReference expensive = self.expensive namedVariables = self.namedVariables indexedVariables = self.indexedVariables source = self.source line = self.line column = self.column endLine = self.endLine endColumn = self.endColumn if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'name': name, 'variablesReference': variablesReference, 'expensive': expensive, } if namedVariables is not None: dct['namedVariables'] = namedVariables if indexedVariables is not None: dct['indexedVariables'] = indexedVariables if source is not None: dct['source'] = source.to_dict(update_ids_to_dap=update_ids_to_dap) if line is not None: dct['line'] = line if column is not None: dct['column'] = column if endLine is not None: dct['endLine'] = endLine if endColumn is not None: dct['endColumn'] = endColumn dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register class Variable(BaseSchema): """ A Variable is a name/value pair. Optionally a variable can have a 'type' that is shown if space permits or when hovering over the variable's name. An optional 'kind' is used to render additional properties of the variable, e.g. different icons can be used to indicate that a variable is public or private. If the value is structured (has children), a handle is provided to retrieve the children with the VariablesRequest. If the number of named or indexed children is large, the numbers should be returned via the optional 'namedVariables' and 'indexedVariables' attributes. The client can use this optional information to present the children in a paged UI and fetch them in chunks. Note: automatically generated code. Do not edit manually. """ __props__ = { "name": { "type": "string", "description": "The variable's name." }, "value": { "type": "string", "description": "The variable's value. This can be a multi-line text, e.g. for a function the body of a function." }, "type": { "type": "string", "description": "The type of the variable's value. Typically shown in the UI when hovering over the value." }, "presentationHint": { "description": "Properties of a variable that can be used to determine how to render the variable in the UI.", "type": "VariablePresentationHint" }, "evaluateName": { "type": "string", "description": "Optional evaluatable name of this variable which can be passed to the 'EvaluateRequest' to fetch the variable's value." }, "variablesReference": { "type": "integer", "description": "If variablesReference is > 0, the variable is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." }, "namedVariables": { "type": "integer", "description": "The number of named child variables.\nThe client can use this optional information to present the children in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "integer", "description": "The number of indexed child variables.\nThe client can use this optional information to present the children in a paged UI and fetch them in chunks." } } __refs__ = set(['presentationHint']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, name, value, variablesReference, type=None, presentationHint=None, evaluateName=None, namedVariables=None, indexedVariables=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string name: The variable's name. :param string value: The variable's value. This can be a multi-line text, e.g. for a function the body of a function. :param integer variablesReference: If variablesReference is > 0, the variable is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. :param string type: The type of the variable's value. Typically shown in the UI when hovering over the value. :param VariablePresentationHint presentationHint: Properties of a variable that can be used to determine how to render the variable in the UI. :param string evaluateName: Optional evaluatable name of this variable which can be passed to the 'EvaluateRequest' to fetch the variable's value. :param integer namedVariables: The number of named child variables. The client can use this optional information to present the children in a paged UI and fetch them in chunks. :param integer indexedVariables: The number of indexed child variables. The client can use this optional information to present the children in a paged UI and fetch them in chunks. """ self.name = name self.value = value self.variablesReference = variablesReference self.type = type if presentationHint is None: self.presentationHint = VariablePresentationHint() else: self.presentationHint = VariablePresentationHint(update_ids_from_dap=update_ids_from_dap, **presentationHint) if presentationHint.__class__ != VariablePresentationHint else presentationHint self.evaluateName = evaluateName self.namedVariables = namedVariables self.indexedVariables = indexedVariables if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) name = self.name value = self.value variablesReference = self.variablesReference type = self.type # noqa (assign to builtin) presentationHint = self.presentationHint evaluateName = self.evaluateName namedVariables = self.namedVariables indexedVariables = self.indexedVariables if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'name': name, 'value': value, 'variablesReference': variablesReference, } if type is not None: dct['type'] = type if presentationHint is not None: dct['presentationHint'] = presentationHint.to_dict(update_ids_to_dap=update_ids_to_dap) if evaluateName is not None: dct['evaluateName'] = evaluateName if namedVariables is not None: dct['namedVariables'] = namedVariables if indexedVariables is not None: dct['indexedVariables'] = indexedVariables dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register class VariablePresentationHint(BaseSchema): """ Optional properties of a variable that can be used to determine how to render the variable in the UI. Note: automatically generated code. Do not edit manually. """ __props__ = { "kind": { "description": "The kind of variable. Before introducing additional values, try to use the listed values.", "type": "string", "_enum": [ "property", "method", "class", "data", "event", "baseClass", "innerClass", "interface", "mostDerivedClass", "virtual" ], "enumDescriptions": [ "Indicates that the object is a property.", "Indicates that the object is a method.", "Indicates that the object is a class.", "Indicates that the object is data.", "Indicates that the object is an event.", "Indicates that the object is a base class.", "Indicates that the object is an inner class.", "Indicates that the object is an interface.", "Indicates that the object is the most derived class.", "Indicates that the object is virtual, that means it is a synthetic object introduced by the adapter for rendering purposes, e.g. an index range for large arrays." ] }, "attributes": { "description": "Set of attributes represented as an array of strings. Before introducing additional values, try to use the listed values.", "type": "array", "items": { "type": "string", "_enum": [ "static", "constant", "readOnly", "rawString", "hasObjectId", "canHaveObjectId", "hasSideEffects" ], "enumDescriptions": [ "Indicates that the object is static.", "Indicates that the object is a constant.", "Indicates that the object is read only.", "Indicates that the object is a raw string.", "Indicates that the object can have an Object ID created for it.", "Indicates that the object has an Object ID associated with it.", "Indicates that the evaluation had side effects." ] } }, "visibility": { "description": "Visibility of variable. Before introducing additional values, try to use the listed values.", "type": "string", "_enum": [ "public", "private", "protected", "internal", "final" ] } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, kind=None, attributes=None, visibility=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string kind: The kind of variable. Before introducing additional values, try to use the listed values. :param array attributes: Set of attributes represented as an array of strings. Before introducing additional values, try to use the listed values. :param string visibility: Visibility of variable. Before introducing additional values, try to use the listed values. """ self.kind = kind self.attributes = attributes self.visibility = visibility self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) kind = self.kind attributes = self.attributes visibility = self.visibility dct = { } if kind is not None: dct['kind'] = kind if attributes is not None: dct['attributes'] = attributes if visibility is not None: dct['visibility'] = visibility dct.update(self.kwargs) return dct @register class SourceBreakpoint(BaseSchema): """ Properties of a breakpoint or logpoint passed to the setBreakpoints request. Note: automatically generated code. Do not edit manually. """ __props__ = { "line": { "type": "integer", "description": "The source line of the breakpoint or logpoint." }, "column": { "type": "integer", "description": "An optional source column of the breakpoint." }, "condition": { "type": "string", "description": "An optional expression for conditional breakpoints." }, "hitCondition": { "type": "string", "description": "An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed." }, "logMessage": { "type": "string", "description": "If this attribute exists and is non-empty, the backend must not 'break' (stop) but log the message instead. Expressions within {} are interpolated." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, line, column=None, condition=None, hitCondition=None, logMessage=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer line: The source line of the breakpoint or logpoint. :param integer column: An optional source column of the breakpoint. :param string condition: An optional expression for conditional breakpoints. :param string hitCondition: An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed. :param string logMessage: If this attribute exists and is non-empty, the backend must not 'break' (stop) but log the message instead. Expressions within {} are interpolated. """ self.line = line self.column = column self.condition = condition self.hitCondition = hitCondition self.logMessage = logMessage self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) line = self.line column = self.column condition = self.condition hitCondition = self.hitCondition logMessage = self.logMessage dct = { 'line': line, } if column is not None: dct['column'] = column if condition is not None: dct['condition'] = condition if hitCondition is not None: dct['hitCondition'] = hitCondition if logMessage is not None: dct['logMessage'] = logMessage dct.update(self.kwargs) return dct @register class FunctionBreakpoint(BaseSchema): """ Properties of a breakpoint passed to the setFunctionBreakpoints request. Note: automatically generated code. Do not edit manually. """ __props__ = { "name": { "type": "string", "description": "The name of the function." }, "condition": { "type": "string", "description": "An optional expression for conditional breakpoints." }, "hitCondition": { "type": "string", "description": "An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, name, condition=None, hitCondition=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string name: The name of the function. :param string condition: An optional expression for conditional breakpoints. :param string hitCondition: An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed. """ self.name = name self.condition = condition self.hitCondition = hitCondition self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) name = self.name condition = self.condition hitCondition = self.hitCondition dct = { 'name': name, } if condition is not None: dct['condition'] = condition if hitCondition is not None: dct['hitCondition'] = hitCondition dct.update(self.kwargs) return dct @register class Breakpoint(BaseSchema): """ Information about a Breakpoint created in setBreakpoints or setFunctionBreakpoints. Note: automatically generated code. Do not edit manually. """ __props__ = { "id": { "type": "integer", "description": "An optional identifier for the breakpoint. It is needed if breakpoint events are used to update or remove breakpoints." }, "verified": { "type": "boolean", "description": "If true breakpoint could be set (but not necessarily at the desired location)." }, "message": { "type": "string", "description": "An optional message about the state of the breakpoint. This is shown to the user and can be used to explain why a breakpoint could not be verified." }, "source": { "description": "The source where the breakpoint is located.", "type": "Source" }, "line": { "type": "integer", "description": "The start line of the actual range covered by the breakpoint." }, "column": { "type": "integer", "description": "An optional start column of the actual range covered by the breakpoint." }, "endLine": { "type": "integer", "description": "An optional end line of the actual range covered by the breakpoint." }, "endColumn": { "type": "integer", "description": "An optional end column of the actual range covered by the breakpoint. If no end line is given, then the end column is assumed to be in the start line." } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, verified, id=None, message=None, source=None, line=None, column=None, endLine=None, endColumn=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean verified: If true breakpoint could be set (but not necessarily at the desired location). :param integer id: An optional identifier for the breakpoint. It is needed if breakpoint events are used to update or remove breakpoints. :param string message: An optional message about the state of the breakpoint. This is shown to the user and can be used to explain why a breakpoint could not be verified. :param Source source: The source where the breakpoint is located. :param integer line: The start line of the actual range covered by the breakpoint. :param integer column: An optional start column of the actual range covered by the breakpoint. :param integer endLine: An optional end line of the actual range covered by the breakpoint. :param integer endColumn: An optional end column of the actual range covered by the breakpoint. If no end line is given, then the end column is assumed to be in the start line. """ self.verified = verified self.id = id self.message = message if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.line = line self.column = column self.endLine = endLine self.endColumn = endColumn self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) verified = self.verified id = self.id # noqa (assign to builtin) message = self.message source = self.source line = self.line column = self.column endLine = self.endLine endColumn = self.endColumn dct = { 'verified': verified, } if id is not None: dct['id'] = id if message is not None: dct['message'] = message if source is not None: dct['source'] = source.to_dict(update_ids_to_dap=update_ids_to_dap) if line is not None: dct['line'] = line if column is not None: dct['column'] = column if endLine is not None: dct['endLine'] = endLine if endColumn is not None: dct['endColumn'] = endColumn dct.update(self.kwargs) return dct @register class StepInTarget(BaseSchema): """ A StepInTarget can be used in the 'stepIn' request and determines into which single target the stepIn request should step. Note: automatically generated code. Do not edit manually. """ __props__ = { "id": { "type": "integer", "description": "Unique identifier for a stepIn target." }, "label": { "type": "string", "description": "The name of the stepIn target (shown in the UI)." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, id, label, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer id: Unique identifier for a stepIn target. :param string label: The name of the stepIn target (shown in the UI). """ self.id = id self.label = label self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) id = self.id # noqa (assign to builtin) label = self.label dct = { 'id': id, 'label': label, } dct.update(self.kwargs) return dct @register class GotoTarget(BaseSchema): """ A GotoTarget describes a code location that can be used as a target in the 'goto' request. The possible goto targets can be determined via the 'gotoTargets' request. Note: automatically generated code. Do not edit manually. """ __props__ = { "id": { "type": "integer", "description": "Unique identifier for a goto target. This is used in the goto request." }, "label": { "type": "string", "description": "The name of the goto target (shown in the UI)." }, "line": { "type": "integer", "description": "The line of the goto target." }, "column": { "type": "integer", "description": "An optional column of the goto target." }, "endLine": { "type": "integer", "description": "An optional end line of the range covered by the goto target." }, "endColumn": { "type": "integer", "description": "An optional end column of the range covered by the goto target." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, id, label, line, column=None, endLine=None, endColumn=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer id: Unique identifier for a goto target. This is used in the goto request. :param string label: The name of the goto target (shown in the UI). :param integer line: The line of the goto target. :param integer column: An optional column of the goto target. :param integer endLine: An optional end line of the range covered by the goto target. :param integer endColumn: An optional end column of the range covered by the goto target. """ self.id = id self.label = label self.line = line self.column = column self.endLine = endLine self.endColumn = endColumn self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) id = self.id # noqa (assign to builtin) label = self.label line = self.line column = self.column endLine = self.endLine endColumn = self.endColumn dct = { 'id': id, 'label': label, 'line': line, } if column is not None: dct['column'] = column if endLine is not None: dct['endLine'] = endLine if endColumn is not None: dct['endColumn'] = endColumn dct.update(self.kwargs) return dct @register class CompletionItem(BaseSchema): """ CompletionItems are the suggestions returned from the CompletionsRequest. Note: automatically generated code. Do not edit manually. """ __props__ = { "label": { "type": "string", "description": "The label of this completion item. By default this is also the text that is inserted when selecting this completion." }, "text": { "type": "string", "description": "If text is not falsy then it is inserted instead of the label." }, "type": { "description": "The item's type. Typically the client uses this information to render the item in the UI with an icon.", "type": "CompletionItemType" }, "start": { "type": "integer", "description": "This value determines the location (in the CompletionsRequest's 'text' attribute) where the completion text is added.\nIf missing the text is added at the location specified by the CompletionsRequest's 'column' attribute." }, "length": { "type": "integer", "description": "This value determines how many characters are overwritten by the completion text.\nIf missing the value 0 is assumed which results in the completion text being inserted." } } __refs__ = set(['type']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, label, text=None, type=None, start=None, length=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string label: The label of this completion item. By default this is also the text that is inserted when selecting this completion. :param string text: If text is not falsy then it is inserted instead of the label. :param CompletionItemType type: The item's type. Typically the client uses this information to render the item in the UI with an icon. :param integer start: This value determines the location (in the CompletionsRequest's 'text' attribute) where the completion text is added. If missing the text is added at the location specified by the CompletionsRequest's 'column' attribute. :param integer length: This value determines how many characters are overwritten by the completion text. If missing the value 0 is assumed which results in the completion text being inserted. """ self.label = label self.text = text assert type in CompletionItemType.VALID_VALUES self.type = type self.start = start self.length = length self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) label = self.label text = self.text type = self.type # noqa (assign to builtin) start = self.start length = self.length dct = { 'label': label, } if text is not None: dct['text'] = text if type is not None: dct['type'] = type if start is not None: dct['start'] = start if length is not None: dct['length'] = length dct.update(self.kwargs) return dct @register class CompletionItemType(BaseSchema): """ Some predefined types for the CompletionItem. Please note that not all clients have specific icons for all of them. Note: automatically generated code. Do not edit manually. """ METHOD = 'method' FUNCTION = 'function' CONSTRUCTOR = 'constructor' FIELD = 'field' VARIABLE = 'variable' CLASS = 'class' INTERFACE = 'interface' MODULE = 'module' PROPERTY = 'property' UNIT = 'unit' VALUE = 'value' ENUM = 'enum' KEYWORD = 'keyword' SNIPPET = 'snippet' TEXT = 'text' COLOR = 'color' FILE = 'file' REFERENCE = 'reference' CUSTOMCOLOR = 'customcolor' VALID_VALUES = set(['method', 'function', 'constructor', 'field', 'variable', 'class', 'interface', 'module', 'property', 'unit', 'value', 'enum', 'keyword', 'snippet', 'text', 'color', 'file', 'reference', 'customcolor']) __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register class ChecksumAlgorithm(BaseSchema): """ Names of checksum algorithms that may be supported by a debug adapter. Note: automatically generated code. Do not edit manually. """ MD5 = 'MD5' SHA1 = 'SHA1' SHA256 = 'SHA256' TIMESTAMP = 'timestamp' VALID_VALUES = set(['MD5', 'SHA1', 'SHA256', 'timestamp']) __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register class Checksum(BaseSchema): """ The checksum of an item calculated by the specified algorithm. Note: automatically generated code. Do not edit manually. """ __props__ = { "algorithm": { "description": "The algorithm used to calculate this checksum.", "type": "ChecksumAlgorithm" }, "checksum": { "type": "string", "description": "Value of the checksum." } } __refs__ = set(['algorithm']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, algorithm, checksum, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param ChecksumAlgorithm algorithm: The algorithm used to calculate this checksum. :param string checksum: Value of the checksum. """ assert algorithm in ChecksumAlgorithm.VALID_VALUES self.algorithm = algorithm self.checksum = checksum self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) algorithm = self.algorithm checksum = self.checksum dct = { 'algorithm': algorithm, 'checksum': checksum, } dct.update(self.kwargs) return dct @register class ValueFormat(BaseSchema): """ Provides formatting information for a value. Note: automatically generated code. Do not edit manually. """ __props__ = { "hex": { "type": "boolean", "description": "Display the value in hex." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, hex=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean hex: Display the value in hex. """ self.hex = hex self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) hex = self.hex # noqa (assign to builtin) dct = { } if hex is not None: dct['hex'] = hex dct.update(self.kwargs) return dct @register class StackFrameFormat(BaseSchema): """ Provides formatting information for a stack frame. Note: automatically generated code. Do not edit manually. """ __props__ = { "hex": { "type": "boolean", "description": "Display the value in hex." }, "parameters": { "type": "boolean", "description": "Displays parameters for the stack frame." }, "parameterTypes": { "type": "boolean", "description": "Displays the types of parameters for the stack frame." }, "parameterNames": { "type": "boolean", "description": "Displays the names of parameters for the stack frame." }, "parameterValues": { "type": "boolean", "description": "Displays the values of parameters for the stack frame." }, "line": { "type": "boolean", "description": "Displays the line number of the stack frame." }, "module": { "type": "boolean", "description": "Displays the module of the stack frame." }, "includeAll": { "type": "boolean", "description": "Includes all stack frames, including those the debug adapter might otherwise hide." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, hex=None, parameters=None, parameterTypes=None, parameterNames=None, parameterValues=None, line=None, module=None, includeAll=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean hex: Display the value in hex. :param boolean parameters: Displays parameters for the stack frame. :param boolean parameterTypes: Displays the types of parameters for the stack frame. :param boolean parameterNames: Displays the names of parameters for the stack frame. :param boolean parameterValues: Displays the values of parameters for the stack frame. :param boolean line: Displays the line number of the stack frame. :param boolean module: Displays the module of the stack frame. :param boolean includeAll: Includes all stack frames, including those the debug adapter might otherwise hide. """ self.hex = hex self.parameters = parameters self.parameterTypes = parameterTypes self.parameterNames = parameterNames self.parameterValues = parameterValues self.line = line self.module = module self.includeAll = includeAll self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) hex = self.hex # noqa (assign to builtin) parameters = self.parameters parameterTypes = self.parameterTypes parameterNames = self.parameterNames parameterValues = self.parameterValues line = self.line module = self.module includeAll = self.includeAll dct = { } if hex is not None: dct['hex'] = hex if parameters is not None: dct['parameters'] = parameters if parameterTypes is not None: dct['parameterTypes'] = parameterTypes if parameterNames is not None: dct['parameterNames'] = parameterNames if parameterValues is not None: dct['parameterValues'] = parameterValues if line is not None: dct['line'] = line if module is not None: dct['module'] = module if includeAll is not None: dct['includeAll'] = includeAll dct.update(self.kwargs) return dct @register class ExceptionOptions(BaseSchema): """ An ExceptionOptions assigns configuration options to a set of exceptions. Note: automatically generated code. Do not edit manually. """ __props__ = { "path": { "type": "array", "items": { "$ref": "#/definitions/ExceptionPathSegment" }, "description": "A path that selects a single or multiple exceptions in a tree. If 'path' is missing, the whole tree is selected. By convention the first segment of the path is a category that is used to group exceptions in the UI." }, "breakMode": { "description": "Condition when a thrown exception should result in a break.", "type": "ExceptionBreakMode" } } __refs__ = set(['breakMode']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, breakMode, path=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param ExceptionBreakMode breakMode: Condition when a thrown exception should result in a break. :param array path: A path that selects a single or multiple exceptions in a tree. If 'path' is missing, the whole tree is selected. By convention the first segment of the path is a category that is used to group exceptions in the UI. """ assert breakMode in ExceptionBreakMode.VALID_VALUES self.breakMode = breakMode self.path = path if update_ids_from_dap and self.path: for o in self.path: ExceptionPathSegment.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) breakMode = self.breakMode path = self.path dct = { 'breakMode': breakMode, } if path is not None: dct['path'] = [ExceptionPathSegment.update_dict_ids_to_dap(o) for o in path] if (update_ids_to_dap and path) else path dct.update(self.kwargs) return dct @register class ExceptionBreakMode(BaseSchema): """ This enumeration defines all possible conditions when a thrown exception should result in a break. never: never breaks, always: always breaks, unhandled: breaks when excpetion unhandled, userUnhandled: breaks if the exception is not handled by user code. Note: automatically generated code. Do not edit manually. """ NEVER = 'never' ALWAYS = 'always' UNHANDLED = 'unhandled' USERUNHANDLED = 'userUnhandled' VALID_VALUES = set(['never', 'always', 'unhandled', 'userUnhandled']) __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register class ExceptionPathSegment(BaseSchema): """ An ExceptionPathSegment represents a segment in a path that is used to match leafs or nodes in a tree of exceptions. If a segment consists of more than one name, it matches the names provided if 'negate' is false or missing or it matches anything except the names provided if 'negate' is true. Note: automatically generated code. Do not edit manually. """ __props__ = { "negate": { "type": "boolean", "description": "If false or missing this segment matches the names provided, otherwise it matches anything except the names provided." }, "names": { "type": "array", "items": { "type": "string" }, "description": "Depending on the value of 'negate' the names that should match or not match." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, names, negate=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array names: Depending on the value of 'negate' the names that should match or not match. :param boolean negate: If false or missing this segment matches the names provided, otherwise it matches anything except the names provided. """ self.names = names self.negate = negate self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) names = self.names negate = self.negate dct = { 'names': names, } if negate is not None: dct['negate'] = negate dct.update(self.kwargs) return dct @register class ExceptionDetails(BaseSchema): """ Detailed information about an exception that has occurred. Note: automatically generated code. Do not edit manually. """ __props__ = { "message": { "type": "string", "description": "Message contained in the exception." }, "typeName": { "type": "string", "description": "Short type name of the exception object." }, "fullTypeName": { "type": "string", "description": "Fully-qualified type name of the exception object." }, "evaluateName": { "type": "string", "description": "Optional expression that can be evaluated in the current scope to obtain the exception object." }, "stackTrace": { "type": "string", "description": "Stack trace at the time the exception was thrown." }, "innerException": { "type": "array", "items": { "$ref": "#/definitions/ExceptionDetails" }, "description": "Details of the exception contained by this exception, if any." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, message=None, typeName=None, fullTypeName=None, evaluateName=None, stackTrace=None, innerException=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string message: Message contained in the exception. :param string typeName: Short type name of the exception object. :param string fullTypeName: Fully-qualified type name of the exception object. :param string evaluateName: Optional expression that can be evaluated in the current scope to obtain the exception object. :param string stackTrace: Stack trace at the time the exception was thrown. :param array innerException: Details of the exception contained by this exception, if any. """ self.message = message self.typeName = typeName self.fullTypeName = fullTypeName self.evaluateName = evaluateName self.stackTrace = stackTrace self.innerException = innerException if update_ids_from_dap and self.innerException: for o in self.innerException: ExceptionDetails.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) message = self.message typeName = self.typeName fullTypeName = self.fullTypeName evaluateName = self.evaluateName stackTrace = self.stackTrace innerException = self.innerException dct = { } if message is not None: dct['message'] = message if typeName is not None: dct['typeName'] = typeName if fullTypeName is not None: dct['fullTypeName'] = fullTypeName if evaluateName is not None: dct['evaluateName'] = evaluateName if stackTrace is not None: dct['stackTrace'] = stackTrace if innerException is not None: dct['innerException'] = [ExceptionDetails.update_dict_ids_to_dap(o) for o in innerException] if (update_ids_to_dap and innerException) else innerException dct.update(self.kwargs) return dct @register_request('setDebuggerProperty') @register class SetDebuggerPropertyRequest(BaseSchema): """ The request can be used to enable or disable debugger features. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "enum": [ "setDebuggerProperty" ] }, "arguments": { "type": "SetDebuggerPropertyArguments" } } __refs__ = set(['arguments']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, arguments, seq=-1, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param string command: :param SetDebuggerPropertyArguments arguments: :param integer seq: Sequence number. """ self.type = 'request' self.command = 'setDebuggerProperty' if arguments is None: self.arguments = SetDebuggerPropertyArguments() else: self.arguments = SetDebuggerPropertyArguments(update_ids_from_dap=update_ids_from_dap, **arguments) if arguments.__class__ != SetDebuggerPropertyArguments else arguments self.seq = seq self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) command = self.command arguments = self.arguments seq = self.seq dct = { 'type': type, 'command': command, 'arguments': arguments.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } dct.update(self.kwargs) return dct @register class SetDebuggerPropertyArguments(BaseSchema): """ Arguments for 'setDebuggerProperty' request. Note: automatically generated code. Do not edit manually. """ __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register_response('setDebuggerProperty') @register class SetDebuggerPropertyResponse(BaseSchema): """ Response to 'setDebuggerProperty' request. This is just an acknowledgement, so no body field is required. Note: automatically generated code. Do not edit manually. """ __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "response" ] }, "request_seq": { "type": "integer", "description": "Sequence number of the corresponding request." }, "success": { "type": "boolean", "description": "Outcome of the request." }, "command": { "type": "string", "description": "The command requested." }, "message": { "type": "string", "description": "Contains error message if success == false." }, "body": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Contains request result if success is true and optional error details if success is false." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, request_seq, success, command, seq=-1, message=None, body=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string type: :param integer request_seq: Sequence number of the corresponding request. :param boolean success: Outcome of the request. :param string command: The command requested. :param integer seq: Sequence number. :param string message: Contains error message if success == false. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] body: Contains request result if success is true and optional error details if success is false. """ self.type = 'response' self.request_seq = request_seq self.success = success self.command = command self.seq = seq self.message = message self.body = body self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) type = self.type # noqa (assign to builtin) request_seq = self.request_seq success = self.success command = self.command seq = self.seq message = self.message body = self.body dct = { 'type': type, 'request_seq': request_seq, 'success': success, 'command': command, 'seq': seq, } if message is not None: dct['message'] = message if body is not None: dct['body'] = body dct.update(self.kwargs) return dct @register class ErrorResponseBody(BaseSchema): """ "body" of ErrorResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "error": { "description": "An optional, structured error message.", "type": "Message" } } __refs__ = set(['error']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, error=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param Message error: An optional, structured error message. """ if error is None: self.error = Message() else: self.error = Message(update_ids_from_dap=update_ids_from_dap, **error) if error.__class__ != Message else error self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) error = self.error dct = { } if error is not None: dct['error'] = error.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register class StoppedEventBody(BaseSchema): """ "body" of StoppedEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "reason": { "type": "string", "description": "The reason for the event.\nFor backward compatibility this string is shown in the UI if the 'description' attribute is missing (but it must not be translated).", "_enum": [ "step", "breakpoint", "exception", "pause", "entry", "goto" ] }, "description": { "type": "string", "description": "The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and must be translated." }, "threadId": { "type": "integer", "description": "The thread which was stopped." }, "preserveFocusHint": { "type": "boolean", "description": "A value of true hints to the frontend that this event should not change the focus." }, "text": { "type": "string", "description": "Additional information. E.g. if reason is 'exception', text contains the exception name. This string is shown in the UI." }, "allThreadsStopped": { "type": "boolean", "description": "If 'allThreadsStopped' is true, a debug adapter can announce that all threads have stopped.\n- The client should use this information to enable that all threads can be expanded to access their stacktraces.\n- If the attribute is missing or false, only the thread with the given threadId can be expanded." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, reason, description=None, threadId=None, preserveFocusHint=None, text=None, allThreadsStopped=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string reason: The reason for the event. For backward compatibility this string is shown in the UI if the 'description' attribute is missing (but it must not be translated). :param string description: The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and must be translated. :param integer threadId: The thread which was stopped. :param boolean preserveFocusHint: A value of true hints to the frontend that this event should not change the focus. :param string text: Additional information. E.g. if reason is 'exception', text contains the exception name. This string is shown in the UI. :param boolean allThreadsStopped: If 'allThreadsStopped' is true, a debug adapter can announce that all threads have stopped. - The client should use this information to enable that all threads can be expanded to access their stacktraces. - If the attribute is missing or false, only the thread with the given threadId can be expanded. """ self.reason = reason self.description = description self.threadId = threadId self.preserveFocusHint = preserveFocusHint self.text = text self.allThreadsStopped = allThreadsStopped self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) reason = self.reason description = self.description threadId = self.threadId preserveFocusHint = self.preserveFocusHint text = self.text allThreadsStopped = self.allThreadsStopped dct = { 'reason': reason, } if description is not None: dct['description'] = description if threadId is not None: dct['threadId'] = threadId if preserveFocusHint is not None: dct['preserveFocusHint'] = preserveFocusHint if text is not None: dct['text'] = text if allThreadsStopped is not None: dct['allThreadsStopped'] = allThreadsStopped dct.update(self.kwargs) return dct @register class ContinuedEventBody(BaseSchema): """ "body" of ContinuedEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "threadId": { "type": "integer", "description": "The thread which was continued." }, "allThreadsContinued": { "type": "boolean", "description": "If 'allThreadsContinued' is true, a debug adapter can announce that all threads have continued." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threadId, allThreadsContinued=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer threadId: The thread which was continued. :param boolean allThreadsContinued: If 'allThreadsContinued' is true, a debug adapter can announce that all threads have continued. """ self.threadId = threadId self.allThreadsContinued = allThreadsContinued self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threadId = self.threadId allThreadsContinued = self.allThreadsContinued dct = { 'threadId': threadId, } if allThreadsContinued is not None: dct['allThreadsContinued'] = allThreadsContinued dct.update(self.kwargs) return dct @register class ExitedEventBody(BaseSchema): """ "body" of ExitedEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "exitCode": { "type": "integer", "description": "The exit code returned from the debuggee." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, exitCode, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param integer exitCode: The exit code returned from the debuggee. """ self.exitCode = exitCode self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) exitCode = self.exitCode dct = { 'exitCode': exitCode, } dct.update(self.kwargs) return dct @register class TerminatedEventBody(BaseSchema): """ "body" of TerminatedEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "restart": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "A debug adapter may set 'restart' to true (or to an arbitrary object) to request that the front end restarts the session.\nThe value is not interpreted by the client and passed unmodified as an attribute '__restart' to the 'launch' and 'attach' requests." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, restart=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] restart: A debug adapter may set 'restart' to true (or to an arbitrary object) to request that the front end restarts the session. The value is not interpreted by the client and passed unmodified as an attribute '__restart' to the 'launch' and 'attach' requests. """ self.restart = restart self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) restart = self.restart dct = { } if restart is not None: dct['restart'] = restart dct.update(self.kwargs) return dct @register class ThreadEventBody(BaseSchema): """ "body" of ThreadEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "reason": { "type": "string", "description": "The reason for the event.", "_enum": [ "started", "exited" ] }, "threadId": { "type": "integer", "description": "The identifier of the thread." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, reason, threadId, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string reason: The reason for the event. :param integer threadId: The identifier of the thread. """ self.reason = reason self.threadId = threadId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) reason = self.reason threadId = self.threadId dct = { 'reason': reason, 'threadId': threadId, } dct.update(self.kwargs) return dct @register class OutputEventBody(BaseSchema): """ "body" of OutputEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "category": { "type": "string", "description": "The output category. If not specified, 'console' is assumed.", "_enum": [ "console", "stdout", "stderr", "telemetry" ] }, "output": { "type": "string", "description": "The output to report." }, "variablesReference": { "type": "number", "description": "If an attribute 'variablesReference' exists and its value is > 0, the output contains objects which can be retrieved by passing 'variablesReference' to the 'variables' request." }, "source": { "description": "An optional source location where the output was produced.", "type": "Source" }, "line": { "type": "integer", "description": "An optional source location line where the output was produced." }, "column": { "type": "integer", "description": "An optional source location column where the output was produced." }, "data": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Optional data to report. For the 'telemetry' category the data will be sent to telemetry, for the other categories the data is shown in JSON format." } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, output, category=None, variablesReference=None, source=None, line=None, column=None, data=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string output: The output to report. :param string category: The output category. If not specified, 'console' is assumed. :param number variablesReference: If an attribute 'variablesReference' exists and its value is > 0, the output contains objects which can be retrieved by passing 'variablesReference' to the 'variables' request. :param Source source: An optional source location where the output was produced. :param integer line: An optional source location line where the output was produced. :param integer column: An optional source location column where the output was produced. :param ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] data: Optional data to report. For the 'telemetry' category the data will be sent to telemetry, for the other categories the data is shown in JSON format. """ self.output = output self.category = category self.variablesReference = variablesReference if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.line = line self.column = column self.data = data if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) output = self.output category = self.category variablesReference = self.variablesReference source = self.source line = self.line column = self.column data = self.data if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'output': output, } if category is not None: dct['category'] = category if variablesReference is not None: dct['variablesReference'] = variablesReference if source is not None: dct['source'] = source.to_dict(update_ids_to_dap=update_ids_to_dap) if line is not None: dct['line'] = line if column is not None: dct['column'] = column if data is not None: dct['data'] = data dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register class BreakpointEventBody(BaseSchema): """ "body" of BreakpointEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "reason": { "type": "string", "description": "The reason for the event.", "_enum": [ "changed", "new", "removed" ] }, "breakpoint": { "description": "The 'id' attribute is used to find the target breakpoint and the other attributes are used as the new values.", "type": "Breakpoint" } } __refs__ = set(['breakpoint']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, reason, breakpoint, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string reason: The reason for the event. :param Breakpoint breakpoint: The 'id' attribute is used to find the target breakpoint and the other attributes are used as the new values. """ self.reason = reason if breakpoint is None: self.breakpoint = Breakpoint() else: self.breakpoint = Breakpoint(update_ids_from_dap=update_ids_from_dap, **breakpoint) if breakpoint.__class__ != Breakpoint else breakpoint self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) reason = self.reason breakpoint = self.breakpoint # noqa (assign to builtin) dct = { 'reason': reason, 'breakpoint': breakpoint.to_dict(update_ids_to_dap=update_ids_to_dap), } dct.update(self.kwargs) return dct @register class ModuleEventBody(BaseSchema): """ "body" of ModuleEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "reason": { "type": "string", "description": "The reason for the event.", "enum": [ "new", "changed", "removed" ] }, "module": { "description": "The new, changed, or removed module. In case of 'removed' only the module id is used.", "type": "Module" } } __refs__ = set(['module']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, reason, module, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string reason: The reason for the event. :param Module module: The new, changed, or removed module. In case of 'removed' only the module id is used. """ self.reason = reason if module is None: self.module = Module() else: self.module = Module(update_ids_from_dap=update_ids_from_dap, **module) if module.__class__ != Module else module self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) reason = self.reason module = self.module dct = { 'reason': reason, 'module': module.to_dict(update_ids_to_dap=update_ids_to_dap), } dct.update(self.kwargs) return dct @register class LoadedSourceEventBody(BaseSchema): """ "body" of LoadedSourceEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "reason": { "type": "string", "description": "The reason for the event.", "enum": [ "new", "changed", "removed" ] }, "source": { "description": "The new, changed, or removed source.", "type": "Source" } } __refs__ = set(['source']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, reason, source, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string reason: The reason for the event. :param Source source: The new, changed, or removed source. """ self.reason = reason if source is None: self.source = Source() else: self.source = Source(update_ids_from_dap=update_ids_from_dap, **source) if source.__class__ != Source else source self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) reason = self.reason source = self.source dct = { 'reason': reason, 'source': source.to_dict(update_ids_to_dap=update_ids_to_dap), } dct.update(self.kwargs) return dct @register class ProcessEventBody(BaseSchema): """ "body" of ProcessEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "name": { "type": "string", "description": "The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js." }, "systemProcessId": { "type": "integer", "description": "The system process id of the debugged process. This property will be missing for non-system processes." }, "isLocalProcess": { "type": "boolean", "description": "If true, the process is running on the same computer as the debug adapter." }, "startMethod": { "type": "string", "enum": [ "launch", "attach", "attachForSuspendedLaunch" ], "description": "Describes how the debug engine started debugging this process.", "enumDescriptions": [ "Process was launched under the debugger.", "Debugger attached to an existing process.", "A project launcher component has launched a new process in a suspended state and then asked the debugger to attach." ] } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, name, systemProcessId=None, isLocalProcess=None, startMethod=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string name: The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js. :param integer systemProcessId: The system process id of the debugged process. This property will be missing for non-system processes. :param boolean isLocalProcess: If true, the process is running on the same computer as the debug adapter. :param string startMethod: Describes how the debug engine started debugging this process. """ self.name = name self.systemProcessId = systemProcessId self.isLocalProcess = isLocalProcess self.startMethod = startMethod self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) name = self.name systemProcessId = self.systemProcessId isLocalProcess = self.isLocalProcess startMethod = self.startMethod dct = { 'name': name, } if systemProcessId is not None: dct['systemProcessId'] = systemProcessId if isLocalProcess is not None: dct['isLocalProcess'] = isLocalProcess if startMethod is not None: dct['startMethod'] = startMethod dct.update(self.kwargs) return dct @register class CapabilitiesEventBody(BaseSchema): """ "body" of CapabilitiesEvent Note: automatically generated code. Do not edit manually. """ __props__ = { "capabilities": { "description": "The set of updated capabilities.", "type": "Capabilities" } } __refs__ = set(['capabilities']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, capabilities, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param Capabilities capabilities: The set of updated capabilities. """ if capabilities is None: self.capabilities = Capabilities() else: self.capabilities = Capabilities(update_ids_from_dap=update_ids_from_dap, **capabilities) if capabilities.__class__ != Capabilities else capabilities self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) capabilities = self.capabilities dct = { 'capabilities': capabilities.to_dict(update_ids_to_dap=update_ids_to_dap), } dct.update(self.kwargs) return dct @register class RunInTerminalRequestArgumentsEnv(BaseSchema): """ "env" of RunInTerminalRequestArguments Note: automatically generated code. Do not edit manually. """ __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct @register class RunInTerminalResponseBody(BaseSchema): """ "body" of RunInTerminalResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "processId": { "type": "number", "description": "The process ID." }, "shellProcessId": { "type": "number", "description": "The process ID of the terminal shell." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, processId=None, shellProcessId=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param number processId: The process ID. :param number shellProcessId: The process ID of the terminal shell. """ self.processId = processId self.shellProcessId = shellProcessId self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) processId = self.processId shellProcessId = self.shellProcessId dct = { } if processId is not None: dct['processId'] = processId if shellProcessId is not None: dct['shellProcessId'] = shellProcessId dct.update(self.kwargs) return dct @register class SetBreakpointsResponseBody(BaseSchema): """ "body" of SetBreakpointsResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "breakpoints": { "type": "array", "items": { "$ref": "#/definitions/Breakpoint" }, "description": "Information about the breakpoints. The array elements are in the same order as the elements of the 'breakpoints' (or the deprecated 'lines') array in the arguments." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, breakpoints, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array breakpoints: Information about the breakpoints. The array elements are in the same order as the elements of the 'breakpoints' (or the deprecated 'lines') array in the arguments. """ self.breakpoints = breakpoints if update_ids_from_dap and self.breakpoints: for o in self.breakpoints: Breakpoint.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) breakpoints = self.breakpoints dct = { 'breakpoints': [Breakpoint.update_dict_ids_to_dap(o) for o in breakpoints] if (update_ids_to_dap and breakpoints) else breakpoints, } dct.update(self.kwargs) return dct @register class SetFunctionBreakpointsResponseBody(BaseSchema): """ "body" of SetFunctionBreakpointsResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "breakpoints": { "type": "array", "items": { "$ref": "#/definitions/Breakpoint" }, "description": "Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, breakpoints, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array breakpoints: Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array. """ self.breakpoints = breakpoints if update_ids_from_dap and self.breakpoints: for o in self.breakpoints: Breakpoint.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) breakpoints = self.breakpoints dct = { 'breakpoints': [Breakpoint.update_dict_ids_to_dap(o) for o in breakpoints] if (update_ids_to_dap and breakpoints) else breakpoints, } dct.update(self.kwargs) return dct @register class ContinueResponseBody(BaseSchema): """ "body" of ContinueResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "allThreadsContinued": { "type": "boolean", "description": "If true, the 'continue' request has ignored the specified thread and continued all threads instead. If this attribute is missing a value of 'true' is assumed for backward compatibility." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, allThreadsContinued=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param boolean allThreadsContinued: If true, the 'continue' request has ignored the specified thread and continued all threads instead. If this attribute is missing a value of 'true' is assumed for backward compatibility. """ self.allThreadsContinued = allThreadsContinued self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) allThreadsContinued = self.allThreadsContinued dct = { } if allThreadsContinued is not None: dct['allThreadsContinued'] = allThreadsContinued dct.update(self.kwargs) return dct @register class StackTraceResponseBody(BaseSchema): """ "body" of StackTraceResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "stackFrames": { "type": "array", "items": { "$ref": "#/definitions/StackFrame" }, "description": "The frames of the stackframe. If the array has length zero, there are no stackframes available.\nThis means that there is no location information available." }, "totalFrames": { "type": "integer", "description": "The total number of frames available." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, stackFrames, totalFrames=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array stackFrames: The frames of the stackframe. If the array has length zero, there are no stackframes available. This means that there is no location information available. :param integer totalFrames: The total number of frames available. """ self.stackFrames = stackFrames if update_ids_from_dap and self.stackFrames: for o in self.stackFrames: StackFrame.update_dict_ids_from_dap(o) self.totalFrames = totalFrames self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) stackFrames = self.stackFrames totalFrames = self.totalFrames dct = { 'stackFrames': [StackFrame.update_dict_ids_to_dap(o) for o in stackFrames] if (update_ids_to_dap and stackFrames) else stackFrames, } if totalFrames is not None: dct['totalFrames'] = totalFrames dct.update(self.kwargs) return dct @register class ScopesResponseBody(BaseSchema): """ "body" of ScopesResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "scopes": { "type": "array", "items": { "$ref": "#/definitions/Scope" }, "description": "The scopes of the stackframe. If the array has length zero, there are no scopes available." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, scopes, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array scopes: The scopes of the stackframe. If the array has length zero, there are no scopes available. """ self.scopes = scopes if update_ids_from_dap and self.scopes: for o in self.scopes: Scope.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) scopes = self.scopes dct = { 'scopes': [Scope.update_dict_ids_to_dap(o) for o in scopes] if (update_ids_to_dap and scopes) else scopes, } dct.update(self.kwargs) return dct @register class VariablesResponseBody(BaseSchema): """ "body" of VariablesResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "variables": { "type": "array", "items": { "$ref": "#/definitions/Variable" }, "description": "All (or a range) of variables for the given variable reference." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, variables, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array variables: All (or a range) of variables for the given variable reference. """ self.variables = variables if update_ids_from_dap and self.variables: for o in self.variables: Variable.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) variables = self.variables dct = { 'variables': [Variable.update_dict_ids_to_dap(o) for o in variables] if (update_ids_to_dap and variables) else variables, } dct.update(self.kwargs) return dct @register class SetVariableResponseBody(BaseSchema): """ "body" of SetVariableResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "value": { "type": "string", "description": "The new value of the variable." }, "type": { "type": "string", "description": "The type of the new value. Typically shown in the UI when hovering over the value." }, "variablesReference": { "type": "number", "description": "If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." }, "namedVariables": { "type": "number", "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "number", "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, value, type=None, variablesReference=None, namedVariables=None, indexedVariables=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string value: The new value of the variable. :param string type: The type of the new value. Typically shown in the UI when hovering over the value. :param number variablesReference: If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. :param number namedVariables: The number of named child variables. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. :param number indexedVariables: The number of indexed child variables. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. """ self.value = value self.type = type self.variablesReference = variablesReference self.namedVariables = namedVariables self.indexedVariables = indexedVariables if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) value = self.value type = self.type # noqa (assign to builtin) variablesReference = self.variablesReference namedVariables = self.namedVariables indexedVariables = self.indexedVariables if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'value': value, } if type is not None: dct['type'] = type if variablesReference is not None: dct['variablesReference'] = variablesReference if namedVariables is not None: dct['namedVariables'] = namedVariables if indexedVariables is not None: dct['indexedVariables'] = indexedVariables dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register class SourceResponseBody(BaseSchema): """ "body" of SourceResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "content": { "type": "string", "description": "Content of the source reference." }, "mimeType": { "type": "string", "description": "Optional content type (mime type) of the source." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, content, mimeType=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string content: Content of the source reference. :param string mimeType: Optional content type (mime type) of the source. """ self.content = content self.mimeType = mimeType self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) content = self.content mimeType = self.mimeType dct = { 'content': content, } if mimeType is not None: dct['mimeType'] = mimeType dct.update(self.kwargs) return dct @register class ThreadsResponseBody(BaseSchema): """ "body" of ThreadsResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "threads": { "type": "array", "items": { "$ref": "#/definitions/Thread" }, "description": "All threads." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, threads, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array threads: All threads. """ self.threads = threads if update_ids_from_dap and self.threads: for o in self.threads: Thread.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) threads = self.threads dct = { 'threads': [Thread.update_dict_ids_to_dap(o) for o in threads] if (update_ids_to_dap and threads) else threads, } dct.update(self.kwargs) return dct @register class ModulesResponseBody(BaseSchema): """ "body" of ModulesResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "modules": { "type": "array", "items": { "$ref": "#/definitions/Module" }, "description": "All modules or range of modules." }, "totalModules": { "type": "integer", "description": "The total number of modules available." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, modules, totalModules=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array modules: All modules or range of modules. :param integer totalModules: The total number of modules available. """ self.modules = modules if update_ids_from_dap and self.modules: for o in self.modules: Module.update_dict_ids_from_dap(o) self.totalModules = totalModules self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) modules = self.modules totalModules = self.totalModules dct = { 'modules': [Module.update_dict_ids_to_dap(o) for o in modules] if (update_ids_to_dap and modules) else modules, } if totalModules is not None: dct['totalModules'] = totalModules dct.update(self.kwargs) return dct @register class LoadedSourcesResponseBody(BaseSchema): """ "body" of LoadedSourcesResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "sources": { "type": "array", "items": { "$ref": "#/definitions/Source" }, "description": "Set of loaded sources." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, sources, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array sources: Set of loaded sources. """ self.sources = sources if update_ids_from_dap and self.sources: for o in self.sources: Source.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) sources = self.sources dct = { 'sources': [Source.update_dict_ids_to_dap(o) for o in sources] if (update_ids_to_dap and sources) else sources, } dct.update(self.kwargs) return dct @register class EvaluateResponseBody(BaseSchema): """ "body" of EvaluateResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "result": { "type": "string", "description": "The result of the evaluate request." }, "type": { "type": "string", "description": "The optional type of the evaluate result." }, "presentationHint": { "description": "Properties of a evaluate result that can be used to determine how to render the result in the UI.", "type": "VariablePresentationHint" }, "variablesReference": { "type": "number", "description": "If variablesReference is > 0, the evaluate result is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." }, "namedVariables": { "type": "number", "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "number", "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." } } __refs__ = set(['presentationHint']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, result, variablesReference, type=None, presentationHint=None, namedVariables=None, indexedVariables=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string result: The result of the evaluate request. :param number variablesReference: If variablesReference is > 0, the evaluate result is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. :param string type: The optional type of the evaluate result. :param VariablePresentationHint presentationHint: Properties of a evaluate result that can be used to determine how to render the result in the UI. :param number namedVariables: The number of named child variables. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. :param number indexedVariables: The number of indexed child variables. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. """ self.result = result self.variablesReference = variablesReference self.type = type if presentationHint is None: self.presentationHint = VariablePresentationHint() else: self.presentationHint = VariablePresentationHint(update_ids_from_dap=update_ids_from_dap, **presentationHint) if presentationHint.__class__ != VariablePresentationHint else presentationHint self.namedVariables = namedVariables self.indexedVariables = indexedVariables if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) result = self.result variablesReference = self.variablesReference type = self.type # noqa (assign to builtin) presentationHint = self.presentationHint namedVariables = self.namedVariables indexedVariables = self.indexedVariables if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'result': result, 'variablesReference': variablesReference, } if type is not None: dct['type'] = type if presentationHint is not None: dct['presentationHint'] = presentationHint.to_dict(update_ids_to_dap=update_ids_to_dap) if namedVariables is not None: dct['namedVariables'] = namedVariables if indexedVariables is not None: dct['indexedVariables'] = indexedVariables dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register class SetExpressionResponseBody(BaseSchema): """ "body" of SetExpressionResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "value": { "type": "string", "description": "The new value of the expression." }, "type": { "type": "string", "description": "The optional type of the value." }, "presentationHint": { "description": "Properties of a value that can be used to determine how to render the result in the UI.", "type": "VariablePresentationHint" }, "variablesReference": { "type": "number", "description": "If variablesReference is > 0, the value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." }, "namedVariables": { "type": "number", "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." }, "indexedVariables": { "type": "number", "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." } } __refs__ = set(['presentationHint']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, value, type=None, presentationHint=None, variablesReference=None, namedVariables=None, indexedVariables=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string value: The new value of the expression. :param string type: The optional type of the value. :param VariablePresentationHint presentationHint: Properties of a value that can be used to determine how to render the result in the UI. :param number variablesReference: If variablesReference is > 0, the value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. :param number namedVariables: The number of named child variables. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. :param number indexedVariables: The number of indexed child variables. The client can use this optional information to present the variables in a paged UI and fetch them in chunks. """ self.value = value self.type = type if presentationHint is None: self.presentationHint = VariablePresentationHint() else: self.presentationHint = VariablePresentationHint(update_ids_from_dap=update_ids_from_dap, **presentationHint) if presentationHint.__class__ != VariablePresentationHint else presentationHint self.variablesReference = variablesReference self.namedVariables = namedVariables self.indexedVariables = indexedVariables if update_ids_from_dap: self.variablesReference = self._translate_id_from_dap(self.variablesReference) self.kwargs = kwargs @classmethod def update_dict_ids_from_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference']) return dct def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) value = self.value type = self.type # noqa (assign to builtin) presentationHint = self.presentationHint variablesReference = self.variablesReference namedVariables = self.namedVariables indexedVariables = self.indexedVariables if update_ids_to_dap: if variablesReference is not None: variablesReference = self._translate_id_to_dap(variablesReference) dct = { 'value': value, } if type is not None: dct['type'] = type if presentationHint is not None: dct['presentationHint'] = presentationHint.to_dict(update_ids_to_dap=update_ids_to_dap) if variablesReference is not None: dct['variablesReference'] = variablesReference if namedVariables is not None: dct['namedVariables'] = namedVariables if indexedVariables is not None: dct['indexedVariables'] = indexedVariables dct.update(self.kwargs) return dct @classmethod def update_dict_ids_to_dap(cls, dct): if 'variablesReference' in dct: dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference']) return dct @register class StepInTargetsResponseBody(BaseSchema): """ "body" of StepInTargetsResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "targets": { "type": "array", "items": { "$ref": "#/definitions/StepInTarget" }, "description": "The possible stepIn targets of the specified source location." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, targets, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array targets: The possible stepIn targets of the specified source location. """ self.targets = targets if update_ids_from_dap and self.targets: for o in self.targets: StepInTarget.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) targets = self.targets dct = { 'targets': [StepInTarget.update_dict_ids_to_dap(o) for o in targets] if (update_ids_to_dap and targets) else targets, } dct.update(self.kwargs) return dct @register class GotoTargetsResponseBody(BaseSchema): """ "body" of GotoTargetsResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "targets": { "type": "array", "items": { "$ref": "#/definitions/GotoTarget" }, "description": "The possible goto targets of the specified location." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, targets, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array targets: The possible goto targets of the specified location. """ self.targets = targets if update_ids_from_dap and self.targets: for o in self.targets: GotoTarget.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) targets = self.targets dct = { 'targets': [GotoTarget.update_dict_ids_to_dap(o) for o in targets] if (update_ids_to_dap and targets) else targets, } dct.update(self.kwargs) return dct @register class CompletionsResponseBody(BaseSchema): """ "body" of CompletionsResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "targets": { "type": "array", "items": { "$ref": "#/definitions/CompletionItem" }, "description": "The possible completions for ." } } __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, targets, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param array targets: The possible completions for . """ self.targets = targets if update_ids_from_dap and self.targets: for o in self.targets: CompletionItem.update_dict_ids_from_dap(o) self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) targets = self.targets dct = { 'targets': [CompletionItem.update_dict_ids_to_dap(o) for o in targets] if (update_ids_to_dap and targets) else targets, } dct.update(self.kwargs) return dct @register class ExceptionInfoResponseBody(BaseSchema): """ "body" of ExceptionInfoResponse Note: automatically generated code. Do not edit manually. """ __props__ = { "exceptionId": { "type": "string", "description": "ID of the exception that was thrown." }, "description": { "type": "string", "description": "Descriptive text for the exception provided by the debug adapter." }, "breakMode": { "description": "Mode that caused the exception notification to be raised.", "type": "ExceptionBreakMode" }, "details": { "description": "Detailed information about the exception.", "type": "ExceptionDetails" } } __refs__ = set(['breakMode', 'details']) __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, exceptionId, breakMode, description=None, details=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ :param string exceptionId: ID of the exception that was thrown. :param ExceptionBreakMode breakMode: Mode that caused the exception notification to be raised. :param string description: Descriptive text for the exception provided by the debug adapter. :param ExceptionDetails details: Detailed information about the exception. """ self.exceptionId = exceptionId assert breakMode in ExceptionBreakMode.VALID_VALUES self.breakMode = breakMode self.description = description if details is None: self.details = ExceptionDetails() else: self.details = ExceptionDetails(update_ids_from_dap=update_ids_from_dap, **details) if details.__class__ != ExceptionDetails else details self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) exceptionId = self.exceptionId breakMode = self.breakMode description = self.description details = self.details dct = { 'exceptionId': exceptionId, 'breakMode': breakMode, } if description is not None: dct['description'] = description if details is not None: dct['details'] = details.to_dict(update_ids_to_dap=update_ids_to_dap) dct.update(self.kwargs) return dct @register class MessageVariables(BaseSchema): """ "variables" of Message Note: automatically generated code. Do not edit manually. """ __props__ = {} __refs__ = set() __slots__ = list(__props__.keys()) + ['kwargs'] def __init__(self, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ """ self.kwargs = kwargs def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused) dct = { } dct.update(self.kwargs) return dct
[ "user@localhost.localdomain" ]
user@localhost.localdomain
01968ccfc10c8906002b14ee24cc1c38bf584d05
fdab73ba3ec2e74190d3feea84606b069e8142d8
/forum/templatetags/thread_extras.py
56d81ba8468f55123ccbbbcf989e242eb1174710
[]
no_license
Cvd2014/final_project
de9d9ec0a597e795d49074e38c6a4343a5f045c4
cd2ecc57a1fb1f13198280719ee6a789d5224af1
refs/heads/master
2021-01-17T12:36:59.507174
2016-06-27T12:43:14
2016-06-27T12:43:14
57,976,930
0
0
null
null
null
null
UTF-8
Python
false
false
1,242
py
import arrow from django import template from django.core.urlresolvers import reverse register = template.Library() @register.filter def get_total_subject_posts(subject): total_posts = 0 for thread in subject.threads.all(): total_posts += thread.posts.count() return total_posts @register.filter def started_time(created_at): return arrow.get(created_at).humanize() @register.simple_tag def last_posted_user_name(thread): posts = thread.posts.all().order_by('-created_at') return posts[posts.count() - 1].user.username @register.simple_tag def user_vote_button( thread, subject, user): vote = thread.poll.votes.filter(user_id=user.id).first() if not vote: if user.is_authenticated(): link=""" <div class = "col-md-3 btn-vote"> <a href ="%s" class="btn btn default btn-sm"> Add my Vote! </a> </div>"""%reverse('cast_vote', kwargs={'thread_id':thread.id, 'subject_id':subject.id}) return link return "" @register.filter def vote_percentage(subject): count=subject.votes.count() if count==0: return 0 total_votes= subject.poll.votes.count() return (100/total_votes)*count
[ "ciaran.darcy1@gmail.com" ]
ciaran.darcy1@gmail.com
c725b6994884317444e1b8e1810a24b1a71fc6b6
48c1b225220035002cdf26cdfda7e462bf45887b
/Balanceamento.py
756a9a43d47bddd27ad1eaeef0cdb2c716b32753
[]
no_license
Natanna99/ED2
5859f0e295bc09c030b5c235f2686b1ea09c6fb1
c2ba9c63b1fb05043f09594bb3bddd9fad9f7db6
refs/heads/main
2023-01-24T09:29:38.927113
2020-12-06T17:11:19
2020-12-06T17:11:19
319,086,595
1
0
null
null
null
null
UTF-8
Python
false
false
109
py
import Tree t= Tree.Tree() t.insere(29) t.insere(13) t.insere(24) t.insere(18) t.insere(1) t.preOrdem()
[ "erzafairy79@gmail.com" ]
erzafairy79@gmail.com
ac4e4a70866d6a91faef0a4e82b070473cf94505
56551ddc4668c550d1cf3261f01d22cfd85e3365
/libraries/ExampleCamera.py
d38f7f23c68736142318e08a9ab9cf627bc6586a
[]
no_license
degrace1/Autonomous-Line-Tracking-Car
6268c988c4c31eefb7340ad79dfc140ccf6a3edc
276a6035e69d20ff08c199314a326885e65d27c2
refs/heads/main
2023-01-29T15:11:49.333796
2020-12-12T01:46:21
2020-12-12T01:46:21
309,524,238
0
0
null
null
null
null
UTF-8
Python
false
false
735
py
from BallCapture import * from ExampleCamera import * from DistanceCamera import * from imutils.video import VideoStream import cv2 import imutils # HSV threshold, we use the yellow color ball here yellowLower = (26,43,46) yellowUpper = (34,255,255) #initilize a ball capture class vs =VideoStream(src=0).start() c = BallCapture(vs = vs) time.sleep(2.0) for i in range(1000): #get the information of each frame print(c.captureOne()) #end the program c.endAll() ''' you can also use this class c = BallCapture() time.sleep(2.0) for i in range(1000): #get the information of each frame x,y,radius = c.captureOne() distance = c.dVision(radius) print(x,y,radius,distance) #end the program c.endAll() '''
[ "2669561343@qq.com" ]
2669561343@qq.com
867372a05716df492868b9e1821f0f1eac39c54f
0fe842da8a3b9202298e60a5e9c1bdbe01c6f06c
/test/make_pickle_v_1_3_3.py
8482b882e3db001bcaac9eaec26405f8dc03e8ad
[ "MIT" ]
permissive
realmariano/GTC
484e6e4d4e22fcb9337f8fec80c8c510f3fb0d19
25902c01e894b2d310c9700403fc52c19ee7c805
refs/heads/master
2023-05-11T15:49:57.665397
2021-05-13T22:49:43
2021-05-13T22:49:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,032
py
""" Script used to create 'test_file_v_1_3_3.gar' as a reference file that must be readable by subsequent versions of GTC. The unit test 'test_files_v_1_3_3.py' expects to find 'test_file_v_1_3_3.gar' in the local directory. """ import os from GTC import * ar = persistence.Archive() x = ureal(1,1) y = ureal(2,1) z = result( x + y ) ar.add(x=x,y=y,z=z) x1 = ureal(1,1,3,label='x') y1 = ureal(2,1,4,label='y') z1 = result( x1 + y1 ) ar.add(z1=z1) x2 = ureal(1,1,independent=False) y2 = ureal(2,1,independent=False) r = 0.5 set_correlation(r,x2,y2) z2 = result( x2 + y2 ) ar.add(x2=x2,y2=y2,z2=z2) x3,y3 = multiple_ureal([1,2],[1,1],4) r = 0.5 set_correlation(r,x3,y3) z3 = result( x3 + y3 ) ar.add(x3=x3,y3=y3,z3=z3) x4 = ucomplex(1,[10,2,2,10],5) y4 = ucomplex(1-6j,[10,2,2,10],7) z4 = result( log( x4 * y4 ) ) ar.add(x4=x4,y4=y4,z4=z4) wdir = os.path.dirname(__file__) fname = 'ref_file_v_1_3_3.gar' path = os.path.join(wdir,fname) with open(path,'wb') as f: persistence.dump(f,ar) f.close()
[ "blairdhall@gmail.com" ]
blairdhall@gmail.com
e5819dd6a730bdb1c9966178b30aa69e05859b21
6596a5861fd1f6c8b7f866409784513db02d27b8
/python/Two Sum/Solution.py
a247e55292f525af7fc500b89cf7191cd986db0e
[]
no_license
HaiFongPan/LeetCode
3de579c5d7dd7bfa6b7533c5626d0499c42adead
c6dfd840d394405f01169d94da1b1e8c823e07ec
refs/heads/master
2022-06-02T05:14:27.464185
2022-05-23T13:42:33
2022-05-23T13:42:33
23,945,209
0
0
null
null
null
null
UTF-8
Python
false
false
375
py
# -*- coding: utf-8 -*- class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): dictNum = dict.fromkeys(num) for i in xrange(0,len(num)): if dictNum.has_key(target - num[i]): for v in xrange(i+1,len(num)): if num[v] + num[i] ==target: return (i+1,v+1)
[ "leopan.me@gmail.com" ]
leopan.me@gmail.com
8651aedc05201202ab849f7a2fc03cb57a94b9ef
eb4559cfc62afb4f9145d12854bae28ea81a126b
/CAMELYON16/deepMIL_multiscale_15inst_embed_10/main.py
8236e3b4ad46300ee1ceac7195ee04e7fd5f66d4
[]
no_license
zhangrenyuuchicago/PathHyperbolic
f38e45e0cea84df51a132247af61038913ea7bf9
7f009475db4ac33e9f27081263c92da45473275e
refs/heads/master
2023-02-16T15:53:16.748427
2023-02-15T21:30:33
2023-02-15T21:30:33
275,686,297
1
0
null
null
null
null
UTF-8
Python
false
false
8,610
py
import torchvision import torch import SlideDataset import pickle import ntpath import os import numpy as np import torch.nn.functional as F from tensorboardX import SummaryWriter from optparse import OptionParser from datetime import datetime from Model import MINet from sklearn.metrics import roc_auc_score from keras.utils import to_categorical import uuid uid = uuid.uuid1() usage = "usage: python main.py " parser = OptionParser(usage) parser.add_option("-l", "--learning_rate", dest="learning_rate", type="float", default=0.0001, help="set learning rate for optimizor") parser.add_option("-m", "--mu", dest="mu", type="float", default=1.0, help="set mu") parser.add_option("-b", "--batch_size", dest="batch_size", type="int", default=32, help="batch size") parser.add_option("-o", "--output", dest="output", type="string", default="specified_format.csv", help="output file") parser.add_option("-r", "--resume", dest="model_file", type="string", default="", help="resume the file from a model file") parser.add_option("-f", "--fold", dest="fold", type="int", default=0, help="fold in [0,1,2,3,4]") (options, args) = parser.parse_args() fold = options.fold batch_size = options.batch_size mu = options.mu embed_len = 10 epoch_num = 2000 inst_num = 5 sample_num_each_epoch = 500 patience = 25 best_epoch = 0 best_val_auc = 0.0 test_times = 10 if options.model_file == "": minet = MINet(embed_len, inst_num) minet = torch.nn.DataParallel(minet).cuda() else: print('not implemented') learning_rate = options.learning_rate optimizer = torch.optim.Adam([ {'params': minet.parameters()} ], lr=learning_rate) nn_loss_label = torch.nn.CrossEntropyLoss().cuda() loss = 0 train_transform = torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.ColorJitter(brightness=64.0/255, contrast=0.75, saturation=0.25, hue=0.04), torchvision.transforms.RandomHorizontalFlip(), torchvision.transforms.RandomVerticalFlip(), torchvision.transforms.ToTensor() ]) val_transform = torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.ToTensor() ]) train_image_data = SlideDataset.SlideDataset('train', '../settings/train_label.csv', '../gen_tiles_2000_step_1000/train_20X/', '../gen_tiles_1000/train_20X/', '../gen_tiles_500/train_20X', train_transform, fold, inst_num) weight = np.loadtxt('weight.txt') train_sampler = torch.utils.data.WeightedRandomSampler(weight, num_samples= sample_num_each_epoch, replacement=True) train_sampler = torch.utils.data.BatchSampler(train_sampler, batch_size=batch_size, drop_last=False) train_data_loader = torch.utils.data.DataLoader(train_image_data, num_workers=5, batch_sampler= train_sampler) #train_data_loader = torch.utils.data.DataLoader(train_image_data, num_workers=5, batch_size=batch_size) val_image_data = SlideDataset.SlideDataset('val', '../settings/train_label.csv', '../gen_tiles_2000_step_1000/train_20X/', '../gen_tiles_1000/train_20X/', '../gen_tiles_500/train_20X', val_transform, fold, inst_num) val_data_loader = torch.utils.data.DataLoader(val_image_data, num_workers=5, batch_size=5) from sklearn.metrics import roc_auc_score, accuracy_score def get_acc(pred, var): max_value, index = torch.max(pred, 1) index = index.data.cpu().numpy() var = var.data.cpu().numpy() return np.sum(index == var)*1.0/index.shape[0] writer = SummaryWriter(logdir="logs/MINet_hashtag_cluster_" + datetime.now().strftime('%b%d_%H-%M-%S')) step = 0 for epoch in range(epoch_num): print("Epoch: " + str(epoch)) sum_label_acc = 0.0 sum_loss = 0.0 count = 0 gender_true_lt = [] gender_pred_lt = [] minet.train() for id, (item, label, img_name) in enumerate(train_data_loader): item = item.cuda() label = label.cuda() input_var = torch.autograd.Variable(item, requires_grad=True) label_var = torch.autograd.Variable(label.squeeze(dim=1)) optimizer.zero_grad() label_pred, out_weight = minet(input_var) loss_label = nn_loss_label(label_pred, label_var) loss = loss_label loss.backward() optimizer.step() label_soft_pred = torch.nn.Softmax(dim=1)(label_pred) cur_loss_np = loss.data.cpu().numpy() writer.add_scalar('step/total_loss', cur_loss_np, step) sum_loss += cur_loss_np #print('age acc') cur_label_acc = get_acc(label_pred, label_var) print( f"Epoch: {epoch}, id: {id}, loss: {cur_loss_np},\ label acc: {cur_label_acc}") writer.add_scalar('step/label_acc', cur_label_acc, step) sum_label_acc += cur_label_acc step += 1 count += 1 print( f"training average label acc: { sum_label_acc / count}") writer.add_scalar('epoch/train_label_acc', sum_label_acc / count, epoch) print( f"training average loss: {sum_loss / count}") writer.add_scalar('epoch/train_sum_loss', sum_loss / count, epoch) print("Epoch val: " + str(epoch)) sum_loss = 0.0 label_true_lt, label_pred_lt, img_name_lt = [], [], [] minet.eval() for _ in range(test_times): for id, (item, label, img_name) in enumerate(val_data_loader): item = item.cuda() label = label.cuda() input_var = torch.autograd.Variable(item, requires_grad=False) label_size = label.size() if label_size[0] == 1: label = label.view(-1) label_var = torch.autograd.Variable(label) else: label_var = torch.autograd.Variable(label.squeeze(dim=1)) with torch.no_grad(): label_pred, out_weight = minet(input_var) loss_label = nn_loss_label(label_pred, label_var) loss = loss_label label_soft_pred = torch.nn.Softmax(dim=1)(label_pred) cur_loss_np = loss.data.cpu().numpy() #writer.add_scalar('step/total_loss', cur_loss_np, step) sum_loss += cur_loss_np cur_label_acc = get_acc(label_pred, label_var) #print( f"Epoch val: {epoch}, id: {id}, loss: {cur_loss_np},\ # label acc: {cur_label_acc}") label_true_lt += list(label_var.data.cpu().numpy()) label_pred_lt += list(label_soft_pred.data.cpu().numpy()) img_name_lt += list(img_name) label_true_lt = np.array(label_true_lt) label_pred_lt = np.array(label_pred_lt) img_pred = {} img_ground_truth = {} for i in range(len(img_name_lt)): img_name = img_name_lt[i] if img_name not in img_pred: img_pred[img_name] = [label_pred_lt[i]] else: img_pred[img_name].append(label_pred_lt[i]) if img_name in img_ground_truth: assert img_ground_truth[img_name] == label_true_lt[i] else: img_ground_truth[img_name] = label_true_lt[i] for img_name in img_pred: img_pred[img_name] = np.mean(np.array(img_pred[img_name]), axis=0) ground_truth_lt = [] pred_lt = [] for img_name in img_pred: pred_lt.append(img_pred[img_name]) ground_truth_lt.append(img_ground_truth[img_name]) label_true_lt = np.array(ground_truth_lt) label_pred_lt = np.array(pred_lt) label_true_lt = to_categorical(label_true_lt) label_auc = roc_auc_score(label_true_lt, label_pred_lt, average='macro') print( f"val average label auc: {label_auc}") writer.add_scalar('epoch/val_label_auc', label_auc, epoch) print( f"val sum loss: {sum_loss}") writer.add_scalar('epoch/val_sum_loss', sum_loss, epoch) if label_auc > best_val_auc: print(f'save best checkpoint: {epoch}') with open(f"best_checkpoint_{uid}_fold_{fold}.pt", 'wb') as f: checkpoint = {'minet': minet.state_dict(), 'epoch': epoch, 'best_val_auc': label_auc } torch.save(checkpoint, f) best_val_auc = label_auc best_epoch = epoch else: if epoch - best_epoch > patience: print('patience end') break writer.close()
[ "zhangr@uchicago.edu" ]
zhangr@uchicago.edu
32d0b1ecacdfe91bc82912e19118eb80bd30936b
2ce0c07faa149768fa24c03a434ae4ccf4c237b6
/update.py
976f67a4c8bf38ff5e3b78eb34a7e10f914cc5fa
[ "MIT" ]
permissive
CzzzzH/ETSHelper
2a80467e6358561126ee740ac9c3a87c4ae062a1
c81b96330653ab2dc5f67e810869ead2039b15b4
refs/heads/main
2023-03-28T20:00:49.988041
2021-03-18T08:47:19
2021-03-18T08:47:19
346,248,834
6
0
null
null
null
null
UTF-8
Python
false
false
2,068
py
from gre_seat import gre_run from toefl_seat import toefl_run import json import time import datetime import os import traceback def update(): print("Start Update !") # 更新GRE考位信息 change_log = gre_run() os.system("kill -9 $(pidof /usr/local/bin/geckodriver)") os.system("kill -9 $(pidof /usr/lib/firefox/firefox)") while change_log == ['更新失败']: time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(f"[{time_stamp}] 更新失败,重试中...") change_log = gre_run() os.system("kill -9 $(pidof /usr/local/bin/geckodriver)") os.system("kill -9 $(pidof /usr/lib/firefox/firefox)") time.sleep(5) time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(f"[{time_stamp}] 更新成功\n {change_log}") with open("./GRE_changelog.json", "w") as f: json.dump(change_log, f) time.sleep(10) # 更新TOEFL考位信息 change_log = toefl_run() os.system("kill -9 $(pidof /usr/local/bin/geckodriver)") os.system("kill -9 $(pidof /usr/lib/firefox/firefox)") while change_log == ['更新失败']: time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(f"[{time_stamp}] 更新失败,重试中...") change_log = toefl_run() os.system("kill -9 $(pidof /usr/local/bin/geckodriver)") os.system("kill -9 $(pidof /usr/lib/firefox/firefox)") time.sleep(5) time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(f"[{time_stamp}] 更新成功\n {change_log}") with open("./TOEFL_changelog.json", "w") as f: json.dump(change_log, f) time.sleep(10) if __name__ == '__main__': while True: try: update() os.system("rm -rf /tmp/rust*") except: print(traceback.format_exc()) os.system("kill -9 $(pidof /usr/local/bin/geckodriver)") os.system("kill -9 $(pidof /usr/lib/firefox/firefox)") os.system("rm -rf /tmp/rust*")
[ "morphling233@gmail.com" ]
morphling233@gmail.com
84b5dbc4ea63754c6fb4567547d8f73a174ea383
521efcd158f4c69a686ed1c63dd8e4b0b68cc011
/airflow/providers/amazon/aws/example_dags/example_s3_bucket_tagging.py
9ded09ba70e3baec59645806115c40c6bea33854
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
coutureai/RaWorkflowOrchestrator
33fd8e253bfea2f9a82bb122ca79e8cf9dffb003
cd3ea2579dff7bbab0d6235fcdeba2bb9edfc01f
refs/heads/main
2022-10-01T06:24:18.560652
2021-12-29T04:52:56
2021-12-29T04:52:56
184,547,783
5
12
Apache-2.0
2022-11-04T00:02:55
2019-05-02T08:38:38
Python
UTF-8
Python
false
false
2,227
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os from datetime import datetime from airflow.models.dag import DAG from airflow.providers.amazon.aws.operators.s3 import ( S3CreateBucketOperator, S3DeleteBucketOperator, S3DeleteBucketTaggingOperator, S3GetBucketTaggingOperator, S3PutBucketTaggingOperator, ) BUCKET_NAME = os.environ.get('BUCKET_NAME', 'test-s3-bucket-tagging') TAG_KEY = os.environ.get('TAG_KEY', 'test-s3-bucket-tagging-key') TAG_VALUE = os.environ.get('TAG_VALUE', 'test-s3-bucket-tagging-value') # [START howto_operator_s3_bucket_tagging] with DAG( dag_id='s3_bucket_tagging_dag', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, default_args={"bucket_name": BUCKET_NAME}, max_active_runs=1, tags=['example'], ) as dag: create_bucket = S3CreateBucketOperator(task_id='s3_bucket_tagging_dag_create', region_name='us-east-1') delete_bucket = S3DeleteBucketOperator(task_id='s3_bucket_tagging_dag_delete', force_delete=True) get_tagging = S3GetBucketTaggingOperator(task_id='s3_bucket_tagging_dag_get_tagging') put_tagging = S3PutBucketTaggingOperator( task_id='s3_bucket_tagging_dag_put_tagging', key=TAG_KEY, value=TAG_VALUE ) delete_tagging = S3DeleteBucketTaggingOperator(task_id='s3_bucket_tagging_dag_delete_tagging') create_bucket >> put_tagging >> get_tagging >> delete_tagging >> delete_bucket # [END howto_operator_s3_bucket_tagging]
[ "noreply@github.com" ]
coutureai.noreply@github.com
520e6c48ff4c494fbb0a7f4f63eea63da963dbff
894c3eaeda2f41d80b9b409784fc6daedcc12aa5
/service20/migrations/0082_auto_20190217_2205.py
ebda5a16a648fc599a2710b40513a134b126bd55
[]
no_license
ohsehwan/django_admin_nanum_osh01
b1f3fc51e53d8f23c5b06d83c395f4cf085892f0
bb9090c60ca215dd7f6b65959d7f154b4b4b9951
refs/heads/master
2022-12-21T07:25:05.912098
2019-02-19T03:40:43
2019-02-19T03:40:43
171,399,538
0
0
null
2022-11-22T03:26:10
2019-02-19T03:37:23
JavaScript
UTF-8
Python
false
false
568
py
# Generated by Django 2.1.5 on 2019-02-17 22:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('service20', '0081_auto_20190217_2205'), ] operations = [ migrations.AlterModelOptions( name='mp_sub', options={'verbose_name': '멘토링프로그램 속성', 'verbose_name_plural': '멘토링프로그램 속성'}, ), migrations.AlterUniqueTogether( name='mp_sub', unique_together={('ms_id', 'att_id', 'att_seq')}, ), ]
[ "dxman@naver.com" ]
dxman@naver.com
b1ed99bbdc23dc4e7924b7a158a5835860a7a3d3
499715b1ba009b2081547bbf70a2f9ef02ca1162
/orders/models.py
391886364be7d2343d0f0b28a7c41e13102a3c96
[]
no_license
ariel-brassesco/CS50-Project3
09f84030ad3d93ec4af2871bf00e2b04dd974894
cd7b99965f9f391b73bcfbd33d3a41fc36f2fbb2
refs/heads/master
2023-08-11T12:16:06.021418
2020-06-20T19:20:00
2020-06-20T19:20:00
273,132,885
0
0
null
2021-09-22T19:16:02
2020-06-18T03:28:28
Python
UTF-8
Python
false
false
6,147
py
from django.db import models from django.db.models import Min # Models for products. class MenuItem(models.Model): item_type = models.CharField('Menu Item', max_length=30, unique=True) def __str__(self): return self.item_type def get_sizes(self): sizes = self.sizes.select_related().order_by('id') return sizes class ProductSize(models.Model): item_size = models.CharField('Size', max_length=20, unique=True) item_type = models.ManyToManyField(MenuItem, related_name='sizes') def __str__(self): return self.item_size class ProductVariation(models.Model): variation = models.CharField('Variation', max_length=20, unique=True) type_variation = models.CharField(max_length=20, default='base') def __str__(self): return self.variation def is_base(self): return self.type_variation == 'base' class Topping(models.Model): topping_type = models.ForeignKey(MenuItem, on_delete=models.CASCADE) topping = models.CharField('Topping', max_length=30) price = models.FloatField('Price', default=0.0) def __str__(self): return f"{self.topping} ({self.topping_type})" def is_for_all(self): menu_products = self.topping_type.product_set.select_related() topping_products = self.additional.select_related() if len(menu_products) == len(topping_products): return True return False class Product(models.Model): menu_type = models.ForeignKey(MenuItem, on_delete=models.CASCADE) name = models.CharField('Product', max_length=100) description = models.TextField('Description', max_length=400, blank=True) additional = models.ManyToManyField(Topping, blank=True, related_name='additional') image = models.ImageField(upload_to='products/%Y/%m/%d') max_add = models.IntegerField(default=0) def __str__(self): return f"{self.menu_type}: {self.name}" def get_sizes(self): sizes = self.menu_type.get_sizes() return sizes def get_presentations(self): presentations = self.pricelist_set.values('presentation').distinct() variations = [] for p in presentations: variation = ProductVariation.objects.get(pk=p['presentation']) variations.append(variation) return variations def get_price_min(self): return self.pricelist_set.aggregate(Min('price')) def get_data(self): data = {} # Get the prices for each variation and size for variation in self.get_presentations(): data[variation.id] = {} data[variation.variation] = {} for size in self.get_sizes(): try: data[variation.id][size.id] = self.pricelist_set.get(presentation=variation, size=size).price data[variation.variation][size.item_size] = self.pricelist_set.get(presentation=variation, size=size).price except PriceList.DoesNotExist: pass if not self.get_sizes(): try: data[variation.id] = self.pricelist_set.get(presentation=variation).price data[variation.variation] = self.pricelist_set.get(presentation=variation).price except PriceList.DoesNotExist: pass #Get the prices for each topping data['additionals'] = {} data['additionals']['max'] = self.max_add for additional in self.additional.select_related(): data['additionals'][additional.id] = additional.price return data # Models for Prices class PriceList(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) presentation = models.ForeignKey(ProductVariation, null=True, on_delete=models.SET_NULL) size = models.ForeignKey(ProductSize, blank=True,null=True, on_delete=models.SET_NULL) price = models.FloatField('Price', default=0.0) def __str__(self): if self.presentation.variation == 'base': return f'{self.product} ({self.size}): $ {self.price}' return f'{self.product} + {self.presentation} ({self.size}): $ {self.price}' # Model for Restaurant information class OpenHours(models.Model): time = models.TimeField() def __str__(self): return self.get_AMPM_time() def get_AMPM_time(self): if (self.time.hour <= 12): return f"{self.time.hour:02}:{self.time.minute:02} AM" return f"{self.time.hour-12:02}:{self.time.minute:02} PM" class Schedule(models.Model): DAYS_OF_WEEK = [ (0, 'Sunday'), (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday') ] day = models.IntegerField(choices=DAYS_OF_WEEK, default=1) hour_from = models.ForeignKey(OpenHours, on_delete=models.CASCADE, related_name="hourfrom") hour_to = models.ForeignKey(OpenHours, on_delete=models.CASCADE, related_name="hourto") def __str__(self): return f"{self.get_day_display()}: {self.hour_from}-{self.hour_to}" class Place(models.Model): name = models.CharField('Restaurant', max_length=100) address = models.CharField('Address', max_length=150) phone_number = models.CharField('Phone Number', max_length=17) image = models.ImageField(upload_to='owner/%Y/%m/%d') schedule = models.ManyToManyField(Schedule, related_name="opening") def __str__(self): return self.name def get_phone(self): phone = self.phone_number return '-'.join([phone[:3], phone[3:6],phone[6:]]) def get_schedule(self): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Fridat', 'Saturday', 'Sunday'] lst = [[] for _ in range(7)] for schedule in self.schedule.order_by('day'): lst[schedule.day].append([schedule.hour_from, schedule.hour_to]) # Move Sunday to the last position last = lst[0] del lst[0] lst.append(last) return tuple(zip(days, lst))
[ "ariel.brassesco@gmail.com" ]
ariel.brassesco@gmail.com
cee0c5b145014f70f31ebe10711c150ecc647f51
28a462a28f443c285ca5efec181ebe36b147c167
/tests/compile/basic/es2018/Assertion[4,0].Evaluation.spec
c6487fde85d442d46f9d1e4adf9959a75d0175ad
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
kaist-plrg/jstar
63e71f9156860dc21cccc33a9f6c638dfee448ea
1282919127ea18a7e40c7a55e63a1ddaaf7d9db4
refs/heads/main
2022-07-22T08:12:34.947712
2022-02-27T04:19:33
2022-02-27T11:06:14
384,045,526
6
4
NOASSERTION
2022-02-27T11:05:26
2021-07-08T07:53:21
Python
UTF-8
Python
false
false
702
spec
1. Evaluate |Disjunction| with +1 as its _direction_ argument to obtain a Matcher _m_. 1. Return an internal Matcher closure that takes two arguments, a State _x_ and a Continuation _c_, and performs the following steps: 1. Let _d_ be a Continuation that always returns its State argument as a successful MatchResult. 1. Call _m_(_x_, _d_) and let _r_ be its result. 1. If _r_ is ~failure~, return ~failure~. 1. Let _y_ be _r_'s State. 1. Let _cap_ be _y_'s _captures_ List. 1. Let _xe_ be _x_'s _endIndex_. 1. Let _z_ be the State (_xe_, _cap_). 1. Call _c_(_z_) and return its result.
[ "h2oche22@gmail.com" ]
h2oche22@gmail.com
3e51eb477a1493edf93e6f7d3c51183ac3f06340
5baac45bee5b6f541ace9afc1b59b6e394d43043
/mosharov.ru/mosharov_site/mosharov_site/urls.py
462ddc203abf89dbdabbed1267344e61538b6292
[]
no_license
askovorodka/mosharov
811248563fc2965a47a4c8f0ae87d01c8618e320
dbd6bad95e0531cd61c8c6f08c263a1d3c8f9345
refs/heads/master
2021-01-25T03:54:31.718567
2018-05-21T12:58:58
2018-05-21T12:58:58
3,637,722
0
0
null
null
null
null
UTF-8
Python
false
false
617
py
from django.conf.urls import patterns, include, url from mosharov_site.views import home, pages # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', home), url(r'^pages$', pages), # url(r'^mosharov_site/', include('mosharov_site.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
[ "andrey.schmitz@gmail.com" ]
andrey.schmitz@gmail.com
a102abadacc2b327a8ab89d237c940477e194e6c
c7575317d903b4fea5acfa0a52bf6805150d428c
/MatchParser.py
84f35e91d63b9c6eecac874b94b181398f4c26a3
[]
no_license
foanwang/nssdparser
89e662888f95af76b087ff06db04f6ea50de75e2
e74588132e540186e2bb134458ee0dc362969a36
refs/heads/master
2021-01-07T21:09:58.001148
2020-03-09T09:42:59
2020-03-09T09:42:59
241,821,471
0
0
null
null
null
null
UTF-8
Python
false
false
3,802
py
from datetime import datetime from mongoengine import * from mongoengine.queryset.visitor import Q import json from model.team_basic_data import team_basic_data as teambasic from model.league_category import league_category as league from model.match import match from model.dto import * from model.raw_api_data import * HomeTeamInfo = Match_Team_Info() AwayTemainfo = Match_Team_Info() def parserHomeTeamInfo(teamid, nameinfo, logo): HomeTeamInfo.teamid = teamid HomeTeamInfo.name_info = nameinfo HomeTeamInfo.logo = logo return HomeTeamInfo def parserAwayTemainfo(teamid, nameinfo, logo): AwayTemainfo.teamid = teamid AwayTemainfo.name_info = nameinfo AwayTemainfo.logo = logo return AwayTemainfo def FootballHistoryParser(): # get our league list leaguedfilter = Q(sport_type=2) referenceIdList = list() leaguelist = league.find(leaguedfilter) for doc in leaguelist: referenceIdList.append(doc.referenceid) # get each league team list from nami leagueteamdic = dict() leaguefilter = Q(api_name="season_list") lastleaguedata = raw_api_data.findlastOrderbyDate(leaguefilter) competitionlist = lastleaguedata.raw_data.get("competitions") # print("competitionlist", competitionlist) for leagueid in referenceIdList: print("leagueid", leagueid) for doc in competitionlist: # print("doc:", doc) # print("doc id:", doc.get('id'), "leagueid:", leagueid) if doc.get('id') == int(leagueid): print("doc id:", doc.get('id'), "leagueid:", leagueid) if doc.get("seasons")[0] is None: print(leagueid, "is not data on season_list") continue # here need change to all season seasonid = doc.get("seasons")[0].get("id") seasonyear =doc.get("seasons")[0].get("seasons") print("seasonid:", seasonid) leaguefilter = Q(api_name="season_detail", query_parameter=str(seasonid)) seasondata = raw_api_data.findfirst(leaguefilter) print('seasondata:', seasondata.to_json()) RawMatchList = seasondata.raw_data.get("matches") for rawmatch in RawMatchList: # print("rawmatch:",rawmatch) hometeam = teambasic.findTeambyreferenceId(rawmatch.get("home_team_id")) if hometeam is not None: parserHomeTeamInfo(hometeam.id, hometeam.name_info, hometeam.logo) awayteam = teambasic.findTeambyreferenceId(rawmatch.get("away_team_id")) if awayteam is not None: parserAwayTemainfo(awayteam.id, awayteam.name_info, awayteam.logo) print("id:",rawmatch.get("id")) leaguefilter = Q(api_name="match_lineup", query_parameter=rawmatch.get("id")) matchlineup = raw_api_data.findfirst(leaguefilter) print("matchlineup:", matchlineup) # match( # leagueid=leagueid, year=seasonyear, # race_no=IntField(), sport_type=2, # season_type= (), # home_info=HomeTeamInfo, # away_info=AwayTemainfo, # arena_data=None, # status=IntField(), # match_time=rawmatch.get("match_time"), # referenceId=rawmatch.get("id"), # update_user=None, # update_time=None, # create_time=datetime.now() # ).save() # FootballHistoryParser()
[ "foan.wang@funpodium.net" ]
foan.wang@funpodium.net
9f2e8183a87cc7d599418d98783575ad15544f1b
f947e38cf14a1aca05b47abbe93405a97c31e314
/app.py
129469ae681705908858d7960a1b365c9b91c303
[]
no_license
oscarli916/OneTimePassword-OTP-
0f9208be1546b74bb758cf9c78af315f4e853441
c4d67258171a51a07d55e7abef2fe0eb145db12b
refs/heads/master
2023-08-01T12:05:36.517280
2021-09-15T06:32:37
2021-09-15T06:32:37
406,640,171
0
0
null
null
null
null
UTF-8
Python
false
false
3,932
py
from flask import Flask, request, session from flask.helpers import flash, url_for from flask.templating import render_template from flask_bootstrap import Bootstrap from werkzeug.utils import redirect from werkzeug.security import generate_password_hash, check_password_hash import pyotp from datetime import timedelta from db import Database app = Flask(__name__) app.config['SECRET_KEY'] = "APP_SECRET_KEY" Bootstrap(app) db = Database() # homepage route @app.route("/") def index(): print(session.get('logged_in')) if not session.get('logged_in'): return redirect(url_for("login")) return "<h1>Hellooo World!!!</h1>" # login route @app.route("/login") def login(): return render_template("login.html") # login POST method @app.route("/login", methods=["POST"]) def login_form(): db_user_phone_list = db.select_all_phone() # get from data phone = request.form.get("phone") password = request.form.get("password") if phone not in db_user_phone_list: flash("You have not yet registered", "danger") return redirect(url_for("login")) else: password_hash = db.select_password(phone) if not check_password_hash(password_hash, password): flash("Wrong password", "danger") return redirect(url_for("login")) else: flash("Logged in successfully", "success") return redirect(url_for("login_2fa", phone=phone)) # login_2fa route @app.route("/login_2fa") def login_2fa(): return render_template("login_2fa.html", phone=request.args.get('phone')) # login_2fa POST method @app.route("/login_2fa", methods=["POST"]) def login_2fa_form(): phone = request.args.get('phone') secret = db.select_secret_key(phone) otp = int(request.form.get("otp")) if pyotp.TOTP(secret).verify(otp): flash("The TOTP 2FA token is valid", "success") print("SUCCESS") # Set session session["logged_in"] = True session.permanent = True app.permanent_session_lifetime = timedelta(minutes=1) return redirect(url_for("index")) else: flash("You have supplied an invalid 2FA token! Please try again", "danger") print("FAILED") return redirect(url_for("login_2fa", phone=phone)) # register route @app.route("/register") def register(): return render_template("register.html") # register POST method @app.route("/register", methods=["POST"]) def register_form(): user_phone_list = ["852 69959681", "852 87654321"] # Google sheet phone list phone = request.form.get("phone") password = request.form.get("password") confirm_password = request.form.get("confirmPassword") if phone not in user_phone_list: flash("You are not telegram bot user", "danger") print("FAILED") return redirect(url_for("register")) elif password != confirm_password: flash("Passwords are not the same", "danger") print("FAILED") return redirect(url_for("register")) else: password_hash = generate_password_hash(password) print("SUCCESS") db_user_phone_list = db.select_all_phone() if phone in db_user_phone_list: # Get secret key from database secret = db.select_secret_key(phone) else: # Add user input to database secret = pyotp.random_base32() db.insert_values("user", {'phone': phone, 'password': password_hash, 'secret': secret}) # output corresponding qr code qr_url = pyotp.totp.TOTP(secret).provisioning_uri(name=phone, issuer_name="QuantRaiser") print(qr_url) return redirect(url_for("register2fa", qr_url=qr_url)) # register 2fa route @app.route("/register2fa") def register2fa(): return render_template("register2fa.html", qr_url=request.args.get("qr_url")) if __name__ == "__main__": app.run(debug=True)
[ "oscar_li916@yahoo.com.hk" ]
oscar_li916@yahoo.com.hk
90f55e46af96e2acd0d4e8f0651e121d21a6be50
ad22b829448a35ee1d2ce80c3f4fa6661f4666cc
/p49.py
a75925f79cc7e17f8d9a4241674ff6751d5e1b63
[]
no_license
JohnEFerguson/ProjectEuler
487357f4f56541bc322cde8fd3baaacb2facb0b6
d5f805bfb199df72cdba7643028b6922c93af5f7
refs/heads/master
2021-09-16T01:43:33.195624
2018-06-14T15:29:20
2018-06-14T15:29:20
115,482,126
0
0
null
null
null
null
UTF-8
Python
false
false
823
py
#!/usr/bin/env python # # Jack Ferguson 2018 # # Problem 49 # # q: # a: # from helpers.pandigital import get_pandigital_nums from helpers.prime import is_prime def check_prime_permutations(i): if is_prime(i): nums = get_pandigital_nums(str(i)) pos = set() for n in nums: if is_prime(int(n)): pos.add(int(n)) nums.remove(n) if len(pos) >= 3: for a in pos: for b in pos: if a < b and a + ((b-a)*2) in pos: return str(a) + str(b) + str(a + (b-a)*2) else: return '' return '' for i in range(1000, 10000): pos = check_prime_permutations(i) if len(pos) > 0 and '1487' not in pos: ans = pos break print 'p49: ' + ans
[ "jef1@williams.edu" ]
jef1@williams.edu
ad7fb6e1578e8b62d7e1d0e0ae1c2be7ec9ce6a4
25c83ddd3521376d67933bfcdd191974ac460657
/mars/services/scheduling/worker/workerslot.py
702873c9bab6d8ad0fa597d7c258a5111c260328
[ "BSD-3-Clause", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "ISC", "Apache-2.0", "BSD-2-Clause", "MIT" ]
permissive
AnirbanBall/mars
acb8468578e393eb596bfdfc08822407e9c84c6c
1bfad0c04dcd8f47d4422537a397b51f3464deee
refs/heads/master
2023-08-03T09:39:13.251627
2021-09-10T10:15:34
2021-09-10T10:15:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,304
py
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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. import asyncio import logging import os import time from typing import Dict, List, NamedTuple, Optional, Set, Tuple import psutil from .... import oscar as mo from ....oscar.backends.allocate_strategy import IdleLabel from ....typing import BandType from ...cluster import WorkerSlotInfo, ClusterAPI logger = logging.getLogger(__name__) class DispatchDumpType(NamedTuple): free_slots: Set fresh_slots: Set class WorkerSlotManagerActor(mo.Actor): _band_slot_infos: Dict[str, List[WorkerSlotInfo]] def __init__(self): self._cluster_api = None self._global_slots_ref = None self._band_slot_managers = dict() # type: Dict[str, mo.ActorRef] async def __post_create__(self): self._cluster_api = await ClusterAPI.create(self.address) band_to_slots = await self._cluster_api.get_bands() for band, n_slot in band_to_slots.items(): self._band_slot_managers[band] = await mo.create_actor( BandSlotManagerActor, band, n_slot, self._global_slots_ref, uid=BandSlotManagerActor.gen_uid(band[1]), address=self.address) async def __pre_destroy__(self): await asyncio.gather(*[mo.destroy_actor(ref) for ref in self._band_slot_managers.values()]) class BandSlotManagerActor(mo.Actor): _free_slots: Set[int] _fresh_slots: Set[int] @classmethod def gen_uid(cls, band_name: str): return f'{band_name}_band_slot_manager' def __init__(self, band: BandType, n_slots: int, global_slots_ref: mo.ActorRef = None): super().__init__() self._cluster_api = None self._band = band self._band_name = band[1] self._global_slots_ref = global_slots_ref self._n_slots = n_slots self._semaphore = asyncio.Semaphore(0) self._slot_control_refs = dict() self._free_slots = set() self._fresh_slots = set() self._slot_kill_events = dict() self._restarting = False self._restart_done_event = asyncio.Event() self._session_stid_to_slot = dict() self._slot_to_session_stid = dict() self._last_report_time = time.time() self._slot_to_proc = dict() self._usage_upload_task = None async def __post_create__(self): try: self._cluster_api = await ClusterAPI.create(self.address) except mo.ActorNotExist: pass strategy = IdleLabel(self._band_name, f'worker_slot_control') for slot_id in range(self._n_slots): self._slot_control_refs[slot_id] = await mo.create_actor( BandSlotControlActor, self.ref(), self._band_name, slot_id, uid=BandSlotControlActor.gen_uid(self._band_name, slot_id), address=self.address, allocate_strategy=strategy) self._fresh_slots.add(slot_id) self._usage_upload_task = self.ref().upload_slot_usages.tell_delay( periodical=True, delay=1) async def __pre_destroy__(self): self._usage_upload_task.cancel() async def _get_global_slot_ref(self): if self._global_slots_ref is not None: return self._global_slots_ref from ..supervisor import GlobalSlotManagerActor [self._global_slots_ref] = await self._cluster_api.get_supervisor_refs([ GlobalSlotManagerActor.default_uid()]) return self._global_slots_ref async def acquire_free_slot(self, session_stid: Tuple[str, str]): yield self._semaphore.acquire() if self._restarting: yield self._restart_done_event.wait() slot_id = self._free_slots.pop() self._fresh_slots.difference_update([slot_id]) self._slot_to_session_stid[slot_id] = session_stid self._session_stid_to_slot[session_stid] = slot_id logger.debug('Slot %d acquired for subtask %r', slot_id, session_stid) raise mo.Return(slot_id) def get_slot_address(self, slot_id: int): return self._slot_control_refs[slot_id].address def get_subtask_slot(self, session_stid: Tuple[str, str]): return self._session_stid_to_slot.get(session_stid) def release_free_slot(self, slot_id: int, pid: Optional[int] = None): if pid is not None: self._slot_to_proc[slot_id] = proc = psutil.Process(pid) self._fresh_slots.add(slot_id) # collect initial stats for the process proc.cpu_percent(interval=None) if slot_id in self._slot_kill_events: event = self._slot_kill_events.pop(slot_id) event.set() session_stid = self._slot_to_session_stid.pop(slot_id, None) self._session_stid_to_slot.pop(session_stid, None) logger.debug('Slot %d released', slot_id) if slot_id not in self._free_slots: self._free_slots.add(slot_id) self._semaphore.release() async def _kill_slot(self, slot_id: int): if slot_id in self._slot_kill_events: await self._slot_kill_events[slot_id].wait() return event = self._slot_kill_events[slot_id] = asyncio.Event() # TODO(fyrestone): Make it more reliable. e.g. kill_actor # success but the actor does not restart. try: await mo.kill_actor(self._slot_control_refs[slot_id]) except ConnectionError: pass await event.wait() async def kill_slot(self, slot_id: int): self._free_slots.difference_update([slot_id]) yield self._kill_slot(slot_id) async def restart_free_slots(self): if self._restarting: yield self._restart_done_event.wait() return self._restart_done_event = asyncio.Event() self._restarting = True slot_ids = [slot_id for slot_id in self._free_slots if slot_id not in self._fresh_slots] if slot_ids: yield asyncio.gather(*[self._kill_slot(slot_id) for slot_id in slot_ids]) logger.info('%d idle slots restarted', len(slot_ids)) self._restarting = False self._restart_done_event.set() async def upload_slot_usages(self, periodical: bool = False): delays = [] slot_infos = [] global_slots_ref = await self._get_global_slot_ref() for slot_id, proc in self._slot_to_proc.items(): if slot_id not in self._slot_to_session_stid: continue session_id, subtask_id = self._slot_to_session_stid[slot_id] try: usage = proc.cpu_percent(interval=None) / 100.0 except psutil.NoSuchProcess: # pragma: no cover continue slot_infos.append(WorkerSlotInfo( slot_id=slot_id, session_id=session_id, subtask_id=subtask_id, processor_usage=usage )) if global_slots_ref is not None: # pragma: no branch # FIXME fix band slot mistake delays.append(global_slots_ref.update_subtask_slots.delay( self._band[1], session_id, subtask_id, max(1.0, usage))) if delays: # pragma: no branch yield global_slots_ref.update_subtask_slots.batch(*delays) if self._cluster_api is not None: await self._cluster_api.set_band_slot_infos(self._band_name, slot_infos) if periodical: self._usage_upload_task = self.ref().upload_slot_usages.tell_delay( periodical=True, delay=1) def dump_data(self): """ Get all refs of slots of a queue """ return DispatchDumpType(self._free_slots, self._fresh_slots) class BandSlotControlActor(mo.Actor): @classmethod def gen_uid(cls, band_name: str, slot_id: int): return f'{band_name}_{slot_id}_band_slot_control' def __init__(self, manager_ref, band_name, slot_id: int): self._manager_ref = manager_ref self._band_name = band_name self._slot_id = slot_id self._report_task = None async def __post_create__(self): self._report_task = asyncio.create_task(self._report_slot_ready()) async def _report_slot_ready(self): from ...cluster.api import ClusterAPI try: self._cluster_api = await ClusterAPI.create(self.address) await self._cluster_api.wait_node_ready() except mo.ActorNotExist: pass await mo.wait_actor_pool_recovered(self.address) await self._manager_ref.release_free_slot.tell(self._slot_id, os.getpid())
[ "noreply@github.com" ]
AnirbanBall.noreply@github.com
8e842067b3c7178efa206985248ceb4db9fdc8a5
d00b9bbcb14e5534d18f30d9fffe7a5231e8d17c
/game.py
4b311adb847ac8c3bfb90a24624e1a0baf068719
[]
no_license
Montana/py-chess
66cab7dcdbcf23195d376ac6a9b7520be49fad23
6c91bac66c35cea53c1f5108c0e42b886fb64c1f
refs/heads/master
2023-04-25T03:36:01.738449
2021-05-15T18:59:11
2021-05-15T18:59:11
367,717,067
1
0
null
2021-05-15T19:45:31
2021-05-15T19:45:30
null
UTF-8
Python
false
false
5,045
py
from moves import * from piece import * from enum import Enum class IllegalMoveError(Exception): pass class Game: def __init__(self, board = None): if board is None: self.setup_board() else: self.board = board self.current_turn = "white" self.move_history = [] def setup_board(self): board = [[None for col in range(8)] for row in range(8)] black_pawn = Piece("black", "P") black_knight = Piece("black", "N") black_bishop = Piece("black", "B") black_rook = Piece("black", "R") black_queen = Piece("black", "Q") black_king = Piece("black", "K") white_pawn = Piece("white", "P") white_knight = Piece("white", "N") white_bishop = Piece("white", "B") white_rook = Piece("white", "R") white_queen = Piece("white", "Q") white_king = Piece("white", "K") for col in range(8): board[1][col] = black_pawn board[6][col] = white_pawn board[0] = [black_rook, black_knight, black_bishop, black_queen, black_king, black_bishop, black_knight, black_rook] board[7] = [white_rook, white_knight, white_bishop, white_queen, white_king, white_bishop, white_knight, white_rook] self.board = board def switch_turn(self): if self.current_turn == "white": self.current_turn = "black" else: self.current_turn = "white" def get_piece_legal_moves(self, row, col): #TODO: add the starting coordinate so we can simplify the helpers piece = self.board[row][col] if piece.piece_type == "P": return get_pawn_moves(self.board, row, col) elif piece.piece_type == "N": return get_knight_moves(self.board, row, col) elif piece.piece_type == "B": return get_bishop_moves(self.board, row, col) elif piece.piece_type == "R": return get_rook_moves(self.board, row, col) elif piece.piece_type == "Q": return get_queen_moves(self.board, row, col) # this can be bishop and rook together elif piece.piece_type == "K": return get_king_moves(self.board, row, col) # Later: https://en.wikipedia.org/wiki/Chess_symbols_in_Unicode def print_piece(self, piece): if piece is None: print(".", end =" ") return piece_type = piece.piece_type if (piece.team == "white"): print(piece_type, end =" ") else: print(piece_type.lower(), end =" ") def print_board(self): for i in range(8): for j in range(8): self.print_piece(self.board[i][j]) print("\r") print("Current turn: " + self.current_turn) print("\r") def move_square_to_coordinates(self, square): col = square[0].lower() if (col == "a"): col = 0 elif (col == "b"): col = 1 elif (col == "c"): col = 2 elif (col == "d"): col = 3 elif (col == "e"): col = 4 elif (col == "f"): col = 5 elif (col == "g"): col = 6 elif (col == "h"): col = 7 else: raise('Invalid column: ' + col) row = 8 - int(square[1]) return [row, col] def move_to_coordinates(self, move): return [self.move_square_to_coordinates(move[:2]), self.move_square_to_coordinates(move[2:4])] def make_move(self, move): move = self.move_to_coordinates(move) legal_moves = self.get_legal_moves() if move not in legal_moves: raise IllegalMoveError start_coord, end_coord = move self.board[end_coord[0]][end_coord[1]] = self.board[start_coord[0]][start_coord[1]] self.board[start_coord[0]][start_coord[1]] = None self.move_history.append(move) self.switch_turn() # TODO: incorporate checks def get_legal_moves(self): legal_moves = [] for row in range(8): for col in range(8): piece = self.board[row][col] if piece and piece.team == self.current_turn: # Only look at the current player's pieces # Map in starting position of the piece piece_moves = list(map(lambda move: [[row, col], move], self.get_piece_legal_moves(row, col))) legal_moves.extend(piece_moves) return legal_moves def play_game(self): while True: self.print_board() next_move = input("What's your move? E.g. e4e5\n") try: self.make_move(next_move) except IllegalMoveError: print("Illegal Move!") game = Game() game.play_game() #TODO: implement Game class, which will have board and turn variables instead of these globals
[ "bsgreenb@gmail.com" ]
bsgreenb@gmail.com
6aa5b9c547468626093dd1e1b0a3fa6cc1dcecfb
4533d12dc4f724a5c50decf15e70b6cf69d8a052
/src/you_get/extractor/nicovideo.py
7d384f3146f3f7b5c00405d570f4c5a853b9bcc2
[ "MIT" ]
permissive
shabeermothi/you-get
dd276c4c6155a83e4b24fa6913376bc6c00a80bf
59e505b5bceaca6f223afbb55a3c79feb1eba144
refs/heads/master
2021-01-15T19:14:29.663048
2014-02-08T03:38:37
2014-02-08T03:38:37
16,658,779
1
0
null
null
null
null
UTF-8
Python
false
false
1,454
py
#!/usr/bin/env python __all__ = ['nicovideo_download'] from ..common import * def nicovideo_login(user, password): data = "current_form=login&mail=" + user +"&password=" + password + "&login_submit=Log+In" response = request.urlopen(request.Request("https://secure.nicovideo.jp/secure/login?site=niconico", headers = fake_headers, data = data.encode('utf-8'))) return response.headers def nicovideo_download(url, output_dir = '.', merge = True, info_only = False): request.install_opener(request.build_opener(request.HTTPCookieProcessor())) import netrc, getpass info = netrc.netrc().authenticators('nicovideo') if info is None: user = input("User: ") password = getpass.getpass("Password: ") else: user, password = info[0], info[2] print("Logging in...") nicovideo_login(user, password) html = get_html(url) # necessary! title = unicodize(r1(r'<span class="videoHeaderTitle">([^<]+)</span>', html)) api_html = get_html('http://www.nicovideo.jp/api/getflv?v=%s' % url.split('/')[-1]) real_url = parse.unquote(r1(r'url=([^&]+)&', api_html)) type, ext, size = url_info(real_url) print_info(site_info, title, type, size) if not info_only: download_urls([real_url], title, ext, size, output_dir, merge = merge) site_info = "Nicovideo.jp" download = nicovideo_download download_playlist = playlist_not_supported('nicovideo')
[ "mort.yao@gmail.com" ]
mort.yao@gmail.com
9868e0ff63d7c2e5e044ffb7dfdba00dc89af939
555eaa076cc5d3a85e4a5b7db418d312a084bc23
/Euler67.py
39f2fca46e18b0e512f7bf7381da12af6b32e10d
[]
no_license
QuestionC/euler
8b5c1f4014373354f14a30c18522e4615137d903
32a1c6f1572e5e4faf4780b9667391c5dbf475e3
refs/heads/master
2020-05-04T23:15:06.892080
2019-04-04T16:57:18
2019-04-04T16:57:18
179,537,781
0
0
null
null
null
null
UTF-8
Python
false
false
1,265
py
from array import array f = open('p067_triangle.txt', 'r') # f = open ('Euler67_test.txt', 'r') heap = [] global max_depth max_depth = 0 for linenum, line in enumerate(f.readlines()): max_depth = linenum for inner_index, x in enumerate(line.split()): value = int(x) index = len(heap) left_parent = index - linenum - 1 right_parent = index - linenum if linenum == 0: # Root node heap.append (value) elif inner_index == 0: print (str(value) + ' has no left parent. using rig') # No left parent. Just use right parent. heap.append (heap[right_parent] + value) elif inner_index == linenum: print (str(value) + ' has no right parent') # No right parent. heap.append (heap[left_parent] + value) else: heap.append (value + max (heap[left_parent], heap[right_parent])) max_left = int(max_depth * (max_depth + 1) / 2) max_right = max_left + max_depth + 2 print ( str ( (max_depth, max_left, max_right) ) ) # heap[] now contains each element's distance. Find the max of the lowest row print ( str (max (heap[max_left : max_right] ) ) )
[ "questionc@gmail.com" ]
questionc@gmail.com
e5e322c8ce9a6e49b893fe091a93bf40f5588940
667bff70d8e189af7ab54faf879d6a9851b6418c
/Converter_Files/convert_schema_to_json.py
7e69a0d83677552e30ebc3b5adda58dcb3da635b
[]
no_license
SpenDM/LabKeySchemaToMetadataConverter
ac034a740a62639df694272e8ed374544803ea4d
a67b71d4c2ed279af062bec41cbd3bde94b11b76
refs/heads/master
2021-09-09T09:04:14.617529
2018-03-14T14:30:35
2018-03-14T14:30:35
104,756,499
0
1
null
null
null
null
UTF-8
Python
false
false
5,283
py
import argparse import os from typing import List from SchemaReader import * def main(schema_file): print("Checking schema...") json_file = get_file_path_and_names(schema_file) try: with open(schema_file, "rU", encoding="utf-8") as in_file: schema_lines = in_file.readlines() convert_file(json_file, schema_lines) except IOError: print("Error: could not locate " + schema_file) def convert_file(json_file, schema_lines): json_file_content = [] schema_contents, schema_is_valid = get_schema_contents(schema_lines) if schema_is_valid: print("Schema is valid. Converting to JSON...") # Get header json_file_content, schema_is_valid = get_header_or_footer(json_file_content, json_header_file, schema_is_valid) # Convert schema lines to json json_file_content = convert_schema_lines_to_json(schema_contents, json_file_content) # Get footer json_file_content, schema_is_valid = get_header_or_footer(json_file_content, json_footer_file, schema_is_valid) if schema_is_valid: write_json_file(json_file_content, json_file) def get_header_or_footer(json_file_content, file, schema_is_valid): try: with open(file, "rU", encoding="utf8") as in_file: lines = in_file.readlines() json_file_content.extend(lines) except IOError: schema_is_valid = False print("Error: can't find supporting file " + file + " from current directory " + os.getcwd()) return json_file_content, schema_is_valid def convert_schema_lines_to_json(schema: List[Section], json_file_content: List): for section_index, section in enumerate(schema): section_line = TABLE_LINE_START + section.name + TABLE_LINE_END json_file_content.append(section_line) json_file_content.append(FIELD_LIST_LINE) for field_index, field in enumerate(section.fields): # Field name line field_line = FIELD_LINE_START + field.name + FIELD_LINE_END json_file_content.append(field_line) # Datatype line datatype = property_conversion_table[field.datatype] datatype_line = DATATYPE_LINE_START + datatype + DATATYPE_LINE_END json_file_content.append(datatype_line) # Class type line class_type = property_conversion_table[field.class_type] class_type_line = CLASS_LINE_START + class_type + CLASS_LINE_END json_file_content.append(class_type_line) # Dropdown options lines json_file_content = add_dropdown_lines(json_file_content, field.dropdown) # Field ending line if field_index == len(section.fields) - 1: json_file_content.append(FINAL_FIELD_END_LINE) else: json_file_content.append(CONTINUING_FIELD_END_LINE) # Section ending lines json_file_content.append(FIELD_LIST_END_LINE) if section_index == len(schema) - 1: json_file_content.append(FINAL_TABLE_END_LINE) else: json_file_content.append(CONTINUING_TABLE_END_LINE) return json_file_content def add_dropdown_lines(json_file_content, dropdown_list): json_file_content.append(DISEASE_PROPERTIES_LINE) json_file_content.append(DISEASE_PROPERTIES_START_BRACKET_LINE) json_file_content.append(DISEASE_GROUP_LINE) dropdown_options = "\", \"".join(dropdown_list) dropdown_line = DROPDOWN_OPTIONS_LINE_START + dropdown_options + DROPDOWN_OPTIONS_LINE_END json_file_content.append(dropdown_line) json_file_content.append(DISEASE_GROUP_END_LINE) json_file_content.append(DISEASE_PROPERTIES_END_BRACKET_LINE) return json_file_content def write_json_file(json_file_content, json_filename): try: with open(json_filename, "w", encoding="ascii") as out_file: out_file.writelines(json_file_content) print("Done") except IOError: print("Error: could not locate destination for " + json_filename) except UnicodeEncodeError: print("Error: character encoding error. ") with open(json_filename, "w", encoding="ascii") as out_file: out_file.write("Schema Conversion Failed - character encoding issue") def get_file_path_and_names(schema_file): # Get path and schema file name path_chunks = schema_file.split("\\") schema_filename = path_chunks[-1] path = "\\\\".join(path_chunks[0:-1]) # Create json file name and path from schema file json_filename = get_metadata_filename(schema_filename) json_filename = re.sub(SCHEMA, METADATA, json_filename, flags=re.I) if path: json_file = path + "\\\\" + json_filename else: json_file = json_filename return json_file def get_metadata_filename(schema_filename): # remove extension (anything after final dot) and replace with new extension name = ".".join(schema_filename.split(".")[0:-1]) return name + JSON_EXTENSION if __name__ == '__main__': # Arguments: schema_file parser = argparse.ArgumentParser() parser.add_argument("schema_file", help="the input file name") args = parser.parse_args() main(args.schema_file)
[ "spencer.d.morris@gmail.com" ]
spencer.d.morris@gmail.com
21360d446d3efefe75b79804bd9ee3f9c33d9122
ed8847f5799981a0f61e634f3469853ce2e4d807
/dfvo/libs/deep_models/checkpoint_logger.py
9ef8b73eca4558fe923bcab4c6e1069b52311ee9
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "MIT" ]
permissive
Arslan-Z/toposlam
05179a1601eeaed20528c0dc5328a1ab258e04d4
3ec1dda210722d86bf77f101dca57ba27baa5833
refs/heads/main
2023-06-29T04:34:50.752890
2021-03-03T07:53:16
2021-03-03T07:53:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,438
py
''' @Author: Huangying Zhan (huangying.zhan.work@gmail.com) @Date: 1970-01-01 @Copyright: Copyright (C) Huangying Zhan 2020. All rights reserved. Please refer to the license file. @LastEditTime: 2020-06-11 @LastEditors: Huangying Zhan @Description: ''' import os import torch from dfvo.libs.general.utils import mkdir_if_not_exists class CheckpointLogger(): def __init__(self, epoch_freq, step_freq, result_dir): # # logging frequency # self.freqs = {} # self.freqs['epoch'] = epoch_freq # self.freqs['step'] = step_freq # directory self.result_dir = result_dir def save_checkpoint(self, item, cur_cnt, ckpt_data, is_best=False): """Save trained models, optimizer and training states Args: item (str): epoch / iter cur_counter (int): current counter ckpt_data (dict): checkpoint data dictionary - models: network model states - optimzier: optimizer state - train_state: extra information - epoch - step is_best (bool): model with best validation loss """ models = ckpt_data['models'] optimizer = ckpt_data['optimizer'] train_state = ckpt_data['train_state'] # Save current checkpoint save_folder = os.path.join( self.result_dir, "models", "{}_{}".format(item, cur_cnt) ) mkdir_if_not_exists(save_folder) print("==> Save checkpoint at {} {}".format(item, cur_cnt)) self.save_model(save_folder, models) self.save_optimizer(save_folder, optimizer) self.save_train_state(save_folder, train_state) # Save best model if is_best: save_folder = os.path.join( self.result_dir, "models", "best" ) mkdir_if_not_exists(save_folder) print("==> Save best model.") self.save_model(save_folder, models) self.save_optimizer(save_folder, optimizer) self.save_train_state(save_folder, train_state) with open(os.path.join(save_folder, "best.txt"), 'w') as f: line = "{}: {}".format(item, cur_cnt) f.writelines(line) def save_model(self, save_folder, models): """Save model checkpoints Args: save_folder (str): directory for saving models models (dict): model dictionary """ for model_name, model in models.items(): ckpt_path = os.path.join(save_folder, "{}.pth".format(model_name)) torch.save(model.state_dict(), ckpt_path) def save_optimizer(self, save_folder, optimizer): """Save optimizer data Args: save_folder (str): directory for saving models optimizer (torch.optim): torch optimizer data """ ckpt_path = os.path.join(save_folder, "optimizer.pth") torch.save(optimizer.state_dict(), ckpt_path) def save_train_state(self, save_folder, train_state): """Save optimizer data Args: save_folder (str): directory for saving models train_state (dict): extra training state information """ ckpt_path = os.path.join(save_folder, "train_state.pth") torch.save(train_state, ckpt_path)
[ "zhanhuangying@gmail.com" ]
zhanhuangying@gmail.com
16378bf48bfd7238f44a28bed30982747dd094a3
37f8f912a3a58c279885af6c5d5df91e20209ebf
/day15.py
8f76d8b9e1a3e4aec890aa4edaee226e4728a628
[]
no_license
Parag357/30_Days_Of_Code
d9e81b17e4e56f2d55d8e5b1a70343eb2b247985
7e289c64001a9043fd70fbb88e66f3107d08bc00
refs/heads/master
2022-11-27T23:19:35.659214
2020-08-04T07:14:03
2020-08-04T07:14:03
280,176,238
0
0
null
null
null
null
UTF-8
Python
false
false
586
py
class Node: def __init__(self,data): self.data = data self.next = None class Solution: def display(self,head): current = head while current: print(current.data,end=' ') current = current.next def insert(self,head,data): #Complete this method n1= Node(data) if head==None: head=n1 else: start = head while start.next != None: start = start.next start.next=n1 n1.next=None return head mylist= Solution()
[ "psychoprg357@gmail.com" ]
psychoprg357@gmail.com
a930af263368f408509f886a31e54dd514c98f32
b1a10d673c5cda24fba4ab58eb312ac337914be5
/nmt_try/models/bert2gpt2.py
59553f98974aa58f94bf2d1cefe9f179c6ffec3a
[ "Apache-2.0" ]
permissive
cwza/nmt_try
c70574a048bbc8422dc25a5243457156511ac3bb
2ac616a218cdc6470c48f4da1b44fa12e1ffc75a
refs/heads/master
2023-04-13T09:56:38.595323
2020-02-26T12:27:27
2020-02-27T01:46:18
239,925,195
0
0
Apache-2.0
2023-03-09T05:55:49
2020-02-12T04:16:19
Jupyter Notebook
UTF-8
Python
false
false
6,311
py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03c_models.bert2gpt2.ipynb (unless otherwise specified). __all__ = ['gen_attention_mask', 'BertEncoder', 'GPT2Decoder', 'Bert2GPT2', 'GeneratedBert2GPT2', 'generate_from_ids'] # Cell from fastai2.basics import * from transformers import AutoModel, AutoTokenizer, PreTrainedTokenizer from fastai2_utils.pytorch.transformer import * from fastai_transformers_utils.tokenizers import GPT2DecoderTokenizer from fastai_transformers_utils.generated_lm import GeneratedLM, GenerateArgs # Cell def gen_attention_mask(inp_ids, pad_id): ''' Returns Tensor where 0 are positions that contain pad_id, others 1. input_ids: (bs, seq_len) returns: (bs, seq_len) ''' key_padding_mask = gen_key_padding_mask(inp_ids, pad_id) return (~key_padding_mask).long() # Cell class BertEncoder(nn.Module): def __init__(self, model_name): ''' model_name: pretrained bert model name from huggingface ''' super().__init__() self.bert = AutoModel.from_pretrained(model_name) self.layer_groups = [self.bert.embeddings, *self.bert.encoder.layer, self.bert.pooler] def forward(self, src_input_ids, src_attention_mask): ''' src_input_ids: (bs, enc_seq_len) src_attention_mask: (bs, enc_seq_len) returns: (bs, enc_seq_len, embed_size) ''' return self.bert(src_input_ids, attention_mask=src_attention_mask)[0] # Cell def _adujsted_gpt2wte(gpt2): ''' Adjust pretrained gpt2 wte layer to adapt the GPT2DecoderTokenizer. Add bos_token and pad_token at the last of gpt2.wte. Use GPT2DecoderTokenizer or make sure the pad token is at the last of your tokenizer and the bos token is at the second-last. ''' old_wte = gpt2.wte old_weight = old_wte.weight num_embeddings = old_wte.num_embeddings+2 embedding_dim = old_wte.embedding_dim bos_weight = old_weight.mean(dim=0)[None] # (1, embedding_dim) pad_weight = torch.zeros((1, embedding_dim)) new_weight = torch.cat([old_weight, bos_weight, pad_weight], dim=0) # (num_embeddings, embedding_dim) new_wte = nn.Embedding(num_embeddings, embedding_dim, padding_idx=num_embeddings-1) new_wte.weight.data = new_weight return new_wte # Cell class GPT2Decoder(nn.Module): def __init__( self, model_name, pad_id, # for GPT2 vocab_size, # for classifier num_heads=1, drop_p=0, num_layers=1, # for CrossAttention ): ''' model_name: pretrained gpt2 model name from huggingface ''' super().__init__() self.gpt2 = AutoModel.from_pretrained(model_name) self.gpt2.wte = _adujsted_gpt2wte(self.gpt2) self.cross_attn = CrossAttention(self.gpt2.config.n_embd, num_heads, drop_p, num_layers) self.classifier = nn.Linear(self.gpt2.config.n_embd, vocab_size) self.pad_id = pad_id self.layer_groups = [ self.gpt2.wte, self.gpt2.wpe, *self.gpt2.h, self.gpt2.ln_f, *self.cross_attn.cross_attn_layers, self.classifier ] def forward(self, tgt_input_ids, memory, memory_key_padding_mask): ''' tgt_input_ids: (bs, dec_seq_len) memory: (bs, enc_seq_len, embed_size) memory_key_padding_mask: (bs, enc_seq_len) returns: output, attn_weight output: (bs, dec_seq_len, dec_vocab_size) attn_weight: (bs, dec_seq_len, enc_seq_len) ''' tgt_attention_mask = gen_attention_mask(tgt_input_ids, self.pad_id) # (bs, dec_seq_len) gpt2_out = self.gpt2(tgt_input_ids, attention_mask=tgt_attention_mask)[0] # (bs, dec_seq_len, 768) attn_output, attn_weight = self.cross_attn(gpt2_out, memory, src_key_padding_mask=memory_key_padding_mask) # (bs, dec_seq_len, 768), (bs, dec_seq_len, enc_seq_len) output = self.classifier(attn_output) # (bs, dec_seq_len, dec_vocab_size) return output, attn_weight # Cell class Bert2GPT2(nn.Module): def __init__( self, encoder: BertEncoder, decoder: GPT2Decoder, enc_pad_id, # for src_key_padding_mask and memory_key_padding_mask ): super().__init__() self.encoder = encoder self.decoder = decoder self.enc_pad_id = enc_pad_id def forward(self, src_input_ids, tgt_input_ids): ''' src_input_ids: (bs, enc_seq_len) tgt_input_ids: (bs, dec_seq_len) ''' src_attention_mask = gen_attention_mask(src_input_ids, self.enc_pad_id) # (bs, enc_seq_len) memory = self.encoder(src_input_ids, src_attention_mask) # (bs, enc_seq_len, embed_size) memory_key_padding_mask = (1-src_attention_mask).bool() output, _ = self.decoder(tgt_input_ids, memory, memory_key_padding_mask=memory_key_padding_mask) # (bs, dec_seq_len, embeded_size) return output # Cell class GeneratedBert2GPT2(): def __init__( self, seq2seq: Bert2GPT2, enc_tokenizer: PreTrainedTokenizer, dec_tokenizer: PreTrainedTokenizer, ): self.seq2seq = seq2seq self.enc_tokenizer = enc_tokenizer self.dec_tokenizer = dec_tokenizer self.generatedLM = GeneratedLM(seq2seq.decoder, len(dec_tokenizer), dec_tokenizer.pad_token_id, [dec_tokenizer.eos_token_id], support_past=False) # Cell @patch @torch.no_grad() def generate_from_ids(self: GeneratedBert2GPT2, src_input_ids, generate_args: GenerateArgs): ''' src_input_ids: (bs, enc_seq_len), returns: (bs, max_length)''' self.seq2seq.eval() device = src_input_ids.device bs = src_input_ids.shape[0] tgt_input_ids = torch.zeros((bs, 1), dtype=torch.long, device=device).fill_(self.dec_tokenizer.bos_token_id) # (bs, 1) src_attention_mask = gen_attention_mask(src_input_ids, self.enc_tokenizer.pad_token_id) # (bs, enc_seq_len) memory = self.seq2seq.encoder(src_input_ids, src_attention_mask) # (bs, enc_seq_len, embed_size) memory_key_padding_mask = (1-src_attention_mask).bool() model_otherargs = self.generatedLM.build_model_otherargs_for_beam([memory, memory_key_padding_mask], generate_args.num_beams) result = self.generatedLM.generate(tgt_input_ids, generate_args, [model_otherargs[0]], dict(memory_key_padding_mask=model_otherargs[1])) return result
[ "cwz0205a@gmail.com" ]
cwz0205a@gmail.com
9a1a4e319901d0a370dd8a355c45e35589a6a8e6
181f1809e0fdd60277a66d1ec62f801b202f9834
/Aula_25/Phone/__init__.py
8c8414a4f7ab3453d039879b66a8ff79551a8ec1
[]
no_license
Donzellini/pythonCampinasTech
a1096af54b7013bad8b46f4a9b2683c7414bbba5
8ed19209eeba0582c56715e9e6eb7eeec16899c9
refs/heads/master
2023-03-07T00:16:34.031888
2021-02-25T00:50:35
2021-02-25T00:50:35
328,802,944
0
0
null
null
null
null
UTF-8
Python
false
false
65
py
from .Pots import Pots from .Isdn import Isdn from .G3 import G3
[ "muriel.donzellini@gmail.com" ]
muriel.donzellini@gmail.com
fcd556f98183b9086c4ff0e3a85ee27e1b8039cc
55c250525bd7198ac905b1f2f86d16a44f73e03a
/Python/Projects/twilio/build/lib/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py
841596491a9c386e78df4a5bef448c1bc307ec56
[ "LicenseRef-scancode-other-permissive" ]
permissive
NateWeiler/Resources
213d18ba86f7cc9d845741b8571b9e2c2c6be916
bd4a8a82a3e83a381c97d19e5df42cbababfc66c
refs/heads/master
2023-09-03T17:50:31.937137
2023-08-28T23:50:57
2023-08-28T23:50:57
267,368,545
2
1
null
2022-09-08T15:20:18
2020-05-27T16:18:17
null
UTF-8
Python
false
false
130
py
version https://git-lfs.github.com/spec/v1 oid sha256:309ff8b793431f10b723664f42c344c7e09025e2409c33e9826fa1db60574049 size 20006
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
e461e65423de835ed1aec2c692797091aec42829
3f28b697f570ded0502de70c706200005ab62525
/env/lib/python2.7/site-packages/pandas/tools/tests/test_util.py
9480ea7ee5bf80d19ca8f751edc3e549ca4fd090
[ "MIT" ]
permissive
Ram-Aditya/Healthcare-Data-Analytics
5387e41ad8e56af474e10fa2d1c9d8a2847c5ead
d1a15d2cc067410f82a9ded25f7a782ef56b4729
refs/heads/master
2022-12-09T12:49:59.027010
2019-11-23T20:10:55
2019-11-23T20:10:55
223,639,339
0
1
MIT
2022-11-22T00:37:48
2019-11-23T19:06:20
Jupyter Notebook
UTF-8
Python
false
false
3,094
py
import os import locale import codecs import nose import numpy as np from numpy.testing import assert_equal from pandas import date_range, Index import pandas.util.testing as tm from pandas.tools.util import cartesian_product CURRENT_LOCALE = locale.getlocale() LOCALE_OVERRIDE = os.environ.get('LOCALE_OVERRIDE', None) class TestCartesianProduct(tm.TestCase): def test_simple(self): x, y = list('ABC'), [1, 22] result = cartesian_product([x, y]) expected = [np.array(['A', 'A', 'B', 'B', 'C', 'C']), np.array([ 1, 22, 1, 22, 1, 22])] assert_equal(result, expected) def test_datetimeindex(self): # regression test for GitHub issue #6439 # make sure that the ordering on datetimeindex is consistent x = date_range('2000-01-01', periods=2) result = [Index(y).day for y in cartesian_product([x, x])] expected = [np.array([1, 1, 2, 2]), np.array([1, 2, 1, 2])] assert_equal(result, expected) class TestLocaleUtils(tm.TestCase): @classmethod def setUpClass(cls): super(TestLocaleUtils, cls).setUpClass() cls.locales = tm.get_locales() if not cls.locales: raise nose.SkipTest("No locales found") if os.name == 'nt': # we're on windows raise nose.SkipTest("Running on Windows") @classmethod def tearDownClass(cls): super(TestLocaleUtils, cls).tearDownClass() del cls.locales def test_get_locales(self): # all systems should have at least a single locale assert len(tm.get_locales()) > 0 def test_get_locales_prefix(self): if len(self.locales) == 1: raise nose.SkipTest("Only a single locale found, no point in " "trying to test filtering locale prefixes") first_locale = self.locales[0] assert len(tm.get_locales(prefix=first_locale[:2])) > 0 def test_set_locale(self): if len(self.locales) == 1: raise nose.SkipTest("Only a single locale found, no point in " "trying to test setting another locale") if LOCALE_OVERRIDE is not None: lang, enc = LOCALE_OVERRIDE.split('.') else: lang, enc = 'it_CH', 'UTF-8' enc = codecs.lookup(enc).name new_locale = lang, enc if not tm._can_set_locale(new_locale): with tm.assertRaises(locale.Error): with tm.set_locale(new_locale): pass else: with tm.set_locale(new_locale) as normalized_locale: new_lang, new_enc = normalized_locale.split('.') new_enc = codecs.lookup(enc).name normalized_locale = new_lang, new_enc self.assertEqual(normalized_locale, new_locale) current_locale = locale.getlocale() self.assertEqual(current_locale, CURRENT_LOCALE) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
[ "ramaditya.danbrown@gmail.com" ]
ramaditya.danbrown@gmail.com
41b266851b432847dc080b742c50c7cddb33494a
5eb58b2bcaacd5dd38bd57a1e745ccb65e654bdf
/bin/actuary.py
e2e8a255afbcc1488513a9e5d8c6fe5b545f758b
[ "MIT" ]
permissive
Amorymeltzer/dotfiles
f8cadb6df4f3978e3273a7f15b3b9cec02cb560e
f4b6d2fb25c54a7f191a9b387a38b14e8b1d6a71
refs/heads/main
2023-09-01T21:32:27.652765
2023-08-01T14:01:49
2023-08-01T14:01:49
24,949,592
6
1
null
null
null
null
UTF-8
Python
false
false
7,460
py
#!/usr/bin/env python2 import sys import datetime # Calculates death probabilities based on Social Security # actuarial tables for a given group of people. # Run with a list of ages/genders and an optional timespan (or year in the future): # python actuary.py 63m 80m 75f 73m 10 # or: # python actuary.py 63m 80m 75f 73m 2022 # This will give statistics for that group, including # various probabilities over 10 years. Years can be # ommitted and it will still give some statistics. # If "Years" exceeds the current calendar year, it will be interpreted as a date. bothtables=[[0.00756, 0.00052, 0.00035, 0.00025, 0.00020, 0.00018, 0.00017, 0.00016, 0.00014, 0.00011, 0.00009, 0.00010, 0.00015, 0.00027, 0.00043, 0.00061, 0.00078, 0.00094, 0.00107, 0.00119, 0.00131, 0.00142, 0.00149, 0.00151, 0.00148, 0.00143, 0.00140, 0.00138, 0.00137, 0.00139, 0.00141, 0.00143, 0.00147, 0.00152, 0.00158, 0.00165, 0.00174, 0.00186, 0.00202, 0.00221, 0.00243, 0.00267, 0.00291, 0.00317, 0.00344, 0.00373, 0.00405, 0.00441, 0.00480, 0.00524, 0.00573, 0.00623, 0.00671, 0.00714, 0.00756, 0.00800, 0.00853, 0.00917, 0.00995, 0.01086, 0.01190, 0.01301, 0.01413, 0.01522, 0.01635, 0.01760, 0.01906, 0.02073, 0.02265, 0.02482, 0.02729, 0.03001, 0.03289, 0.03592, 0.03918, 0.04292, 0.04715, 0.05173, 0.05665, 0.06206, 0.06821, 0.07522, 0.08302, 0.09163, 0.10119, 0.11183, 0.12367, 0.13679, 0.15124, 0.16702, 0.18414, 0.20255, 0.22224, 0.24314, 0.26520, 0.28709, 0.30846, 0.32891, 0.34803, 0.36544, 0.38371, 0.40289, 0.42304, 0.44419, 0.46640, 0.48972, 0.51421, 0.53992, 0.56691, 0.59526, 0.62502, 0.65628, 0.68909, 0.72354, 0.75972, 0.79771, 0.83759, 0.87947, 0.92345, 0.96962], [0.00615, 0.00041, 0.00025, 0.00018, 0.00015, 0.00014, 0.00014, 0.00013, 0.00012, 0.00011, 0.00010, 0.00010, 0.00012, 0.00016, 0.00021, 0.00028, 0.00034, 0.00039, 0.00042, 0.00043, 0.00045, 0.00047, 0.00048, 0.00049, 0.00050, 0.00051, 0.00052, 0.00053, 0.00056, 0.00059, 0.00063, 0.00068, 0.00073, 0.00078, 0.00084, 0.00091, 0.00098, 0.00108, 0.00118, 0.00130, 0.00144, 0.00158, 0.00173, 0.00189, 0.00206, 0.00225, 0.00244, 0.00264, 0.00285, 0.00306, 0.00329, 0.00355, 0.00382, 0.00409, 0.00437, 0.00468, 0.00505, 0.00549, 0.00603, 0.00665, 0.00736, 0.00813, 0.00890, 0.00967, 0.01047, 0.01136, 0.01239, 0.01357, 0.01491, 0.01641, 0.01816, 0.02008, 0.02210, 0.02418, 0.02641, 0.02902, 0.03206, 0.03538, 0.03899, 0.04301, 0.04766, 0.05307, 0.05922, 0.06618, 0.07403, 0.08285, 0.09270, 0.10365, 0.11574, 0.12899, 0.14343, 0.15907, 0.17591, 0.19393, 0.21312, 0.23254, 0.25193, 0.27097, 0.28933, 0.30670, 0.32510, 0.34460, 0.36528, 0.38720, 0.41043, 0.43505, 0.46116, 0.48883, 0.51816, 0.54925, 0.58220, 0.61714, 0.65416, 0.69341, 0.73502, 0.77912, 0.82587, 0.87542, 0.92345, 0.96962]] def deathprob(age, years): #negative ages = female act=[] if age<0: act=bothtables[1] age=-1*age else: act=bothtables[0] while(len(act)<int(age+years+2)): # slower/bloaiter but keeps things clean act.append(act[-1]**0.5) liveprob=1 i=0 iage=int(age) fage=age%1 while i<=years-1: thisyear=(1-fage)*act[iage+i]+fage*act[iage+i+1] liveprob*=1-thisyear i+=1 if years%1: # Amortizes risk of dying over a partial year, which is # 1-P(living last full year)^(year fraction) lastyear=(1-fage)*act[iage+i]+fage*act[iage+i+1] lastyearlive=1-lastyear lastyearlive=lastyearlive**((years%1)) liveprob*=lastyearlive return 1-liveprob def proballdie(ages, years): probsliving=[] for i in ages: probsliving.append(1-deathprob(i, years)) prod=1 for i in probsliving: prod*=(1-i) return prod def probanydie(ages, years): probsliving=[] for i in ages: probsliving.append(1-deathprob(i, years)) prod=1 for i in probsliving: prod*=i return 1-prod def calcexp(ages, prob, flag): i=0 for interval in (10, 1, 0.1, 0.01): probs=0 while(probs<prob): i+=interval if flag==0: probs=proballdie(ages, i) else: probs=probanydie(ages, i) i-=interval return i ages=[] # print sys.argv[1:] for arg in sys.argv[1:]: gender=1 years=1.0 if arg[-1]=='m' or arg[-1]=='M': try: ages.append(1*float(arg[:-1])) except: print "Error parsing argument", arg elif arg[-1]=='f' or arg[-1]=='F': try: ages.append(-1*float(arg[:-1])) except: print "Error parsing argument", arg else: try: years=float(arg) break except: print "Error parsing argument", arg if not sys.argv[1:]: print "The format is 'actuary.py 15m 80f 23', with a list of ages and a number of years to run the projections." raise SystemExit if not ages: print "No ages specified. Format is 12m, 17f, etc." raise SystemExit # print "Ages:", ages # print "Years:", years (datetime.date.today()+datetime.timedelta(days=365.242191*1)).year someone_years=[calcexp(ages, 0.05, 1), calcexp(ages, 0.5, 1), calcexp(ages, 0.95, 1)] someone_dates=[(datetime.date.today()+datetime.timedelta(days=365.242191*someone_years[0])).year, (datetime.date.today()+datetime.timedelta(days=365.242191*someone_years[1])).year, (datetime.date.today()+datetime.timedelta(days=365.242191*someone_years[2])).year] print "There is a 5% chance of someone dying within", someone_years[0], "years (by", str(someone_dates[0])+")." print "There is a 50% chance of someone dying within", someone_years[1], "years (by", str(someone_dates[1])+")." print "There is a 95% chance of someone dying within", someone_years[2], "years (by", str(someone_dates[2])+")." print "" if len(ages)>1: everyone_years=[calcexp(ages, 0.05, 0), calcexp(ages, 0.5, 0), calcexp(ages, 0.95, 0)] everyone_dates=[(datetime.date.today()+datetime.timedelta(days=365.242191*everyone_years[0])).year, (datetime.date.today()+datetime.timedelta(days=365.242191*everyone_years[1])).year, (datetime.date.today()+datetime.timedelta(days=365.242191*everyone_years[2])).year] print "There is a 5% chance of everyone dying within", everyone_years[0], "years (by", str(everyone_dates[0])+")." print "There is a 50% chance of everyone dying within", everyone_years[1], "years (by", str(everyone_dates[1])+")." print "There is a 95% chance of everyone dying within", everyone_years[2], "years (by", str(everyone_dates[2])+")." if years: yearword="years" if years==1: yearword="year" print "" if years>datetime.date.today().year: years=years-datetime.date.today().year if len(ages)>1: p=100*proballdie(ages, years) printable="" if p<0.001: printable="<0.001" elif p>99.99: printable=">99.99" else: printable=str(p)[:5] print "Probability of all dying in", years, yearword+": ", printable+"%" p=100*probanydie(ages, years) printable="" if p<0.001: printable="<0.001" elif p>99.99: printable=">99.99" print p else: printable=str(p)[:5] print "Probability of a death within", years, yearword+":", printable+"%" raise SystemExit
[ "Amorymeltzer@gmail.com" ]
Amorymeltzer@gmail.com
2fcf3d10ceaace2b68cdc1f7e87469423b3a1a99
5471de6fd11cc36e8ad9c05ea25d13ae568ad060
/Encapsulation/wild_cat_zoo/caretaker.py
cb50b88116632274b6627bd1d92478ccc541bc20
[]
no_license
olgayordanova/PythonOOP
75bbf9a20c612be7212de7bed59edccef1e02304
2d177d17bf50335b17f6246198b1cf85719de1df
refs/heads/main
2023-03-30T18:59:56.751037
2021-04-03T19:48:37
2021-04-03T19:48:37
333,202,583
1
0
null
null
null
null
UTF-8
Python
false
false
244
py
class Caretaker: def __init__(self, name, age, salary): self.name=name self.age = age self.salary = salary def __repr__(self): return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
[ "noreply@github.com" ]
olgayordanova.noreply@github.com
b61244a1c5d4574f9ff50e1f6975f5d98ff2415f
0b55b6c9a0532e1ccdc8e16b7742e84cf4bdbc80
/tools/operations.py
8ab6804f7237e55d394eb5ecc00f53a5f68f628c
[]
no_license
Skar0/gamesolver
689d9dde4acf17855ddbeec65b4b2a7780696b7e
8e511d7c15cfb92eae22f493305489f6c22c03bd
refs/heads/master
2021-03-27T19:17:09.344159
2018-08-16T22:28:35
2018-08-16T22:28:35
97,278,415
11
3
null
null
null
null
UTF-8
Python
false
false
7,018
py
""" This module contains general-purpose functions used in several of our algorithms. """ import ctypes import collections from antichains.library_linker import createGraph_c, addEdge_c, displayGraph_c def opponent(j): """ Returns the opponent of player j. :param j: the player (0 or 1). :return: its opponent. """ if j == 1: return 0 else: return 1 def i_priority_node(g, i): """ Returns all nodes of priority i in game graph g. :param g: the game graph. :param i: the requested priority. :return: a list of nodes of priority i in g. """ nodes = g.nodes # Nodes from g # get all node indexes in node tuple (index, (node_player, node_priority)) when node_priority is i return [k for k, v in nodes.iteritems() if v[1] == i] def i_priority_node_function_j(g, i, j): """ :param g: the game graph. :param i: the requested priority. :param j: the priority function. :return: all nodes of priority i in game graph g according to priority function j. """ nodes = g.nodes # Nodes from g # get all node indexes in node tuple (index, (node_player, node_priority)) when node_priority is i return [k for k, v in nodes.iteritems() if v[j] == i] def max_priority(g): """ Returns the maximum priority occurring in game graph g. :param g: a game graph. :return: the maximum priority in g. """ nodes = g.nodes # Nodes from g # get maximum node tuple (index, (node_player, node_priority)) according to its priority, then select its priority return max(nodes.iteritems(), key=lambda (k, v): v[1])[1][1] def i_priority_node_non_removed(g, i, removed): """ Returns all nodes of priority i in game graph g considering the removed nodes. :param removed: the removed nodes. :param g: the game graph. :param i: the requested priority. :return: a list of nodes of priority i in g except for the removed nodes. """ nodes = {k: v for k, v in g.nodes.iteritems() if not removed[k]} # get all node indexes in node tuple (index, (node_player, node_priority)) when node_priority is i return [k for k, v in nodes.iteritems() if v[1] == i] def max_priority_non_removed(g, removed): """ Returns the maximum priority occurring in game graph g, considering the removed nodes. :param removed: the removed nodes. :param g: a game graph. :return: the maximum priority in g except for the removed nodes. """ nodes = {k: v for k, v in g.nodes.iteritems() if not removed[k]} # get maximum node tuple (index, (node_player, node_priority)) according to its priority, then select its priority return max(nodes.iteritems(), key=lambda (k, v): v[1])[1][1] def update_strategy(strat1, strat2): """ Updates strategy 1 by adding key/value pairs of strategy 2. :param strat1: Old strategy. :param strat2: Strategy to add. :return: A new strategy which merges strategies 1 and 2 (2 overwrites 1 in case of duplicate keys) """ new_strat = strat1.copy() new_strat.update(strat2) return new_strat def print_solution(solution, player): """ Formats the solution of a game and prints it in the command line. :param solution: if player is 0, expected solution format is (W_0, sigma_0),(W_1, sigma_1). If player is 1, invert. :param player: the player corresponding to the first tuple in solution. :return: prints formatted solution """ if player == 0: (W_0, sigma_0), (W_1, sigma_1) = solution else: (W_1, sigma_1), (W_0, sigma_0) = solution print "Winning region of player 0 : " + str(W_0) print "Winning strategy of player 0 :" for key, value in sigma_0.iteritems(): print " " + str(key) + " -> " + str(value) print " " print "Winning region of player 1 : " + str(W_1) print "Winning strategy of player 1 :" for key, value in sigma_1.iteritems(): print " " + str(key) + " -> " + str(value) def print_winning_regions(W1, W2): """ Formats the solution of a game and prints it in the command line. :param W1: winning region of player 0 (1) :param W2: winning region of player 1 (2) :return: prints formatted solution """ print "Winning region of player 0 : " + str(W1)+"\n" print "Winning region of player 1 : " + str(W2)+"\n" def transform_graph_into_c(g): """ Transforms a Graph object to a graph structure in c using the c library. This function assumes that nodes are numbered from 1 to n :param g: a game graph. :return: a game graph in c format and the number of nodes in that graph. """ # nbr of nodes in the graph is needed by the c structure nbr_nodes = len(g.get_nodes()) # the c structure needs players (0 for player 0 and 1 for player 1) and priorities as arrays priorities = [0]*nbr_nodes players = [0]*nbr_nodes # need to create every node before creating the edges. /!\ nodes are numbered from 0 to nbr_nodes-1 in the C struct for node in g.get_nodes(): priorities[node-1] = g.nodes[node][1] players[node-1] = g.nodes[node][0] # creating the c graph dir_graph = createGraph_c(nbr_nodes,(ctypes.c_int * len(priorities))(*priorities),(ctypes.c_int * len(players))(*players)) # adding every edge for node in g.get_nodes(): for succ in g.get_successors(node): addEdge_c(dir_graph, node-1, succ-1) return dir_graph, nbr_nodes def transform_graph_into_c_spec(g): """ Transforms a Graph object to a graph structure in c using the c library. This function assumes that nodes are numbered from 0 to n-1 :param g: a game graph. :return: a game graph in c format and the number of nodes in that graph. """ # nbr of nodes in the graph is needed by the c structure nbr_nodes = len(g.get_nodes()) # the c structure needs players (0 for player 0 and 1 for player 1) and priorities priorities = [0]*nbr_nodes players = [0]*nbr_nodes # need to create every node before creating the edges. # here nodes are already numbered from 0 for node in g.get_nodes(): priorities[node] = g.nodes[node][1] players[node] = g.nodes[node][0] # creating the c graph dir_graph = createGraph_c(nbr_nodes,(ctypes.c_int * len(priorities))(*priorities),(ctypes.c_int * len(players))(*players)) # adding every edge for node in g.get_nodes(): for succ in g.get_successors(node): addEdge_c(dir_graph, node, succ) return dir_graph, nbr_nodes def are_lists_equal(list1, list2): """ Checks whether two lists are equal (contain exactly the same elements). Using Counter data structure allows duplicates to be considered i.e. [1, 1, 2] != [1, 2]. :param list1: the first list. :param list2: the second list. :return: true if the two lists contain exactly the same elements. """ return collections.Counter(list1) == collections.Counter(list2)
[ "clement.tamines@gmail.com" ]
clement.tamines@gmail.com
e41a883422139c5e3d037e4c99094e59853de45b
bfad51e4655139a4a7677e73a236821c85c61df0
/utils/parallel_processing.py
7b75f2132bb121b6f20dcc5b30b1918acb0688e5
[]
no_license
pakaste/bayesian_t_mixed_model
2e78cdcec6c7822e630ba084117d63c12ca94129
3757a205d6c7ecf4e7ca578902001c963bbdd8d5
refs/heads/master
2020-03-25T07:11:18.882796
2018-10-29T17:03:46
2018-10-29T17:03:46
143,546,693
0
0
null
null
null
null
UTF-8
Python
false
false
1,118
py
import multiprocessing as mp from numpy.random import normal from estimation.gibbs_sampler import run_one_chain def multiprocess(processes, params, iters, n_chains, normal_params=(0.0, 2.0)): """ Uses multiprocessing for running multiple Gibbs sampler chains with different initial values. Parameters: processes : (int) number of processes to be initialized params : (list) [y_train, X_train, Z_train, s_b, sigma_b, tau_b, Tau_b, nu_b, s_e, sigma_e, tau_e, Tau_e, nu_e, family_indices] iters : (int) number of iterations per chain n_chains : (int) number of chains normal_params : (tuple) mean and std of normal distribution Returns: (list of lists) of estimated parameters for Gibbs sampler for chains. """ pool = mp.Pool(processes=processes) results = [pool.apply_async(run_one_chain, args=(params, iters, init_val)) for init_val in abs(normal(loc=normal_params[0], scale=normal_params[1], size=n_chains))] results = [p.get() for p in results] return results
[ "pauliina.karell@topdatascience.com" ]
pauliina.karell@topdatascience.com
d492043cebddbfd6b8fc8bdfd50e22a7540891fa
e6ab8bb4d08848e194779f20fe9e36f0b8f63672
/counter(a, b).py
5f7b16a184d1d13c37a9e0281dc28b5b94f2a497
[]
no_license
morykon/homework_
a762887a38222843e7d3a1259ec5cfd2bf26317d
29facf2a76421844cc8da8f639c5ba5ff7c46fcd
refs/heads/master
2020-03-12T14:48:31.359260
2018-06-19T00:14:59
2018-06-19T00:14:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
371
py
# coding: utf-8 # In[111]: # 1) def counter(a, b): c = list(map(int, str(a))) v = list(map(int, str(b))) res=list(set(c) & set(v)) ln = len(res) if res: print(ln) else: print('0') # 2) # In[112]: counter(12345, 567) # In[113]: counter(123, 45) # In[114]: counter(1233211, 12128)
[ "noreply@github.com" ]
morykon.noreply@github.com
dca2e663060763d3f2dbeeaebc01bc33ea648640
45a9f797e8c3005fd8f8f77fcc6d59087b45f9c8
/apps/base/admin.py
3ed6618c9e6ac8c2e8563999611b048a1fdb9095
[ "MIT" ]
permissive
goobes/box
529c99439a165e879095b0d1876e888d37c4f07e
42e136d98b2a25ffd8717b3c8c9d97654cc15e54
refs/heads/master
2022-12-23T06:53:07.487899
2020-02-28T12:39:54
2020-02-28T12:39:54
121,276,604
0
1
MIT
2022-12-08T00:53:52
2018-02-12T17:11:23
HTML
UTF-8
Python
false
false
2,258
py
from django.contrib import admin from django.utils.safestring import mark_safe from allauth.socialaccount.models import SocialAccount from .models import Genre, Publisher, Author, Book, Profile, Item, Payment, Box for m in [Genre, Publisher, Item]: admin.site.register(m) @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): fields = ('name', 'ol_id', 'alternate_names', 'year_of_birth', 'year_of_death') list_display = ('name', 'ol_id', 'alternate_names') search_fields = ['name'] @admin.register(Book) class BookAdmin(admin.ModelAdmin): fields = ['title', 'ol_id', 'isbn', 'genres', 'authors', 'publisher', 'year_of_publication'] list_display = ['title', 'ol_id'] autocomplete_fields = ['authors'] search_fields = ['title'] @admin.register(Payment) class PaymentAdmin(admin.ModelAdmin): fields = ['user', 'item', 'payment_date', 'payment_id', 'payment_request_id', 'amount', 'fees', 'status', 'longurl' ,'shorturl', 'fulfilled'] list_display = ['payment_request_id', 'user', 'item', 'payment_date', 'amount', 'status'] readonly_fields = ['payment_date'] list_display_links = ['payment_request_id', 'user'] @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): fields = ('user', 'address', 'city', 'state', 'postal_code', ('phone_mobile', 'phone_landline'), 'genres', 'favourite_books', 'favourite_authors', 'interests', 'boxes_remaining', 'goodreads_link', 'profile_link') readonly_fields = ( 'favourite_books', 'favourite_authors', 'interests', 'goodreads_link', 'profile_link' ) def goodreads_link(self, obj): sa = SocialAccount.objects.filter(user=obj.user, provider='goodreads').first() if sa: return mark_safe("<a href='https://www.goodreads.com/user/show/{0}'>https://www.goodreads.com/user/show/{0}</a>".format(sa.uid)) else: return "" def profile_link(self, obj): return mark_safe("<a href='{}'>View profile</a>".format(obj.get_absolute_url())) @admin.register(Box) class BoxAdmin(admin.ModelAdmin): fields = ( 'shipped_at', 'books', 'payment', 'tracking_code') list_display = ( 'payment', 'created_at', 'shipped_at', ) autocomplete_fields = ('books',)
[ "arunkakorp@gmail.com" ]
arunkakorp@gmail.com
37145b4ae3972f800735a8b8cb5c858bff969032
a735ae1bd7f0f15ee35c17cd1219a2890f25cd01
/mysite/blog/migrations/0001_initial.py
bc8b8183e3f70f3e76ca33b06362c5686c482edd
[]
no_license
stevekutz/django_blog
56e89a0be30c5af400fd4ea1865dfd16fc3292ca
2605e6afa3c367d29a5ac441286532b96135a9df
refs/heads/master
2022-11-28T20:17:11.756140
2020-08-02T01:16:15
2020-08-02T01:16:15
264,799,096
0
0
null
null
null
null
UTF-8
Python
false
false
1,362
py
# Generated by Django 3.0.6 on 2020-05-19 01:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=250)), ('slug', models.SlugField(max_length=250, unique_for_date='publish')), ('body', models.TextField()), ('publish', models.DateTimeField(default=django.utils.timezone.now)), ('created', models.DateField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='draft', max_length=10)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_posts', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-publish',), }, ), ]
[ "stkutz@gmail.com" ]
stkutz@gmail.com
e7556dba9e02cc59489acc277e99a95e1b278bd8
dc40e4ee1ada66625c3851b8decdc2388a9de342
/Python/grabWeb.py
ceceaf94c09a0b53ed186ecc9e495dbdacbc1e37
[]
no_license
BaoLearns/Code
85fbf3091af70d57c2e5c76349ae7ffa5645978b
03931e9c7f6a0451489777213b8f3dc807ff84f3
refs/heads/master
2021-01-13T00:56:58.605701
2016-05-12T07:01:27
2016-05-12T07:01:27
55,779,989
1
1
null
null
null
null
UTF-8
Python
false
false
646
py
from urllib import urlretrieve def firstNonBlank(lines): for eachLine in lines: #if not eachLine.strip(): # continue #return eachLine print eachLine def firstLast(webpage): f = open(webpage, 'r') lines = f.readlines() f.close() firstNonBlank(lines) #print firstNonBlank(lines) #lines.reverse() #print firstNonBlank(lines) def download(url = 'http://www.163.com', process = firstLast): try: retval = urlretrieve(url)[0] except IOError: retval = None if retval: process(retval) if __name__ == '__main__': download()
[ "Royecode@163.com" ]
Royecode@163.com
1443e2d53e6fa26b4f6180e46954831026119337
43ec943dd7c0bbf9ffe0664acf9c3a1fa980ef62
/DaskBot1.0/modules/task_thread.py
2b2a596ba5d24658a8332c8321aec6847998ce97
[]
no_license
RyanLy/SkypeCheckin
56a9b33587d74b3ace5957dc09a39d103af25ac8
9477b4df269cb47e372eec7f97b9774c10ac34d7
refs/heads/master
2020-04-06T05:33:05.562392
2018-06-05T07:41:16
2018-06-05T07:41:16
26,026,657
3
3
null
2017-03-03T06:39:26
2014-10-31T17:45:57
JavaScript
UTF-8
Python
false
false
646
py
import threading class TaskThread(threading.Thread): """Thread that executes a task every N seconds""" def __init__(self, task, **kwargs): threading.Thread.__init__(self) self._finished = threading.Event() self._interval = 3600 self.task = task self.args = kwargs def set_interval(self, interval): """Set the number of seconds we sleep between executing our task""" self._interval = interval def run(self): while 1: if self._finished.isSet(): return self.task(**self.args) self._finished.wait(self._interval)
[ "windask@hotmail.com" ]
windask@hotmail.com
2813a23a9ccc1311c3ce976637552101da781197
a730e6c54cd99beb00fe7b9c08ff92c5e1800bbf
/libretto/migrations/0047_migrate_caracteristique_programme.py
5fa95b41fbfca40c1ebf9520ae51304356717f95
[ "BSD-3-Clause" ]
permissive
pombredanne/dezede
3d2f4b7bdd9163ae1c0b92593bbd5fae71d1cd91
22756da8f949e28b9d789936d58eabe813ef4278
refs/heads/master
2021-01-17T15:29:30.382243
2013-11-09T17:35:42
2013-11-09T17:35:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
52,170
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): CaracteristiqueDElementDeProgramme = orm['libretto.CaracteristiqueDElementDeProgramme'] PolymorphicCaracteristiqueDElementDeProgramme = orm['libretto.PolymorphicCaracteristiqueDElementDeProgramme'] ContentType = orm['contenttypes.ContentType'] ct = ContentType.objects.get_or_create( app_label='libretto', model='caracteristiquedelementdeprogramme', name=u'caractéristique d’élément de programme')[0] if orm['libretto.Caracteristique'].objects.count(): max_pk = db.execute( 'select id from libretto_caracteristique order by id desc limit 1;')[0][0] db.execute( 'alter sequence libretto_caracteristique_id_seq restart with %s;', [max_pk + 1]) if orm['libretto.TypeDeCaracteristique'].objects.count(): max_pk = db.execute( 'select id from libretto_typedecaracteristique order by id desc limit 1;')[0][0] db.execute( 'alter sequence libretto_typedecaracteristique_id_seq restart with' ' %s;', [max_pk + 1]) caracteristiques = CaracteristiqueDElementDeProgramme.objects.order_by('pk') for c in caracteristiques: new_c = PolymorphicCaracteristiqueDElementDeProgramme.objects.create( type=None, valeur=c.nom, classement=c.classement, owner=c.owner, polymorphic_ctype=ct, ) elements = list(c.elements_de_programme.all()) for e in elements: e.caracteristiques.remove(c) c.delete() c.pk = new_c.pk c.save() for e in elements: e.caracteristiques.add(c) def backwards(self, orm): raise RuntimeError("Cannot reverse this migration.") models = { u'accounts.hierarchicuser': { 'Meta': {'object_name': 'HierarchicUser'}, 'avatar': ('filebrowser.fields.FileBrowseField', [], {'max_length': '400', 'null': 'True', 'blank': 'True'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'fonctions': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'legal_person': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'literature': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'mentor': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "u'disciples'", 'null': 'True', 'to': u"orm['accounts.HierarchicUser']"}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'presentation': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'show_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'website_verbose': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'willing_to_be_mentor': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'libretto.ancragespatiotemporel': { 'Meta': {'ordering': "(u'date', u'heure', u'lieu__parent', u'lieu', u'date_approx', u'heure_approx', u'lieu_approx')", 'object_name': 'AncrageSpatioTemporel'}, 'date': ('django.db.models.fields.DateField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'date_approx': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}), 'heure': ('django.db.models.fields.TimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'heure_approx': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'lieu': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'ancrages'", 'null': 'True', 'to': u"orm['libretto.Lieu']"}), 'lieu_approx': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'ancragespatiotemporel'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}) }, u'libretto.auteur': { 'Meta': {'ordering': "(u'profession', u'individu__nom')", 'object_name': 'Auteur'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'on_delete': 'models.PROTECT'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'individu': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'auteurs'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Individu']"}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'auteur'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'profession': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'auteurs'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Profession']"}) }, u'libretto.caracteristique': { 'Meta': {'ordering': "(u'type', u'classement', u'valeur')", 'object_name': 'Caracteristique'}, 'classement': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'caracteristique'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_libretto.caracteristique_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'caracteristiques'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.TypeDeCaracteristique']"}), 'valeur': ('django.db.models.fields.CharField', [], {'max_length': '400'}) }, u'libretto.caracteristiquedelementdeprogramme': { 'Meta': {'ordering': "(u'nom',)", 'object_name': 'CaracteristiqueDElementDeProgramme'}, 'classement': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '110', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'caracteristiquedelementdeprogramme'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}) }, u'libretto.caracteristiquedoeuvre': { 'Meta': {'ordering': "(u'type', u'classement', u'valeur')", 'object_name': 'CaracteristiqueDOeuvre', '_ormbases': [u'libretto.Caracteristique']}, u'caracteristique_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.Caracteristique']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.devise': { 'Meta': {'object_name': 'Devise'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'unique': 'True', 'max_length': '200', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'devise'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'symbole': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10', 'db_index': 'True'}) }, u'libretto.document': { 'Meta': {'ordering': "(u'document',)", 'object_name': 'Document'}, 'description': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'document': ('filebrowser.fields.FileBrowseField', [], {'max_length': '400'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'document'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}) }, u'libretto.elementdedistribution': { 'Meta': {'ordering': "(u'pupitre',)", 'object_name': 'ElementDeDistribution'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'null': 'True', 'on_delete': 'models.PROTECT'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'individus': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'elements_de_distribution'", 'symmetrical': 'False', 'to': u"orm['libretto.Individu']"}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'elementdedistribution'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'profession': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'elements_de_distribution'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Profession']"}), 'pupitre': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'elements_de_distribution'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Pupitre']"}) }, u'libretto.elementdeprogramme': { 'Meta': {'ordering': "(u'position', u'oeuvre')", 'object_name': 'ElementDeProgramme'}, 'autre': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '500', 'blank': 'True'}), 'caracteristiques': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'elements_de_programme'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.CaracteristiqueDElementDeProgramme']"}), 'distribution': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'elements_de_programme'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.ElementDeDistribution']"}), 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'elementdeprogramme_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), 'evenement': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'programme'", 'to': u"orm['libretto.Evenement']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'elementdeprogramme_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'numerotation': ('django.db.models.fields.CharField', [], {'default': "u'O'", 'max_length': '1'}), 'oeuvre': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'elements_de_programme'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Oeuvre']"}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'elementdeprogramme'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'personnels': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'elements_de_programme'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Personnel']"}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {}) }, u'libretto.engagement': { 'Meta': {'object_name': 'Engagement'}, 'devise': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'engagements'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Devise']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'individus': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'related_name': "u'engagements'", 'symmetrical': 'False', 'to': u"orm['libretto.Individu']"}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'engagement'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'profession': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engagements'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Profession']"}), 'salaire': ('django.db.models.fields.FloatField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}) }, u'libretto.etat': { 'Meta': {'ordering': "(u'slug',)", 'object_name': 'Etat'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '230', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'etat'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '50', 'populate_from': "u'get_slug'", 'unique_with': '()'}) }, u'libretto.evenement': { 'Meta': {'ordering': "(u'ancrage_debut',)", 'object_name': 'Evenement'}, 'ancrage_debut': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'evenements_debuts'", 'unique': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.AncrageSpatioTemporel']"}), 'ancrage_fin': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'evenements_fins'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.AncrageSpatioTemporel']", 'blank': 'True', 'unique': 'True'}), 'circonstance': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '500', 'blank': 'True'}), 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'evenement_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'evenement_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'evenement'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'relache': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}) }, u'libretto.genredoeuvre': { 'Meta': {'ordering': "(u'slug',)", 'object_name': 'GenreDOeuvre'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '430', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'genredoeuvre'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'parents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'enfants'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.GenreDOeuvre']"}), 'referent': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "u'get_slug'"}) }, u'libretto.illustration': { 'Meta': {'ordering': "(u'image',)", 'object_name': 'Illustration'}, 'commentaire': ('tinymce.models.HTMLField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('filebrowser.fields.FileBrowseField', [], {'max_length': '400'}), 'legende': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'illustration'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}) }, u'libretto.individu': { 'Meta': {'ordering': "(u'nom',)", 'object_name': 'Individu'}, 'ancrage_approx': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'individus'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.AncrageSpatioTemporel']", 'blank': 'True', 'unique': 'True'}), 'ancrage_deces': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'individus_decedes'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.AncrageSpatioTemporel']", 'blank': 'True', 'unique': 'True'}), 'ancrage_naissance': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'individus_nes'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.AncrageSpatioTemporel']", 'blank': 'True', 'unique': 'True'}), 'biographie': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'designation': ('django.db.models.fields.CharField', [], {'default': "u'S'", 'max_length': '1'}), 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'individu_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'enfants': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'related_name': "u'parents'", 'symmetrical': 'False', 'through': u"orm['libretto.ParenteDIndividus']", 'to': u"orm['libretto.Individu']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'individu_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'nom': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}), 'nom_naissance': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'individu'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'particule_nom': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '10', 'blank': 'True'}), 'particule_nom_naissance': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '10', 'blank': 'True'}), 'prenoms': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'individus'", 'to': u"orm['libretto.Prenom']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True', 'db_index': 'True'}), 'professions': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'individus'", 'to': u"orm['libretto.Profession']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True', 'db_index': 'True'}), 'pseudonyme': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '50', 'populate_from': "u'get_slug'", 'unique_with': '()'}), 'titre': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '1', 'blank': 'True'}) }, u'libretto.institution': { 'Meta': {'ordering': "(u'nom',)", 'object_name': 'Institution', '_ormbases': [u'libretto.Lieu']}, u'lieu_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.Lieu']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.instrument': { 'Meta': {'ordering': "(u'classement', u'nom')", 'object_name': 'Instrument', '_ormbases': [u'libretto.Partie']}, u'partie_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.Partie']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.lieu': { 'Meta': {'ordering': "(u'nom',)", 'unique_together': "((u'nom', u'parent'),)", 'object_name': 'Lieu'}, 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'lieu_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), 'historique': ('tinymce.models.HTMLField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'lieu_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'nature': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'lieux'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.NatureDeLieu']"}), 'nom': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'lieu'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'parent': ('polymorphic_tree.models.PolymorphicTreeForeignKey', [], {'blank': 'True', 'related_name': "u'enfants'", 'null': 'True', 'to': u"orm['libretto.Lieu']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_libretto.lieu_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '50', 'populate_from': "u'get_slug'", 'unique_with': '()'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, u'libretto.lieudivers': { 'Meta': {'ordering': "(u'nom',)", 'object_name': 'LieuDivers', '_ormbases': [u'libretto.Lieu']}, u'lieu_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.Lieu']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.naturedelieu': { 'Meta': {'ordering': "(u'slug',)", 'object_name': 'NatureDeLieu'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '430', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'naturedelieu'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'referent': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "u'get_slug'"}) }, u'libretto.oeuvre': { 'Meta': {'ordering': "(u'titre', u'genre', u'slug')", 'object_name': 'Oeuvre'}, 'ancrage_creation': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'oeuvres_creees'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.AncrageSpatioTemporel']", 'blank': 'True', 'unique': 'True'}), 'caracteristiques': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'oeuvres'", 'to': u"orm['libretto.CaracteristiqueDOeuvre']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True', 'db_index': 'True'}), 'contenu_dans': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "u'enfants'", 'null': 'True', 'to': u"orm['libretto.Oeuvre']"}), 'coordination': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'blank': 'True'}), 'description': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'oeuvre_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), 'evenements': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'related_name': "u'oeuvres'", 'symmetrical': 'False', 'through': u"orm['libretto.ElementDeProgramme']", 'to': u"orm['libretto.Evenement']"}), 'filles': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'related_name': "u'meres'", 'symmetrical': 'False', 'through': u"orm['libretto.ParenteDOeuvres']", 'to': u"orm['libretto.Oeuvre']"}), 'genre': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'oeuvres'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.GenreDOeuvre']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'oeuvre_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lilypond': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'oeuvre'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'prefixe_titre': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'blank': 'True'}), 'prefixe_titre_secondaire': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'blank': 'True'}), 'pupitres': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'oeuvres'", 'to': u"orm['libretto.Pupitre']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True', 'db_index': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '50', 'populate_from': "u'get_slug'", 'unique_with': '()'}), 'titre': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}), 'titre_secondaire': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, u'libretto.parentedindividus': { 'Meta': {'ordering': "(u'type', u'parent', u'enfant')", 'object_name': 'ParenteDIndividus'}, 'enfant': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'parentes'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Individu']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'parentedindividus'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'enfances'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Individu']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'parentes'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.TypeDeParenteDIndividus']"}) }, u'libretto.parentedoeuvres': { 'Meta': {'ordering': "(u'type',)", 'unique_together': "((u'type', u'mere', u'fille'),)", 'object_name': 'ParenteDOeuvres'}, 'fille': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'parentes_meres'", 'to': u"orm['libretto.Oeuvre']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mere': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'parentes_filles'", 'to': u"orm['libretto.Oeuvre']"}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'parentedoeuvres'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'parentes'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.TypeDeParenteDOeuvres']"}) }, u'libretto.partie': { 'Meta': {'ordering': "(u'classement', u'nom')", 'object_name': 'Partie'}, 'classement': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'db_index': 'True'}), 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'partie_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'partie_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200', 'db_index': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '230', 'blank': 'True'}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'partie'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'parent': ('polymorphic_tree.models.PolymorphicTreeForeignKey', [], {'blank': 'True', 'related_name': "u'enfant'", 'null': 'True', 'to': u"orm['libretto.Partie']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_libretto.partie_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}), 'professions': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'related_name': "u'parties'", 'symmetrical': 'False', 'to': u"orm['libretto.Profession']"}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '50', 'populate_from': "u'get_slug'", 'unique_with': '()'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, u'libretto.personnel': { 'Meta': {'object_name': 'Personnel'}, 'engagements': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'related_name': "u'personnels'", 'symmetrical': 'False', 'to': u"orm['libretto.Engagement']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'personnel'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'saison': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'personnels'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Saison']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'personnels'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.TypeDePersonnel']"}) }, u'libretto.polymorphiccaracteristiquedelementdeprogramme': { 'Meta': {'ordering': "(u'type', u'classement', u'valeur')", 'object_name': 'PolymorphicCaracteristiqueDElementDeProgramme', '_ormbases': [u'libretto.Caracteristique']}, u'caracteristique_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.Caracteristique']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.prenom': { 'Meta': {'ordering': "(u'classement', u'prenom')", 'object_name': 'Prenom'}, 'classement': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'db_index': 'True'}), 'favori': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'prenom'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'prenom': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}) }, u'libretto.profession': { 'Meta': {'ordering': "(u'classement', u'nom')", 'object_name': 'Profession'}, 'classement': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'db_index': 'True'}), 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'profession_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'profession_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200', 'db_index': 'True'}), 'nom_feminin': ('django.db.models.fields.CharField', [], {'max_length': '230', 'blank': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '230', 'blank': 'True'}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'profession'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "u'enfant'", 'null': 'True', 'to': u"orm['libretto.Profession']"}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '50', 'populate_from': "u'get_slug'", 'unique_with': '()'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, u'libretto.pupitre': { 'Meta': {'ordering': "(u'partie',)", 'object_name': 'Pupitre'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'pupitre'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'partie': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'pupitres'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.Partie']"}), 'quantite_max': ('django.db.models.fields.IntegerField', [], {'default': '1', 'db_index': 'True'}), 'quantite_min': ('django.db.models.fields.IntegerField', [], {'default': '1', 'db_index': 'True'}) }, u'libretto.role': { 'Meta': {'ordering': "(u'classement', u'nom')", 'object_name': 'Role', '_ormbases': [u'libretto.Partie']}, u'partie_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.Partie']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.saison': { 'Meta': {'ordering': "(u'lieu', u'debut')", 'object_name': 'Saison'}, 'debut': ('django.db.models.fields.DateField', [], {}), 'fin': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'lieu': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'saisons'", 'to': u"orm['libretto.Lieu']"}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'saison'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}) }, u'libretto.source': { 'Meta': {'ordering': "(u'date', u'nom', u'numero', u'page', u'type')", 'object_name': 'Source'}, 'contenu': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'date': ('django.db.models.fields.DateField', [], {'db_index': 'True'}), 'documents': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'source_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Document']"}), 'etat': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['libretto.Etat']", 'on_delete': 'models.PROTECT'}), 'evenements': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'sources'", 'to': u"orm['libretto.Evenement']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'illustrations': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'source_set'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['libretto.Illustration']"}), 'nom': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}), 'notes': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'numero': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '50', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'source'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'page': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'sources'", 'on_delete': 'models.PROTECT', 'to': u"orm['libretto.TypeDeSource']"}) }, u'libretto.typedecaracteristique': { 'Meta': {'ordering': "(u'classement',)", 'object_name': 'TypeDeCaracteristique'}, 'classement': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200', 'db_index': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '230', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'typedecaracteristique'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_libretto.typedecaracteristique_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}) }, u'libretto.typedecaracteristiquedelementdeprogramme': { 'Meta': {'ordering': "(u'classement',)", 'object_name': 'TypeDeCaracteristiqueDElementDeProgramme', '_ormbases': [u'libretto.TypeDeCaracteristique']}, u'typedecaracteristique_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.TypeDeCaracteristique']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.typedecaracteristiquedoeuvre': { 'Meta': {'ordering': "(u'classement',)", 'object_name': 'TypeDeCaracteristiqueDOeuvre', '_ormbases': [u'libretto.TypeDeCaracteristique']}, u'typedecaracteristique_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.TypeDeCaracteristique']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.typedeparente': { 'Meta': {'ordering': "(u'classement',)", 'unique_together': "((u'nom', u'nom_relatif'),)", 'object_name': 'TypeDeParente'}, 'classement': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '55', 'blank': 'True'}), 'nom_relatif': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'nom_relatif_pluriel': ('django.db.models.fields.CharField', [], {'max_length': '130', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'typedeparente'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_libretto.typedeparente_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}) }, u'libretto.typedeparentedindividus': { 'Meta': {'ordering': "(u'classement',)", 'object_name': 'TypeDeParenteDIndividus', '_ormbases': [u'libretto.TypeDeParente']}, u'typedeparente_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.TypeDeParente']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.typedeparentedoeuvres': { 'Meta': {'ordering': "(u'classement',)", 'object_name': 'TypeDeParenteDOeuvres', '_ormbases': [u'libretto.TypeDeParente']}, u'typedeparente_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['libretto.TypeDeParente']", 'unique': 'True', 'primary_key': 'True'}) }, u'libretto.typedepersonnel': { 'Meta': {'ordering': "(u'nom',)", 'object_name': 'TypeDePersonnel'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'typedepersonnel'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}) }, u'libretto.typedesource': { 'Meta': {'ordering': "(u'slug',)", 'object_name': 'TypeDeSource'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200', 'db_index': 'True'}), 'nom_pluriel': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '230', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'typedesource'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['accounts.HierarchicUser']"}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "u'get_slug'"}) } } complete_apps = ['libretto'] symmetrical = True
[ "bordage.bertrand@gmail.com" ]
bordage.bertrand@gmail.com
185e5d561e97907a26684e58720732b92aa9c3c0
20db56d2fb1cb0ef1fd189d442e0ec327d3bdf65
/Game.py
697270854ef5149e2cefc17f383862a76415ab68
[]
no_license
osmo34/Space-Invaders-Pygame
c757f715eed06ca2fdadb82eb33502db646bcf29
4dce48f49392b7a91e27a1f2371a3b918b9c4b57
refs/heads/master
2020-04-03T08:15:47.005733
2018-11-13T21:58:17
2018-11-13T21:58:17
155,127,062
0
1
null
null
null
null
UTF-8
Python
false
false
33,788
py
# space invaders clone 2018 - Steve O https://github.com/osmo34 # CS50 final project # polishing TODO: # player death - goes off screen, slides back on # on death player blows up - pause, score on screen - then game over screen # score on game over screen import pygame import random from enum import Enum, auto import sqlite3 # database high_scores = [] high_score = 0 db = sqlite3.connect('scores.db') c = db.cursor() c.execute('''CREATE TABLE if not exists score("INTEGER scores")''') db.commit() for row in c.execute('SELECT * FROM score'): high_scores.append(row) def calculate_high_score(): global high_score if not high_scores: high_scores.append((0,)) get_score = max(high_scores) high_score = get_score[0] calculate_high_score() # init pygame pygame.init() screen = pygame.display.set_mode((1024, 768)) done = False # game loop clock = pygame.time.Clock() pygame.font.init() # title screen title_sprite = pygame.image.load('textures/title_screen/title.png') game_over_title_sprite = pygame.image.load('textures/title_screen/game_over.png') # load sprites - current images being used are from Kenny https://www.kenney.nl/assets/space-shooter-redux player_sprite = pygame.image.load('textures/player/playerShip2_green.png') player_projectile_sprite = pygame.image.load('textures/projectile/laserBlue07.png') enemy_projectile_sprite = pygame.image.load('textures/projectile/laserRed03.png') enemy_sprite = [ pygame.image.load('textures/enemy/enemyBlack1.png'), pygame.image.load('textures/enemy/enemyBlack2.png'), pygame.image.load('textures/enemy/enemyBlack3.png'), pygame.image.load('textures/enemy/enemyBlack4.png'), pygame.image.load('textures/enemy/enemyBlack5.png'), pygame.image.load('textures/enemy/enemyBlue1.png'), pygame.image.load('textures/enemy/enemyBlue2.png'), pygame.image.load('textures/enemy/enemyBlue3.png'), pygame.image.load('textures/enemy/enemyBlue4.png'), pygame.image.load('textures/enemy/enemyBlue5.png'), pygame.image.load('textures/enemy/enemyGreen1.png'), pygame.image.load('textures/enemy/enemyGreen2.png'), pygame.image.load('textures/enemy/enemyGreen3.png'), pygame.image.load('textures/enemy/enemyGreen4.png'), pygame.image.load('textures/enemy/enemyGreen5.png'), pygame.image.load('textures/enemy/enemyRed1.png'), pygame.image.load('textures/enemy/enemyRed2.png'), pygame.image.load('textures/enemy/enemyRed3.png'), pygame.image.load('textures/enemy/enemyRed4.png'), pygame.image.load('textures/enemy/enemyRed5.png') ] ufo_sprite = [ pygame.image.load('textures/ufo/ufoBlue.png'), pygame.image.load('textures/ufo/ufoGreen.png'), pygame.image.load('textures/ufo/ufoRed.png'), pygame.image.load('textures/ufo/ufoYellow.png') ] explosion_sprite = [ pygame.image.load('textures/explosion_1/explosion1.png'), pygame.image.load('textures/explosion_1/explosion2.png'), pygame.image.load('textures/explosion_1/explosion3.png'), pygame.image.load('textures/explosion_1/explosion4.png'), pygame.image.load('textures/explosion_1/explosion5.png'), pygame.image.load('textures/explosion_1/explosion6.png'), pygame.image.load('textures/explosion_1/explosion7.png'), pygame.image.load('textures/explosion_1/explosion8.png') ] player_explosion_sprite = [ pygame.image.load('textures/explosion_2/explosion1.png'), pygame.image.load('textures/explosion_2/explosion2.png'), pygame.image.load('textures/explosion_2/explosion3.png'), pygame.image.load('textures/explosion_2/explosion4.png'), pygame.image.load('textures/explosion_2/explosion5.png'), pygame.image.load('textures/explosion_2/explosion6.png'), pygame.image.load('textures/explosion_2/explosion7.png'), pygame.image.load('textures/explosion_2/explosion8.png'), pygame.image.load('textures/explosion_2/explosion9.png'), pygame.image.load('textures/explosion_2/explosion10.png'), pygame.image.load('textures/explosion_2/explosion11.png'), pygame.image.load('textures/explosion_2/explosion12.png'), pygame.image.load('textures/explosion_2/explosion13.png'), pygame.image.load('textures/explosion_2/explosion14.png'), pygame.image.load('textures/explosion_2/explosion15.png'), pygame.image.load('textures/explosion_2/explosion16.png'), pygame.image.load('textures/explosion_2/explosion17.png'), pygame.image.load('textures/explosion_2/explosion18.png'), pygame.image.load('textures/explosion_2/explosion19.png'), pygame.image.load('textures/explosion_2/explosion20.png'), pygame.image.load('textures/explosion_2/explosion21.png'), pygame.image.load('textures/explosion_2/explosion22.png'), pygame.image.load('textures/explosion_2/explosion23.png'), pygame.image.load('textures/explosion_2/explosion24.png'), pygame.image.load('textures/explosion_2/explosion25.png'), pygame.image.load('textures/explosion_2/explosion26.png'), pygame.image.load('textures/explosion_2/explosion27.png'), pygame.image.load('textures/explosion_2/explosion28.png') ] # background background_sprite = [ pygame.image.load('textures/bg/background_01.png').convert(), pygame.image.load('textures/bg/background_02.png').convert(), pygame.image.load('textures/bg/background_03.png').convert() ] background_current = 0 # scale sprites player_sprite = pygame.transform.scale(player_sprite, (42, 28)) player_projectile_sprite = pygame.transform.scale(player_projectile_sprite, (5, 25)) enemy_projectile_sprite = pygame.transform.scale(enemy_projectile_sprite, (5, 25)) for i in range(len(enemy_sprite)): enemy_sprite[i] = pygame.transform.scale(enemy_sprite[i], (26, 21)) for i in range(len(ufo_sprite)): ufo_sprite[i] = pygame.transform.scale(ufo_sprite[i], (30, 30)) for i in range(len(explosion_sprite)): explosion_sprite[i] = pygame.transform.scale(explosion_sprite[i], (64, 64)) for i in range(len(player_explosion_sprite)): player_explosion_sprite[i] = pygame.transform.scale(player_explosion_sprite[i], (128, 128)) # music game_music_1 = pygame.mixer.music.load('sound/Steamtech-Mayhem.ogg') # sound effects player_laser = pygame.mixer.Sound('sound/sound_spark_Laser-Like_Synth_Basic_Laser1_14.wav') enemy_exploision = pygame.mixer.Sound('sound/Explosion+3.wav') enemy_exploision.set_volume(0.05) player_laser.set_volume(0.1) # game globals base_score = 0 base_lives = 3 score = base_score lives = base_lives # player globals base_player_start_x = 500 base_player_start_y = 700 player_start_x = base_player_start_x player_start_y = base_player_start_y player_projectile_speed = 15 # ememy globals base_enemy_speed = 2.0 base_enemy_speed_left = -2.0 base_enemy_speed_right = 2.0 enemy_speed = base_enemy_speed enemy_speed_left = base_enemy_speed_left enemy_speed_right = base_enemy_speed_right enemy_speed_multiplier_base = 0.03 enemy_speed_last_5_base = 1.9 enemy_speed_multiplier_final_base = 10.0 enemy_speed_multiplier = enemy_speed_multiplier_base enemy_speed_last_5 = enemy_speed_last_5_base enemy_speed_multiplier_final = enemy_speed_multiplier_final_base base_enemy_drop_height = 4 base_enemy_drop_last_5 = 25 base_enemy_drop_last = 45 enemy_drop_height = base_enemy_drop_height # how many pixels we should move down on hitting the edge of the screen enemy_drop_last_5 = base_enemy_drop_last_5 enemy_drop_last = base_enemy_drop_last base_enemy_update_height = 0 enemy_update_height = base_enemy_update_height # how many pixels we have moved down enemy_horizontal_seperation = 50 enemy_vertical_seperation = 50 enemy_rows = 6 enemy_colums = 11 default_enemy_x_pos = 150 default_enemy_y_pos = 50 enemy_edge_right = 1000 enemy_edge_left = 0 enemy_fire_rate_base = 1000 enemy_fire_rate = enemy_fire_rate_base # max seed enemy_projectile_seed = -5 base_enemy_score = 50 enemy_score = base_enemy_score enemy_count_base = enemy_rows * enemy_colums + 1 enemy_count = enemy_count_base enemy_fire_rate_multiplier_base = enemy_fire_rate_base // enemy_count_base enemy_fire_rate_multiplier = enemy_fire_rate_multiplier_base level_current_base = 1 level_current = level_current_base level_multiplier_base = 1 level_multiplier = level_multiplier_base game_run_time = 0.0 final_time = 0.0 UFO_score_base = 1000 UFO_score = UFO_score_base UFO_speed = 3.0 # game state class GameState(Enum): TITLE_SCREEN = auto() IN_GAME = auto() GAME_OVER = auto() game_state = GameState.TITLE_SCREEN # classes # # sprite base class class Sprite: def __init__(self): self.left = 0 self.right = 0 self.top = 0 self.bottom = 0 # draw which should be inherited def draw(self, sprite, pos_x, pos_y): screen.blit(sprite, (pos_x, pos_y)) self.update_rect(sprite, pos_x, pos_y) def update_rect(self, sprite, posx, posy): sprite_rect = sprite.get_rect() self.left = posx + sprite_rect.left self.right = posx + sprite_rect.right self.top = posy + sprite_rect.top self.bottom = posy + sprite_rect.bottom # create explosion class Explosion: def __init__(self, spr, offset): self.image_count = len(spr) self.sprite = spr self.current_image = 0 self.seconds = 0.0 self.current_time = self.seconds self.new_explosion = True self.created_time = 0 self.stop = False self.pos_x = 0 self.pos_y = 0 self.reset = False self.offset = offset def prepare(self, posx, posy): self.pos_x = posx - self.offset self.pos_y = posy - self.offset # reset counters for the player who could potentially blow up multiple times TODO: might be needed for enemies in multiple levels... if self.stop and self.reset: self.new_explosion = True self.stop = False self.reset = False def update(self): if self.new_explosion: self.created_time = pygame.time.get_ticks() self.new_explosion = False self.seconds = (pygame.time.get_ticks() - self.created_time) / 500 # frame time half a second if not self.stop: self.current_time += self.seconds if (self.current_image == self.image_count - 1): self.stop = True self.current_image = 0 if self.current_time >= 1: self.current_image += 1 self.current_time = 0 def draw(self): if not self.stop: screen.blit(self.sprite[self.current_image], (self.pos_x, self.pos_y)) # player class class Player(Sprite): def __init__(self): super(Player, self).__init__() self.speed = 6 self.position_x = player_start_x self.position_y = player_start_y self.projectile_offset_x = 11.5 self.projectile_offset_y = 25 self.projectile = Projectile(self.position_x + self.projectile_offset_x, self.position_y - self.projectile_offset_y, player_projectile_speed, False) self.dead = False self.hit_right = False self.hit_left = False self.create_explosion = False self.old_pos_x = 0 self.old_pos_y = 0 self.explode = Explosion(player_explosion_sprite, 64) # player updates def update(self): self.__updateInput() self.__updateProjectile() self.__checkDead() self.__checkEdge() self.explosion() # input updates def __updateInput(self): k_pressed = pygame.key.get_pressed() if not self.hit_left: if k_pressed[pygame.K_LEFT]: self.position_x -= self.speed if not self.hit_right: if k_pressed[pygame.K_RIGHT]: self.position_x += self.speed if not self.projectile.firing: global player_laser if k_pressed[pygame.K_SPACE]: player_laser.play() self.projectile.firing = True def __updateProjectile(self): self.projectile.update(self.position_x + self.projectile_offset_x, self.position_y - self.projectile_offset_y) def __checkDead(self): global lives if self.dead: if not self.create_explosion: # get old positions for an explosion self.old_pos_x = self.position_x self.old_pos_y = self.position_y self.create_explosion = True lives -= 1 self.position_x = 0 # todo: temp self.dead = False def __checkEdge(self): if self.position_x >= 950: self.hit_right = True elif self.position_x <= 50: self.hit_left = True else: self.hit_right = False self.hit_left = False def explosion(self): if self.create_explosion: if not self.explode.stop or self.explode.reset: self.explode.prepare(self.old_pos_x, self.old_pos_y) self.explode.update() else: self.create_explosion = False self.explode.reset = True # create projectiles class Projectile(Sprite): def __init__(self, pos_x, pos_y, speed, enemy): super(Projectile, self).__init__() self.position_x = pos_x self.position_y = pos_y self.firing = False self.hit_enemy = False self.projectile_speed = speed self.is_enemy = enemy def update(self, pos_x, pos_y): self.__move_projectile(pos_x, pos_y) if not self.is_enemy: self.__check_screen_top(pos_x, pos_y) if self.hit_enemy: self.__hit_enemy(pos_x, pos_y) elif self.is_enemy: self.__check_screen_bottom(pos_x, pos_y) self.__enemy_fire() # check if projectile hit enemy - player only def __hit_enemy(self, pos_x, pos_y): self.position_x = pos_x self.position_y = pos_y self.firing = False self.hit_enemy = False # move dependent on if we are firing or not def __move_projectile(self, pos_x, pos_y): if not self.firing: self.position_x = pos_x self.position_y = pos_y elif self.firing: self.position_y -= self.projectile_speed # only relevent for player projectile def __check_screen_top(self, pos_x, pos_y): if self.position_y <= 0: self.position_x = pos_x self.position_y = pos_y self.firing = False # only relevent for enemy laser def __check_screen_bottom(self, pos_x, pos_y): if self.position_y >= 768: self.position_x = pos_x self.position_y = pos_y self.firing = False # define when an enemy fires TODO: change this - base on time, not a seed def __enemy_fire(self): # fire at random if not self.firing: seed = random.randint(1, enemy_fire_rate) if seed == 10: # doesn't matter what number this is, as long as it's under enemy_fire_rate self.firing = True # base controller for enemies class EnemyController(): def __init__(self): self.enemy_list = [] self.enemy_movement = EnemyMovement() self.enemy_position_x = default_enemy_x_pos self.enemy_position_y = default_enemy_y_pos self.game_over = False self.hit_bottom = False # place enemies in the game window def initialize(self): for i in range(enemy_rows): for z in range(enemy_colums): self.enemy_list.append(Enemy(self.enemy_position_x, self.enemy_position_y)) self.enemy_position_x += enemy_horizontal_seperation self.enemy_position_y += enemy_vertical_seperation self.enemy_position_x = default_enemy_x_pos def reset_enemies(self): if not self.game_over: self.enemy_list.clear() self.enemy_position_x = default_enemy_x_pos self.enemy_position_y = default_enemy_y_pos self.initialize() self.game_over = True self.hit_bottom = False # check if we hit an edge def update(self): if not self.game_over: self.enemy_movement.check_edge(self.enemy_list) for enemy in self.enemy_list: enemy.update() if enemy.check_bottom_screen(): self.hit_bottom = True # draw all enemies def draw(self): for enemy in self.enemy_list: enemy.draw(enemy_sprite[enemy.sprite_type], enemy.position_x, enemy.position_y) if enemy.projectile.firing: enemy.projectile.draw(enemy_projectile_sprite, enemy.projectile.position_x, enemy.projectile.position_y) else: enemy.projectile.update_rect(enemy_projectile_sprite, enemy.projectile.position_x, enemy.projectile.position_y) if enemy.create_explosion: enemy.explode.draw() # enemy class class Enemy(Sprite): def __init__(self, pos_x, pos_y): super(Enemy, self).__init__() self.position_x = pos_x self.position_y = pos_y self.initial_height = pos_y self.projectile = Projectile(self.position_x + 11, self.position_y + 20, enemy_projectile_seed, True) self.dead = False self.create_explosion = False self.old_pos_x = 0 self.old_pos_y = 0 self.explode = Explosion(explosion_sprite, 16) # create sprite type at random self.sprite_type = random.randint(0, len(enemy_sprite) - 1) def update(self): self.__move_enemy() self.__check_enemy_height() self.projectile.update(self.position_x + 11, self.position_y + 20) self.check_dead() self.explosion() def __move_enemy(self): self.position_x += enemy_speed def __check_enemy_height(self): self.position_y = self.initial_height + enemy_update_height def _boost_speed(self): global enemy_speed if enemy_speed > 0: enemy_speed = enemy_speed_right elif enemy_speed < 0: enemy_speed = enemy_speed_left def check_dead(self): global score global enemy_fire_rate global enemy_speed global enemy_speed_left global enemy_speed_right global enemy_count global enemy_drop_height if self.dead: if not self.create_explosion: # get old positions for an explosion self.old_pos_x = self.position_x self.old_pos_y = self.position_y self.create_explosion = True score += enemy_score enemy_fire_rate -= enemy_fire_rate_multiplier # make the game harder as we lose enemies if enemy_count > 6: enemy_speed_left -= enemy_speed_multiplier enemy_speed_right += enemy_speed_multiplier self._boost_speed() # smooth speed up elif enemy_count <= 6 and enemy_count > 2: enemy_speed_left -= enemy_speed_last_5 enemy_speed_right += enemy_speed_last_5 enemy_drop_height = enemy_drop_last_5 self._boost_speed() elif enemy_count == 2: enemy_speed_left_= -enemy_speed_multiplier_final enemy_speed_right = enemy_speed_multiplier_final enemy_drop_height = enemy_drop_last self._boost_speed() enemy_count -= 1 # if dead throw position into no mans land - way off the screen self.position_x = -1000 self.position_y = 1000 # hit bottom of screen aka game over def check_bottom_screen(self): if self.position_y > 650 and not self.dead: return True else: return False def explosion(self): if self.create_explosion: self.explode.prepare(self.old_pos_x, self.old_pos_y) self.explode.update() # class for enemy movement class EnemyMovement: def check_edge(self, enemies): global enemy_speed global enemy_update_height for enemy in enemies: if enemy.dead: enemy.position_x = enemy.position_x enemy.position_y = enemy.position_y elif enemy.position_x >= enemy_edge_right: enemy_speed = enemy_speed_left enemy_update_height += enemy_drop_height elif enemy.position_x <= enemy_edge_left: enemy_speed = enemy_speed_right enemy_update_height += enemy_drop_height # UFO class UFO(Sprite): def __init__(self): self.current_sprite = 0 self.start_pos_x = - 100 self.pos_x = self.start_pos_x self.speed_x = UFO_speed self.pos_y = 35 self.flying = False self.dead = False self.create_explosion = False self.old_pos_x = 0 self.old_pos_y = 0 self.explode = Explosion(explosion_sprite, 16) self.texture = 0 def update(self): if self.flying: self.pos_x += self.speed_x if self.pos_x >= 1000: self.pos_x = self.start_pos_x self.flying = False self.__start_flight() self.__checkDead() self.__get_textureID() self.explosion() def __start_flight(self): if not self.flying: if game_run_time < 10: return else: seed = random.randint(1, 750) if seed == 100: self.flying = True def __checkDead(self): if self.dead: if not self.create_explosion: # get old positions for an explosion self.old_pos_x = self.pos_x self.old_pos_y = self.pos_y self.create_explosion = True self.flying = False self.pos_x = self.start_pos_x self.dead = False global lives global score lives += 1 score += UFO_score def __get_textureID(self): if not self.flying: seed = random.randint(0, 2) self.texture = seed def explosion(self): if self.create_explosion: if not self.explode.stop or self.explode.reset: self.explode.prepare(self.old_pos_x, self.old_pos_y) self.explode.update() else: self.create_explosion = False self.explode.reset = True # all collisions class Collision: def checkCollision(self, target, projectile): projectile_position = (projectile.left, projectile.right, projectile.top) target_position = (target.left, target.right, target.top, target.bottom) # default position at start of game is 0 - ignore this if (projectile_position[0]) == 0: del projectile_position del target_position return False if projectile_position[0] <= target_position[1] and projectile_position[1] >= target_position[0] and projectile_position[2] <= target_position[3] and projectile_position[2] >= target_position[2]: del projectile_position del target_position return True else: del projectile_position del target_position return False # create on-screen text class Hud: def __init__(self, text, font, colour, position): self.text = text self.font = font self.position = position self.colour = colour self.textsurface = self.font.render(self.text, False, self.colour) # call this when text needs to be updated def update(self, text): self.text = text self.textsurface = self.font.render(self.text, False, self.colour) def draw(self): screen.blit(self.textsurface, self.position) # title screen class TitleScreen(Sprite): def update(self): global game_state k_pressed = pygame.key.get_pressed() if k_pressed[pygame.K_SPACE]: game_state = GameState.IN_GAME # game over screen class GameOverScreen(Sprite): def __ini__(self): self.score = 0 def get_score_value(self, score): self.score = score def update(self): global game_state k_pressed = pygame.key.get_pressed() if k_pressed[pygame.K_RETURN]: game_state = GameState.TITLE_SCREEN # set up game # create instances title_screen = TitleScreen() game_over_screen = GameOverScreen() player = Player() enemy_controller = EnemyController() enemy_controller.initialize() collision = Collision() background = Sprite() ufo = UFO() # create display text font = pygame.font.Font('font/kenvector_future.ttf', 20) green_text = (75, 244, 66) yellow_text = (233, 244, 66) hud_text = [] hud_text.append(Hud("Score", font, green_text, (10, 10))) hud_text.append(Hud("Lives", font, green_text, (400, 10))) hud_text.append(Hud("High Score", font, green_text, (700, 10))) # text that needs to be updated at runtime info_text = [] show_high_score = int(high_score) text_display = [str(score), str(lives), str(show_high_score)] info_text.append(Hud(text_display[0], font, yellow_text, (120, 10))) info_text.append(Hud(text_display[1], font, yellow_text, (500, 10))) info_text.append(Hud(text_display[2], font, yellow_text, (875, 10))) # start music pygame.mixer.music.play(-1) def process_events(): global done for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # reset game def reset_game(): global lives global score global player_start_x global player_start_y global enemy_speed global enemy_speed_left global enemy_speed_right global enemy_drop_height global enemy_drop_last_5 global enemy_drop_last global enemy_update_height global enemy_score global enemy_count global enemy_fire_rate_multiplier global enemy_fire_rate global level_current global level_multiplier global player global game_run_time global final_time global enemy_speed_multiplier global enemy_speed_last_5 global enemy_speed_multiplier_final player_start_x = base_player_start_x player.position_x = player_start_x enemy_speed = base_enemy_speed enemy_speed_left = base_enemy_speed_left enemy_speed_right = base_enemy_speed_right enemy_drop_height = base_enemy_drop_height enemy_drop_last_5 = base_enemy_drop_last_5 enemy_drop_last = base_enemy_drop_last enemy_update_height = base_enemy_update_height enemy_score = base_enemy_score enemy_count = enemy_count_base enemy_fire_rate = enemy_fire_rate_base enemy_fire_rate_multiplier = enemy_fire_rate_multiplier_base enemy_speed_multiplier = enemy_speed_multiplier_base enemy_speed_last_5 = enemy_speed_last_5_base enemy_speed_multiplier_final = enemy_speed_multiplier_final_base level_current = level_current_base level_multiplier = level_multiplier_base player.dead = False enemy_controller.reset_enemies() final_time += game_run_time game_run_time = 0 def death_reset(): global score global lives global background_current score = base_score lives = base_lives background_current = 0 # todo - increase level def increase_level(): reset_game() global enemy_speed global enemy_speed_left global enemy_speed_right global enemy_speed_multiplier global enemy_speed_last_5 global enemy_speed_multiplier_final global enemy_drop_height global enemy_drop_last_5 global enemy_drop_last global enemy_score global background_current # make it harder enemy_speed += 0.1 enemy_speed_left -= 0.1 enemy_speed_right += 0.1 enemy_speed_multiplier += 0.02 enemy_speed_last_5 += 0.2 enemy_speed_multiplier_final += 3 enemy_drop_height += 1 enemy_drop_last_5 += 5 enemy_drop_last += 5 enemy_score *= 2 # change backdrop if background_current == 2: background_current = 0 else: background_current += 1 # run game loop while not done: while game_state == GameState.TITLE_SCREEN and not done: process_events() title_screen.update() screen.fill((0,0,0)) title_screen.draw(title_sprite, 0, 0) pygame.display.update() while game_state == GameState.GAME_OVER and not done: process_events() game_over_screen.update() screen.fill((0,0,0)) title_screen.draw(game_over_title_sprite, 0, 0) pygame.display.update() while game_state == GameState.IN_GAME and not done: clock.tick(60) # tick at indicated fps # timer variable game_run_time = pygame.time.get_ticks() / 1000 - final_time # we hit a new game and ensure we are not in game over state if enemy_controller.game_over: enemy_controller.game_over = False # pygame events process_events() # update game items player.update() enemy_controller.update() # ufo ufo.update() # track score per enemy enemy_score = base_enemy_score * abs(enemy_speed) * level_multiplier # update lives and score text for i in range(len(info_text)): text_display.clear() _show_score = int(high_score) text_display = [str(int(score)), str(lives), str(_show_score)] info_text[i].update(text_display[i]) # check collisions for enemies in enemy_controller.enemy_list: if collision.checkCollision(enemies, player.projectile): enemy_exploision.play() enemies.dead = True player.projectile.hit_enemy = True break if collision.checkCollision(player, enemies.projectile): player.dead = True break # end game if lives == 0 or enemy_controller.hit_bottom: # TODO - or enemy hits bottom of screen # update scores, update high score if we have the highest value score = abs(score) c.execute("INSERT INTO score VALUES (?)", (score,)) db.commit() high_scores.append((score,)) calculate_high_score() # start reset reset_game() death_reset() game_over_screen.get_score_value(score) game_state = GameState.GAME_OVER # Complete level if enemy_count == 1: increase_level() # draw screen.fill((0,0,0)) background.draw(background_sprite[background_current], 0, 0) player.draw(player_sprite, player.position_x, player.position_y) if player.projectile.firing: player.projectile.draw(player_projectile_sprite, player.projectile.position_x, player.projectile.position_y) else: player.projectile.update_rect(player_projectile_sprite, player.projectile.position_x, player.projectile.position_y) # if we are not drawing we still need to track the sprite position if player.create_explosion: player.explode.draw() enemy_controller.draw() ufo.draw(ufo_sprite[ufo.texture], ufo.pos_x, ufo.pos_y) if ufo.create_explosion: ufo.explode.draw() # fussy - only works after draw code - ufo collisions if collision.checkCollision(ufo, player.projectile): ufo.dead = True break # draw hud items for text in hud_text: text.draw() for text in info_text: text.draw() pygame.display.update() db.close() pygame.quit()
[ "noreply@github.com" ]
osmo34.noreply@github.com
9ccf065b4b4ab8bc95682b6a4ec384525b18ce62
8e093064c914334df4b9fd3e4b489b82fb688b74
/Lab/lab03/ok_tests/q03a.py
8c7d7d3ea4216f2d4a18ac67136827ee85bb8aa3
[]
no_license
keddinger/DS100
f78de1f9a2c3b983010bbbfa3f7e97a584a14cf3
6ca567080bdf40ab3a1b805028aa733160c4f54c
refs/heads/master
2023-03-28T10:17:51.904427
2021-03-31T02:01:47
2021-03-31T02:01:47
349,178,305
0
0
null
null
null
null
UTF-8
Python
false
false
655
py
test = { 'name': 'Question 3a', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> set(calls["Day"]) == {'Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday'} True >>> list(calls["Day"][:5]) == ['Sunday', 'Thursday', 'Thursday', 'Thursday', 'Tuesday'] True """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': r''' >>> def ascii_sum(ans): ... return sum([sum(map(ord, s.strip())) for s in ans]) ''', 'teardown': '', 'type': 'doctest' } ] }
[ "kath.eddinger@berkeley.edu" ]
kath.eddinger@berkeley.edu
1a06bbc21da4311b56698423f8aa212055723d16
4f120540689e17ce086a31832f2687108d9f2810
/process2.py
8fde232b81afd7d14da4b34d02bac3ca91c016be
[]
no_license
Park-liv/Capstone
1979bdcbd4a12c5c99fd971c1a4eb50c897a75b7
907dc703ef7b7431c143e4e3cdfa47e16d443f72
refs/heads/master
2021-02-18T23:14:54.726082
2020-03-05T19:36:41
2020-03-05T19:36:41
245,248,629
0
0
null
null
null
null
UTF-8
Python
false
false
3,671
py
import numpy as np from os import listdir from os.path import isfile, join def MD(act, num_label): X = [] lenFile = [] files = [f for f in listdir('MobiAct_Dataset/{}/'.format(act)) if isfile(join('MobiAct_Dataset/{}/'.format(act), f))] for i in range(len(files)): if 'acc' in files[i]: temp = np.loadtxt('MobiAct_Dataset/{}/{}'.format(act,files[i]), skiprows=16, delimiter=',', dtype=str) temp = temp[:,1:] lenFile.append(len(temp)) temp = temp[:582, :] temp = temp.astype('float32') temp = np.transpose(temp) X.append(temp) # print(min(lenFile)) X = np.array(X) Y = np.full((X.shape[0],1),num_label) return X, Y BSC_X, BSC_Y = MD('BSC', 1) print(BSC_X.shape, BSC_Y.shape) FKL_X, FKL_Y = MD('FKL', 1) print(FKL_X.shape, FKL_Y.shape) FOL_X, FOL_Y = MD('FOL', 1) print(FOL_X.shape, FOL_Y.shape) SDL_X, SDL_Y = MD('SDL', 1) print(SDL_X.shape, SDL_Y.shape) STD_X, STD_Y = MD('STD', 0) print(STD_X.shape, STD_Y.shape) WAL_X, WAL_Y = MD('WAL', 0) print(WAL_X.shape, WAL_Y.shape) JOG_X, JOG_Y = MD('JOG', 0) print(JOG_X.shape, JOG_Y.shape) JUM_X, JUM_Y = MD('JUM', 0) print(JUM_X.shape, JUM_Y.shape) STU_X, STU_Y = MD('STU', 0) print(STU_X.shape, STU_Y.shape) STN_X, STN_Y = MD('STN', 0) print(STN_X.shape, STN_Y.shape) ADL_Fall_X = np.concatenate((BSC_X, FKL_X, FOL_X, SDL_X, STD_X, WAL_X, JOG_X, JUM_X, STU_X, STN_X), axis=0) ADL_Fall_Y = np.concatenate((BSC_Y, FKL_Y, FOL_Y, SDL_Y, STD_Y, WAL_Y, JOG_Y, JUM_Y, STU_Y, STN_Y), axis=0) print(ADL_Fall_X.shape, ADL_Fall_Y.shape) np.save('ADL_Fall_X', ADL_Fall_X) np.save('ADL_Fall_Y', ADL_Fall_Y) print('Done!') BSC_X, BSC_Y = MD('BSC', 6) print(BSC_X.shape, BSC_Y.shape) FKL_X, FKL_Y = MD('FKL', 7) print(FKL_X.shape, FKL_Y.shape) FOL_X, FOL_Y = MD('FOL', 8) print(FOL_X.shape, FOL_Y.shape) SDL_X, SDL_Y = MD('SDL', 9) print(SDL_X.shape, SDL_Y.shape) STD_X, STD_Y = MD('STD', 0) print(STD_X.shape, STD_Y.shape) WAL_X, WAL_Y = MD('WAL', 1) print(WAL_X.shape, WAL_Y.shape) JOG_X, JOG_Y = MD('JOG', 2) print(JOG_X.shape, JOG_Y.shape) JUM_X, JUM_Y = MD('JUM', 3) print(JUM_X.shape, JUM_Y.shape) STU_X, STU_Y = MD('STU', 4) print(STU_X.shape, STU_Y.shape) STN_X, STN_Y = MD('STN', 5) print(STN_X.shape, STN_Y.shape) Ten_Move_X = np.concatenate((BSC_X, FKL_X, FOL_X, SDL_X, STD_X, WAL_X, JOG_X, JUM_X, STU_X, STN_X), axis=0) Ten_Move_Y = np.concatenate((BSC_Y, FKL_Y, FOL_Y, SDL_Y, STD_Y, WAL_Y, JOG_Y, JUM_Y, STU_Y, STN_Y), axis=0) print(Ten_Move_X.shape, Ten_Move_Y.shape) np.save('Ten_Move_X', Ten_Move_X) np.save('Ten_Move_Y', Ten_Move_Y) print('Done!')
[ "52243152+Park-liv@users.noreply.github.com" ]
52243152+Park-liv@users.noreply.github.com
3c7d5dd083ab64ca003b497ca57b3112b93f8870
e503dc955e2feaebade4327ca1fcde7d73843812
/latextomd/prepandoc.py
e8be42e8260866c60a9686859a0b5b7d66f0efda
[ "MIT" ]
permissive
DavidCouronne/latextomd
28eee67e61630aed147721b26dea1e318a5cdb1c
30ed7f5beddecdd44832cbd26ccee85bc66e66f5
refs/heads/master
2022-12-23T06:00:10.093285
2022-10-29T06:09:43
2022-10-29T06:09:43
234,710,531
0
0
MIT
2022-12-09T08:58:54
2020-01-18T09:24:16
Python
UTF-8
Python
false
false
478
py
import codecs import os import re class Prepandoc(object): def __init__(self, latex_string="", export_file=""): self.content = latex_string self.export_file = export_file def process(self): if "\\begin{document}" in self.content: self.preamble, self.content = self.content.split("\\begin{document}") else: self.preamble = "\\documentclass{article}" self.content = self.content + "\n\\end{document}"
[ "couronne.david@gmail.com" ]
couronne.david@gmail.com
b040e8b3e60274af7ab371eb5d8158325791626c
dbc2449adae08dc08571211dd75d4179002e4b0e
/Session2 - Flask and APIs/1-pandas_numpy/pandas_v1.py
d03eee9c247400c0d849259ff6b4c78c3573a17b
[]
no_license
DominiquePaul/data-science-and-cloud-solution-course
b87a8142f81d8da3610f163bd8a6d4b6e226becb
f63f99142025717f56fffb7e6454d5a23943b578
refs/heads/master
2022-12-14T17:05:33.908968
2019-11-07T06:44:59
2019-11-07T06:44:59
219,464,395
0
1
null
2022-12-08T06:50:28
2019-11-04T09:32:27
Python
UTF-8
Python
false
false
4,506
py
""" This script serves as a basic run-through of the numpy and flask package. Its purpose is not to explain all of the essential functions of the two functions, but rather to demonstrate briefly what is possible and give you a feel for what you can do with these packages, so you know where to look for when you have an idea For more information on how pandas and numpy work check out this youtube series: https://www.youtube.com/watch?v=Iqjy9UqKKuo&list=PLQVvvaa0QuDc-3szzjeP6N6b0aDrrKyL- To run the script you might have to run the following commands in your terminal first. If you have installed python with anaconda then replace 'pip' with 'conda' pip install numpy pip install pandas pip install statsmodels pip install seaborn """ import pandas as pd import numpy as np import statsmodels.api as sm import seaborn as sns # reading in a dataframe as csv df = pd.read_csv("./data/wdbc_csv_dirty.csv", sep=",") # selecting a single cell/value df.iloc[1,4] # selecting multiple rows and a column df.loc[1:10,"mean_perimeter"] # selecting multiple rows and several columns df.loc[1:10,["mean_perimeter","mean_area", "Class"]] # creating a subset of our original data df_subset = df.iloc[:, [1,2,3,4,5,-1]] # we split it into out training and test set row_to_split_at = np.round(0.7 * len(df_subset), 0) # split into training and testing data --> does not work df_train = df_subset.iloc[:row_to_split_at, :] df_test = df_subset.iloc[row_to_split_at:, :] # the number we received is a float, but we need an integer, so we just repeat # repeat the previous step and convert the number to an integer type(row_to_split_at) row_to_split_at = int(np.round(0.7 * len(df_subset), 0)) # repeat the splitting df_train = df_subset.iloc[:row_to_split_at, :] df_test = df_subset.iloc[row_to_split_at:, :] # creating a logistic regression --> does not work reg = sm.Logit(np.asarray(df_train.iloc[:,5]), np.asarray(df_train.iloc[:,0:5])) # we cant run our regression because some of our values are empty intermediate_output = df_train.isna().any(axis=1).sum() # we can use this to create a 'mask' of our original dataframe df_train[df_train.isna().any(axis=1)] # but we want exactly the opposite! # or defined the other way around df_train.notna().product(axis=1) # but we need booleans for our next step, so we just convert them df_train.notna().product(axis=1).astype("bool") # using this list of 'boolean' values we can select a 'mask' of our dataset # we re-run this on the subset data to make sure we have the correct alignment # of the decision features and the class labels df_train = df_train.loc[df_train.notna().product(axis=1).astype("bool"), :] df_test = df_test.loc[df_test.notna().product(axis=1).astype("bool"), :] # For most of the problems that not only we but also others are likely to # encounter, there are often pre-written functions in packages which make these # things easier. In this case, we could for example use the dropna command of # pandas. # df_train = df_train.dropna() # df_test = df_test.dropna() # we repeat our regression --> does not work reg = sm.Logit(np.asarray(df_train.iloc[:,5]), np.asarray(df_train.iloc[:,0:5])) reg_fitted = reg.fit() reg_fitted.summary() # another problem! Our classification variables must be between 0 and 1, not 1 # and 2. We can quickly fix this though by subtracting 1 one from the entire # column. Thanks to pandas, this is very easy to do for the entire column df_train["Class"] = df_train["Class"] - 1 df_test["Class"] = df_test["Class"] - 1 # now finally our logistic regression works reg = sm.Logit(np.asarray(df_train.iloc[:,5]), np.asarray(df_train.iloc[:,0:5])) reg_fitted = reg.fit() reg_fitted.summary() # no we can use our model to make predictions predictions = reg_fitted.predict(df_test.iloc[:,:5]) sns.scatterplot(df_test["mean_area"], predictions) predictions = np.where(predictions >0.9, 1, 0) df_test["predictions"] = predictions # plot one of our graphs sns.scatterplot(df_test["mean_area"], df_test["predictions"]) # we save our results for a potential review and analysis df_test.to_csv("./saved_predictions.csv", sep=",") # Say we are just interest in a single value, e.g. if making a prediction for # just one user on our website. Then we can also feed in data like this single_data_point = [21.02, 124.5, 993.0, 0.124, 0.25] single_prediction = reg_fitted.predict(single_data_point) # we are going to receive our single value returned as an array, so we have to # 'unpack' it single_prediction[0]
[ "dominique.paul.info@gmail.com" ]
dominique.paul.info@gmail.com
abe6ec4da2d48927eb8deee11bcf648ef5c0d146
c39c6f9d8339361d9a906d25955e55f49f8f5a67
/multi-model-server-container/docker/code/serve.py
abe27ca62af76b785ad4deee65b941e93a456d83
[]
no_license
cuiIRISA/sagemaker-custom-serving-containers
5fb8e510cfa9192e6214fbc6b4a5aa285297e448
49e0f373dbfe204996cc70100eae78dfb5653be3
refs/heads/master
2023-02-09T20:25:22.329058
2021-01-04T16:33:04
2021-01-04T16:33:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
739
py
from __future__ import absolute_import from subprocess import CalledProcessError from retrying import retry from multi_model_serving import handler_service from sagemaker_inference import model_server HANDLER_SERVICE = handler_service.__name__ def _retry_if_error(exception): return isinstance(exception, CalledProcessError) @retry(stop_max_delay=1000 * 30, retry_on_exception=_retry_if_error) def _start_model_server(): # there's a race condition that causes the model server command to # sometimes fail with 'bad address'. more investigation needed # retry starting mms until it's ready model_server.start_model_server(handler_service=HANDLER_SERVICE) if __name__ == '__main__': _start_model_server()
[ "ec2-user@ip-172-16-37-5.eu-west-1.compute.internal" ]
ec2-user@ip-172-16-37-5.eu-west-1.compute.internal
1115f2bd84bce227a005fe696998bc3c063ce07b
56ce55f61fbd47fef9f7aead809c752d18f7b266
/dj_polls/settings.py
258ef8b7119da6000caf65d828d453a0ad83be13
[]
no_license
rajalokan/dj_polls
a1b69ead36022d8a50bbb989b1807665f6abda14
eb9058e77d6636cd155131656265c12b97e6b010
refs/heads/master
2020-12-31T00:54:09.778388
2017-02-01T04:04:24
2017-02-01T04:04:24
80,588,163
0
0
null
null
null
null
UTF-8
Python
false
false
3,132
py
""" Django settings for dj_polls project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'c17*--_wkc7*12(l&tar4h*_3#y4_fp3ut%b-h+alk)l(zm60r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dj_polls.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dj_polls.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/'
[ "rajalokan@gmail.com" ]
rajalokan@gmail.com
76db24f39a4f84fc44bdd0d6c61fe60ac558333b
15877f137879f9893d550285c973f086e581449c
/demo.py
6fe50785413adf5c26b41e20092dd98cf113b719
[]
no_license
liamkirsh/python-sword2-demo
9526af216699d4e5ba2fc6ccbc94265f390e63eb
22e293bcdfd1e241f3dadff9a2d4469ec5a7fcd9
refs/heads/master
2020-05-29T15:12:53.237291
2016-07-12T16:06:38
2016-07-12T16:06:38
62,222,972
0
0
null
null
null
null
UTF-8
Python
false
false
1,664
py
#!/usr/bin/python from sword2 import * import logging SD_URI = "http://localhost:8080/sd-uri" user = "sword" pw = "sword" def main(): logging.basicConfig() # NSA is watching c = Connection(SD_URI, user_name=user, user_pass=pw) #import ipdb; ipdb.set_trace() c.get_service_document() assert c.sd != None and c.sd.parsed and c.sd.valid print len(c.workspaces) print "workspaces", c.workspaces print "workspace 1 collections", c.workspaces[0][0] workspace_1_title, workspace_1_collections = c.workspaces[0] collection = workspace_1_collections[0] return #print collection # get a human-readable report for it with open("foo.jpg", "rb") as data: # docs are outdated: create replaced create_resource receipt = c.create(col_iri = collection.href, payload = data, mimetype = "application/zip", filename = "foo.jpg", packaging = "http://purl.org/net/sword/package/Binary") #print "\n\n\n" + str(receipt) e = Entry(id = "atomid", title = "atom title") #receipt2 = c.create(col_iri = collection.href, # metadata_entry = e) e.add_fields(dcterms_title = "dcterms title", dcterms_some_other_field = "other") e.add_fields(author={"name":"Ben", "email":"foo@example.org"}) print str(e) e.register_namespace("myschema", "http://example.org") e.add_fields(myscema_foo = "bar") receipt2 = c.create(col_iri = collection.href, metadata_entry = e) if __name__ == '__main__': main()
[ "liam.kirsh@cern.ch" ]
liam.kirsh@cern.ch
84672ce35d56a82848c6674ea16400d957344c45
46feb53d24d3903158c9881dd8a66ccfd04c1329
/cone_high_freq.py
caeafcf1ab99d2cac9638a0e8ef21c75ea037f27
[]
no_license
itoledoc/coneHighFreq
6aeaa91abd75593bb876e1449b1642f7a5269db7
6c8b97a120367334fdb6e8f87fa0a5dbbe16b446
refs/heads/master
2021-01-10T10:23:49.091904
2015-11-26T20:06:05
2015-11-26T20:06:05
46,750,574
0
0
null
null
null
null
UTF-8
Python
false
false
2,961
py
#!/usr/bin/env python import calcsens as cs import longbaseline_cal as lbl import pandas as pd import os import warnings from optparse import OptionParser warnings.simplefilter(action="ignore", category=FutureWarning) if __name__ == "__main__": parser = OptionParser() parser.add_option( "--bw", type=float, default=1.875e9, help="Bandwidth in Hz [default=1.875e9]") parser.add_option( "--npol", type=int, default=2, help="Number of polarizations [default=%default]") parser.add_option( "-s", "--snr", default=10, type=float, help="Signal to noise desired [defaul=%default]") parser.add_option( "-m", "--mode", default="antenna", help="Specify the sensitivy solution mode: " " 'image' - Imaging sensitivity; 'antenna' - Antenna based gain " "solution sensitivity. " "[default=%default]") parser.add_option( "-i", "--intTime", default=60., type=float, help="Integration Time on calibrator [default=%60 s] in seconds" ) parser.add_option( "-e", "--el", type=float, default=45., help="Elevation in degrees [default=%default]") parser.add_option( "-n", "--numAntennas", default=36, type=int, help="Specify the number of antennas. " "[default=%default]") parser.add_option( "-c", "--arrayType", default="12m", help="Specify the type of array configuration ('TP', '7m', '12m'" "[default=%default]") parser.add_option( "-r", "--radius", default=15., type=float, help="Search radius in degrees [default=%default]") parser.usage = """ %prog <coord string [HH:mm:ss.ss DD:mm:ss.ss]> <frequency_in_Hz> """ opts, args = parser.parse_args() coords = str(args[0]) frequency = float(args[1]) spwList = [dict(freq=frequency, BW=opts.bw)] sensDataList = cs.calcMinimumCalibratorFlux( 'phase', returnFull=True, spwList=spwList, tint=opts.intTime, el=opts.el, verbose=True, npol=opts.npol, nant=opts.numAntennas, mode=opts.mode, array=opts.arrayType, SNR=opts.snr) minFluxList = cs.np.array([s["minFlux"] for s in sensDataList]) for s in sensDataList: print "# Assumed PWV=%.3f [mm] Trx=%d [K] Tsys=%d [K] " % ( s["pwv"], s["Trx"], s["Tsys"]) print print "Required calibrator flux: %.2f [mJy]" % (minFluxList[0] * 1.e3) print minflux = minFluxList[0] a = lbl.find_nearest_vlbi_sources( coords, radius=opts.radius, frequency=frequency, phasecal_flux_limit=minflux) df = pd.DataFrame(a).transpose() df.query('fluxDensity >= @minflux').sort( 'separationDegrees').to_csv('calib_candidates_hf.csv') df[(df.fluxDensity.isnull()) | (df.fluxDensity < minflux)].sort( 'separationDegrees').to_csv('cone_hf.csv')
[ "itoledoc@gmail.com" ]
itoledoc@gmail.com
0d4d5a2018ede36d0a80544b4b0b97a70c2cbf64
558a86a0a8cb00866b4015265088701208c91ed0
/chapter2/ex5.py
c418e1c37cb95f4be8d9a9136c0675c7beccc208
[]
no_license
jColeChanged/Programming-Collective-Intelligence
7bbce1a4bfc6374791c4ba73d524ce9605f5714a
1434e8a4677a5790dc8a1ece65b5dd563a09fe7d
refs/heads/master
2022-01-22T00:59:39.112720
2022-01-13T17:41:57
2022-01-13T17:41:57
15,484,924
1
1
null
null
null
null
UTF-8
Python
false
false
832
py
""" Exercise 5 """ import pylast from ex5secrets import API_KEY, API_SECRET, username, password_hash network = pylast.LastFMNetwork(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash) seed_track = network.get_track("Daft Punk", "Get Lucky") def build_user_list(track): return [top.item for top in seed_track.get_top_fans()] def construct_prefs_dict(user_list): prefs = {} all_tracks = set() for user in user_list: prefs[user] = {} loved_tracks = [loved.track for loved in user.get_loved_tracks()] for track in loved_tracks: prefs[user][track] = 1.0 all_tracks.add(track) for track in all_tracks: for ratings in prefs.values(): if track not in ratings: ratings[track] = 0.0 return prefs user_ratings = construct_prefs_dict(build_user_list(seed_track))
[ "jColeChanged@gmail.com" ]
jColeChanged@gmail.com
40d4f1f0fa84bb7ab6095bd4201aa7c592d7808c
3937b980585362f488a98a9fa30c8730afc8fd8f
/Analyze_performance-tc-train-data.py
c5beb270086ce6b9082db635ea9676f242543ee9
[]
no_license
saadiabadi/Convolutional-LSTMs-for-Motion-Forcasting
02effc6a881c7b8903bbbb511f4cc3b77b3895ca
17c8329972d281244fdd5a15acef44676b8fe61f
refs/heads/main
2023-06-09T06:28:15.498488
2021-07-05T16:06:23
2021-07-05T16:06:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,366
py
import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, roc_auc_score from tensorflow.keras.preprocessing.image import img_to_array, load_img import plotly.graph_objects as go import plotly.express as px model = keras.models.load_model(r"C:\Users\MrLin\Documents\Experiments\ConvLSTM_forcasting\checkpoint_tc-augm-lastepoch-retarget-noclassweights") Y_label = np.load(r'D:\Datasets\Fish\processed\targets\train\Y_label.npy') print("shape: {x.shape}, dtype: {x.dtype}".format(x=Y_label)) # Build test dataset generator # define parameters for this dataset fps = 30 # frames per second. the input tensor will cover 4*n/fps seconds T = len(Y_label) # number of images in the dataset batch_size = 4 n = 30 # the length of the time axis of the model's input tensor. 4n video frames are divided up to construct n tensor slices h = 10 # look-ahead. we average the consecutive frame difference over the h+1 next frames, including the current tc_start_frame = 4 * n - 1 # first frame inded in the valid range tc_end_frame = T - 2 - h # last frame index in the valid range, assuming images start at t=0 and go to t=T-1 target_size = (120, 160) clip_tensor_shape = (n,) + tuple(target_size) + (4,) steps_per_epoch_tuning = 100 #1250 training_dir = "D:/Datasets/Fish/processed/train/New folder/" def tc_inputs_generator(t_start, t_end, image_folder): t = t_start while t <= t_end: clip_tensor = [] for j in range(t - 4 * n + 1, t + 1, 1): pil_img = load_img(image_folder.decode('UTF-8') + f'{j:05}' + '.png', color_mode='grayscale', target_size=target_size) clip_tensor.append( img_to_array(pil_img, data_format='channels_last', dtype='uint8').astype(np.float32) / 255) clip_tensor = np.array(clip_tensor) # concat all 4n clip frames along time axis clip_tensor = np.transpose(clip_tensor, axes=(3, 1, 2, 0)) # permute dims so tensor.shape = (1, height, width, 4n) clip_tensor = np.array_split(clip_tensor, n, axis=3) # returns a list of n tensors, each with shape=(1, height, width, 4) clip_tensor = np.concatenate(clip_tensor, axis=0) # finally concat along time axis, producing shape (n, height, width, 4) yield clip_tensor t += 1 # formula to get cardinality of the batched dataset if .cardinality wont work print("number of samples in dataset: ", (tc_end_frame - tc_start_frame + 1) / 1) ds_train = tf.data.Dataset.from_generator( tc_inputs_generator, args=[tc_start_frame, tc_end_frame, training_dir], output_types=(tf.float32), output_shapes=clip_tensor_shape) print(ds_train.element_spec) ds_train = ds_train.batch(batch_size, drop_remainder=False) ds_train = ds_train.take(steps_per_epoch_tuning) # PREDICT USING MODEL Y_pred = model.predict(ds_train) np.save(r'D:\Datasets\Fish\processed\targets\train\Y_pred', Y_pred) Y_tilde = np.load(r'D:\Datasets\Fish\processed\targets\train\Y_tilde.npy') Y_pred = np.load(r'D:\Datasets\Fish\processed\targets\train\Y_pred.npy') def pad_y_pred(Y, T, start, end): out = np.zeros(T) out[start:end] = Y return out # crop data to valid range def crop_to_valid_range(Y, n, h): T = len(Y) start_frame = 4 * n - 1 # first frame inded in the valid range end_frame = T - 2 - h return Y[start_frame:end_frame + 1] print("number of samples in dataset: ", (tc_end_frame - tc_start_frame + 1) / 1) print(f"crop_to_valid_range(Y_label, n, h).shape: {crop_to_valid_range(Y_label, n, h).shape}, y_pred.shape: {Y_pred.shape}") # NOTE: y_pred may not have the same length as crop_to_valid_range(Y_label, n, h). The reason is drop_remainder was set to True during batching # Therefore we need to take elements [:len(y_pred)] in the lines below. if predicting over a truncated training set, we must use [:len(Y_pred)] because y_pred is much shorter than y_label fpr, tpr, thresholds = roc_curve(crop_to_valid_range(Y_label, n, h)[0:len(Y_pred)+0], Y_pred[:, 0], drop_intermediate=True) # to shift Y_label backward by 70 frames, [70:len(Y_pred)+70] auc = roc_auc_score(crop_to_valid_range(Y_label, n, h)[:len(Y_pred)], Y_pred[:, 0]) print(f"auc: {auc}") plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % auc, linestyle=':') plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show() # Plot timeseries------------------- y_pred_padded = pad_y_pred(Y_pred[:,0], T, tc_start_frame, tc_start_frame+len(Y_pred)) # we dont use end_frame because Y_pred is going to be short. That is the whole point of this file: to avoid predicting over the entire dataset print(f"y_pred_padded.shape: {y_pred_padded.shape}") x = np.arange(0, len(Y_label), 1) start_frame = tc_start_frame end_frame = tc_start_frame + len(Y_pred) # Create traces fig = go.Figure() fig.add_trace(go.Scatter(name='ytilde', x=x[start_frame:end_frame], y=Y_tilde[start_frame:end_frame], mode='lines', line=dict( width=1, color='gray' ), showlegend=False )) fig.add_trace(go.Scatter(name='ConvLSTM prediction', x=x[start_frame:end_frame], y=Y_tilde[start_frame:end_frame], mode='markers', marker=dict( color=y_pred_padded[start_frame:end_frame], size=10, opacity=0.7, colorscale="Jet", line=dict( color='black', width=1 ) ), )) fig.add_trace(go.Scatter(name='positive (ground truth)', x=x[Y_label == 1], y=Y_tilde[Y_label == 1], mode='markers', marker=dict( size=5, color='hotpink' ), )) fig.update_layout( width=900, height=700, legend=dict( yanchor="top", y=0.98, xanchor="left", x=0.01, font_size=14 ), xaxis=dict(title_text='frames', title_font_size=18), yaxis=dict(title_text='\u1EF9', title_font_size=18) ) fig.show() # histogram of Y_pred print(np.mean(y_pred_padded[start_frame:end_frame])) # fig = go.Figure(data=[go.Histogram(x=y_pred, cumulative_enabled=False, histnorm='probability')]) fig2 = px.histogram(Y_pred, nbins=50) fig2.show() print(y_pred_padded[start_frame:end_frame])
[ "noreply@github.com" ]
saadiabadi.noreply@github.com
b9eec3c420a027dd0b839e06cf7655b8fbdd08e9
146fb568cd8d1427bf7afd8a0b2682eeb4fef127
/ML.py
fcecf46d24e67e9602f0e3d7299bf9ad20476570
[]
no_license
AiyappaND/automated_music_tagging
8ecb3e03e2108c986b38347b633718193ca1edc3
5956bf463a920c89b63fbbcde90542571cb8e1ca
refs/heads/master
2020-07-14T10:51:52.029354
2017-03-25T09:38:31
2017-03-25T09:38:31
205,303,997
1
0
null
2019-08-30T04:24:43
2019-08-30T04:24:43
null
UTF-8
Python
false
false
5,038
py
from collections import Counter from sklearn.ensemble import VotingClassifier from sklearn.metrics import confusion_matrix from sklearn.neural_network import MLPClassifier from Database_connections import getData, getTestData from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score from sklearn.svm import SVC from sklearn import tree from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import GradientBoostingClassifier import numpy as np from sklearn.multiclass import OneVsRestClassifier from sklearn import preprocessing from sklearn.externals import joblib key_activity_map = {1: "dinner", 2: "party", 3: "sleep", 4: "workout"} training_data_map = dict() testing_data_map = dict() for key in key_activity_map: training_data_map[key] = getData(key_activity_map[key]) testing_data_map[key] = getTestData(key_activity_map[key]) X = [] Y = [] for key in training_data_map: temp = training_data_map[key] X.extend(temp) for ele in temp: Y.append(key) min_max_scaler = preprocessing.MinMaxScaler() #print(Y[-1]) scaler = preprocessing.StandardScaler().fit(X) X = scaler.transform(X) #print(X[-1]) Y = np.asarray(Y) Knnclf = KNeighborsClassifier(n_neighbors=3) Knnclf.fit(X, Y) svmclf = SVC(C=2.015, gamma=0.005, decision_function_shape='ovo') svmclf.fit(X, Y) svmclf.decision_function(X) gnbclf = GaussianNB() gnbclf.fit(X, Y) dtclf = tree.DecisionTreeClassifier(criterion='entropy') dtclf.fit(X, Y) rfclf = RandomForestClassifier(n_estimators=100, criterion="entropy", max_features='auto', random_state=1) rfclf.fit(X, Y) etclf = ExtraTreesClassifier(criterion='entropy', n_estimators=100, max_features='auto') etclf.fit(X, Y) gbclf = GradientBoostingClassifier(criterion='mse', max_features='auto', min_samples_split=3) gbclf.fit(X, Y) MLclf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 25), random_state=1, warm_start=True) eclf = VotingClassifier(estimators=[('svm', svmclf), ('rf', rfclf), ('et', etclf)], voting='hard') eclf.fit(X, Y) for i in range(10): MLclf.fit(X, Y) # joblib.dump(svmclf, 'svm_Classifier_track.pkl') # joblib.dump(Knnclf, 'kNeighbors_Classifier_track.pkl') # joblib.dump(gnbclf, 'gaussian_NB_Classifier_track.pkl') # joblib.dump(rfclf, 'random_forest_Classifier_track.pkl') # joblib.dump(etclf, 'extra_tree_classifier_track.pkl') # joblib.dump(scaler, 'scaler_track.pkl') # joblib.dump(eclf, 'voting_classifier_track.pkl') XTest = [] YTrue = [] for key in testing_data_map: temp = testing_data_map[key] XTest.extend(temp) for ele in temp: YTrue.append(key) XTest = scaler.transform(XTest) KnnYPred = Knnclf.predict(XTest) knnlist = KnnYPred.tolist() svmYPred = svmclf.predict(XTest) svmlist = svmYPred.tolist() gnbclfYPred = gnbclf.predict(XTest) gnblist = gnbclfYPred.tolist() dtYPred = dtclf.predict(XTest) dtlist = dtYPred.tolist() rfYpred = rfclf.predict(XTest) rflist = rfYpred.tolist() etYpred = etclf.predict(XTest) etlist = etYpred.tolist() gbYpred = gbclf.predict(XTest) gblist = gbYpred.tolist() classif = OneVsRestClassifier(estimator=SVC(C=2.5, gamma=0.005)) classif.fit(X, Y) mplclf = classif.predict(XTest) MLYpred = MLclf.predict(XTest) MLYpred = MLYpred.tolist() votingPred = eclf.predict(XTest) votingPred = votingPred.tolist() combinedYPred = [] def getconfusion_matrix(classifier): """ :param classifier: :return: the confusion matrix of one of the classifiers or an error string """ return {'svm': confusion_matrix(YTrue, svmYPred), 'rf': confusion_matrix(YTrue, rfYpred), 'et': confusion_matrix(YTrue, etYpred), 'vote': confusion_matrix(YTrue, votingPred)}.get(classifier, "No classifier of that name") '''print("kNN accuracy = {}% ".format(accuracy_score(YTrue, KnnYPred) * 100)) print("SVM accuracy = {}% ".format(accuracy_score(YTrue, svmYPred) * 100)) print("GNB accuracy = {}% ".format(accuracy_score(YTrue, gnbclfYPred) * 100)) print("DT accuracy = {}% ".format(accuracy_score(YTrue, dtYPred) * 100)) print("RFaccuracy = {}% ".format(accuracy_score(YTrue, rfYpred) * 100)) print("ETaccuracy = {}% ".format(accuracy_score(YTrue, etYpred) * 100)) print("GBaccuracy = {}% ".format(accuracy_score(YTrue, gbYpred) * 100)) print("MCaccuracy = {}% ".format(accuracy_score(YTrue, mplclf) * 100)) print("NNaccuracy = {}%".format(accuracy_score(YTrue, MLYpred) * 100)) print("Votingaccuracy = {}%".format(accuracy_score(YTrue, votingPred) * 100)) print("confusion matrix svm=\n", confusion_matrix(YTrue, svmYPred)) print("confusion matrix rf=\n", confusion_matrix(YTrue, rfYpred)) print("confusion matrix et=\n", confusion_matrix(YTrue, etYpred)) print("confusion matrix voting=\n", confusion_matrix(YTrue, votingPred))''' #print("Votingaccuracy = {}%".format(accuracy_score(YTrue, votingPred) * 100))
[ "aniruddha.achar@gmail.com" ]
aniruddha.achar@gmail.com
3b30f04eaf59c5fbf94c07f8f730a49d1f183cce
53fca43d15ce2271ee3b7a7be30c4467b27c2e67
/Archive/rootme4.py
6778a6920c928d4860d9bd49f946c2f9eaea8ba1
[]
no_license
jeromeksi/ML
89c1ff0d422c956b4e5d5b86b3aa3d825e8f645b
450e0a77dbd79ff774c5718f6b01f28ba806b2c1
refs/heads/master
2021-02-13T00:07:12.342938
2020-03-11T16:44:17
2020-03-11T16:44:17
244,644,469
0
0
null
null
null
null
UTF-8
Python
false
false
112
py
from PIL import Image from pytesser import * im = Image.open('wjNL6.jpg') text = image_to_string(im) print(text)
[ "jerome.ksigzkiewiez@cbre.com" ]
jerome.ksigzkiewiez@cbre.com
39d685f9482325819df2b7826e0f50f2a9136843
356acee6e0dc39c8c6cdd8f56fec1180aaebe184
/python/208ImplementTrie.py
8afc20c570a0c186f74cf976d122a973acffc881
[]
no_license
helkey/algorithm
775a761122ce1c6728295847c73cd771536a15e8
a88f7507b6135d186d7fa126a5ed95f597affd33
refs/heads/master
2021-11-22T14:24:05.091827
2021-09-22T21:16:02
2021-09-22T21:16:02
175,725,711
2
0
null
null
null
null
UTF-8
Python
false
false
1,568
py
""" 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. https://leetcode.com/problems/implement-trie-prefix-tree/ Faster than 85% of Python submisisons """ # from collections import defaultdict class Trie: def __init__(self): """ Initialize your data structure here. """ self.end_char = "#" self.trie = {} def insert(self, word: str) -> None: """ Inserts a word into the trie. """ t = self.trie for c in word: if c not in t: t[c] = {} t = t[c] t[self.end_char] = None def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ t = self.trie for c in word: if c not in t: return False t = t[c] if self.end_char not in t: return False return True def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ t = self.trie for c in prefix: if c not in t: return False t = t[c] return True trie = Trie() trie.insert("apple") print(trie.search("apple")) # -> True print(trie.search("app")) # -> False print(trie.startsWith("app")) # -> True print(trie.startsWith("apple")) # -> True trie.insert("app") print(trie.search("app")) # -> True
[ "rogerx123@gmail.com" ]
rogerx123@gmail.com
af62c15b702f615df9f2f6609895f5222fe1b64c
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
/docdb_write_f/db-cluster-parameter-group_modify.py
867226508b9b77c117bf31b7682454987a3cb87b
[]
no_license
lxtxl/aws_cli
c31fc994c9a4296d6bac851e680d5adbf7e93481
aaf35df1b7509abf5601d3f09ff1fece482facda
refs/heads/master
2023-02-06T09:00:33.088379
2020-12-27T13:38:45
2020-12-27T13:38:45
318,686,394
0
0
null
null
null
null
UTF-8
Python
false
false
1,150
py
#!/usr/bin/python # -*- codding: utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from common.execute_command import write_parameter # url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instances.html if __name__ == '__main__': """ copy-db-cluster-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/copy-db-cluster-parameter-group.html create-db-cluster-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/create-db-cluster-parameter-group.html delete-db-cluster-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/delete-db-cluster-parameter-group.html describe-db-cluster-parameter-groups : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-cluster-parameter-groups.html reset-db-cluster-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/reset-db-cluster-parameter-group.html """ write_parameter("docdb", "modify-db-cluster-parameter-group")
[ "hcseo77@gmail.com" ]
hcseo77@gmail.com